PackageManagerService.java revision eb6195c7a2b59d11ff934ead59b2ff7201769502
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 // We could have touched GID membership, so flush out packages.list 1589 synchronized (mPackages) { 1590 mSettings.writePackageListLPr(); 1591 } 1592 } 1593 1594 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1595 SettingBase sb = (SettingBase) pkg.mExtras; 1596 if (sb == null) { 1597 return; 1598 } 1599 1600 PermissionsState permissionsState = sb.getPermissionsState(); 1601 1602 for (String permission : pkg.requestedPermissions) { 1603 BasePermission bp = mSettings.mPermissions.get(permission); 1604 if (bp != null && bp.isRuntime()) { 1605 permissionsState.grantRuntimePermission(bp, userId); 1606 } 1607 } 1608 } 1609 1610 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1611 Bundle extras = null; 1612 switch (res.returnCode) { 1613 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1614 extras = new Bundle(); 1615 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1616 res.origPermission); 1617 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1618 res.origPackage); 1619 break; 1620 } 1621 case PackageManager.INSTALL_SUCCEEDED: { 1622 extras = new Bundle(); 1623 extras.putBoolean(Intent.EXTRA_REPLACING, 1624 res.removedInfo != null && res.removedInfo.removedPackage != null); 1625 break; 1626 } 1627 } 1628 return extras; 1629 } 1630 1631 void scheduleWriteSettingsLocked() { 1632 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1633 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1634 } 1635 } 1636 1637 void scheduleWritePackageRestrictionsLocked(int userId) { 1638 if (!sUserManager.exists(userId)) return; 1639 mDirtyUsers.add(userId); 1640 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1641 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1642 } 1643 } 1644 1645 public static PackageManagerService main(Context context, Installer installer, 1646 boolean factoryTest, boolean onlyCore) { 1647 PackageManagerService m = new PackageManagerService(context, installer, 1648 factoryTest, onlyCore); 1649 ServiceManager.addService("package", m); 1650 return m; 1651 } 1652 1653 static String[] splitString(String str, char sep) { 1654 int count = 1; 1655 int i = 0; 1656 while ((i=str.indexOf(sep, i)) >= 0) { 1657 count++; 1658 i++; 1659 } 1660 1661 String[] res = new String[count]; 1662 i=0; 1663 count = 0; 1664 int lastI=0; 1665 while ((i=str.indexOf(sep, i)) >= 0) { 1666 res[count] = str.substring(lastI, i); 1667 count++; 1668 i++; 1669 lastI = i; 1670 } 1671 res[count] = str.substring(lastI, str.length()); 1672 return res; 1673 } 1674 1675 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1676 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1677 Context.DISPLAY_SERVICE); 1678 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1679 } 1680 1681 public PackageManagerService(Context context, Installer installer, 1682 boolean factoryTest, boolean onlyCore) { 1683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1684 SystemClock.uptimeMillis()); 1685 1686 if (mSdkVersion <= 0) { 1687 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1688 } 1689 1690 mContext = context; 1691 mFactoryTest = factoryTest; 1692 mOnlyCore = onlyCore; 1693 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1694 mMetrics = new DisplayMetrics(); 1695 mSettings = new Settings(mPackages); 1696 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1703 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1704 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1705 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1706 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1707 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1708 1709 // TODO: add a property to control this? 1710 long dexOptLRUThresholdInMinutes; 1711 if (mLazyDexOpt) { 1712 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1713 } else { 1714 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1715 } 1716 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1717 1718 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1719 if (separateProcesses != null && separateProcesses.length() > 0) { 1720 if ("*".equals(separateProcesses)) { 1721 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1722 mSeparateProcesses = null; 1723 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1724 } else { 1725 mDefParseFlags = 0; 1726 mSeparateProcesses = separateProcesses.split(","); 1727 Slog.w(TAG, "Running with debug.separate_processes: " 1728 + separateProcesses); 1729 } 1730 } else { 1731 mDefParseFlags = 0; 1732 mSeparateProcesses = null; 1733 } 1734 1735 mInstaller = installer; 1736 mPackageDexOptimizer = new PackageDexOptimizer(this); 1737 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1738 1739 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1740 FgThread.get().getLooper()); 1741 1742 getDefaultDisplayMetrics(context, mMetrics); 1743 1744 SystemConfig systemConfig = SystemConfig.getInstance(); 1745 mGlobalGids = systemConfig.getGlobalGids(); 1746 mSystemPermissions = systemConfig.getSystemPermissions(); 1747 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1748 1749 synchronized (mInstallLock) { 1750 // writer 1751 synchronized (mPackages) { 1752 mHandlerThread = new ServiceThread(TAG, 1753 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1754 mHandlerThread.start(); 1755 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1756 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1757 1758 File dataDir = Environment.getDataDirectory(); 1759 mAppDataDir = new File(dataDir, "data"); 1760 mAppInstallDir = new File(dataDir, "app"); 1761 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1762 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1763 mUserAppDataDir = new File(dataDir, "user"); 1764 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1765 1766 sUserManager = new UserManagerService(context, this, 1767 mInstallLock, mPackages); 1768 1769 // Propagate permission configuration in to package manager. 1770 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1771 = systemConfig.getPermissions(); 1772 for (int i=0; i<permConfig.size(); i++) { 1773 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1774 BasePermission bp = mSettings.mPermissions.get(perm.name); 1775 if (bp == null) { 1776 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1777 mSettings.mPermissions.put(perm.name, bp); 1778 } 1779 if (perm.gids != null) { 1780 bp.setGids(perm.gids, perm.perUser); 1781 } 1782 } 1783 1784 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1785 for (int i=0; i<libConfig.size(); i++) { 1786 mSharedLibraries.put(libConfig.keyAt(i), 1787 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1788 } 1789 1790 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1791 1792 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1793 mSdkVersion, mOnlyCore); 1794 1795 String customResolverActivity = Resources.getSystem().getString( 1796 R.string.config_customResolverActivity); 1797 if (TextUtils.isEmpty(customResolverActivity)) { 1798 customResolverActivity = null; 1799 } else { 1800 mCustomResolverComponentName = ComponentName.unflattenFromString( 1801 customResolverActivity); 1802 } 1803 1804 long startTime = SystemClock.uptimeMillis(); 1805 1806 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1807 startTime); 1808 1809 // Set flag to monitor and not change apk file paths when 1810 // scanning install directories. 1811 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1812 1813 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1814 1815 /** 1816 * Add everything in the in the boot class path to the 1817 * list of process files because dexopt will have been run 1818 * if necessary during zygote startup. 1819 */ 1820 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1821 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1822 1823 if (bootClassPath != null) { 1824 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1825 for (String element : bootClassPathElements) { 1826 alreadyDexOpted.add(element); 1827 } 1828 } else { 1829 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1830 } 1831 1832 if (systemServerClassPath != null) { 1833 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1834 for (String element : systemServerClassPathElements) { 1835 alreadyDexOpted.add(element); 1836 } 1837 } else { 1838 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1839 } 1840 1841 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1842 final String[] dexCodeInstructionSets = 1843 getDexCodeInstructionSets( 1844 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1845 1846 /** 1847 * Ensure all external libraries have had dexopt run on them. 1848 */ 1849 if (mSharedLibraries.size() > 0) { 1850 // NOTE: For now, we're compiling these system "shared libraries" 1851 // (and framework jars) into all available architectures. It's possible 1852 // to compile them only when we come across an app that uses them (there's 1853 // already logic for that in scanPackageLI) but that adds some complexity. 1854 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1855 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1856 final String lib = libEntry.path; 1857 if (lib == null) { 1858 continue; 1859 } 1860 1861 try { 1862 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1863 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1864 alreadyDexOpted.add(lib); 1865 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1866 } 1867 } catch (FileNotFoundException e) { 1868 Slog.w(TAG, "Library not found: " + lib); 1869 } catch (IOException e) { 1870 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1871 + e.getMessage()); 1872 } 1873 } 1874 } 1875 } 1876 1877 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1878 1879 // Gross hack for now: we know this file doesn't contain any 1880 // code, so don't dexopt it to avoid the resulting log spew. 1881 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1882 1883 // Gross hack for now: we know this file is only part of 1884 // the boot class path for art, so don't dexopt it to 1885 // avoid the resulting log spew. 1886 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1887 1888 /** 1889 * There are a number of commands implemented in Java, which 1890 * we currently need to do the dexopt on so that they can be 1891 * run from a non-root shell. 1892 */ 1893 String[] frameworkFiles = frameworkDir.list(); 1894 if (frameworkFiles != null) { 1895 // TODO: We could compile these only for the most preferred ABI. We should 1896 // first double check that the dex files for these commands are not referenced 1897 // by other system apps. 1898 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1899 for (int i=0; i<frameworkFiles.length; i++) { 1900 File libPath = new File(frameworkDir, frameworkFiles[i]); 1901 String path = libPath.getPath(); 1902 // Skip the file if we already did it. 1903 if (alreadyDexOpted.contains(path)) { 1904 continue; 1905 } 1906 // Skip the file if it is not a type we want to dexopt. 1907 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1908 continue; 1909 } 1910 try { 1911 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1912 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1913 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1914 } 1915 } catch (FileNotFoundException e) { 1916 Slog.w(TAG, "Jar not found: " + path); 1917 } catch (IOException e) { 1918 Slog.w(TAG, "Exception reading jar: " + path, e); 1919 } 1920 } 1921 } 1922 } 1923 1924 // Collect vendor overlay packages. 1925 // (Do this before scanning any apps.) 1926 // For security and version matching reason, only consider 1927 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1928 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1929 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1931 1932 // Find base frameworks (resource packages without code). 1933 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1934 | PackageParser.PARSE_IS_SYSTEM_DIR 1935 | PackageParser.PARSE_IS_PRIVILEGED, 1936 scanFlags | SCAN_NO_DEX, 0); 1937 1938 // Collected privileged system packages. 1939 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1940 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1941 | PackageParser.PARSE_IS_SYSTEM_DIR 1942 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1943 1944 // Collect ordinary system packages. 1945 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1946 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 // Collect all vendor packages. 1950 File vendorAppDir = new File("/vendor/app"); 1951 try { 1952 vendorAppDir = vendorAppDir.getCanonicalFile(); 1953 } catch (IOException e) { 1954 // failed to look up canonical path, continue with original one 1955 } 1956 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1957 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1958 1959 // Collect all OEM packages. 1960 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1961 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1962 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1963 1964 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1965 mInstaller.moveFiles(); 1966 1967 // Prune any system packages that no longer exist. 1968 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1969 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1970 if (!mOnlyCore) { 1971 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1972 while (psit.hasNext()) { 1973 PackageSetting ps = psit.next(); 1974 1975 /* 1976 * If this is not a system app, it can't be a 1977 * disable system app. 1978 */ 1979 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1980 continue; 1981 } 1982 1983 /* 1984 * If the package is scanned, it's not erased. 1985 */ 1986 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1987 if (scannedPkg != null) { 1988 /* 1989 * If the system app is both scanned and in the 1990 * disabled packages list, then it must have been 1991 * added via OTA. Remove it from the currently 1992 * scanned package so the previously user-installed 1993 * application can be scanned. 1994 */ 1995 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1996 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1997 + ps.name + "; removing system app. Last known codePath=" 1998 + ps.codePathString + ", installStatus=" + ps.installStatus 1999 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2000 + scannedPkg.mVersionCode); 2001 removePackageLI(ps, true); 2002 expectingBetter.put(ps.name, ps.codePath); 2003 } 2004 2005 continue; 2006 } 2007 2008 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2009 psit.remove(); 2010 logCriticalInfo(Log.WARN, "System package " + ps.name 2011 + " no longer exists; wiping its data"); 2012 removeDataDirsLI(null, ps.name); 2013 } else { 2014 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2015 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2016 possiblyDeletedUpdatedSystemApps.add(ps.name); 2017 } 2018 } 2019 } 2020 } 2021 2022 //look for any incomplete package installations 2023 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2024 //clean up list 2025 for(int i = 0; i < deletePkgsList.size(); i++) { 2026 //clean up here 2027 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2028 } 2029 //delete tmp files 2030 deleteTempPackageFiles(); 2031 2032 // Remove any shared userIDs that have no associated packages 2033 mSettings.pruneSharedUsersLPw(); 2034 2035 if (!mOnlyCore) { 2036 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2037 SystemClock.uptimeMillis()); 2038 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2039 2040 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2041 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2042 2043 /** 2044 * Remove disable package settings for any updated system 2045 * apps that were removed via an OTA. If they're not a 2046 * previously-updated app, remove them completely. 2047 * Otherwise, just revoke their system-level permissions. 2048 */ 2049 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2050 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2051 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2052 2053 String msg; 2054 if (deletedPkg == null) { 2055 msg = "Updated system package " + deletedAppName 2056 + " no longer exists; wiping its data"; 2057 removeDataDirsLI(null, deletedAppName); 2058 } else { 2059 msg = "Updated system app + " + deletedAppName 2060 + " no longer present; removing system privileges for " 2061 + deletedAppName; 2062 2063 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2064 2065 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2066 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2067 } 2068 logCriticalInfo(Log.WARN, msg); 2069 } 2070 2071 /** 2072 * Make sure all system apps that we expected to appear on 2073 * the userdata partition actually showed up. If they never 2074 * appeared, crawl back and revive the system version. 2075 */ 2076 for (int i = 0; i < expectingBetter.size(); i++) { 2077 final String packageName = expectingBetter.keyAt(i); 2078 if (!mPackages.containsKey(packageName)) { 2079 final File scanFile = expectingBetter.valueAt(i); 2080 2081 logCriticalInfo(Log.WARN, "Expected better " + packageName 2082 + " but never showed up; reverting to system"); 2083 2084 final int reparseFlags; 2085 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2086 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR 2088 | PackageParser.PARSE_IS_PRIVILEGED; 2089 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2090 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2091 | PackageParser.PARSE_IS_SYSTEM_DIR; 2092 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2093 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR; 2095 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2096 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2097 | PackageParser.PARSE_IS_SYSTEM_DIR; 2098 } else { 2099 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2100 continue; 2101 } 2102 2103 mSettings.enableSystemPackageLPw(packageName); 2104 2105 try { 2106 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2107 } catch (PackageManagerException e) { 2108 Slog.e(TAG, "Failed to parse original system package: " 2109 + e.getMessage()); 2110 } 2111 } 2112 } 2113 } 2114 2115 // Now that we know all of the shared libraries, update all clients to have 2116 // the correct library paths. 2117 updateAllSharedLibrariesLPw(); 2118 2119 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2120 // NOTE: We ignore potential failures here during a system scan (like 2121 // the rest of the commands above) because there's precious little we 2122 // can do about it. A settings error is reported, though. 2123 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2124 false /* force dexopt */, false /* defer dexopt */); 2125 } 2126 2127 // Now that we know all the packages we are keeping, 2128 // read and update their last usage times. 2129 mPackageUsage.readLP(); 2130 2131 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2132 SystemClock.uptimeMillis()); 2133 Slog.i(TAG, "Time to scan packages: " 2134 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2135 + " seconds"); 2136 2137 // If the platform SDK has changed since the last time we booted, 2138 // we need to re-grant app permission to catch any new ones that 2139 // appear. This is really a hack, and means that apps can in some 2140 // cases get permissions that the user didn't initially explicitly 2141 // allow... it would be nice to have some better way to handle 2142 // this situation. 2143 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2144 != mSdkVersion; 2145 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2146 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2147 + "; regranting permissions for internal storage"); 2148 mSettings.mInternalSdkPlatform = mSdkVersion; 2149 2150 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2151 | (regrantPermissions 2152 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2153 : 0)); 2154 2155 // If this is the first boot, and it is a normal boot, then 2156 // we need to initialize the default preferred apps. 2157 if (!mRestoredSettings && !onlyCore) { 2158 mSettings.readDefaultPreferredAppsLPw(this, 0); 2159 } 2160 2161 // If this is first boot after an OTA, and a normal boot, then 2162 // we need to clear code cache directories. 2163 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2164 if (mIsUpgrade && !onlyCore) { 2165 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2166 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2167 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2168 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2169 } 2170 mSettings.mFingerprint = Build.FINGERPRINT; 2171 } 2172 2173 primeDomainVerificationsLPw(); 2174 checkDefaultBrowser(); 2175 2176 // All the changes are done during package scanning. 2177 mSettings.updateInternalDatabaseVersion(); 2178 2179 // can downgrade to reader 2180 mSettings.writeLPr(); 2181 2182 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2183 SystemClock.uptimeMillis()); 2184 2185 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2186 2187 mInstallerService = new PackageInstallerService(context, this); 2188 2189 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2190 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2191 mIntentFilterVerifierComponent); 2192 2193 } // synchronized (mPackages) 2194 } // synchronized (mInstallLock) 2195 2196 // Now after opening every single application zip, make sure they 2197 // are all flushed. Not really needed, but keeps things nice and 2198 // tidy. 2199 Runtime.getRuntime().gc(); 2200 } 2201 2202 @Override 2203 public boolean isFirstBoot() { 2204 return !mRestoredSettings; 2205 } 2206 2207 @Override 2208 public boolean isOnlyCoreApps() { 2209 return mOnlyCore; 2210 } 2211 2212 @Override 2213 public boolean isUpgrade() { 2214 return mIsUpgrade; 2215 } 2216 2217 private String getRequiredVerifierLPr() { 2218 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2219 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2220 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2221 2222 String requiredVerifier = null; 2223 2224 final int N = receivers.size(); 2225 for (int i = 0; i < N; i++) { 2226 final ResolveInfo info = receivers.get(i); 2227 2228 if (info.activityInfo == null) { 2229 continue; 2230 } 2231 2232 final String packageName = info.activityInfo.packageName; 2233 2234 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2235 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2236 continue; 2237 } 2238 2239 if (requiredVerifier != null) { 2240 throw new RuntimeException("There can be only one required verifier"); 2241 } 2242 2243 requiredVerifier = packageName; 2244 } 2245 2246 return requiredVerifier; 2247 } 2248 2249 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2250 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2251 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2252 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2253 2254 ComponentName verifierComponentName = null; 2255 2256 int priority = -1000; 2257 final int N = receivers.size(); 2258 for (int i = 0; i < N; i++) { 2259 final ResolveInfo info = receivers.get(i); 2260 2261 if (info.activityInfo == null) { 2262 continue; 2263 } 2264 2265 final String packageName = info.activityInfo.packageName; 2266 2267 final PackageSetting ps = mSettings.mPackages.get(packageName); 2268 if (ps == null) { 2269 continue; 2270 } 2271 2272 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2273 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2274 continue; 2275 } 2276 2277 // Select the IntentFilterVerifier with the highest priority 2278 if (priority < info.priority) { 2279 priority = info.priority; 2280 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2281 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2282 + verifierComponentName + " with priority: " + info.priority); 2283 } 2284 } 2285 2286 return verifierComponentName; 2287 } 2288 2289 private void primeDomainVerificationsLPw() { 2290 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2291 boolean updated = false; 2292 ArraySet<String> allHostsSet = new ArraySet<>(); 2293 for (PackageParser.Package pkg : mPackages.values()) { 2294 final String packageName = pkg.packageName; 2295 if (!hasDomainURLs(pkg)) { 2296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2297 "package with no domain URLs: " + packageName); 2298 continue; 2299 } 2300 if (!pkg.isSystemApp()) { 2301 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2302 "No priming domain verifications for a non system package : " + 2303 packageName); 2304 continue; 2305 } 2306 for (PackageParser.Activity a : pkg.activities) { 2307 for (ActivityIntentInfo filter : a.intents) { 2308 if (hasValidDomains(filter)) { 2309 allHostsSet.addAll(filter.getHostsList()); 2310 } 2311 } 2312 } 2313 if (allHostsSet.size() == 0) { 2314 allHostsSet.add("*"); 2315 } 2316 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2317 IntentFilterVerificationInfo ivi = 2318 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2319 if (ivi != null) { 2320 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2321 "Priming domain verifications for package: " + packageName + 2322 " with hosts:" + ivi.getDomainsString()); 2323 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2324 updated = true; 2325 } 2326 else { 2327 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2328 "No priming domain verifications for package: " + packageName); 2329 } 2330 allHostsSet.clear(); 2331 } 2332 if (updated) { 2333 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2334 "Will need to write primed domain verifications"); 2335 } 2336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2337 } 2338 2339 private void checkDefaultBrowser() { 2340 final int myUserId = UserHandle.myUserId(); 2341 final String packageName = getDefaultBrowserPackageName(myUserId); 2342 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2343 if (info == null) { 2344 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2345 packageName); 2346 setDefaultBrowserPackageName(null, myUserId); 2347 } 2348 } 2349 2350 @Override 2351 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2352 throws RemoteException { 2353 try { 2354 return super.onTransact(code, data, reply, flags); 2355 } catch (RuntimeException e) { 2356 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2357 Slog.wtf(TAG, "Package Manager Crash", e); 2358 } 2359 throw e; 2360 } 2361 } 2362 2363 void cleanupInstallFailedPackage(PackageSetting ps) { 2364 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2365 2366 removeDataDirsLI(ps.volumeUuid, ps.name); 2367 if (ps.codePath != null) { 2368 if (ps.codePath.isDirectory()) { 2369 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2370 } else { 2371 ps.codePath.delete(); 2372 } 2373 } 2374 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2375 if (ps.resourcePath.isDirectory()) { 2376 FileUtils.deleteContents(ps.resourcePath); 2377 } 2378 ps.resourcePath.delete(); 2379 } 2380 mSettings.removePackageLPw(ps.name); 2381 } 2382 2383 static int[] appendInts(int[] cur, int[] add) { 2384 if (add == null) return cur; 2385 if (cur == null) return add; 2386 final int N = add.length; 2387 for (int i=0; i<N; i++) { 2388 cur = appendInt(cur, add[i]); 2389 } 2390 return cur; 2391 } 2392 2393 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2394 if (!sUserManager.exists(userId)) return null; 2395 final PackageSetting ps = (PackageSetting) p.mExtras; 2396 if (ps == null) { 2397 return null; 2398 } 2399 2400 final PermissionsState permissionsState = ps.getPermissionsState(); 2401 2402 final int[] gids = permissionsState.computeGids(userId); 2403 final Set<String> permissions = permissionsState.getPermissions(userId); 2404 final PackageUserState state = ps.readUserState(userId); 2405 2406 return PackageParser.generatePackageInfo(p, gids, flags, 2407 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2408 } 2409 2410 @Override 2411 public boolean isPackageFrozen(String packageName) { 2412 synchronized (mPackages) { 2413 final PackageSetting ps = mSettings.mPackages.get(packageName); 2414 if (ps != null) { 2415 return ps.frozen; 2416 } 2417 } 2418 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2419 return true; 2420 } 2421 2422 @Override 2423 public boolean isPackageAvailable(String packageName, int userId) { 2424 if (!sUserManager.exists(userId)) return false; 2425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2426 synchronized (mPackages) { 2427 PackageParser.Package p = mPackages.get(packageName); 2428 if (p != null) { 2429 final PackageSetting ps = (PackageSetting) p.mExtras; 2430 if (ps != null) { 2431 final PackageUserState state = ps.readUserState(userId); 2432 if (state != null) { 2433 return PackageParser.isAvailable(state); 2434 } 2435 } 2436 } 2437 } 2438 return false; 2439 } 2440 2441 @Override 2442 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2443 if (!sUserManager.exists(userId)) return null; 2444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2445 // reader 2446 synchronized (mPackages) { 2447 PackageParser.Package p = mPackages.get(packageName); 2448 if (DEBUG_PACKAGE_INFO) 2449 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2450 if (p != null) { 2451 return generatePackageInfo(p, flags, userId); 2452 } 2453 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2454 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2455 } 2456 } 2457 return null; 2458 } 2459 2460 @Override 2461 public String[] currentToCanonicalPackageNames(String[] names) { 2462 String[] out = new String[names.length]; 2463 // reader 2464 synchronized (mPackages) { 2465 for (int i=names.length-1; i>=0; i--) { 2466 PackageSetting ps = mSettings.mPackages.get(names[i]); 2467 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2468 } 2469 } 2470 return out; 2471 } 2472 2473 @Override 2474 public String[] canonicalToCurrentPackageNames(String[] names) { 2475 String[] out = new String[names.length]; 2476 // reader 2477 synchronized (mPackages) { 2478 for (int i=names.length-1; i>=0; i--) { 2479 String cur = mSettings.mRenamedPackages.get(names[i]); 2480 out[i] = cur != null ? cur : names[i]; 2481 } 2482 } 2483 return out; 2484 } 2485 2486 @Override 2487 public int getPackageUid(String packageName, int userId) { 2488 if (!sUserManager.exists(userId)) return -1; 2489 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2490 2491 // reader 2492 synchronized (mPackages) { 2493 PackageParser.Package p = mPackages.get(packageName); 2494 if(p != null) { 2495 return UserHandle.getUid(userId, p.applicationInfo.uid); 2496 } 2497 PackageSetting ps = mSettings.mPackages.get(packageName); 2498 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2499 return -1; 2500 } 2501 p = ps.pkg; 2502 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2503 } 2504 } 2505 2506 @Override 2507 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2508 if (!sUserManager.exists(userId)) { 2509 return null; 2510 } 2511 2512 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2513 "getPackageGids"); 2514 2515 // reader 2516 synchronized (mPackages) { 2517 PackageParser.Package p = mPackages.get(packageName); 2518 if (DEBUG_PACKAGE_INFO) { 2519 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2520 } 2521 if (p != null) { 2522 PackageSetting ps = (PackageSetting) p.mExtras; 2523 return ps.getPermissionsState().computeGids(userId); 2524 } 2525 } 2526 2527 return null; 2528 } 2529 2530 static PermissionInfo generatePermissionInfo( 2531 BasePermission bp, int flags) { 2532 if (bp.perm != null) { 2533 return PackageParser.generatePermissionInfo(bp.perm, flags); 2534 } 2535 PermissionInfo pi = new PermissionInfo(); 2536 pi.name = bp.name; 2537 pi.packageName = bp.sourcePackage; 2538 pi.nonLocalizedLabel = bp.name; 2539 pi.protectionLevel = bp.protectionLevel; 2540 return pi; 2541 } 2542 2543 @Override 2544 public PermissionInfo getPermissionInfo(String name, int flags) { 2545 // reader 2546 synchronized (mPackages) { 2547 final BasePermission p = mSettings.mPermissions.get(name); 2548 if (p != null) { 2549 return generatePermissionInfo(p, flags); 2550 } 2551 return null; 2552 } 2553 } 2554 2555 @Override 2556 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2557 // reader 2558 synchronized (mPackages) { 2559 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2560 for (BasePermission p : mSettings.mPermissions.values()) { 2561 if (group == null) { 2562 if (p.perm == null || p.perm.info.group == null) { 2563 out.add(generatePermissionInfo(p, flags)); 2564 } 2565 } else { 2566 if (p.perm != null && group.equals(p.perm.info.group)) { 2567 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2568 } 2569 } 2570 } 2571 2572 if (out.size() > 0) { 2573 return out; 2574 } 2575 return mPermissionGroups.containsKey(group) ? out : null; 2576 } 2577 } 2578 2579 @Override 2580 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2581 // reader 2582 synchronized (mPackages) { 2583 return PackageParser.generatePermissionGroupInfo( 2584 mPermissionGroups.get(name), flags); 2585 } 2586 } 2587 2588 @Override 2589 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2590 // reader 2591 synchronized (mPackages) { 2592 final int N = mPermissionGroups.size(); 2593 ArrayList<PermissionGroupInfo> out 2594 = new ArrayList<PermissionGroupInfo>(N); 2595 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2596 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2597 } 2598 return out; 2599 } 2600 } 2601 2602 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2603 int userId) { 2604 if (!sUserManager.exists(userId)) return null; 2605 PackageSetting ps = mSettings.mPackages.get(packageName); 2606 if (ps != null) { 2607 if (ps.pkg == null) { 2608 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2609 flags, userId); 2610 if (pInfo != null) { 2611 return pInfo.applicationInfo; 2612 } 2613 return null; 2614 } 2615 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2616 ps.readUserState(userId), userId); 2617 } 2618 return null; 2619 } 2620 2621 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2622 int userId) { 2623 if (!sUserManager.exists(userId)) return null; 2624 PackageSetting ps = mSettings.mPackages.get(packageName); 2625 if (ps != null) { 2626 PackageParser.Package pkg = ps.pkg; 2627 if (pkg == null) { 2628 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2629 return null; 2630 } 2631 // Only data remains, so we aren't worried about code paths 2632 pkg = new PackageParser.Package(packageName); 2633 pkg.applicationInfo.packageName = packageName; 2634 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2635 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2636 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2637 packageName, userId).getAbsolutePath(); 2638 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2639 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2640 } 2641 return generatePackageInfo(pkg, flags, userId); 2642 } 2643 return null; 2644 } 2645 2646 @Override 2647 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2648 if (!sUserManager.exists(userId)) return null; 2649 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2650 // writer 2651 synchronized (mPackages) { 2652 PackageParser.Package p = mPackages.get(packageName); 2653 if (DEBUG_PACKAGE_INFO) Log.v( 2654 TAG, "getApplicationInfo " + packageName 2655 + ": " + p); 2656 if (p != null) { 2657 PackageSetting ps = mSettings.mPackages.get(packageName); 2658 if (ps == null) return null; 2659 // Note: isEnabledLP() does not apply here - always return info 2660 return PackageParser.generateApplicationInfo( 2661 p, flags, ps.readUserState(userId), userId); 2662 } 2663 if ("android".equals(packageName)||"system".equals(packageName)) { 2664 return mAndroidApplication; 2665 } 2666 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2667 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2668 } 2669 } 2670 return null; 2671 } 2672 2673 @Override 2674 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2675 final IPackageDataObserver observer) { 2676 mContext.enforceCallingOrSelfPermission( 2677 android.Manifest.permission.CLEAR_APP_CACHE, null); 2678 // Queue up an async operation since clearing cache may take a little while. 2679 mHandler.post(new Runnable() { 2680 public void run() { 2681 mHandler.removeCallbacks(this); 2682 int retCode = -1; 2683 synchronized (mInstallLock) { 2684 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2685 if (retCode < 0) { 2686 Slog.w(TAG, "Couldn't clear application caches"); 2687 } 2688 } 2689 if (observer != null) { 2690 try { 2691 observer.onRemoveCompleted(null, (retCode >= 0)); 2692 } catch (RemoteException e) { 2693 Slog.w(TAG, "RemoveException when invoking call back"); 2694 } 2695 } 2696 } 2697 }); 2698 } 2699 2700 @Override 2701 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2702 final IntentSender pi) { 2703 mContext.enforceCallingOrSelfPermission( 2704 android.Manifest.permission.CLEAR_APP_CACHE, null); 2705 // Queue up an async operation since clearing cache may take a little while. 2706 mHandler.post(new Runnable() { 2707 public void run() { 2708 mHandler.removeCallbacks(this); 2709 int retCode = -1; 2710 synchronized (mInstallLock) { 2711 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2712 if (retCode < 0) { 2713 Slog.w(TAG, "Couldn't clear application caches"); 2714 } 2715 } 2716 if(pi != null) { 2717 try { 2718 // Callback via pending intent 2719 int code = (retCode >= 0) ? 1 : 0; 2720 pi.sendIntent(null, code, null, 2721 null, null); 2722 } catch (SendIntentException e1) { 2723 Slog.i(TAG, "Failed to send pending intent"); 2724 } 2725 } 2726 } 2727 }); 2728 } 2729 2730 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2731 synchronized (mInstallLock) { 2732 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2733 throw new IOException("Failed to free enough space"); 2734 } 2735 } 2736 } 2737 2738 @Override 2739 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2740 if (!sUserManager.exists(userId)) return null; 2741 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2742 synchronized (mPackages) { 2743 PackageParser.Activity a = mActivities.mActivities.get(component); 2744 2745 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2746 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2747 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2748 if (ps == null) return null; 2749 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2750 userId); 2751 } 2752 if (mResolveComponentName.equals(component)) { 2753 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2754 new PackageUserState(), userId); 2755 } 2756 } 2757 return null; 2758 } 2759 2760 @Override 2761 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2762 String resolvedType) { 2763 synchronized (mPackages) { 2764 PackageParser.Activity a = mActivities.mActivities.get(component); 2765 if (a == null) { 2766 return false; 2767 } 2768 for (int i=0; i<a.intents.size(); i++) { 2769 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2770 intent.getData(), intent.getCategories(), TAG) >= 0) { 2771 return true; 2772 } 2773 } 2774 return false; 2775 } 2776 } 2777 2778 @Override 2779 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2780 if (!sUserManager.exists(userId)) return null; 2781 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2782 synchronized (mPackages) { 2783 PackageParser.Activity a = mReceivers.mActivities.get(component); 2784 if (DEBUG_PACKAGE_INFO) Log.v( 2785 TAG, "getReceiverInfo " + component + ": " + a); 2786 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2787 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2788 if (ps == null) return null; 2789 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2790 userId); 2791 } 2792 } 2793 return null; 2794 } 2795 2796 @Override 2797 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2798 if (!sUserManager.exists(userId)) return null; 2799 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2800 synchronized (mPackages) { 2801 PackageParser.Service s = mServices.mServices.get(component); 2802 if (DEBUG_PACKAGE_INFO) Log.v( 2803 TAG, "getServiceInfo " + component + ": " + s); 2804 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2805 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2806 if (ps == null) return null; 2807 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2808 userId); 2809 } 2810 } 2811 return null; 2812 } 2813 2814 @Override 2815 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2816 if (!sUserManager.exists(userId)) return null; 2817 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2818 synchronized (mPackages) { 2819 PackageParser.Provider p = mProviders.mProviders.get(component); 2820 if (DEBUG_PACKAGE_INFO) Log.v( 2821 TAG, "getProviderInfo " + component + ": " + p); 2822 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2823 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2824 if (ps == null) return null; 2825 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2826 userId); 2827 } 2828 } 2829 return null; 2830 } 2831 2832 @Override 2833 public String[] getSystemSharedLibraryNames() { 2834 Set<String> libSet; 2835 synchronized (mPackages) { 2836 libSet = mSharedLibraries.keySet(); 2837 int size = libSet.size(); 2838 if (size > 0) { 2839 String[] libs = new String[size]; 2840 libSet.toArray(libs); 2841 return libs; 2842 } 2843 } 2844 return null; 2845 } 2846 2847 /** 2848 * @hide 2849 */ 2850 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2851 synchronized (mPackages) { 2852 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2853 if (lib != null && lib.apk != null) { 2854 return mPackages.get(lib.apk); 2855 } 2856 } 2857 return null; 2858 } 2859 2860 @Override 2861 public FeatureInfo[] getSystemAvailableFeatures() { 2862 Collection<FeatureInfo> featSet; 2863 synchronized (mPackages) { 2864 featSet = mAvailableFeatures.values(); 2865 int size = featSet.size(); 2866 if (size > 0) { 2867 FeatureInfo[] features = new FeatureInfo[size+1]; 2868 featSet.toArray(features); 2869 FeatureInfo fi = new FeatureInfo(); 2870 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2871 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2872 features[size] = fi; 2873 return features; 2874 } 2875 } 2876 return null; 2877 } 2878 2879 @Override 2880 public boolean hasSystemFeature(String name) { 2881 synchronized (mPackages) { 2882 return mAvailableFeatures.containsKey(name); 2883 } 2884 } 2885 2886 private void checkValidCaller(int uid, int userId) { 2887 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2888 return; 2889 2890 throw new SecurityException("Caller uid=" + uid 2891 + " is not privileged to communicate with user=" + userId); 2892 } 2893 2894 @Override 2895 public int checkPermission(String permName, String pkgName, int userId) { 2896 if (!sUserManager.exists(userId)) { 2897 return PackageManager.PERMISSION_DENIED; 2898 } 2899 2900 synchronized (mPackages) { 2901 final PackageParser.Package p = mPackages.get(pkgName); 2902 if (p != null && p.mExtras != null) { 2903 final PackageSetting ps = (PackageSetting) p.mExtras; 2904 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2905 return PackageManager.PERMISSION_GRANTED; 2906 } 2907 } 2908 } 2909 2910 return PackageManager.PERMISSION_DENIED; 2911 } 2912 2913 @Override 2914 public int checkUidPermission(String permName, int uid) { 2915 final int userId = UserHandle.getUserId(uid); 2916 2917 if (!sUserManager.exists(userId)) { 2918 return PackageManager.PERMISSION_DENIED; 2919 } 2920 2921 synchronized (mPackages) { 2922 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2923 if (obj != null) { 2924 final SettingBase ps = (SettingBase) obj; 2925 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } else { 2929 ArraySet<String> perms = mSystemPermissions.get(uid); 2930 if (perms != null && perms.contains(permName)) { 2931 return PackageManager.PERMISSION_GRANTED; 2932 } 2933 } 2934 } 2935 2936 return PackageManager.PERMISSION_DENIED; 2937 } 2938 2939 /** 2940 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2941 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2942 * @param checkShell TODO(yamasani): 2943 * @param message the message to log on security exception 2944 */ 2945 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2946 boolean checkShell, String message) { 2947 if (userId < 0) { 2948 throw new IllegalArgumentException("Invalid userId " + userId); 2949 } 2950 if (checkShell) { 2951 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2952 } 2953 if (userId == UserHandle.getUserId(callingUid)) return; 2954 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2955 if (requireFullPermission) { 2956 mContext.enforceCallingOrSelfPermission( 2957 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2958 } else { 2959 try { 2960 mContext.enforceCallingOrSelfPermission( 2961 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2962 } catch (SecurityException se) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2965 } 2966 } 2967 } 2968 } 2969 2970 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2971 if (callingUid == Process.SHELL_UID) { 2972 if (userHandle >= 0 2973 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2974 throw new SecurityException("Shell does not have permission to access user " 2975 + userHandle); 2976 } else if (userHandle < 0) { 2977 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2978 + Debug.getCallers(3)); 2979 } 2980 } 2981 } 2982 2983 private BasePermission findPermissionTreeLP(String permName) { 2984 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2985 if (permName.startsWith(bp.name) && 2986 permName.length() > bp.name.length() && 2987 permName.charAt(bp.name.length()) == '.') { 2988 return bp; 2989 } 2990 } 2991 return null; 2992 } 2993 2994 private BasePermission checkPermissionTreeLP(String permName) { 2995 if (permName != null) { 2996 BasePermission bp = findPermissionTreeLP(permName); 2997 if (bp != null) { 2998 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2999 return bp; 3000 } 3001 throw new SecurityException("Calling uid " 3002 + Binder.getCallingUid() 3003 + " is not allowed to add to permission tree " 3004 + bp.name + " owned by uid " + bp.uid); 3005 } 3006 } 3007 throw new SecurityException("No permission tree found for " + permName); 3008 } 3009 3010 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3011 if (s1 == null) { 3012 return s2 == null; 3013 } 3014 if (s2 == null) { 3015 return false; 3016 } 3017 if (s1.getClass() != s2.getClass()) { 3018 return false; 3019 } 3020 return s1.equals(s2); 3021 } 3022 3023 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3024 if (pi1.icon != pi2.icon) return false; 3025 if (pi1.logo != pi2.logo) return false; 3026 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3027 if (!compareStrings(pi1.name, pi2.name)) return false; 3028 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3029 // We'll take care of setting this one. 3030 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3031 // These are not currently stored in settings. 3032 //if (!compareStrings(pi1.group, pi2.group)) return false; 3033 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3034 //if (pi1.labelRes != pi2.labelRes) return false; 3035 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3036 return true; 3037 } 3038 3039 int permissionInfoFootprint(PermissionInfo info) { 3040 int size = info.name.length(); 3041 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3042 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3043 return size; 3044 } 3045 3046 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3047 int size = 0; 3048 for (BasePermission perm : mSettings.mPermissions.values()) { 3049 if (perm.uid == tree.uid) { 3050 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3051 } 3052 } 3053 return size; 3054 } 3055 3056 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3057 // We calculate the max size of permissions defined by this uid and throw 3058 // if that plus the size of 'info' would exceed our stated maximum. 3059 if (tree.uid != Process.SYSTEM_UID) { 3060 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3061 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3062 throw new SecurityException("Permission tree size cap exceeded"); 3063 } 3064 } 3065 } 3066 3067 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3068 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3069 throw new SecurityException("Label must be specified in permission"); 3070 } 3071 BasePermission tree = checkPermissionTreeLP(info.name); 3072 BasePermission bp = mSettings.mPermissions.get(info.name); 3073 boolean added = bp == null; 3074 boolean changed = true; 3075 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3076 if (added) { 3077 enforcePermissionCapLocked(info, tree); 3078 bp = new BasePermission(info.name, tree.sourcePackage, 3079 BasePermission.TYPE_DYNAMIC); 3080 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3081 throw new SecurityException( 3082 "Not allowed to modify non-dynamic permission " 3083 + info.name); 3084 } else { 3085 if (bp.protectionLevel == fixedLevel 3086 && bp.perm.owner.equals(tree.perm.owner) 3087 && bp.uid == tree.uid 3088 && comparePermissionInfos(bp.perm.info, info)) { 3089 changed = false; 3090 } 3091 } 3092 bp.protectionLevel = fixedLevel; 3093 info = new PermissionInfo(info); 3094 info.protectionLevel = fixedLevel; 3095 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3096 bp.perm.info.packageName = tree.perm.info.packageName; 3097 bp.uid = tree.uid; 3098 if (added) { 3099 mSettings.mPermissions.put(info.name, bp); 3100 } 3101 if (changed) { 3102 if (!async) { 3103 mSettings.writeLPr(); 3104 } else { 3105 scheduleWriteSettingsLocked(); 3106 } 3107 } 3108 return added; 3109 } 3110 3111 @Override 3112 public boolean addPermission(PermissionInfo info) { 3113 synchronized (mPackages) { 3114 return addPermissionLocked(info, false); 3115 } 3116 } 3117 3118 @Override 3119 public boolean addPermissionAsync(PermissionInfo info) { 3120 synchronized (mPackages) { 3121 return addPermissionLocked(info, true); 3122 } 3123 } 3124 3125 @Override 3126 public void removePermission(String name) { 3127 synchronized (mPackages) { 3128 checkPermissionTreeLP(name); 3129 BasePermission bp = mSettings.mPermissions.get(name); 3130 if (bp != null) { 3131 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3132 throw new SecurityException( 3133 "Not allowed to modify non-dynamic permission " 3134 + name); 3135 } 3136 mSettings.mPermissions.remove(name); 3137 mSettings.writeLPr(); 3138 } 3139 } 3140 } 3141 3142 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3143 BasePermission bp) { 3144 int index = pkg.requestedPermissions.indexOf(bp.name); 3145 if (index == -1) { 3146 throw new SecurityException("Package " + pkg.packageName 3147 + " has not requested permission " + bp.name); 3148 } 3149 if (!bp.isRuntime()) { 3150 throw new SecurityException("Permission " + bp.name 3151 + " is not a changeable permission type"); 3152 } 3153 } 3154 3155 @Override 3156 public void grantRuntimePermission(String packageName, String name, int userId) { 3157 if (!sUserManager.exists(userId)) { 3158 Log.e(TAG, "No such user:" + userId); 3159 return; 3160 } 3161 3162 mContext.enforceCallingOrSelfPermission( 3163 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3164 "grantRuntimePermission"); 3165 3166 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3167 "grantRuntimePermission"); 3168 3169 boolean gidsChanged = false; 3170 final SettingBase sb; 3171 3172 synchronized (mPackages) { 3173 final PackageParser.Package pkg = mPackages.get(packageName); 3174 if (pkg == null) { 3175 throw new IllegalArgumentException("Unknown package: " + packageName); 3176 } 3177 3178 final BasePermission bp = mSettings.mPermissions.get(name); 3179 if (bp == null) { 3180 throw new IllegalArgumentException("Unknown permission: " + name); 3181 } 3182 3183 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3184 3185 sb = (SettingBase) pkg.mExtras; 3186 if (sb == null) { 3187 throw new IllegalArgumentException("Unknown package: " + packageName); 3188 } 3189 3190 final PermissionsState permissionsState = sb.getPermissionsState(); 3191 3192 final int flags = permissionsState.getPermissionFlags(name, userId); 3193 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3194 throw new SecurityException("Cannot grant system fixed permission: " 3195 + name + " for package: " + packageName); 3196 } 3197 3198 final int result = permissionsState.grantRuntimePermission(bp, userId); 3199 switch (result) { 3200 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3201 return; 3202 } 3203 3204 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3205 gidsChanged = true; 3206 } break; 3207 } 3208 3209 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3210 3211 // Not critical if that is lost - app has to request again. 3212 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3213 } 3214 3215 if (gidsChanged) { 3216 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3217 } 3218 } 3219 3220 @Override 3221 public void revokeRuntimePermission(String packageName, String name, int userId) { 3222 if (!sUserManager.exists(userId)) { 3223 Log.e(TAG, "No such user:" + userId); 3224 return; 3225 } 3226 3227 mContext.enforceCallingOrSelfPermission( 3228 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3229 "revokeRuntimePermission"); 3230 3231 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3232 "revokeRuntimePermission"); 3233 3234 final SettingBase sb; 3235 3236 synchronized (mPackages) { 3237 final PackageParser.Package pkg = mPackages.get(packageName); 3238 if (pkg == null) { 3239 throw new IllegalArgumentException("Unknown package: " + packageName); 3240 } 3241 3242 final BasePermission bp = mSettings.mPermissions.get(name); 3243 if (bp == null) { 3244 throw new IllegalArgumentException("Unknown permission: " + name); 3245 } 3246 3247 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3248 3249 sb = (SettingBase) pkg.mExtras; 3250 if (sb == null) { 3251 throw new IllegalArgumentException("Unknown package: " + packageName); 3252 } 3253 3254 final PermissionsState permissionsState = sb.getPermissionsState(); 3255 3256 final int flags = permissionsState.getPermissionFlags(name, userId); 3257 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3258 throw new SecurityException("Cannot revoke system fixed permission: " 3259 + name + " for package: " + packageName); 3260 } 3261 3262 if (permissionsState.revokeRuntimePermission(bp, userId) == 3263 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3264 return; 3265 } 3266 3267 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3268 3269 // Critical, after this call app should never have the permission. 3270 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3271 } 3272 3273 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3274 } 3275 3276 @Override 3277 public int getPermissionFlags(String name, String packageName, int userId) { 3278 if (!sUserManager.exists(userId)) { 3279 return 0; 3280 } 3281 3282 mContext.enforceCallingOrSelfPermission( 3283 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3284 "getPermissionFlags"); 3285 3286 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3287 "getPermissionFlags"); 3288 3289 synchronized (mPackages) { 3290 final PackageParser.Package pkg = mPackages.get(packageName); 3291 if (pkg == null) { 3292 throw new IllegalArgumentException("Unknown package: " + packageName); 3293 } 3294 3295 final BasePermission bp = mSettings.mPermissions.get(name); 3296 if (bp == null) { 3297 throw new IllegalArgumentException("Unknown permission: " + name); 3298 } 3299 3300 SettingBase sb = (SettingBase) pkg.mExtras; 3301 if (sb == null) { 3302 throw new IllegalArgumentException("Unknown package: " + packageName); 3303 } 3304 3305 PermissionsState permissionsState = sb.getPermissionsState(); 3306 return permissionsState.getPermissionFlags(name, userId); 3307 } 3308 } 3309 3310 @Override 3311 public void updatePermissionFlags(String name, String packageName, int flagMask, 3312 int flagValues, int userId) { 3313 if (!sUserManager.exists(userId)) { 3314 return; 3315 } 3316 3317 mContext.enforceCallingOrSelfPermission( 3318 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3319 "updatePermissionFlags"); 3320 3321 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3322 "updatePermissionFlags"); 3323 3324 // Only the system can change policy flags. 3325 if (getCallingUid() != Process.SYSTEM_UID) { 3326 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3327 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3328 } 3329 3330 // Only the package manager can change system flags. 3331 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3332 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3333 3334 synchronized (mPackages) { 3335 final PackageParser.Package pkg = mPackages.get(packageName); 3336 if (pkg == null) { 3337 throw new IllegalArgumentException("Unknown package: " + packageName); 3338 } 3339 3340 final BasePermission bp = mSettings.mPermissions.get(name); 3341 if (bp == null) { 3342 throw new IllegalArgumentException("Unknown permission: " + name); 3343 } 3344 3345 SettingBase sb = (SettingBase) pkg.mExtras; 3346 if (sb == null) { 3347 throw new IllegalArgumentException("Unknown package: " + packageName); 3348 } 3349 3350 PermissionsState permissionsState = sb.getPermissionsState(); 3351 3352 // Only the package manager can change flags for system component permissions. 3353 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3354 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3355 return; 3356 } 3357 3358 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3359 // Install and runtime permissions are stored in different places, 3360 // so figure out what permission changed and persist the change. 3361 if (permissionsState.getInstallPermissionState(name) != null) { 3362 scheduleWriteSettingsLocked(); 3363 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3365 } 3366 } 3367 } 3368 } 3369 3370 @Override 3371 public boolean shouldShowRequestPermissionRationale(String permissionName, 3372 String packageName, int userId) { 3373 if (UserHandle.getCallingUserId() != userId) { 3374 mContext.enforceCallingPermission( 3375 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3376 "canShowRequestPermissionRationale for user " + userId); 3377 } 3378 3379 final int uid = getPackageUid(packageName, userId); 3380 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3381 return false; 3382 } 3383 3384 if (checkPermission(permissionName, packageName, userId) 3385 == PackageManager.PERMISSION_GRANTED) { 3386 return false; 3387 } 3388 3389 final int flags; 3390 3391 final long identity = Binder.clearCallingIdentity(); 3392 try { 3393 flags = getPermissionFlags(permissionName, 3394 packageName, userId); 3395 } finally { 3396 Binder.restoreCallingIdentity(identity); 3397 } 3398 3399 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3400 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3401 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3402 3403 if ((flags & fixedFlags) != 0) { 3404 return false; 3405 } 3406 3407 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3408 } 3409 3410 @Override 3411 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3412 mContext.enforceCallingOrSelfPermission( 3413 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3414 "addOnPermissionsChangeListener"); 3415 3416 synchronized (mPackages) { 3417 mOnPermissionChangeListeners.addListenerLocked(listener); 3418 } 3419 } 3420 3421 @Override 3422 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3423 synchronized (mPackages) { 3424 mOnPermissionChangeListeners.removeListenerLocked(listener); 3425 } 3426 } 3427 3428 @Override 3429 public boolean isProtectedBroadcast(String actionName) { 3430 synchronized (mPackages) { 3431 return mProtectedBroadcasts.contains(actionName); 3432 } 3433 } 3434 3435 @Override 3436 public int checkSignatures(String pkg1, String pkg2) { 3437 synchronized (mPackages) { 3438 final PackageParser.Package p1 = mPackages.get(pkg1); 3439 final PackageParser.Package p2 = mPackages.get(pkg2); 3440 if (p1 == null || p1.mExtras == null 3441 || p2 == null || p2.mExtras == null) { 3442 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3443 } 3444 return compareSignatures(p1.mSignatures, p2.mSignatures); 3445 } 3446 } 3447 3448 @Override 3449 public int checkUidSignatures(int uid1, int uid2) { 3450 // Map to base uids. 3451 uid1 = UserHandle.getAppId(uid1); 3452 uid2 = UserHandle.getAppId(uid2); 3453 // reader 3454 synchronized (mPackages) { 3455 Signature[] s1; 3456 Signature[] s2; 3457 Object obj = mSettings.getUserIdLPr(uid1); 3458 if (obj != null) { 3459 if (obj instanceof SharedUserSetting) { 3460 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3461 } else if (obj instanceof PackageSetting) { 3462 s1 = ((PackageSetting)obj).signatures.mSignatures; 3463 } else { 3464 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3465 } 3466 } else { 3467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3468 } 3469 obj = mSettings.getUserIdLPr(uid2); 3470 if (obj != null) { 3471 if (obj instanceof SharedUserSetting) { 3472 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3473 } else if (obj instanceof PackageSetting) { 3474 s2 = ((PackageSetting)obj).signatures.mSignatures; 3475 } else { 3476 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3477 } 3478 } else { 3479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3480 } 3481 return compareSignatures(s1, s2); 3482 } 3483 } 3484 3485 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3486 final long identity = Binder.clearCallingIdentity(); 3487 try { 3488 if (sb instanceof SharedUserSetting) { 3489 SharedUserSetting sus = (SharedUserSetting) sb; 3490 final int packageCount = sus.packages.size(); 3491 for (int i = 0; i < packageCount; i++) { 3492 PackageSetting susPs = sus.packages.valueAt(i); 3493 if (userId == UserHandle.USER_ALL) { 3494 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3495 } else { 3496 final int uid = UserHandle.getUid(userId, susPs.appId); 3497 killUid(uid, reason); 3498 } 3499 } 3500 } else if (sb instanceof PackageSetting) { 3501 PackageSetting ps = (PackageSetting) sb; 3502 if (userId == UserHandle.USER_ALL) { 3503 killApplication(ps.pkg.packageName, ps.appId, reason); 3504 } else { 3505 final int uid = UserHandle.getUid(userId, ps.appId); 3506 killUid(uid, reason); 3507 } 3508 } 3509 } finally { 3510 Binder.restoreCallingIdentity(identity); 3511 } 3512 } 3513 3514 private static void killUid(int uid, String reason) { 3515 IActivityManager am = ActivityManagerNative.getDefault(); 3516 if (am != null) { 3517 try { 3518 am.killUid(uid, reason); 3519 } catch (RemoteException e) { 3520 /* ignore - same process */ 3521 } 3522 } 3523 } 3524 3525 /** 3526 * Compares two sets of signatures. Returns: 3527 * <br /> 3528 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3529 * <br /> 3530 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3531 * <br /> 3532 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3533 * <br /> 3534 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3535 * <br /> 3536 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3537 */ 3538 static int compareSignatures(Signature[] s1, Signature[] s2) { 3539 if (s1 == null) { 3540 return s2 == null 3541 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3542 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3543 } 3544 3545 if (s2 == null) { 3546 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3547 } 3548 3549 if (s1.length != s2.length) { 3550 return PackageManager.SIGNATURE_NO_MATCH; 3551 } 3552 3553 // Since both signature sets are of size 1, we can compare without HashSets. 3554 if (s1.length == 1) { 3555 return s1[0].equals(s2[0]) ? 3556 PackageManager.SIGNATURE_MATCH : 3557 PackageManager.SIGNATURE_NO_MATCH; 3558 } 3559 3560 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3561 for (Signature sig : s1) { 3562 set1.add(sig); 3563 } 3564 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3565 for (Signature sig : s2) { 3566 set2.add(sig); 3567 } 3568 // Make sure s2 contains all signatures in s1. 3569 if (set1.equals(set2)) { 3570 return PackageManager.SIGNATURE_MATCH; 3571 } 3572 return PackageManager.SIGNATURE_NO_MATCH; 3573 } 3574 3575 /** 3576 * If the database version for this type of package (internal storage or 3577 * external storage) is less than the version where package signatures 3578 * were updated, return true. 3579 */ 3580 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3581 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3582 DatabaseVersion.SIGNATURE_END_ENTITY)) 3583 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3584 DatabaseVersion.SIGNATURE_END_ENTITY)); 3585 } 3586 3587 /** 3588 * Used for backward compatibility to make sure any packages with 3589 * certificate chains get upgraded to the new style. {@code existingSigs} 3590 * will be in the old format (since they were stored on disk from before the 3591 * system upgrade) and {@code scannedSigs} will be in the newer format. 3592 */ 3593 private int compareSignaturesCompat(PackageSignatures existingSigs, 3594 PackageParser.Package scannedPkg) { 3595 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3596 return PackageManager.SIGNATURE_NO_MATCH; 3597 } 3598 3599 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3600 for (Signature sig : existingSigs.mSignatures) { 3601 existingSet.add(sig); 3602 } 3603 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3604 for (Signature sig : scannedPkg.mSignatures) { 3605 try { 3606 Signature[] chainSignatures = sig.getChainSignatures(); 3607 for (Signature chainSig : chainSignatures) { 3608 scannedCompatSet.add(chainSig); 3609 } 3610 } catch (CertificateEncodingException e) { 3611 scannedCompatSet.add(sig); 3612 } 3613 } 3614 /* 3615 * Make sure the expanded scanned set contains all signatures in the 3616 * existing one. 3617 */ 3618 if (scannedCompatSet.equals(existingSet)) { 3619 // Migrate the old signatures to the new scheme. 3620 existingSigs.assignSignatures(scannedPkg.mSignatures); 3621 // The new KeySets will be re-added later in the scanning process. 3622 synchronized (mPackages) { 3623 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3624 } 3625 return PackageManager.SIGNATURE_MATCH; 3626 } 3627 return PackageManager.SIGNATURE_NO_MATCH; 3628 } 3629 3630 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3631 if (isExternal(scannedPkg)) { 3632 return mSettings.isExternalDatabaseVersionOlderThan( 3633 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3634 } else { 3635 return mSettings.isInternalDatabaseVersionOlderThan( 3636 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3637 } 3638 } 3639 3640 private int compareSignaturesRecover(PackageSignatures existingSigs, 3641 PackageParser.Package scannedPkg) { 3642 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3643 return PackageManager.SIGNATURE_NO_MATCH; 3644 } 3645 3646 String msg = null; 3647 try { 3648 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3649 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3650 + scannedPkg.packageName); 3651 return PackageManager.SIGNATURE_MATCH; 3652 } 3653 } catch (CertificateException e) { 3654 msg = e.getMessage(); 3655 } 3656 3657 logCriticalInfo(Log.INFO, 3658 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3659 return PackageManager.SIGNATURE_NO_MATCH; 3660 } 3661 3662 @Override 3663 public String[] getPackagesForUid(int uid) { 3664 uid = UserHandle.getAppId(uid); 3665 // reader 3666 synchronized (mPackages) { 3667 Object obj = mSettings.getUserIdLPr(uid); 3668 if (obj instanceof SharedUserSetting) { 3669 final SharedUserSetting sus = (SharedUserSetting) obj; 3670 final int N = sus.packages.size(); 3671 final String[] res = new String[N]; 3672 final Iterator<PackageSetting> it = sus.packages.iterator(); 3673 int i = 0; 3674 while (it.hasNext()) { 3675 res[i++] = it.next().name; 3676 } 3677 return res; 3678 } else if (obj instanceof PackageSetting) { 3679 final PackageSetting ps = (PackageSetting) obj; 3680 return new String[] { ps.name }; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 @Override 3687 public String getNameForUid(int uid) { 3688 // reader 3689 synchronized (mPackages) { 3690 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3691 if (obj instanceof SharedUserSetting) { 3692 final SharedUserSetting sus = (SharedUserSetting) obj; 3693 return sus.name + ":" + sus.userId; 3694 } else if (obj instanceof PackageSetting) { 3695 final PackageSetting ps = (PackageSetting) obj; 3696 return ps.name; 3697 } 3698 } 3699 return null; 3700 } 3701 3702 @Override 3703 public int getUidForSharedUser(String sharedUserName) { 3704 if(sharedUserName == null) { 3705 return -1; 3706 } 3707 // reader 3708 synchronized (mPackages) { 3709 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3710 if (suid == null) { 3711 return -1; 3712 } 3713 return suid.userId; 3714 } 3715 } 3716 3717 @Override 3718 public int getFlagsForUid(int uid) { 3719 synchronized (mPackages) { 3720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3721 if (obj instanceof SharedUserSetting) { 3722 final SharedUserSetting sus = (SharedUserSetting) obj; 3723 return sus.pkgFlags; 3724 } else if (obj instanceof PackageSetting) { 3725 final PackageSetting ps = (PackageSetting) obj; 3726 return ps.pkgFlags; 3727 } 3728 } 3729 return 0; 3730 } 3731 3732 @Override 3733 public int getPrivateFlagsForUid(int uid) { 3734 synchronized (mPackages) { 3735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3736 if (obj instanceof SharedUserSetting) { 3737 final SharedUserSetting sus = (SharedUserSetting) obj; 3738 return sus.pkgPrivateFlags; 3739 } else if (obj instanceof PackageSetting) { 3740 final PackageSetting ps = (PackageSetting) obj; 3741 return ps.pkgPrivateFlags; 3742 } 3743 } 3744 return 0; 3745 } 3746 3747 @Override 3748 public boolean isUidPrivileged(int uid) { 3749 uid = UserHandle.getAppId(uid); 3750 // reader 3751 synchronized (mPackages) { 3752 Object obj = mSettings.getUserIdLPr(uid); 3753 if (obj instanceof SharedUserSetting) { 3754 final SharedUserSetting sus = (SharedUserSetting) obj; 3755 final Iterator<PackageSetting> it = sus.packages.iterator(); 3756 while (it.hasNext()) { 3757 if (it.next().isPrivileged()) { 3758 return true; 3759 } 3760 } 3761 } else if (obj instanceof PackageSetting) { 3762 final PackageSetting ps = (PackageSetting) obj; 3763 return ps.isPrivileged(); 3764 } 3765 } 3766 return false; 3767 } 3768 3769 @Override 3770 public String[] getAppOpPermissionPackages(String permissionName) { 3771 synchronized (mPackages) { 3772 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3773 if (pkgs == null) { 3774 return null; 3775 } 3776 return pkgs.toArray(new String[pkgs.size()]); 3777 } 3778 } 3779 3780 @Override 3781 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3782 int flags, int userId) { 3783 if (!sUserManager.exists(userId)) return null; 3784 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3785 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3786 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3787 } 3788 3789 @Override 3790 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3791 IntentFilter filter, int match, ComponentName activity) { 3792 final int userId = UserHandle.getCallingUserId(); 3793 if (DEBUG_PREFERRED) { 3794 Log.v(TAG, "setLastChosenActivity intent=" + intent 3795 + " resolvedType=" + resolvedType 3796 + " flags=" + flags 3797 + " filter=" + filter 3798 + " match=" + match 3799 + " activity=" + activity); 3800 filter.dump(new PrintStreamPrinter(System.out), " "); 3801 } 3802 intent.setComponent(null); 3803 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3804 // Find any earlier preferred or last chosen entries and nuke them 3805 findPreferredActivity(intent, resolvedType, 3806 flags, query, 0, false, true, false, userId); 3807 // Add the new activity as the last chosen for this filter 3808 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3809 "Setting last chosen"); 3810 } 3811 3812 @Override 3813 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3814 final int userId = UserHandle.getCallingUserId(); 3815 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3816 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3817 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3818 false, false, false, userId); 3819 } 3820 3821 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3822 int flags, List<ResolveInfo> query, int userId) { 3823 if (query != null) { 3824 final int N = query.size(); 3825 if (N == 1) { 3826 return query.get(0); 3827 } else if (N > 1) { 3828 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3829 // If there is more than one activity with the same priority, 3830 // then let the user decide between them. 3831 ResolveInfo r0 = query.get(0); 3832 ResolveInfo r1 = query.get(1); 3833 if (DEBUG_INTENT_MATCHING || debug) { 3834 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3835 + r1.activityInfo.name + "=" + r1.priority); 3836 } 3837 // If the first activity has a higher priority, or a different 3838 // default, then it is always desireable to pick it. 3839 if (r0.priority != r1.priority 3840 || r0.preferredOrder != r1.preferredOrder 3841 || r0.isDefault != r1.isDefault) { 3842 return query.get(0); 3843 } 3844 // If we have saved a preference for a preferred activity for 3845 // this Intent, use that. 3846 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3847 flags, query, r0.priority, true, false, debug, userId); 3848 if (ri != null) { 3849 return ri; 3850 } 3851 if (userId != 0) { 3852 ri = new ResolveInfo(mResolveInfo); 3853 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3854 ri.activityInfo.applicationInfo = new ApplicationInfo( 3855 ri.activityInfo.applicationInfo); 3856 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3857 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3858 return ri; 3859 } 3860 return mResolveInfo; 3861 } 3862 } 3863 return null; 3864 } 3865 3866 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3867 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3868 final int N = query.size(); 3869 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3870 .get(userId); 3871 // Get the list of persistent preferred activities that handle the intent 3872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3873 List<PersistentPreferredActivity> pprefs = ppir != null 3874 ? ppir.queryIntent(intent, resolvedType, 3875 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3876 : null; 3877 if (pprefs != null && pprefs.size() > 0) { 3878 final int M = pprefs.size(); 3879 for (int i=0; i<M; i++) { 3880 final PersistentPreferredActivity ppa = pprefs.get(i); 3881 if (DEBUG_PREFERRED || debug) { 3882 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3883 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3884 + "\n component=" + ppa.mComponent); 3885 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3886 } 3887 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3888 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3889 if (DEBUG_PREFERRED || debug) { 3890 Slog.v(TAG, "Found persistent preferred activity:"); 3891 if (ai != null) { 3892 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3893 } else { 3894 Slog.v(TAG, " null"); 3895 } 3896 } 3897 if (ai == null) { 3898 // This previously registered persistent preferred activity 3899 // component is no longer known. Ignore it and do NOT remove it. 3900 continue; 3901 } 3902 for (int j=0; j<N; j++) { 3903 final ResolveInfo ri = query.get(j); 3904 if (!ri.activityInfo.applicationInfo.packageName 3905 .equals(ai.applicationInfo.packageName)) { 3906 continue; 3907 } 3908 if (!ri.activityInfo.name.equals(ai.name)) { 3909 continue; 3910 } 3911 // Found a persistent preference that can handle the intent. 3912 if (DEBUG_PREFERRED || debug) { 3913 Slog.v(TAG, "Returning persistent preferred activity: " + 3914 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3915 } 3916 return ri; 3917 } 3918 } 3919 } 3920 return null; 3921 } 3922 3923 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3924 List<ResolveInfo> query, int priority, boolean always, 3925 boolean removeMatches, boolean debug, int userId) { 3926 if (!sUserManager.exists(userId)) return null; 3927 // writer 3928 synchronized (mPackages) { 3929 if (intent.getSelector() != null) { 3930 intent = intent.getSelector(); 3931 } 3932 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3933 3934 // Try to find a matching persistent preferred activity. 3935 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3936 debug, userId); 3937 3938 // If a persistent preferred activity matched, use it. 3939 if (pri != null) { 3940 return pri; 3941 } 3942 3943 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3944 // Get the list of preferred activities that handle the intent 3945 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3946 List<PreferredActivity> prefs = pir != null 3947 ? pir.queryIntent(intent, resolvedType, 3948 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3949 : null; 3950 if (prefs != null && prefs.size() > 0) { 3951 boolean changed = false; 3952 try { 3953 // First figure out how good the original match set is. 3954 // We will only allow preferred activities that came 3955 // from the same match quality. 3956 int match = 0; 3957 3958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3959 3960 final int N = query.size(); 3961 for (int j=0; j<N; j++) { 3962 final ResolveInfo ri = query.get(j); 3963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3964 + ": 0x" + Integer.toHexString(match)); 3965 if (ri.match > match) { 3966 match = ri.match; 3967 } 3968 } 3969 3970 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3971 + Integer.toHexString(match)); 3972 3973 match &= IntentFilter.MATCH_CATEGORY_MASK; 3974 final int M = prefs.size(); 3975 for (int i=0; i<M; i++) { 3976 final PreferredActivity pa = prefs.get(i); 3977 if (DEBUG_PREFERRED || debug) { 3978 Slog.v(TAG, "Checking PreferredActivity ds=" 3979 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3980 + "\n component=" + pa.mPref.mComponent); 3981 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3982 } 3983 if (pa.mPref.mMatch != match) { 3984 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3985 + Integer.toHexString(pa.mPref.mMatch)); 3986 continue; 3987 } 3988 // If it's not an "always" type preferred activity and that's what we're 3989 // looking for, skip it. 3990 if (always && !pa.mPref.mAlways) { 3991 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3992 continue; 3993 } 3994 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3995 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3996 if (DEBUG_PREFERRED || debug) { 3997 Slog.v(TAG, "Found preferred activity:"); 3998 if (ai != null) { 3999 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4000 } else { 4001 Slog.v(TAG, " null"); 4002 } 4003 } 4004 if (ai == null) { 4005 // This previously registered preferred activity 4006 // component is no longer known. Most likely an update 4007 // to the app was installed and in the new version this 4008 // component no longer exists. Clean it up by removing 4009 // it from the preferred activities list, and skip it. 4010 Slog.w(TAG, "Removing dangling preferred activity: " 4011 + pa.mPref.mComponent); 4012 pir.removeFilter(pa); 4013 changed = true; 4014 continue; 4015 } 4016 for (int j=0; j<N; j++) { 4017 final ResolveInfo ri = query.get(j); 4018 if (!ri.activityInfo.applicationInfo.packageName 4019 .equals(ai.applicationInfo.packageName)) { 4020 continue; 4021 } 4022 if (!ri.activityInfo.name.equals(ai.name)) { 4023 continue; 4024 } 4025 4026 if (removeMatches) { 4027 pir.removeFilter(pa); 4028 changed = true; 4029 if (DEBUG_PREFERRED) { 4030 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4031 } 4032 break; 4033 } 4034 4035 // Okay we found a previously set preferred or last chosen app. 4036 // If the result set is different from when this 4037 // was created, we need to clear it and re-ask the 4038 // user their preference, if we're looking for an "always" type entry. 4039 if (always && !pa.mPref.sameSet(query)) { 4040 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4041 + intent + " type " + resolvedType); 4042 if (DEBUG_PREFERRED) { 4043 Slog.v(TAG, "Removing preferred activity since set changed " 4044 + pa.mPref.mComponent); 4045 } 4046 pir.removeFilter(pa); 4047 // Re-add the filter as a "last chosen" entry (!always) 4048 PreferredActivity lastChosen = new PreferredActivity( 4049 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4050 pir.addFilter(lastChosen); 4051 changed = true; 4052 return null; 4053 } 4054 4055 // Yay! Either the set matched or we're looking for the last chosen 4056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4057 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4058 return ri; 4059 } 4060 } 4061 } finally { 4062 if (changed) { 4063 if (DEBUG_PREFERRED) { 4064 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4065 } 4066 scheduleWritePackageRestrictionsLocked(userId); 4067 } 4068 } 4069 } 4070 } 4071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4072 return null; 4073 } 4074 4075 /* 4076 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4077 */ 4078 @Override 4079 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4080 int targetUserId) { 4081 mContext.enforceCallingOrSelfPermission( 4082 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4083 List<CrossProfileIntentFilter> matches = 4084 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4085 if (matches != null) { 4086 int size = matches.size(); 4087 for (int i = 0; i < size; i++) { 4088 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4089 } 4090 } 4091 return false; 4092 } 4093 4094 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4095 String resolvedType, int userId) { 4096 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4097 if (resolver != null) { 4098 return resolver.queryIntent(intent, resolvedType, false, userId); 4099 } 4100 return null; 4101 } 4102 4103 @Override 4104 public List<ResolveInfo> queryIntentActivities(Intent intent, 4105 String resolvedType, int flags, int userId) { 4106 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4107 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4108 ComponentName comp = intent.getComponent(); 4109 if (comp == null) { 4110 if (intent.getSelector() != null) { 4111 intent = intent.getSelector(); 4112 comp = intent.getComponent(); 4113 } 4114 } 4115 4116 if (comp != null) { 4117 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4118 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4119 if (ai != null) { 4120 final ResolveInfo ri = new ResolveInfo(); 4121 ri.activityInfo = ai; 4122 list.add(ri); 4123 } 4124 return list; 4125 } 4126 4127 // reader 4128 synchronized (mPackages) { 4129 final String pkgName = intent.getPackage(); 4130 if (pkgName == null) { 4131 List<CrossProfileIntentFilter> matchingFilters = 4132 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4133 // Check for results that need to skip the current profile. 4134 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4135 resolvedType, flags, userId); 4136 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4137 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4138 result.add(resolveInfo); 4139 return filterIfNotPrimaryUser(result, userId); 4140 } 4141 4142 // Check for results in the current profile. 4143 List<ResolveInfo> result = mActivities.queryIntent( 4144 intent, resolvedType, flags, userId); 4145 4146 // Check for cross profile results. 4147 resolveInfo = queryCrossProfileIntents( 4148 matchingFilters, intent, resolvedType, flags, userId); 4149 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4150 result.add(resolveInfo); 4151 Collections.sort(result, mResolvePrioritySorter); 4152 } 4153 result = filterIfNotPrimaryUser(result, userId); 4154 if (result.size() > 1 && hasWebURI(intent)) { 4155 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4156 } 4157 return result; 4158 } 4159 final PackageParser.Package pkg = mPackages.get(pkgName); 4160 if (pkg != null) { 4161 return filterIfNotPrimaryUser( 4162 mActivities.queryIntentForPackage( 4163 intent, resolvedType, flags, pkg.activities, userId), 4164 userId); 4165 } 4166 return new ArrayList<ResolveInfo>(); 4167 } 4168 } 4169 4170 private boolean isUserEnabled(int userId) { 4171 long callingId = Binder.clearCallingIdentity(); 4172 try { 4173 UserInfo userInfo = sUserManager.getUserInfo(userId); 4174 return userInfo != null && userInfo.isEnabled(); 4175 } finally { 4176 Binder.restoreCallingIdentity(callingId); 4177 } 4178 } 4179 4180 /** 4181 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4182 * 4183 * @return filtered list 4184 */ 4185 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4186 if (userId == UserHandle.USER_OWNER) { 4187 return resolveInfos; 4188 } 4189 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4190 ResolveInfo info = resolveInfos.get(i); 4191 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4192 resolveInfos.remove(i); 4193 } 4194 } 4195 return resolveInfos; 4196 } 4197 4198 private static boolean hasWebURI(Intent intent) { 4199 if (intent.getData() == null) { 4200 return false; 4201 } 4202 final String scheme = intent.getScheme(); 4203 if (TextUtils.isEmpty(scheme)) { 4204 return false; 4205 } 4206 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4207 } 4208 4209 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4210 int flags, List<ResolveInfo> candidates) { 4211 if (DEBUG_PREFERRED) { 4212 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4213 candidates.size()); 4214 } 4215 4216 final int userId = UserHandle.getCallingUserId(); 4217 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4218 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4219 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4220 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4221 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4222 4223 synchronized (mPackages) { 4224 final int count = candidates.size(); 4225 // First, try to use the domain prefered App. Partition the candidates into four lists: 4226 // one for the final results, one for the "do not use ever", one for "undefined status" 4227 // and finally one for "Browser App type". 4228 for (int n=0; n<count; n++) { 4229 ResolveInfo info = candidates.get(n); 4230 String packageName = info.activityInfo.packageName; 4231 PackageSetting ps = mSettings.mPackages.get(packageName); 4232 if (ps != null) { 4233 // Add to the special match all list (Browser use case) 4234 if (info.handleAllWebDataURI) { 4235 matchAllList.add(info); 4236 continue; 4237 } 4238 // Try to get the status from User settings first 4239 int status = getDomainVerificationStatusLPr(ps, userId); 4240 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4241 alwaysList.add(info); 4242 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4243 neverList.add(info); 4244 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4245 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4246 undefinedList.add(info); 4247 } 4248 } 4249 } 4250 // First try to add the "always" if there is any 4251 if (alwaysList.size() > 0) { 4252 result.addAll(alwaysList); 4253 } else { 4254 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4255 result.addAll(undefinedList); 4256 // Also add Browsers (all of them or only the default one) 4257 if ((flags & MATCH_ALL) != 0) { 4258 result.addAll(matchAllList); 4259 } else { 4260 // Try to add the Default Browser if we can 4261 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4262 UserHandle.myUserId()); 4263 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4264 boolean defaultBrowserFound = false; 4265 final int browserCount = matchAllList.size(); 4266 for (int n=0; n<browserCount; n++) { 4267 ResolveInfo browser = matchAllList.get(n); 4268 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4269 result.add(browser); 4270 defaultBrowserFound = true; 4271 break; 4272 } 4273 } 4274 if (!defaultBrowserFound) { 4275 result.addAll(matchAllList); 4276 } 4277 } else { 4278 result.addAll(matchAllList); 4279 } 4280 } 4281 4282 // If there is nothing selected, add all candidates and remove the ones that the User 4283 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4284 if (result.size() == 0) { 4285 result.addAll(candidates); 4286 result.removeAll(neverList); 4287 } 4288 } 4289 } 4290 if (DEBUG_PREFERRED) { 4291 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4292 result.size()); 4293 } 4294 return result; 4295 } 4296 4297 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4298 int status = ps.getDomainVerificationStatusForUser(userId); 4299 // if none available, get the master status 4300 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4301 if (ps.getIntentFilterVerificationInfo() != null) { 4302 status = ps.getIntentFilterVerificationInfo().getStatus(); 4303 } 4304 } 4305 return status; 4306 } 4307 4308 private ResolveInfo querySkipCurrentProfileIntents( 4309 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4310 int flags, int sourceUserId) { 4311 if (matchingFilters != null) { 4312 int size = matchingFilters.size(); 4313 for (int i = 0; i < size; i ++) { 4314 CrossProfileIntentFilter filter = matchingFilters.get(i); 4315 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4316 // Checking if there are activities in the target user that can handle the 4317 // intent. 4318 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4319 flags, sourceUserId); 4320 if (resolveInfo != null) { 4321 return resolveInfo; 4322 } 4323 } 4324 } 4325 } 4326 return null; 4327 } 4328 4329 // Return matching ResolveInfo if any for skip current profile intent filters. 4330 private ResolveInfo queryCrossProfileIntents( 4331 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4332 int flags, int sourceUserId) { 4333 if (matchingFilters != null) { 4334 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4335 // match the same intent. For performance reasons, it is better not to 4336 // run queryIntent twice for the same userId 4337 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4338 int size = matchingFilters.size(); 4339 for (int i = 0; i < size; i++) { 4340 CrossProfileIntentFilter filter = matchingFilters.get(i); 4341 int targetUserId = filter.getTargetUserId(); 4342 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4343 && !alreadyTriedUserIds.get(targetUserId)) { 4344 // Checking if there are activities in the target user that can handle the 4345 // intent. 4346 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4347 flags, sourceUserId); 4348 if (resolveInfo != null) return resolveInfo; 4349 alreadyTriedUserIds.put(targetUserId, true); 4350 } 4351 } 4352 } 4353 return null; 4354 } 4355 4356 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4357 String resolvedType, int flags, int sourceUserId) { 4358 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4359 resolvedType, flags, filter.getTargetUserId()); 4360 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4361 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4362 } 4363 return null; 4364 } 4365 4366 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4367 int sourceUserId, int targetUserId) { 4368 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4369 String className; 4370 if (targetUserId == UserHandle.USER_OWNER) { 4371 className = FORWARD_INTENT_TO_USER_OWNER; 4372 } else { 4373 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4374 } 4375 ComponentName forwardingActivityComponentName = new ComponentName( 4376 mAndroidApplication.packageName, className); 4377 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4378 sourceUserId); 4379 if (targetUserId == UserHandle.USER_OWNER) { 4380 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4381 forwardingResolveInfo.noResourceId = true; 4382 } 4383 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4384 forwardingResolveInfo.priority = 0; 4385 forwardingResolveInfo.preferredOrder = 0; 4386 forwardingResolveInfo.match = 0; 4387 forwardingResolveInfo.isDefault = true; 4388 forwardingResolveInfo.filter = filter; 4389 forwardingResolveInfo.targetUserId = targetUserId; 4390 return forwardingResolveInfo; 4391 } 4392 4393 @Override 4394 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4395 Intent[] specifics, String[] specificTypes, Intent intent, 4396 String resolvedType, int flags, int userId) { 4397 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4398 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4399 false, "query intent activity options"); 4400 final String resultsAction = intent.getAction(); 4401 4402 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4403 | PackageManager.GET_RESOLVED_FILTER, userId); 4404 4405 if (DEBUG_INTENT_MATCHING) { 4406 Log.v(TAG, "Query " + intent + ": " + results); 4407 } 4408 4409 int specificsPos = 0; 4410 int N; 4411 4412 // todo: note that the algorithm used here is O(N^2). This 4413 // isn't a problem in our current environment, but if we start running 4414 // into situations where we have more than 5 or 10 matches then this 4415 // should probably be changed to something smarter... 4416 4417 // First we go through and resolve each of the specific items 4418 // that were supplied, taking care of removing any corresponding 4419 // duplicate items in the generic resolve list. 4420 if (specifics != null) { 4421 for (int i=0; i<specifics.length; i++) { 4422 final Intent sintent = specifics[i]; 4423 if (sintent == null) { 4424 continue; 4425 } 4426 4427 if (DEBUG_INTENT_MATCHING) { 4428 Log.v(TAG, "Specific #" + i + ": " + sintent); 4429 } 4430 4431 String action = sintent.getAction(); 4432 if (resultsAction != null && resultsAction.equals(action)) { 4433 // If this action was explicitly requested, then don't 4434 // remove things that have it. 4435 action = null; 4436 } 4437 4438 ResolveInfo ri = null; 4439 ActivityInfo ai = null; 4440 4441 ComponentName comp = sintent.getComponent(); 4442 if (comp == null) { 4443 ri = resolveIntent( 4444 sintent, 4445 specificTypes != null ? specificTypes[i] : null, 4446 flags, userId); 4447 if (ri == null) { 4448 continue; 4449 } 4450 if (ri == mResolveInfo) { 4451 // ACK! Must do something better with this. 4452 } 4453 ai = ri.activityInfo; 4454 comp = new ComponentName(ai.applicationInfo.packageName, 4455 ai.name); 4456 } else { 4457 ai = getActivityInfo(comp, flags, userId); 4458 if (ai == null) { 4459 continue; 4460 } 4461 } 4462 4463 // Look for any generic query activities that are duplicates 4464 // of this specific one, and remove them from the results. 4465 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4466 N = results.size(); 4467 int j; 4468 for (j=specificsPos; j<N; j++) { 4469 ResolveInfo sri = results.get(j); 4470 if ((sri.activityInfo.name.equals(comp.getClassName()) 4471 && sri.activityInfo.applicationInfo.packageName.equals( 4472 comp.getPackageName())) 4473 || (action != null && sri.filter.matchAction(action))) { 4474 results.remove(j); 4475 if (DEBUG_INTENT_MATCHING) Log.v( 4476 TAG, "Removing duplicate item from " + j 4477 + " due to specific " + specificsPos); 4478 if (ri == null) { 4479 ri = sri; 4480 } 4481 j--; 4482 N--; 4483 } 4484 } 4485 4486 // Add this specific item to its proper place. 4487 if (ri == null) { 4488 ri = new ResolveInfo(); 4489 ri.activityInfo = ai; 4490 } 4491 results.add(specificsPos, ri); 4492 ri.specificIndex = i; 4493 specificsPos++; 4494 } 4495 } 4496 4497 // Now we go through the remaining generic results and remove any 4498 // duplicate actions that are found here. 4499 N = results.size(); 4500 for (int i=specificsPos; i<N-1; i++) { 4501 final ResolveInfo rii = results.get(i); 4502 if (rii.filter == null) { 4503 continue; 4504 } 4505 4506 // Iterate over all of the actions of this result's intent 4507 // filter... typically this should be just one. 4508 final Iterator<String> it = rii.filter.actionsIterator(); 4509 if (it == null) { 4510 continue; 4511 } 4512 while (it.hasNext()) { 4513 final String action = it.next(); 4514 if (resultsAction != null && resultsAction.equals(action)) { 4515 // If this action was explicitly requested, then don't 4516 // remove things that have it. 4517 continue; 4518 } 4519 for (int j=i+1; j<N; j++) { 4520 final ResolveInfo rij = results.get(j); 4521 if (rij.filter != null && rij.filter.hasAction(action)) { 4522 results.remove(j); 4523 if (DEBUG_INTENT_MATCHING) Log.v( 4524 TAG, "Removing duplicate item from " + j 4525 + " due to action " + action + " at " + i); 4526 j--; 4527 N--; 4528 } 4529 } 4530 } 4531 4532 // If the caller didn't request filter information, drop it now 4533 // so we don't have to marshall/unmarshall it. 4534 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4535 rii.filter = null; 4536 } 4537 } 4538 4539 // Filter out the caller activity if so requested. 4540 if (caller != null) { 4541 N = results.size(); 4542 for (int i=0; i<N; i++) { 4543 ActivityInfo ainfo = results.get(i).activityInfo; 4544 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4545 && caller.getClassName().equals(ainfo.name)) { 4546 results.remove(i); 4547 break; 4548 } 4549 } 4550 } 4551 4552 // If the caller didn't request filter information, 4553 // drop them now so we don't have to 4554 // marshall/unmarshall it. 4555 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4556 N = results.size(); 4557 for (int i=0; i<N; i++) { 4558 results.get(i).filter = null; 4559 } 4560 } 4561 4562 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4563 return results; 4564 } 4565 4566 @Override 4567 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4568 int userId) { 4569 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4570 ComponentName comp = intent.getComponent(); 4571 if (comp == null) { 4572 if (intent.getSelector() != null) { 4573 intent = intent.getSelector(); 4574 comp = intent.getComponent(); 4575 } 4576 } 4577 if (comp != null) { 4578 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4579 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4580 if (ai != null) { 4581 ResolveInfo ri = new ResolveInfo(); 4582 ri.activityInfo = ai; 4583 list.add(ri); 4584 } 4585 return list; 4586 } 4587 4588 // reader 4589 synchronized (mPackages) { 4590 String pkgName = intent.getPackage(); 4591 if (pkgName == null) { 4592 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4593 } 4594 final PackageParser.Package pkg = mPackages.get(pkgName); 4595 if (pkg != null) { 4596 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4597 userId); 4598 } 4599 return null; 4600 } 4601 } 4602 4603 @Override 4604 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4605 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4606 if (!sUserManager.exists(userId)) return null; 4607 if (query != null) { 4608 if (query.size() >= 1) { 4609 // If there is more than one service with the same priority, 4610 // just arbitrarily pick the first one. 4611 return query.get(0); 4612 } 4613 } 4614 return null; 4615 } 4616 4617 @Override 4618 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4619 int userId) { 4620 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4621 ComponentName comp = intent.getComponent(); 4622 if (comp == null) { 4623 if (intent.getSelector() != null) { 4624 intent = intent.getSelector(); 4625 comp = intent.getComponent(); 4626 } 4627 } 4628 if (comp != null) { 4629 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4630 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4631 if (si != null) { 4632 final ResolveInfo ri = new ResolveInfo(); 4633 ri.serviceInfo = si; 4634 list.add(ri); 4635 } 4636 return list; 4637 } 4638 4639 // reader 4640 synchronized (mPackages) { 4641 String pkgName = intent.getPackage(); 4642 if (pkgName == null) { 4643 return mServices.queryIntent(intent, resolvedType, flags, userId); 4644 } 4645 final PackageParser.Package pkg = mPackages.get(pkgName); 4646 if (pkg != null) { 4647 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4648 userId); 4649 } 4650 return null; 4651 } 4652 } 4653 4654 @Override 4655 public List<ResolveInfo> queryIntentContentProviders( 4656 Intent intent, String resolvedType, int flags, int userId) { 4657 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4658 ComponentName comp = intent.getComponent(); 4659 if (comp == null) { 4660 if (intent.getSelector() != null) { 4661 intent = intent.getSelector(); 4662 comp = intent.getComponent(); 4663 } 4664 } 4665 if (comp != null) { 4666 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4667 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4668 if (pi != null) { 4669 final ResolveInfo ri = new ResolveInfo(); 4670 ri.providerInfo = pi; 4671 list.add(ri); 4672 } 4673 return list; 4674 } 4675 4676 // reader 4677 synchronized (mPackages) { 4678 String pkgName = intent.getPackage(); 4679 if (pkgName == null) { 4680 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4681 } 4682 final PackageParser.Package pkg = mPackages.get(pkgName); 4683 if (pkg != null) { 4684 return mProviders.queryIntentForPackage( 4685 intent, resolvedType, flags, pkg.providers, userId); 4686 } 4687 return null; 4688 } 4689 } 4690 4691 @Override 4692 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4693 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4694 4695 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4696 4697 // writer 4698 synchronized (mPackages) { 4699 ArrayList<PackageInfo> list; 4700 if (listUninstalled) { 4701 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4702 for (PackageSetting ps : mSettings.mPackages.values()) { 4703 PackageInfo pi; 4704 if (ps.pkg != null) { 4705 pi = generatePackageInfo(ps.pkg, flags, userId); 4706 } else { 4707 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4708 } 4709 if (pi != null) { 4710 list.add(pi); 4711 } 4712 } 4713 } else { 4714 list = new ArrayList<PackageInfo>(mPackages.size()); 4715 for (PackageParser.Package p : mPackages.values()) { 4716 PackageInfo pi = generatePackageInfo(p, flags, userId); 4717 if (pi != null) { 4718 list.add(pi); 4719 } 4720 } 4721 } 4722 4723 return new ParceledListSlice<PackageInfo>(list); 4724 } 4725 } 4726 4727 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4728 String[] permissions, boolean[] tmp, int flags, int userId) { 4729 int numMatch = 0; 4730 final PermissionsState permissionsState = ps.getPermissionsState(); 4731 for (int i=0; i<permissions.length; i++) { 4732 final String permission = permissions[i]; 4733 if (permissionsState.hasPermission(permission, userId)) { 4734 tmp[i] = true; 4735 numMatch++; 4736 } else { 4737 tmp[i] = false; 4738 } 4739 } 4740 if (numMatch == 0) { 4741 return; 4742 } 4743 PackageInfo pi; 4744 if (ps.pkg != null) { 4745 pi = generatePackageInfo(ps.pkg, flags, userId); 4746 } else { 4747 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4748 } 4749 // The above might return null in cases of uninstalled apps or install-state 4750 // skew across users/profiles. 4751 if (pi != null) { 4752 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4753 if (numMatch == permissions.length) { 4754 pi.requestedPermissions = permissions; 4755 } else { 4756 pi.requestedPermissions = new String[numMatch]; 4757 numMatch = 0; 4758 for (int i=0; i<permissions.length; i++) { 4759 if (tmp[i]) { 4760 pi.requestedPermissions[numMatch] = permissions[i]; 4761 numMatch++; 4762 } 4763 } 4764 } 4765 } 4766 list.add(pi); 4767 } 4768 } 4769 4770 @Override 4771 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4772 String[] permissions, int flags, int userId) { 4773 if (!sUserManager.exists(userId)) return null; 4774 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4775 4776 // writer 4777 synchronized (mPackages) { 4778 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4779 boolean[] tmpBools = new boolean[permissions.length]; 4780 if (listUninstalled) { 4781 for (PackageSetting ps : mSettings.mPackages.values()) { 4782 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4783 } 4784 } else { 4785 for (PackageParser.Package pkg : mPackages.values()) { 4786 PackageSetting ps = (PackageSetting)pkg.mExtras; 4787 if (ps != null) { 4788 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4789 userId); 4790 } 4791 } 4792 } 4793 4794 return new ParceledListSlice<PackageInfo>(list); 4795 } 4796 } 4797 4798 @Override 4799 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4800 if (!sUserManager.exists(userId)) return null; 4801 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4802 4803 // writer 4804 synchronized (mPackages) { 4805 ArrayList<ApplicationInfo> list; 4806 if (listUninstalled) { 4807 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4808 for (PackageSetting ps : mSettings.mPackages.values()) { 4809 ApplicationInfo ai; 4810 if (ps.pkg != null) { 4811 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4812 ps.readUserState(userId), userId); 4813 } else { 4814 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4815 } 4816 if (ai != null) { 4817 list.add(ai); 4818 } 4819 } 4820 } else { 4821 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4822 for (PackageParser.Package p : mPackages.values()) { 4823 if (p.mExtras != null) { 4824 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4825 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4826 if (ai != null) { 4827 list.add(ai); 4828 } 4829 } 4830 } 4831 } 4832 4833 return new ParceledListSlice<ApplicationInfo>(list); 4834 } 4835 } 4836 4837 public List<ApplicationInfo> getPersistentApplications(int flags) { 4838 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4839 4840 // reader 4841 synchronized (mPackages) { 4842 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4843 final int userId = UserHandle.getCallingUserId(); 4844 while (i.hasNext()) { 4845 final PackageParser.Package p = i.next(); 4846 if (p.applicationInfo != null 4847 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4848 && (!mSafeMode || isSystemApp(p))) { 4849 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4850 if (ps != null) { 4851 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4852 ps.readUserState(userId), userId); 4853 if (ai != null) { 4854 finalList.add(ai); 4855 } 4856 } 4857 } 4858 } 4859 } 4860 4861 return finalList; 4862 } 4863 4864 @Override 4865 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4866 if (!sUserManager.exists(userId)) return null; 4867 // reader 4868 synchronized (mPackages) { 4869 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4870 PackageSetting ps = provider != null 4871 ? mSettings.mPackages.get(provider.owner.packageName) 4872 : null; 4873 return ps != null 4874 && mSettings.isEnabledLPr(provider.info, flags, userId) 4875 && (!mSafeMode || (provider.info.applicationInfo.flags 4876 &ApplicationInfo.FLAG_SYSTEM) != 0) 4877 ? PackageParser.generateProviderInfo(provider, flags, 4878 ps.readUserState(userId), userId) 4879 : null; 4880 } 4881 } 4882 4883 /** 4884 * @deprecated 4885 */ 4886 @Deprecated 4887 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4888 // reader 4889 synchronized (mPackages) { 4890 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4891 .entrySet().iterator(); 4892 final int userId = UserHandle.getCallingUserId(); 4893 while (i.hasNext()) { 4894 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4895 PackageParser.Provider p = entry.getValue(); 4896 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4897 4898 if (ps != null && p.syncable 4899 && (!mSafeMode || (p.info.applicationInfo.flags 4900 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4901 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4902 ps.readUserState(userId), userId); 4903 if (info != null) { 4904 outNames.add(entry.getKey()); 4905 outInfo.add(info); 4906 } 4907 } 4908 } 4909 } 4910 } 4911 4912 @Override 4913 public List<ProviderInfo> queryContentProviders(String processName, 4914 int uid, int flags) { 4915 ArrayList<ProviderInfo> finalList = null; 4916 // reader 4917 synchronized (mPackages) { 4918 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4919 final int userId = processName != null ? 4920 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4921 while (i.hasNext()) { 4922 final PackageParser.Provider p = i.next(); 4923 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4924 if (ps != null && p.info.authority != null 4925 && (processName == null 4926 || (p.info.processName.equals(processName) 4927 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4928 && mSettings.isEnabledLPr(p.info, flags, userId) 4929 && (!mSafeMode 4930 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4931 if (finalList == null) { 4932 finalList = new ArrayList<ProviderInfo>(3); 4933 } 4934 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4935 ps.readUserState(userId), userId); 4936 if (info != null) { 4937 finalList.add(info); 4938 } 4939 } 4940 } 4941 } 4942 4943 if (finalList != null) { 4944 Collections.sort(finalList, mProviderInitOrderSorter); 4945 } 4946 4947 return finalList; 4948 } 4949 4950 @Override 4951 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4952 int flags) { 4953 // reader 4954 synchronized (mPackages) { 4955 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4956 return PackageParser.generateInstrumentationInfo(i, flags); 4957 } 4958 } 4959 4960 @Override 4961 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4962 int flags) { 4963 ArrayList<InstrumentationInfo> finalList = 4964 new ArrayList<InstrumentationInfo>(); 4965 4966 // reader 4967 synchronized (mPackages) { 4968 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4969 while (i.hasNext()) { 4970 final PackageParser.Instrumentation p = i.next(); 4971 if (targetPackage == null 4972 || targetPackage.equals(p.info.targetPackage)) { 4973 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4974 flags); 4975 if (ii != null) { 4976 finalList.add(ii); 4977 } 4978 } 4979 } 4980 } 4981 4982 return finalList; 4983 } 4984 4985 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4986 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4987 if (overlays == null) { 4988 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4989 return; 4990 } 4991 for (PackageParser.Package opkg : overlays.values()) { 4992 // Not much to do if idmap fails: we already logged the error 4993 // and we certainly don't want to abort installation of pkg simply 4994 // because an overlay didn't fit properly. For these reasons, 4995 // ignore the return value of createIdmapForPackagePairLI. 4996 createIdmapForPackagePairLI(pkg, opkg); 4997 } 4998 } 4999 5000 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5001 PackageParser.Package opkg) { 5002 if (!opkg.mTrustedOverlay) { 5003 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5004 opkg.baseCodePath + ": overlay not trusted"); 5005 return false; 5006 } 5007 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5008 if (overlaySet == null) { 5009 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5010 opkg.baseCodePath + " but target package has no known overlays"); 5011 return false; 5012 } 5013 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5014 // TODO: generate idmap for split APKs 5015 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5016 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5017 + opkg.baseCodePath); 5018 return false; 5019 } 5020 PackageParser.Package[] overlayArray = 5021 overlaySet.values().toArray(new PackageParser.Package[0]); 5022 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5023 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5024 return p1.mOverlayPriority - p2.mOverlayPriority; 5025 } 5026 }; 5027 Arrays.sort(overlayArray, cmp); 5028 5029 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5030 int i = 0; 5031 for (PackageParser.Package p : overlayArray) { 5032 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5033 } 5034 return true; 5035 } 5036 5037 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5038 final File[] files = dir.listFiles(); 5039 if (ArrayUtils.isEmpty(files)) { 5040 Log.d(TAG, "No files in app dir " + dir); 5041 return; 5042 } 5043 5044 if (DEBUG_PACKAGE_SCANNING) { 5045 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5046 + " flags=0x" + Integer.toHexString(parseFlags)); 5047 } 5048 5049 for (File file : files) { 5050 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5051 && !PackageInstallerService.isStageName(file.getName()); 5052 if (!isPackage) { 5053 // Ignore entries which are not packages 5054 continue; 5055 } 5056 try { 5057 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5058 scanFlags, currentTime, null); 5059 } catch (PackageManagerException e) { 5060 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5061 5062 // Delete invalid userdata apps 5063 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5064 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5065 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5066 if (file.isDirectory()) { 5067 mInstaller.rmPackageDir(file.getAbsolutePath()); 5068 } else { 5069 file.delete(); 5070 } 5071 } 5072 } 5073 } 5074 } 5075 5076 private static File getSettingsProblemFile() { 5077 File dataDir = Environment.getDataDirectory(); 5078 File systemDir = new File(dataDir, "system"); 5079 File fname = new File(systemDir, "uiderrors.txt"); 5080 return fname; 5081 } 5082 5083 static void reportSettingsProblem(int priority, String msg) { 5084 logCriticalInfo(priority, msg); 5085 } 5086 5087 static void logCriticalInfo(int priority, String msg) { 5088 Slog.println(priority, TAG, msg); 5089 EventLogTags.writePmCriticalInfo(msg); 5090 try { 5091 File fname = getSettingsProblemFile(); 5092 FileOutputStream out = new FileOutputStream(fname, true); 5093 PrintWriter pw = new FastPrintWriter(out); 5094 SimpleDateFormat formatter = new SimpleDateFormat(); 5095 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5096 pw.println(dateString + ": " + msg); 5097 pw.close(); 5098 FileUtils.setPermissions( 5099 fname.toString(), 5100 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5101 -1, -1); 5102 } catch (java.io.IOException e) { 5103 } 5104 } 5105 5106 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5107 PackageParser.Package pkg, File srcFile, int parseFlags) 5108 throws PackageManagerException { 5109 if (ps != null 5110 && ps.codePath.equals(srcFile) 5111 && ps.timeStamp == srcFile.lastModified() 5112 && !isCompatSignatureUpdateNeeded(pkg) 5113 && !isRecoverSignatureUpdateNeeded(pkg)) { 5114 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5116 ArraySet<PublicKey> signingKs; 5117 synchronized (mPackages) { 5118 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5119 } 5120 if (ps.signatures.mSignatures != null 5121 && ps.signatures.mSignatures.length != 0 5122 && signingKs != null) { 5123 // Optimization: reuse the existing cached certificates 5124 // if the package appears to be unchanged. 5125 pkg.mSignatures = ps.signatures.mSignatures; 5126 pkg.mSigningKeys = signingKs; 5127 return; 5128 } 5129 5130 Slog.w(TAG, "PackageSetting for " + ps.name 5131 + " is missing signatures. Collecting certs again to recover them."); 5132 } else { 5133 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5134 } 5135 5136 try { 5137 pp.collectCertificates(pkg, parseFlags); 5138 pp.collectManifestDigest(pkg); 5139 } catch (PackageParserException e) { 5140 throw PackageManagerException.from(e); 5141 } 5142 } 5143 5144 /* 5145 * Scan a package and return the newly parsed package. 5146 * Returns null in case of errors and the error code is stored in mLastScanError 5147 */ 5148 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5149 long currentTime, UserHandle user) throws PackageManagerException { 5150 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5151 parseFlags |= mDefParseFlags; 5152 PackageParser pp = new PackageParser(); 5153 pp.setSeparateProcesses(mSeparateProcesses); 5154 pp.setOnlyCoreApps(mOnlyCore); 5155 pp.setDisplayMetrics(mMetrics); 5156 5157 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5158 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5159 } 5160 5161 final PackageParser.Package pkg; 5162 try { 5163 pkg = pp.parsePackage(scanFile, parseFlags); 5164 } catch (PackageParserException e) { 5165 throw PackageManagerException.from(e); 5166 } 5167 5168 PackageSetting ps = null; 5169 PackageSetting updatedPkg; 5170 // reader 5171 synchronized (mPackages) { 5172 // Look to see if we already know about this package. 5173 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5174 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5175 // This package has been renamed to its original name. Let's 5176 // use that. 5177 ps = mSettings.peekPackageLPr(oldName); 5178 } 5179 // If there was no original package, see one for the real package name. 5180 if (ps == null) { 5181 ps = mSettings.peekPackageLPr(pkg.packageName); 5182 } 5183 // Check to see if this package could be hiding/updating a system 5184 // package. Must look for it either under the original or real 5185 // package name depending on our state. 5186 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5187 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5188 } 5189 boolean updatedPkgBetter = false; 5190 // First check if this is a system package that may involve an update 5191 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5192 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5193 // it needs to drop FLAG_PRIVILEGED. 5194 if (locationIsPrivileged(scanFile)) { 5195 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5196 } else { 5197 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5198 } 5199 5200 if (ps != null && !ps.codePath.equals(scanFile)) { 5201 // The path has changed from what was last scanned... check the 5202 // version of the new path against what we have stored to determine 5203 // what to do. 5204 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5205 if (pkg.mVersionCode <= ps.versionCode) { 5206 // The system package has been updated and the code path does not match 5207 // Ignore entry. Skip it. 5208 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5209 + " ignored: updated version " + ps.versionCode 5210 + " better than this " + pkg.mVersionCode); 5211 if (!updatedPkg.codePath.equals(scanFile)) { 5212 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5213 + ps.name + " changing from " + updatedPkg.codePathString 5214 + " to " + scanFile); 5215 updatedPkg.codePath = scanFile; 5216 updatedPkg.codePathString = scanFile.toString(); 5217 updatedPkg.resourcePath = scanFile; 5218 updatedPkg.resourcePathString = scanFile.toString(); 5219 } 5220 updatedPkg.pkg = pkg; 5221 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5222 } else { 5223 // The current app on the system partition is better than 5224 // what we have updated to on the data partition; switch 5225 // back to the system partition version. 5226 // At this point, its safely assumed that package installation for 5227 // apps in system partition will go through. If not there won't be a working 5228 // version of the app 5229 // writer 5230 synchronized (mPackages) { 5231 // Just remove the loaded entries from package lists. 5232 mPackages.remove(ps.name); 5233 } 5234 5235 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5236 + " reverting from " + ps.codePathString 5237 + ": new version " + pkg.mVersionCode 5238 + " better than installed " + ps.versionCode); 5239 5240 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5241 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5242 synchronized (mInstallLock) { 5243 args.cleanUpResourcesLI(); 5244 } 5245 synchronized (mPackages) { 5246 mSettings.enableSystemPackageLPw(ps.name); 5247 } 5248 updatedPkgBetter = true; 5249 } 5250 } 5251 } 5252 5253 if (updatedPkg != null) { 5254 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5255 // initially 5256 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5257 5258 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5259 // flag set initially 5260 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5261 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5262 } 5263 } 5264 5265 // Verify certificates against what was last scanned 5266 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5267 5268 /* 5269 * A new system app appeared, but we already had a non-system one of the 5270 * same name installed earlier. 5271 */ 5272 boolean shouldHideSystemApp = false; 5273 if (updatedPkg == null && ps != null 5274 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5275 /* 5276 * Check to make sure the signatures match first. If they don't, 5277 * wipe the installed application and its data. 5278 */ 5279 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5280 != PackageManager.SIGNATURE_MATCH) { 5281 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5282 + " signatures don't match existing userdata copy; removing"); 5283 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5284 ps = null; 5285 } else { 5286 /* 5287 * If the newly-added system app is an older version than the 5288 * already installed version, hide it. It will be scanned later 5289 * and re-added like an update. 5290 */ 5291 if (pkg.mVersionCode <= ps.versionCode) { 5292 shouldHideSystemApp = true; 5293 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5294 + " but new version " + pkg.mVersionCode + " better than installed " 5295 + ps.versionCode + "; hiding system"); 5296 } else { 5297 /* 5298 * The newly found system app is a newer version that the 5299 * one previously installed. Simply remove the 5300 * already-installed application and replace it with our own 5301 * while keeping the application data. 5302 */ 5303 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5304 + " reverting from " + ps.codePathString + ": new version " 5305 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5306 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5307 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5308 synchronized (mInstallLock) { 5309 args.cleanUpResourcesLI(); 5310 } 5311 } 5312 } 5313 } 5314 5315 // The apk is forward locked (not public) if its code and resources 5316 // are kept in different files. (except for app in either system or 5317 // vendor path). 5318 // TODO grab this value from PackageSettings 5319 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5320 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5321 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5322 } 5323 } 5324 5325 // TODO: extend to support forward-locked splits 5326 String resourcePath = null; 5327 String baseResourcePath = null; 5328 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5329 if (ps != null && ps.resourcePathString != null) { 5330 resourcePath = ps.resourcePathString; 5331 baseResourcePath = ps.resourcePathString; 5332 } else { 5333 // Should not happen at all. Just log an error. 5334 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5335 } 5336 } else { 5337 resourcePath = pkg.codePath; 5338 baseResourcePath = pkg.baseCodePath; 5339 } 5340 5341 // Set application objects path explicitly. 5342 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5343 pkg.applicationInfo.setCodePath(pkg.codePath); 5344 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5345 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5346 pkg.applicationInfo.setResourcePath(resourcePath); 5347 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5348 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5349 5350 // Note that we invoke the following method only if we are about to unpack an application 5351 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5352 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5353 5354 /* 5355 * If the system app should be overridden by a previously installed 5356 * data, hide the system app now and let the /data/app scan pick it up 5357 * again. 5358 */ 5359 if (shouldHideSystemApp) { 5360 synchronized (mPackages) { 5361 /* 5362 * We have to grant systems permissions before we hide, because 5363 * grantPermissions will assume the package update is trying to 5364 * expand its permissions. 5365 */ 5366 grantPermissionsLPw(pkg, true, pkg.packageName); 5367 mSettings.disableSystemPackageLPw(pkg.packageName); 5368 } 5369 } 5370 5371 return scannedPkg; 5372 } 5373 5374 private static String fixProcessName(String defProcessName, 5375 String processName, int uid) { 5376 if (processName == null) { 5377 return defProcessName; 5378 } 5379 return processName; 5380 } 5381 5382 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5383 throws PackageManagerException { 5384 if (pkgSetting.signatures.mSignatures != null) { 5385 // Already existing package. Make sure signatures match 5386 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5387 == PackageManager.SIGNATURE_MATCH; 5388 if (!match) { 5389 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5390 == PackageManager.SIGNATURE_MATCH; 5391 } 5392 if (!match) { 5393 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5394 == PackageManager.SIGNATURE_MATCH; 5395 } 5396 if (!match) { 5397 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5398 + pkg.packageName + " signatures do not match the " 5399 + "previously installed version; ignoring!"); 5400 } 5401 } 5402 5403 // Check for shared user signatures 5404 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5405 // Already existing package. Make sure signatures match 5406 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5407 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5408 if (!match) { 5409 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5410 == PackageManager.SIGNATURE_MATCH; 5411 } 5412 if (!match) { 5413 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5414 == PackageManager.SIGNATURE_MATCH; 5415 } 5416 if (!match) { 5417 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5418 "Package " + pkg.packageName 5419 + " has no signatures that match those in shared user " 5420 + pkgSetting.sharedUser.name + "; ignoring!"); 5421 } 5422 } 5423 } 5424 5425 /** 5426 * Enforces that only the system UID or root's UID can call a method exposed 5427 * via Binder. 5428 * 5429 * @param message used as message if SecurityException is thrown 5430 * @throws SecurityException if the caller is not system or root 5431 */ 5432 private static final void enforceSystemOrRoot(String message) { 5433 final int uid = Binder.getCallingUid(); 5434 if (uid != Process.SYSTEM_UID && uid != 0) { 5435 throw new SecurityException(message); 5436 } 5437 } 5438 5439 @Override 5440 public void performBootDexOpt() { 5441 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5442 5443 // Before everything else, see whether we need to fstrim. 5444 try { 5445 IMountService ms = PackageHelper.getMountService(); 5446 if (ms != null) { 5447 final boolean isUpgrade = isUpgrade(); 5448 boolean doTrim = isUpgrade; 5449 if (doTrim) { 5450 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5451 } else { 5452 final long interval = android.provider.Settings.Global.getLong( 5453 mContext.getContentResolver(), 5454 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5455 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5456 if (interval > 0) { 5457 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5458 if (timeSinceLast > interval) { 5459 doTrim = true; 5460 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5461 + "; running immediately"); 5462 } 5463 } 5464 } 5465 if (doTrim) { 5466 if (!isFirstBoot()) { 5467 try { 5468 ActivityManagerNative.getDefault().showBootMessage( 5469 mContext.getResources().getString( 5470 R.string.android_upgrading_fstrim), true); 5471 } catch (RemoteException e) { 5472 } 5473 } 5474 ms.runMaintenance(); 5475 } 5476 } else { 5477 Slog.e(TAG, "Mount service unavailable!"); 5478 } 5479 } catch (RemoteException e) { 5480 // Can't happen; MountService is local 5481 } 5482 5483 final ArraySet<PackageParser.Package> pkgs; 5484 synchronized (mPackages) { 5485 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5486 } 5487 5488 if (pkgs != null) { 5489 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5490 // in case the device runs out of space. 5491 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5492 // Give priority to core apps. 5493 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5494 PackageParser.Package pkg = it.next(); 5495 if (pkg.coreApp) { 5496 if (DEBUG_DEXOPT) { 5497 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5498 } 5499 sortedPkgs.add(pkg); 5500 it.remove(); 5501 } 5502 } 5503 // Give priority to system apps that listen for pre boot complete. 5504 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5505 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5506 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5507 PackageParser.Package pkg = it.next(); 5508 if (pkgNames.contains(pkg.packageName)) { 5509 if (DEBUG_DEXOPT) { 5510 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5511 } 5512 sortedPkgs.add(pkg); 5513 it.remove(); 5514 } 5515 } 5516 // Give priority to system apps. 5517 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5518 PackageParser.Package pkg = it.next(); 5519 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5520 if (DEBUG_DEXOPT) { 5521 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5522 } 5523 sortedPkgs.add(pkg); 5524 it.remove(); 5525 } 5526 } 5527 // Give priority to updated system apps. 5528 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5529 PackageParser.Package pkg = it.next(); 5530 if (pkg.isUpdatedSystemApp()) { 5531 if (DEBUG_DEXOPT) { 5532 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5533 } 5534 sortedPkgs.add(pkg); 5535 it.remove(); 5536 } 5537 } 5538 // Give priority to apps that listen for boot complete. 5539 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5540 pkgNames = getPackageNamesForIntent(intent); 5541 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5542 PackageParser.Package pkg = it.next(); 5543 if (pkgNames.contains(pkg.packageName)) { 5544 if (DEBUG_DEXOPT) { 5545 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5546 } 5547 sortedPkgs.add(pkg); 5548 it.remove(); 5549 } 5550 } 5551 // Filter out packages that aren't recently used. 5552 filterRecentlyUsedApps(pkgs); 5553 // Add all remaining apps. 5554 for (PackageParser.Package pkg : pkgs) { 5555 if (DEBUG_DEXOPT) { 5556 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5557 } 5558 sortedPkgs.add(pkg); 5559 } 5560 5561 // If we want to be lazy, filter everything that wasn't recently used. 5562 if (mLazyDexOpt) { 5563 filterRecentlyUsedApps(sortedPkgs); 5564 } 5565 5566 int i = 0; 5567 int total = sortedPkgs.size(); 5568 File dataDir = Environment.getDataDirectory(); 5569 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5570 if (lowThreshold == 0) { 5571 throw new IllegalStateException("Invalid low memory threshold"); 5572 } 5573 for (PackageParser.Package pkg : sortedPkgs) { 5574 long usableSpace = dataDir.getUsableSpace(); 5575 if (usableSpace < lowThreshold) { 5576 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5577 break; 5578 } 5579 performBootDexOpt(pkg, ++i, total); 5580 } 5581 } 5582 } 5583 5584 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5585 // Filter out packages that aren't recently used. 5586 // 5587 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5588 // should do a full dexopt. 5589 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5590 int total = pkgs.size(); 5591 int skipped = 0; 5592 long now = System.currentTimeMillis(); 5593 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5594 PackageParser.Package pkg = i.next(); 5595 long then = pkg.mLastPackageUsageTimeInMills; 5596 if (then + mDexOptLRUThresholdInMills < now) { 5597 if (DEBUG_DEXOPT) { 5598 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5599 ((then == 0) ? "never" : new Date(then))); 5600 } 5601 i.remove(); 5602 skipped++; 5603 } 5604 } 5605 if (DEBUG_DEXOPT) { 5606 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5607 } 5608 } 5609 } 5610 5611 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5612 List<ResolveInfo> ris = null; 5613 try { 5614 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5615 intent, null, 0, UserHandle.USER_OWNER); 5616 } catch (RemoteException e) { 5617 } 5618 ArraySet<String> pkgNames = new ArraySet<String>(); 5619 if (ris != null) { 5620 for (ResolveInfo ri : ris) { 5621 pkgNames.add(ri.activityInfo.packageName); 5622 } 5623 } 5624 return pkgNames; 5625 } 5626 5627 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5628 if (DEBUG_DEXOPT) { 5629 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5630 } 5631 if (!isFirstBoot()) { 5632 try { 5633 ActivityManagerNative.getDefault().showBootMessage( 5634 mContext.getResources().getString(R.string.android_upgrading_apk, 5635 curr, total), true); 5636 } catch (RemoteException e) { 5637 } 5638 } 5639 PackageParser.Package p = pkg; 5640 synchronized (mInstallLock) { 5641 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5642 false /* force dex */, false /* defer */, true /* include dependencies */); 5643 } 5644 } 5645 5646 @Override 5647 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5648 return performDexOpt(packageName, instructionSet, false); 5649 } 5650 5651 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5652 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5653 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5654 if (!dexopt && !updateUsage) { 5655 // We aren't going to dexopt or update usage, so bail early. 5656 return false; 5657 } 5658 PackageParser.Package p; 5659 final String targetInstructionSet; 5660 synchronized (mPackages) { 5661 p = mPackages.get(packageName); 5662 if (p == null) { 5663 return false; 5664 } 5665 if (updateUsage) { 5666 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5667 } 5668 mPackageUsage.write(false); 5669 if (!dexopt) { 5670 // We aren't going to dexopt, so bail early. 5671 return false; 5672 } 5673 5674 targetInstructionSet = instructionSet != null ? instructionSet : 5675 getPrimaryInstructionSet(p.applicationInfo); 5676 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5677 return false; 5678 } 5679 } 5680 5681 synchronized (mInstallLock) { 5682 final String[] instructionSets = new String[] { targetInstructionSet }; 5683 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5684 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5685 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5686 } 5687 } 5688 5689 public ArraySet<String> getPackagesThatNeedDexOpt() { 5690 ArraySet<String> pkgs = null; 5691 synchronized (mPackages) { 5692 for (PackageParser.Package p : mPackages.values()) { 5693 if (DEBUG_DEXOPT) { 5694 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5695 } 5696 if (!p.mDexOptPerformed.isEmpty()) { 5697 continue; 5698 } 5699 if (pkgs == null) { 5700 pkgs = new ArraySet<String>(); 5701 } 5702 pkgs.add(p.packageName); 5703 } 5704 } 5705 return pkgs; 5706 } 5707 5708 public void shutdown() { 5709 mPackageUsage.write(true); 5710 } 5711 5712 @Override 5713 public void forceDexOpt(String packageName) { 5714 enforceSystemOrRoot("forceDexOpt"); 5715 5716 PackageParser.Package pkg; 5717 synchronized (mPackages) { 5718 pkg = mPackages.get(packageName); 5719 if (pkg == null) { 5720 throw new IllegalArgumentException("Missing package: " + packageName); 5721 } 5722 } 5723 5724 synchronized (mInstallLock) { 5725 final String[] instructionSets = new String[] { 5726 getPrimaryInstructionSet(pkg.applicationInfo) }; 5727 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5728 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5729 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5730 throw new IllegalStateException("Failed to dexopt: " + res); 5731 } 5732 } 5733 } 5734 5735 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5736 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5737 Slog.w(TAG, "Unable to update from " + oldPkg.name 5738 + " to " + newPkg.packageName 5739 + ": old package not in system partition"); 5740 return false; 5741 } else if (mPackages.get(oldPkg.name) != null) { 5742 Slog.w(TAG, "Unable to update from " + oldPkg.name 5743 + " to " + newPkg.packageName 5744 + ": old package still exists"); 5745 return false; 5746 } 5747 return true; 5748 } 5749 5750 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5751 int[] users = sUserManager.getUserIds(); 5752 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5753 if (res < 0) { 5754 return res; 5755 } 5756 for (int user : users) { 5757 if (user != 0) { 5758 res = mInstaller.createUserData(volumeUuid, packageName, 5759 UserHandle.getUid(user, uid), user, seinfo); 5760 if (res < 0) { 5761 return res; 5762 } 5763 } 5764 } 5765 return res; 5766 } 5767 5768 private int removeDataDirsLI(String volumeUuid, String packageName) { 5769 int[] users = sUserManager.getUserIds(); 5770 int res = 0; 5771 for (int user : users) { 5772 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5773 if (resInner < 0) { 5774 res = resInner; 5775 } 5776 } 5777 5778 return res; 5779 } 5780 5781 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5782 int[] users = sUserManager.getUserIds(); 5783 int res = 0; 5784 for (int user : users) { 5785 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5786 if (resInner < 0) { 5787 res = resInner; 5788 } 5789 } 5790 return res; 5791 } 5792 5793 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5794 PackageParser.Package changingLib) { 5795 if (file.path != null) { 5796 usesLibraryFiles.add(file.path); 5797 return; 5798 } 5799 PackageParser.Package p = mPackages.get(file.apk); 5800 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5801 // If we are doing this while in the middle of updating a library apk, 5802 // then we need to make sure to use that new apk for determining the 5803 // dependencies here. (We haven't yet finished committing the new apk 5804 // to the package manager state.) 5805 if (p == null || p.packageName.equals(changingLib.packageName)) { 5806 p = changingLib; 5807 } 5808 } 5809 if (p != null) { 5810 usesLibraryFiles.addAll(p.getAllCodePaths()); 5811 } 5812 } 5813 5814 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5815 PackageParser.Package changingLib) throws PackageManagerException { 5816 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5817 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5818 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5819 for (int i=0; i<N; i++) { 5820 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5821 if (file == null) { 5822 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5823 "Package " + pkg.packageName + " requires unavailable shared library " 5824 + pkg.usesLibraries.get(i) + "; failing!"); 5825 } 5826 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5827 } 5828 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5829 for (int i=0; i<N; i++) { 5830 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5831 if (file == null) { 5832 Slog.w(TAG, "Package " + pkg.packageName 5833 + " desires unavailable shared library " 5834 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5835 } else { 5836 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5837 } 5838 } 5839 N = usesLibraryFiles.size(); 5840 if (N > 0) { 5841 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5842 } else { 5843 pkg.usesLibraryFiles = null; 5844 } 5845 } 5846 } 5847 5848 private static boolean hasString(List<String> list, List<String> which) { 5849 if (list == null) { 5850 return false; 5851 } 5852 for (int i=list.size()-1; i>=0; i--) { 5853 for (int j=which.size()-1; j>=0; j--) { 5854 if (which.get(j).equals(list.get(i))) { 5855 return true; 5856 } 5857 } 5858 } 5859 return false; 5860 } 5861 5862 private void updateAllSharedLibrariesLPw() { 5863 for (PackageParser.Package pkg : mPackages.values()) { 5864 try { 5865 updateSharedLibrariesLPw(pkg, null); 5866 } catch (PackageManagerException e) { 5867 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5868 } 5869 } 5870 } 5871 5872 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5873 PackageParser.Package changingPkg) { 5874 ArrayList<PackageParser.Package> res = null; 5875 for (PackageParser.Package pkg : mPackages.values()) { 5876 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5877 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5878 if (res == null) { 5879 res = new ArrayList<PackageParser.Package>(); 5880 } 5881 res.add(pkg); 5882 try { 5883 updateSharedLibrariesLPw(pkg, changingPkg); 5884 } catch (PackageManagerException e) { 5885 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5886 } 5887 } 5888 } 5889 return res; 5890 } 5891 5892 /** 5893 * Derive the value of the {@code cpuAbiOverride} based on the provided 5894 * value and an optional stored value from the package settings. 5895 */ 5896 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5897 String cpuAbiOverride = null; 5898 5899 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5900 cpuAbiOverride = null; 5901 } else if (abiOverride != null) { 5902 cpuAbiOverride = abiOverride; 5903 } else if (settings != null) { 5904 cpuAbiOverride = settings.cpuAbiOverrideString; 5905 } 5906 5907 return cpuAbiOverride; 5908 } 5909 5910 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5911 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5912 boolean success = false; 5913 try { 5914 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5915 currentTime, user); 5916 success = true; 5917 return res; 5918 } finally { 5919 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5920 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5921 } 5922 } 5923 } 5924 5925 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5926 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5927 final File scanFile = new File(pkg.codePath); 5928 if (pkg.applicationInfo.getCodePath() == null || 5929 pkg.applicationInfo.getResourcePath() == null) { 5930 // Bail out. The resource and code paths haven't been set. 5931 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5932 "Code and resource paths haven't been set correctly"); 5933 } 5934 5935 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5936 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5937 } else { 5938 // Only allow system apps to be flagged as core apps. 5939 pkg.coreApp = false; 5940 } 5941 5942 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5943 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5944 } 5945 5946 if (mCustomResolverComponentName != null && 5947 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5948 setUpCustomResolverActivity(pkg); 5949 } 5950 5951 if (pkg.packageName.equals("android")) { 5952 synchronized (mPackages) { 5953 if (mAndroidApplication != null) { 5954 Slog.w(TAG, "*************************************************"); 5955 Slog.w(TAG, "Core android package being redefined. Skipping."); 5956 Slog.w(TAG, " file=" + scanFile); 5957 Slog.w(TAG, "*************************************************"); 5958 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5959 "Core android package being redefined. Skipping."); 5960 } 5961 5962 // Set up information for our fall-back user intent resolution activity. 5963 mPlatformPackage = pkg; 5964 pkg.mVersionCode = mSdkVersion; 5965 mAndroidApplication = pkg.applicationInfo; 5966 5967 if (!mResolverReplaced) { 5968 mResolveActivity.applicationInfo = mAndroidApplication; 5969 mResolveActivity.name = ResolverActivity.class.getName(); 5970 mResolveActivity.packageName = mAndroidApplication.packageName; 5971 mResolveActivity.processName = "system:ui"; 5972 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5973 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5974 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5975 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5976 mResolveActivity.exported = true; 5977 mResolveActivity.enabled = true; 5978 mResolveInfo.activityInfo = mResolveActivity; 5979 mResolveInfo.priority = 0; 5980 mResolveInfo.preferredOrder = 0; 5981 mResolveInfo.match = 0; 5982 mResolveComponentName = new ComponentName( 5983 mAndroidApplication.packageName, mResolveActivity.name); 5984 } 5985 } 5986 } 5987 5988 if (DEBUG_PACKAGE_SCANNING) { 5989 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5990 Log.d(TAG, "Scanning package " + pkg.packageName); 5991 } 5992 5993 if (mPackages.containsKey(pkg.packageName) 5994 || mSharedLibraries.containsKey(pkg.packageName)) { 5995 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5996 "Application package " + pkg.packageName 5997 + " already installed. Skipping duplicate."); 5998 } 5999 6000 // If we're only installing presumed-existing packages, require that the 6001 // scanned APK is both already known and at the path previously established 6002 // for it. Previously unknown packages we pick up normally, but if we have an 6003 // a priori expectation about this package's install presence, enforce it. 6004 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6005 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6006 if (known != null) { 6007 if (DEBUG_PACKAGE_SCANNING) { 6008 Log.d(TAG, "Examining " + pkg.codePath 6009 + " and requiring known paths " + known.codePathString 6010 + " & " + known.resourcePathString); 6011 } 6012 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6013 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6014 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6015 "Application package " + pkg.packageName 6016 + " found at " + pkg.applicationInfo.getCodePath() 6017 + " but expected at " + known.codePathString + "; ignoring."); 6018 } 6019 } 6020 } 6021 6022 // Initialize package source and resource directories 6023 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6024 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6025 6026 SharedUserSetting suid = null; 6027 PackageSetting pkgSetting = null; 6028 6029 if (!isSystemApp(pkg)) { 6030 // Only system apps can use these features. 6031 pkg.mOriginalPackages = null; 6032 pkg.mRealPackage = null; 6033 pkg.mAdoptPermissions = null; 6034 } 6035 6036 // writer 6037 synchronized (mPackages) { 6038 if (pkg.mSharedUserId != null) { 6039 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6040 if (suid == null) { 6041 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6042 "Creating application package " + pkg.packageName 6043 + " for shared user failed"); 6044 } 6045 if (DEBUG_PACKAGE_SCANNING) { 6046 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6047 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6048 + "): packages=" + suid.packages); 6049 } 6050 } 6051 6052 // Check if we are renaming from an original package name. 6053 PackageSetting origPackage = null; 6054 String realName = null; 6055 if (pkg.mOriginalPackages != null) { 6056 // This package may need to be renamed to a previously 6057 // installed name. Let's check on that... 6058 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6059 if (pkg.mOriginalPackages.contains(renamed)) { 6060 // This package had originally been installed as the 6061 // original name, and we have already taken care of 6062 // transitioning to the new one. Just update the new 6063 // one to continue using the old name. 6064 realName = pkg.mRealPackage; 6065 if (!pkg.packageName.equals(renamed)) { 6066 // Callers into this function may have already taken 6067 // care of renaming the package; only do it here if 6068 // it is not already done. 6069 pkg.setPackageName(renamed); 6070 } 6071 6072 } else { 6073 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6074 if ((origPackage = mSettings.peekPackageLPr( 6075 pkg.mOriginalPackages.get(i))) != null) { 6076 // We do have the package already installed under its 6077 // original name... should we use it? 6078 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6079 // New package is not compatible with original. 6080 origPackage = null; 6081 continue; 6082 } else if (origPackage.sharedUser != null) { 6083 // Make sure uid is compatible between packages. 6084 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6085 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6086 + " to " + pkg.packageName + ": old uid " 6087 + origPackage.sharedUser.name 6088 + " differs from " + pkg.mSharedUserId); 6089 origPackage = null; 6090 continue; 6091 } 6092 } else { 6093 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6094 + pkg.packageName + " to old name " + origPackage.name); 6095 } 6096 break; 6097 } 6098 } 6099 } 6100 } 6101 6102 if (mTransferedPackages.contains(pkg.packageName)) { 6103 Slog.w(TAG, "Package " + pkg.packageName 6104 + " was transferred to another, but its .apk remains"); 6105 } 6106 6107 // Just create the setting, don't add it yet. For already existing packages 6108 // the PkgSetting exists already and doesn't have to be created. 6109 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6110 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6111 pkg.applicationInfo.primaryCpuAbi, 6112 pkg.applicationInfo.secondaryCpuAbi, 6113 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6114 user, false); 6115 if (pkgSetting == null) { 6116 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6117 "Creating application package " + pkg.packageName + " failed"); 6118 } 6119 6120 if (pkgSetting.origPackage != null) { 6121 // If we are first transitioning from an original package, 6122 // fix up the new package's name now. We need to do this after 6123 // looking up the package under its new name, so getPackageLP 6124 // can take care of fiddling things correctly. 6125 pkg.setPackageName(origPackage.name); 6126 6127 // File a report about this. 6128 String msg = "New package " + pkgSetting.realName 6129 + " renamed to replace old package " + pkgSetting.name; 6130 reportSettingsProblem(Log.WARN, msg); 6131 6132 // Make a note of it. 6133 mTransferedPackages.add(origPackage.name); 6134 6135 // No longer need to retain this. 6136 pkgSetting.origPackage = null; 6137 } 6138 6139 if (realName != null) { 6140 // Make a note of it. 6141 mTransferedPackages.add(pkg.packageName); 6142 } 6143 6144 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6145 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6146 } 6147 6148 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6149 // Check all shared libraries and map to their actual file path. 6150 // We only do this here for apps not on a system dir, because those 6151 // are the only ones that can fail an install due to this. We 6152 // will take care of the system apps by updating all of their 6153 // library paths after the scan is done. 6154 updateSharedLibrariesLPw(pkg, null); 6155 } 6156 6157 if (mFoundPolicyFile) { 6158 SELinuxMMAC.assignSeinfoValue(pkg); 6159 } 6160 6161 pkg.applicationInfo.uid = pkgSetting.appId; 6162 pkg.mExtras = pkgSetting; 6163 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6164 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6165 // We just determined the app is signed correctly, so bring 6166 // over the latest parsed certs. 6167 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6168 } else { 6169 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6170 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6171 "Package " + pkg.packageName + " upgrade keys do not match the " 6172 + "previously installed version"); 6173 } else { 6174 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6175 String msg = "System package " + pkg.packageName 6176 + " signature changed; retaining data."; 6177 reportSettingsProblem(Log.WARN, msg); 6178 } 6179 } 6180 } else { 6181 try { 6182 verifySignaturesLP(pkgSetting, pkg); 6183 // We just determined the app is signed correctly, so bring 6184 // over the latest parsed certs. 6185 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6186 } catch (PackageManagerException e) { 6187 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6188 throw e; 6189 } 6190 // The signature has changed, but this package is in the system 6191 // image... let's recover! 6192 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6193 // However... if this package is part of a shared user, but it 6194 // doesn't match the signature of the shared user, let's fail. 6195 // What this means is that you can't change the signatures 6196 // associated with an overall shared user, which doesn't seem all 6197 // that unreasonable. 6198 if (pkgSetting.sharedUser != null) { 6199 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6200 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6201 throw new PackageManagerException( 6202 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6203 "Signature mismatch for shared user : " 6204 + pkgSetting.sharedUser); 6205 } 6206 } 6207 // File a report about this. 6208 String msg = "System package " + pkg.packageName 6209 + " signature changed; retaining data."; 6210 reportSettingsProblem(Log.WARN, msg); 6211 } 6212 } 6213 // Verify that this new package doesn't have any content providers 6214 // that conflict with existing packages. Only do this if the 6215 // package isn't already installed, since we don't want to break 6216 // things that are installed. 6217 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6218 final int N = pkg.providers.size(); 6219 int i; 6220 for (i=0; i<N; i++) { 6221 PackageParser.Provider p = pkg.providers.get(i); 6222 if (p.info.authority != null) { 6223 String names[] = p.info.authority.split(";"); 6224 for (int j = 0; j < names.length; j++) { 6225 if (mProvidersByAuthority.containsKey(names[j])) { 6226 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6227 final String otherPackageName = 6228 ((other != null && other.getComponentName() != null) ? 6229 other.getComponentName().getPackageName() : "?"); 6230 throw new PackageManagerException( 6231 INSTALL_FAILED_CONFLICTING_PROVIDER, 6232 "Can't install because provider name " + names[j] 6233 + " (in package " + pkg.applicationInfo.packageName 6234 + ") is already used by " + otherPackageName); 6235 } 6236 } 6237 } 6238 } 6239 } 6240 6241 if (pkg.mAdoptPermissions != null) { 6242 // This package wants to adopt ownership of permissions from 6243 // another package. 6244 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6245 final String origName = pkg.mAdoptPermissions.get(i); 6246 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6247 if (orig != null) { 6248 if (verifyPackageUpdateLPr(orig, pkg)) { 6249 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6250 + pkg.packageName); 6251 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6252 } 6253 } 6254 } 6255 } 6256 } 6257 6258 final String pkgName = pkg.packageName; 6259 6260 final long scanFileTime = scanFile.lastModified(); 6261 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6262 pkg.applicationInfo.processName = fixProcessName( 6263 pkg.applicationInfo.packageName, 6264 pkg.applicationInfo.processName, 6265 pkg.applicationInfo.uid); 6266 6267 File dataPath; 6268 if (mPlatformPackage == pkg) { 6269 // The system package is special. 6270 dataPath = new File(Environment.getDataDirectory(), "system"); 6271 6272 pkg.applicationInfo.dataDir = dataPath.getPath(); 6273 6274 } else { 6275 // This is a normal package, need to make its data directory. 6276 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6277 UserHandle.USER_OWNER); 6278 6279 boolean uidError = false; 6280 if (dataPath.exists()) { 6281 int currentUid = 0; 6282 try { 6283 StructStat stat = Os.stat(dataPath.getPath()); 6284 currentUid = stat.st_uid; 6285 } catch (ErrnoException e) { 6286 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6287 } 6288 6289 // If we have mismatched owners for the data path, we have a problem. 6290 if (currentUid != pkg.applicationInfo.uid) { 6291 boolean recovered = false; 6292 if (currentUid == 0) { 6293 // The directory somehow became owned by root. Wow. 6294 // This is probably because the system was stopped while 6295 // installd was in the middle of messing with its libs 6296 // directory. Ask installd to fix that. 6297 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6298 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6299 if (ret >= 0) { 6300 recovered = true; 6301 String msg = "Package " + pkg.packageName 6302 + " unexpectedly changed to uid 0; recovered to " + 6303 + pkg.applicationInfo.uid; 6304 reportSettingsProblem(Log.WARN, msg); 6305 } 6306 } 6307 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6308 || (scanFlags&SCAN_BOOTING) != 0)) { 6309 // If this is a system app, we can at least delete its 6310 // current data so the application will still work. 6311 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6312 if (ret >= 0) { 6313 // TODO: Kill the processes first 6314 // Old data gone! 6315 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6316 ? "System package " : "Third party package "; 6317 String msg = prefix + pkg.packageName 6318 + " has changed from uid: " 6319 + currentUid + " to " 6320 + pkg.applicationInfo.uid + "; old data erased"; 6321 reportSettingsProblem(Log.WARN, msg); 6322 recovered = true; 6323 6324 // And now re-install the app. 6325 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6326 pkg.applicationInfo.seinfo); 6327 if (ret == -1) { 6328 // Ack should not happen! 6329 msg = prefix + pkg.packageName 6330 + " could not have data directory re-created after delete."; 6331 reportSettingsProblem(Log.WARN, msg); 6332 throw new PackageManagerException( 6333 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6334 } 6335 } 6336 if (!recovered) { 6337 mHasSystemUidErrors = true; 6338 } 6339 } else if (!recovered) { 6340 // If we allow this install to proceed, we will be broken. 6341 // Abort, abort! 6342 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6343 "scanPackageLI"); 6344 } 6345 if (!recovered) { 6346 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6347 + pkg.applicationInfo.uid + "/fs_" 6348 + currentUid; 6349 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6350 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6351 String msg = "Package " + pkg.packageName 6352 + " has mismatched uid: " 6353 + currentUid + " on disk, " 6354 + pkg.applicationInfo.uid + " in settings"; 6355 // writer 6356 synchronized (mPackages) { 6357 mSettings.mReadMessages.append(msg); 6358 mSettings.mReadMessages.append('\n'); 6359 uidError = true; 6360 if (!pkgSetting.uidError) { 6361 reportSettingsProblem(Log.ERROR, msg); 6362 } 6363 } 6364 } 6365 } 6366 pkg.applicationInfo.dataDir = dataPath.getPath(); 6367 if (mShouldRestoreconData) { 6368 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6369 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6370 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6371 } 6372 } else { 6373 if (DEBUG_PACKAGE_SCANNING) { 6374 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6375 Log.v(TAG, "Want this data dir: " + dataPath); 6376 } 6377 //invoke installer to do the actual installation 6378 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6379 pkg.applicationInfo.seinfo); 6380 if (ret < 0) { 6381 // Error from installer 6382 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6383 "Unable to create data dirs [errorCode=" + ret + "]"); 6384 } 6385 6386 if (dataPath.exists()) { 6387 pkg.applicationInfo.dataDir = dataPath.getPath(); 6388 } else { 6389 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6390 pkg.applicationInfo.dataDir = null; 6391 } 6392 } 6393 6394 pkgSetting.uidError = uidError; 6395 } 6396 6397 final String path = scanFile.getPath(); 6398 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6399 6400 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6401 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6402 6403 // Some system apps still use directory structure for native libraries 6404 // in which case we might end up not detecting abi solely based on apk 6405 // structure. Try to detect abi based on directory structure. 6406 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6407 pkg.applicationInfo.primaryCpuAbi == null) { 6408 setBundledAppAbisAndRoots(pkg, pkgSetting); 6409 setNativeLibraryPaths(pkg); 6410 } 6411 6412 } else { 6413 if ((scanFlags & SCAN_MOVE) != 0) { 6414 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6415 // but we already have this packages package info in the PackageSetting. We just 6416 // use that and derive the native library path based on the new codepath. 6417 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6418 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6419 } 6420 6421 // Set native library paths again. For moves, the path will be updated based on the 6422 // ABIs we've determined above. For non-moves, the path will be updated based on the 6423 // ABIs we determined during compilation, but the path will depend on the final 6424 // package path (after the rename away from the stage path). 6425 setNativeLibraryPaths(pkg); 6426 } 6427 6428 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6429 final int[] userIds = sUserManager.getUserIds(); 6430 synchronized (mInstallLock) { 6431 // Create a native library symlink only if we have native libraries 6432 // and if the native libraries are 32 bit libraries. We do not provide 6433 // this symlink for 64 bit libraries. 6434 if (pkg.applicationInfo.primaryCpuAbi != null && 6435 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6436 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6437 for (int userId : userIds) { 6438 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6439 nativeLibPath, userId) < 0) { 6440 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6441 "Failed linking native library dir (user=" + userId + ")"); 6442 } 6443 } 6444 } 6445 } 6446 6447 // This is a special case for the "system" package, where the ABI is 6448 // dictated by the zygote configuration (and init.rc). We should keep track 6449 // of this ABI so that we can deal with "normal" applications that run under 6450 // the same UID correctly. 6451 if (mPlatformPackage == pkg) { 6452 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6453 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6454 } 6455 6456 // If there's a mismatch between the abi-override in the package setting 6457 // and the abiOverride specified for the install. Warn about this because we 6458 // would've already compiled the app without taking the package setting into 6459 // account. 6460 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6461 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6462 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6463 " for package: " + pkg.packageName); 6464 } 6465 } 6466 6467 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6468 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6469 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6470 6471 // Copy the derived override back to the parsed package, so that we can 6472 // update the package settings accordingly. 6473 pkg.cpuAbiOverride = cpuAbiOverride; 6474 6475 if (DEBUG_ABI_SELECTION) { 6476 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6477 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6478 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6479 } 6480 6481 // Push the derived path down into PackageSettings so we know what to 6482 // clean up at uninstall time. 6483 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6484 6485 if (DEBUG_ABI_SELECTION) { 6486 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6487 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6488 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6489 } 6490 6491 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6492 // We don't do this here during boot because we can do it all 6493 // at once after scanning all existing packages. 6494 // 6495 // We also do this *before* we perform dexopt on this package, so that 6496 // we can avoid redundant dexopts, and also to make sure we've got the 6497 // code and package path correct. 6498 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6499 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6500 } 6501 6502 if ((scanFlags & SCAN_NO_DEX) == 0) { 6503 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6504 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6505 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6506 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6507 } 6508 } 6509 if (mFactoryTest && pkg.requestedPermissions.contains( 6510 android.Manifest.permission.FACTORY_TEST)) { 6511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6512 } 6513 6514 ArrayList<PackageParser.Package> clientLibPkgs = null; 6515 6516 // writer 6517 synchronized (mPackages) { 6518 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6519 // Only system apps can add new shared libraries. 6520 if (pkg.libraryNames != null) { 6521 for (int i=0; i<pkg.libraryNames.size(); i++) { 6522 String name = pkg.libraryNames.get(i); 6523 boolean allowed = false; 6524 if (pkg.isUpdatedSystemApp()) { 6525 // New library entries can only be added through the 6526 // system image. This is important to get rid of a lot 6527 // of nasty edge cases: for example if we allowed a non- 6528 // system update of the app to add a library, then uninstalling 6529 // the update would make the library go away, and assumptions 6530 // we made such as through app install filtering would now 6531 // have allowed apps on the device which aren't compatible 6532 // with it. Better to just have the restriction here, be 6533 // conservative, and create many fewer cases that can negatively 6534 // impact the user experience. 6535 final PackageSetting sysPs = mSettings 6536 .getDisabledSystemPkgLPr(pkg.packageName); 6537 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6538 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6539 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6540 allowed = true; 6541 allowed = true; 6542 break; 6543 } 6544 } 6545 } 6546 } else { 6547 allowed = true; 6548 } 6549 if (allowed) { 6550 if (!mSharedLibraries.containsKey(name)) { 6551 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6552 } else if (!name.equals(pkg.packageName)) { 6553 Slog.w(TAG, "Package " + pkg.packageName + " library " 6554 + name + " already exists; skipping"); 6555 } 6556 } else { 6557 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6558 + name + " that is not declared on system image; skipping"); 6559 } 6560 } 6561 if ((scanFlags&SCAN_BOOTING) == 0) { 6562 // If we are not booting, we need to update any applications 6563 // that are clients of our shared library. If we are booting, 6564 // this will all be done once the scan is complete. 6565 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6566 } 6567 } 6568 } 6569 } 6570 6571 // We also need to dexopt any apps that are dependent on this library. Note that 6572 // if these fail, we should abort the install since installing the library will 6573 // result in some apps being broken. 6574 if (clientLibPkgs != null) { 6575 if ((scanFlags & SCAN_NO_DEX) == 0) { 6576 for (int i = 0; i < clientLibPkgs.size(); i++) { 6577 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6578 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6579 null /* instruction sets */, forceDex, 6580 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6581 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6582 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6583 "scanPackageLI failed to dexopt clientLibPkgs"); 6584 } 6585 } 6586 } 6587 } 6588 6589 // Also need to kill any apps that are dependent on the library. 6590 if (clientLibPkgs != null) { 6591 for (int i=0; i<clientLibPkgs.size(); i++) { 6592 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6593 killApplication(clientPkg.applicationInfo.packageName, 6594 clientPkg.applicationInfo.uid, "update lib"); 6595 } 6596 } 6597 6598 // Make sure we're not adding any bogus keyset info 6599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6600 ksms.assertScannedPackageValid(pkg); 6601 6602 // writer 6603 synchronized (mPackages) { 6604 // We don't expect installation to fail beyond this point 6605 6606 // Add the new setting to mSettings 6607 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6608 // Add the new setting to mPackages 6609 mPackages.put(pkg.applicationInfo.packageName, pkg); 6610 // Make sure we don't accidentally delete its data. 6611 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6612 while (iter.hasNext()) { 6613 PackageCleanItem item = iter.next(); 6614 if (pkgName.equals(item.packageName)) { 6615 iter.remove(); 6616 } 6617 } 6618 6619 // Take care of first install / last update times. 6620 if (currentTime != 0) { 6621 if (pkgSetting.firstInstallTime == 0) { 6622 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6623 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6624 pkgSetting.lastUpdateTime = currentTime; 6625 } 6626 } else if (pkgSetting.firstInstallTime == 0) { 6627 // We need *something*. Take time time stamp of the file. 6628 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6629 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6630 if (scanFileTime != pkgSetting.timeStamp) { 6631 // A package on the system image has changed; consider this 6632 // to be an update. 6633 pkgSetting.lastUpdateTime = scanFileTime; 6634 } 6635 } 6636 6637 // Add the package's KeySets to the global KeySetManagerService 6638 ksms.addScannedPackageLPw(pkg); 6639 6640 int N = pkg.providers.size(); 6641 StringBuilder r = null; 6642 int i; 6643 for (i=0; i<N; i++) { 6644 PackageParser.Provider p = pkg.providers.get(i); 6645 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6646 p.info.processName, pkg.applicationInfo.uid); 6647 mProviders.addProvider(p); 6648 p.syncable = p.info.isSyncable; 6649 if (p.info.authority != null) { 6650 String names[] = p.info.authority.split(";"); 6651 p.info.authority = null; 6652 for (int j = 0; j < names.length; j++) { 6653 if (j == 1 && p.syncable) { 6654 // We only want the first authority for a provider to possibly be 6655 // syncable, so if we already added this provider using a different 6656 // authority clear the syncable flag. We copy the provider before 6657 // changing it because the mProviders object contains a reference 6658 // to a provider that we don't want to change. 6659 // Only do this for the second authority since the resulting provider 6660 // object can be the same for all future authorities for this provider. 6661 p = new PackageParser.Provider(p); 6662 p.syncable = false; 6663 } 6664 if (!mProvidersByAuthority.containsKey(names[j])) { 6665 mProvidersByAuthority.put(names[j], p); 6666 if (p.info.authority == null) { 6667 p.info.authority = names[j]; 6668 } else { 6669 p.info.authority = p.info.authority + ";" + names[j]; 6670 } 6671 if (DEBUG_PACKAGE_SCANNING) { 6672 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6673 Log.d(TAG, "Registered content provider: " + names[j] 6674 + ", className = " + p.info.name + ", isSyncable = " 6675 + p.info.isSyncable); 6676 } 6677 } else { 6678 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6679 Slog.w(TAG, "Skipping provider name " + names[j] + 6680 " (in package " + pkg.applicationInfo.packageName + 6681 "): name already used by " 6682 + ((other != null && other.getComponentName() != null) 6683 ? other.getComponentName().getPackageName() : "?")); 6684 } 6685 } 6686 } 6687 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(p.info.name); 6694 } 6695 } 6696 if (r != null) { 6697 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6698 } 6699 6700 N = pkg.services.size(); 6701 r = null; 6702 for (i=0; i<N; i++) { 6703 PackageParser.Service s = pkg.services.get(i); 6704 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6705 s.info.processName, pkg.applicationInfo.uid); 6706 mServices.addService(s); 6707 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6708 if (r == null) { 6709 r = new StringBuilder(256); 6710 } else { 6711 r.append(' '); 6712 } 6713 r.append(s.info.name); 6714 } 6715 } 6716 if (r != null) { 6717 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6718 } 6719 6720 N = pkg.receivers.size(); 6721 r = null; 6722 for (i=0; i<N; i++) { 6723 PackageParser.Activity a = pkg.receivers.get(i); 6724 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6725 a.info.processName, pkg.applicationInfo.uid); 6726 mReceivers.addActivity(a, "receiver"); 6727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append(a.info.name); 6734 } 6735 } 6736 if (r != null) { 6737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6738 } 6739 6740 N = pkg.activities.size(); 6741 r = null; 6742 for (i=0; i<N; i++) { 6743 PackageParser.Activity a = pkg.activities.get(i); 6744 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6745 a.info.processName, pkg.applicationInfo.uid); 6746 mActivities.addActivity(a, "activity"); 6747 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6748 if (r == null) { 6749 r = new StringBuilder(256); 6750 } else { 6751 r.append(' '); 6752 } 6753 r.append(a.info.name); 6754 } 6755 } 6756 if (r != null) { 6757 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6758 } 6759 6760 N = pkg.permissionGroups.size(); 6761 r = null; 6762 for (i=0; i<N; i++) { 6763 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6764 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6765 if (cur == null) { 6766 mPermissionGroups.put(pg.info.name, pg); 6767 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6768 if (r == null) { 6769 r = new StringBuilder(256); 6770 } else { 6771 r.append(' '); 6772 } 6773 r.append(pg.info.name); 6774 } 6775 } else { 6776 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6777 + pg.info.packageName + " ignored: original from " 6778 + cur.info.packageName); 6779 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6780 if (r == null) { 6781 r = new StringBuilder(256); 6782 } else { 6783 r.append(' '); 6784 } 6785 r.append("DUP:"); 6786 r.append(pg.info.name); 6787 } 6788 } 6789 } 6790 if (r != null) { 6791 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6792 } 6793 6794 N = pkg.permissions.size(); 6795 r = null; 6796 for (i=0; i<N; i++) { 6797 PackageParser.Permission p = pkg.permissions.get(i); 6798 6799 // Now that permission groups have a special meaning, we ignore permission 6800 // groups for legacy apps to prevent unexpected behavior. In particular, 6801 // permissions for one app being granted to someone just becuase they happen 6802 // to be in a group defined by another app (before this had no implications). 6803 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6804 p.group = mPermissionGroups.get(p.info.group); 6805 // Warn for a permission in an unknown group. 6806 if (p.info.group != null && p.group == null) { 6807 Slog.w(TAG, "Permission " + p.info.name + " from package " 6808 + p.info.packageName + " in an unknown group " + p.info.group); 6809 } 6810 } 6811 6812 ArrayMap<String, BasePermission> permissionMap = 6813 p.tree ? mSettings.mPermissionTrees 6814 : mSettings.mPermissions; 6815 BasePermission bp = permissionMap.get(p.info.name); 6816 6817 // Allow system apps to redefine non-system permissions 6818 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6819 final boolean currentOwnerIsSystem = (bp.perm != null 6820 && isSystemApp(bp.perm.owner)); 6821 if (isSystemApp(p.owner)) { 6822 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6823 // It's a built-in permission and no owner, take ownership now 6824 bp.packageSetting = pkgSetting; 6825 bp.perm = p; 6826 bp.uid = pkg.applicationInfo.uid; 6827 bp.sourcePackage = p.info.packageName; 6828 } else if (!currentOwnerIsSystem) { 6829 String msg = "New decl " + p.owner + " of permission " 6830 + p.info.name + " is system; overriding " + bp.sourcePackage; 6831 reportSettingsProblem(Log.WARN, msg); 6832 bp = null; 6833 } 6834 } 6835 } 6836 6837 if (bp == null) { 6838 bp = new BasePermission(p.info.name, p.info.packageName, 6839 BasePermission.TYPE_NORMAL); 6840 permissionMap.put(p.info.name, bp); 6841 } 6842 6843 if (bp.perm == null) { 6844 if (bp.sourcePackage == null 6845 || bp.sourcePackage.equals(p.info.packageName)) { 6846 BasePermission tree = findPermissionTreeLP(p.info.name); 6847 if (tree == null 6848 || tree.sourcePackage.equals(p.info.packageName)) { 6849 bp.packageSetting = pkgSetting; 6850 bp.perm = p; 6851 bp.uid = pkg.applicationInfo.uid; 6852 bp.sourcePackage = p.info.packageName; 6853 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6854 if (r == null) { 6855 r = new StringBuilder(256); 6856 } else { 6857 r.append(' '); 6858 } 6859 r.append(p.info.name); 6860 } 6861 } else { 6862 Slog.w(TAG, "Permission " + p.info.name + " from package " 6863 + p.info.packageName + " ignored: base tree " 6864 + tree.name + " is from package " 6865 + tree.sourcePackage); 6866 } 6867 } else { 6868 Slog.w(TAG, "Permission " + p.info.name + " from package " 6869 + p.info.packageName + " ignored: original from " 6870 + bp.sourcePackage); 6871 } 6872 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6873 if (r == null) { 6874 r = new StringBuilder(256); 6875 } else { 6876 r.append(' '); 6877 } 6878 r.append("DUP:"); 6879 r.append(p.info.name); 6880 } 6881 if (bp.perm == p) { 6882 bp.protectionLevel = p.info.protectionLevel; 6883 } 6884 } 6885 6886 if (r != null) { 6887 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6888 } 6889 6890 N = pkg.instrumentation.size(); 6891 r = null; 6892 for (i=0; i<N; i++) { 6893 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6894 a.info.packageName = pkg.applicationInfo.packageName; 6895 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6896 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6897 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6898 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6899 a.info.dataDir = pkg.applicationInfo.dataDir; 6900 6901 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6902 // need other information about the application, like the ABI and what not ? 6903 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6904 mInstrumentation.put(a.getComponentName(), a); 6905 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6906 if (r == null) { 6907 r = new StringBuilder(256); 6908 } else { 6909 r.append(' '); 6910 } 6911 r.append(a.info.name); 6912 } 6913 } 6914 if (r != null) { 6915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6916 } 6917 6918 if (pkg.protectedBroadcasts != null) { 6919 N = pkg.protectedBroadcasts.size(); 6920 for (i=0; i<N; i++) { 6921 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6922 } 6923 } 6924 6925 pkgSetting.setTimeStamp(scanFileTime); 6926 6927 // Create idmap files for pairs of (packages, overlay packages). 6928 // Note: "android", ie framework-res.apk, is handled by native layers. 6929 if (pkg.mOverlayTarget != null) { 6930 // This is an overlay package. 6931 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6932 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6933 mOverlays.put(pkg.mOverlayTarget, 6934 new ArrayMap<String, PackageParser.Package>()); 6935 } 6936 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6937 map.put(pkg.packageName, pkg); 6938 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6939 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6940 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6941 "scanPackageLI failed to createIdmap"); 6942 } 6943 } 6944 } else if (mOverlays.containsKey(pkg.packageName) && 6945 !pkg.packageName.equals("android")) { 6946 // This is a regular package, with one or more known overlay packages. 6947 createIdmapsForPackageLI(pkg); 6948 } 6949 } 6950 6951 return pkg; 6952 } 6953 6954 /** 6955 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6956 * is derived purely on the basis of the contents of {@code scanFile} and 6957 * {@code cpuAbiOverride}. 6958 * 6959 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6960 */ 6961 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6962 String cpuAbiOverride, boolean extractLibs) 6963 throws PackageManagerException { 6964 // TODO: We can probably be smarter about this stuff. For installed apps, 6965 // we can calculate this information at install time once and for all. For 6966 // system apps, we can probably assume that this information doesn't change 6967 // after the first boot scan. As things stand, we do lots of unnecessary work. 6968 6969 // Give ourselves some initial paths; we'll come back for another 6970 // pass once we've determined ABI below. 6971 setNativeLibraryPaths(pkg); 6972 6973 // We would never need to extract libs for forward-locked and external packages, 6974 // since the container service will do it for us. We shouldn't attempt to 6975 // extract libs from system app when it was not updated. 6976 if (pkg.isForwardLocked() || isExternal(pkg) || 6977 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6978 extractLibs = false; 6979 } 6980 6981 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6982 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6983 6984 NativeLibraryHelper.Handle handle = null; 6985 try { 6986 handle = NativeLibraryHelper.Handle.create(scanFile); 6987 // TODO(multiArch): This can be null for apps that didn't go through the 6988 // usual installation process. We can calculate it again, like we 6989 // do during install time. 6990 // 6991 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6992 // unnecessary. 6993 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6994 6995 // Null out the abis so that they can be recalculated. 6996 pkg.applicationInfo.primaryCpuAbi = null; 6997 pkg.applicationInfo.secondaryCpuAbi = null; 6998 if (isMultiArch(pkg.applicationInfo)) { 6999 // Warn if we've set an abiOverride for multi-lib packages.. 7000 // By definition, we need to copy both 32 and 64 bit libraries for 7001 // such packages. 7002 if (pkg.cpuAbiOverride != null 7003 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7004 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7005 } 7006 7007 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7008 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7009 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7010 if (extractLibs) { 7011 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7012 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7013 useIsaSpecificSubdirs); 7014 } else { 7015 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7016 } 7017 } 7018 7019 maybeThrowExceptionForMultiArchCopy( 7020 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7021 7022 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7023 if (extractLibs) { 7024 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7025 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7026 useIsaSpecificSubdirs); 7027 } else { 7028 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7029 } 7030 } 7031 7032 maybeThrowExceptionForMultiArchCopy( 7033 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7034 7035 if (abi64 >= 0) { 7036 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7037 } 7038 7039 if (abi32 >= 0) { 7040 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7041 if (abi64 >= 0) { 7042 pkg.applicationInfo.secondaryCpuAbi = abi; 7043 } else { 7044 pkg.applicationInfo.primaryCpuAbi = abi; 7045 } 7046 } 7047 } else { 7048 String[] abiList = (cpuAbiOverride != null) ? 7049 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7050 7051 // Enable gross and lame hacks for apps that are built with old 7052 // SDK tools. We must scan their APKs for renderscript bitcode and 7053 // not launch them if it's present. Don't bother checking on devices 7054 // that don't have 64 bit support. 7055 boolean needsRenderScriptOverride = false; 7056 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7057 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7058 abiList = Build.SUPPORTED_32_BIT_ABIS; 7059 needsRenderScriptOverride = true; 7060 } 7061 7062 final int copyRet; 7063 if (extractLibs) { 7064 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7065 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7066 } else { 7067 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7068 } 7069 7070 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7071 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7072 "Error unpackaging native libs for app, errorCode=" + copyRet); 7073 } 7074 7075 if (copyRet >= 0) { 7076 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7077 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7078 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7079 } else if (needsRenderScriptOverride) { 7080 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7081 } 7082 } 7083 } catch (IOException ioe) { 7084 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7085 } finally { 7086 IoUtils.closeQuietly(handle); 7087 } 7088 7089 // Now that we've calculated the ABIs and determined if it's an internal app, 7090 // we will go ahead and populate the nativeLibraryPath. 7091 setNativeLibraryPaths(pkg); 7092 } 7093 7094 /** 7095 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7096 * i.e, so that all packages can be run inside a single process if required. 7097 * 7098 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7099 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7100 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7101 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7102 * updating a package that belongs to a shared user. 7103 * 7104 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7105 * adds unnecessary complexity. 7106 */ 7107 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7108 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7109 String requiredInstructionSet = null; 7110 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7111 requiredInstructionSet = VMRuntime.getInstructionSet( 7112 scannedPackage.applicationInfo.primaryCpuAbi); 7113 } 7114 7115 PackageSetting requirer = null; 7116 for (PackageSetting ps : packagesForUser) { 7117 // If packagesForUser contains scannedPackage, we skip it. This will happen 7118 // when scannedPackage is an update of an existing package. Without this check, 7119 // we will never be able to change the ABI of any package belonging to a shared 7120 // user, even if it's compatible with other packages. 7121 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7122 if (ps.primaryCpuAbiString == null) { 7123 continue; 7124 } 7125 7126 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7127 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7128 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7129 // this but there's not much we can do. 7130 String errorMessage = "Instruction set mismatch, " 7131 + ((requirer == null) ? "[caller]" : requirer) 7132 + " requires " + requiredInstructionSet + " whereas " + ps 7133 + " requires " + instructionSet; 7134 Slog.w(TAG, errorMessage); 7135 } 7136 7137 if (requiredInstructionSet == null) { 7138 requiredInstructionSet = instructionSet; 7139 requirer = ps; 7140 } 7141 } 7142 } 7143 7144 if (requiredInstructionSet != null) { 7145 String adjustedAbi; 7146 if (requirer != null) { 7147 // requirer != null implies that either scannedPackage was null or that scannedPackage 7148 // did not require an ABI, in which case we have to adjust scannedPackage to match 7149 // the ABI of the set (which is the same as requirer's ABI) 7150 adjustedAbi = requirer.primaryCpuAbiString; 7151 if (scannedPackage != null) { 7152 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7153 } 7154 } else { 7155 // requirer == null implies that we're updating all ABIs in the set to 7156 // match scannedPackage. 7157 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7158 } 7159 7160 for (PackageSetting ps : packagesForUser) { 7161 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7162 if (ps.primaryCpuAbiString != null) { 7163 continue; 7164 } 7165 7166 ps.primaryCpuAbiString = adjustedAbi; 7167 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7168 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7169 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7170 7171 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7172 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7173 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7174 ps.primaryCpuAbiString = null; 7175 ps.pkg.applicationInfo.primaryCpuAbi = null; 7176 return; 7177 } else { 7178 mInstaller.rmdex(ps.codePathString, 7179 getDexCodeInstructionSet(getPreferredInstructionSet())); 7180 } 7181 } 7182 } 7183 } 7184 } 7185 } 7186 7187 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7188 synchronized (mPackages) { 7189 mResolverReplaced = true; 7190 // Set up information for custom user intent resolution activity. 7191 mResolveActivity.applicationInfo = pkg.applicationInfo; 7192 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7193 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7194 mResolveActivity.processName = pkg.applicationInfo.packageName; 7195 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7196 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7197 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7198 mResolveActivity.theme = 0; 7199 mResolveActivity.exported = true; 7200 mResolveActivity.enabled = true; 7201 mResolveInfo.activityInfo = mResolveActivity; 7202 mResolveInfo.priority = 0; 7203 mResolveInfo.preferredOrder = 0; 7204 mResolveInfo.match = 0; 7205 mResolveComponentName = mCustomResolverComponentName; 7206 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7207 mResolveComponentName); 7208 } 7209 } 7210 7211 private static String calculateBundledApkRoot(final String codePathString) { 7212 final File codePath = new File(codePathString); 7213 final File codeRoot; 7214 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7215 codeRoot = Environment.getRootDirectory(); 7216 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7217 codeRoot = Environment.getOemDirectory(); 7218 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7219 codeRoot = Environment.getVendorDirectory(); 7220 } else { 7221 // Unrecognized code path; take its top real segment as the apk root: 7222 // e.g. /something/app/blah.apk => /something 7223 try { 7224 File f = codePath.getCanonicalFile(); 7225 File parent = f.getParentFile(); // non-null because codePath is a file 7226 File tmp; 7227 while ((tmp = parent.getParentFile()) != null) { 7228 f = parent; 7229 parent = tmp; 7230 } 7231 codeRoot = f; 7232 Slog.w(TAG, "Unrecognized code path " 7233 + codePath + " - using " + codeRoot); 7234 } catch (IOException e) { 7235 // Can't canonicalize the code path -- shenanigans? 7236 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7237 return Environment.getRootDirectory().getPath(); 7238 } 7239 } 7240 return codeRoot.getPath(); 7241 } 7242 7243 /** 7244 * Derive and set the location of native libraries for the given package, 7245 * which varies depending on where and how the package was installed. 7246 */ 7247 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7248 final ApplicationInfo info = pkg.applicationInfo; 7249 final String codePath = pkg.codePath; 7250 final File codeFile = new File(codePath); 7251 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7252 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7253 7254 info.nativeLibraryRootDir = null; 7255 info.nativeLibraryRootRequiresIsa = false; 7256 info.nativeLibraryDir = null; 7257 info.secondaryNativeLibraryDir = null; 7258 7259 if (isApkFile(codeFile)) { 7260 // Monolithic install 7261 if (bundledApp) { 7262 // If "/system/lib64/apkname" exists, assume that is the per-package 7263 // native library directory to use; otherwise use "/system/lib/apkname". 7264 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7265 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7266 getPrimaryInstructionSet(info)); 7267 7268 // This is a bundled system app so choose the path based on the ABI. 7269 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7270 // is just the default path. 7271 final String apkName = deriveCodePathName(codePath); 7272 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7273 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7274 apkName).getAbsolutePath(); 7275 7276 if (info.secondaryCpuAbi != null) { 7277 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7278 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7279 secondaryLibDir, apkName).getAbsolutePath(); 7280 } 7281 } else if (asecApp) { 7282 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7283 .getAbsolutePath(); 7284 } else { 7285 final String apkName = deriveCodePathName(codePath); 7286 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7287 .getAbsolutePath(); 7288 } 7289 7290 info.nativeLibraryRootRequiresIsa = false; 7291 info.nativeLibraryDir = info.nativeLibraryRootDir; 7292 } else { 7293 // Cluster install 7294 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7295 info.nativeLibraryRootRequiresIsa = true; 7296 7297 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7298 getPrimaryInstructionSet(info)).getAbsolutePath(); 7299 7300 if (info.secondaryCpuAbi != null) { 7301 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7302 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7303 } 7304 } 7305 } 7306 7307 /** 7308 * Calculate the abis and roots for a bundled app. These can uniquely 7309 * be determined from the contents of the system partition, i.e whether 7310 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7311 * of this information, and instead assume that the system was built 7312 * sensibly. 7313 */ 7314 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7315 PackageSetting pkgSetting) { 7316 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7317 7318 // If "/system/lib64/apkname" exists, assume that is the per-package 7319 // native library directory to use; otherwise use "/system/lib/apkname". 7320 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7321 setBundledAppAbi(pkg, apkRoot, apkName); 7322 // pkgSetting might be null during rescan following uninstall of updates 7323 // to a bundled app, so accommodate that possibility. The settings in 7324 // that case will be established later from the parsed package. 7325 // 7326 // If the settings aren't null, sync them up with what we've just derived. 7327 // note that apkRoot isn't stored in the package settings. 7328 if (pkgSetting != null) { 7329 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7330 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7331 } 7332 } 7333 7334 /** 7335 * Deduces the ABI of a bundled app and sets the relevant fields on the 7336 * parsed pkg object. 7337 * 7338 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7339 * under which system libraries are installed. 7340 * @param apkName the name of the installed package. 7341 */ 7342 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7343 final File codeFile = new File(pkg.codePath); 7344 7345 final boolean has64BitLibs; 7346 final boolean has32BitLibs; 7347 if (isApkFile(codeFile)) { 7348 // Monolithic install 7349 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7350 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7351 } else { 7352 // Cluster install 7353 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7354 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7355 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7356 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7357 has64BitLibs = (new File(rootDir, isa)).exists(); 7358 } else { 7359 has64BitLibs = false; 7360 } 7361 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7362 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7363 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7364 has32BitLibs = (new File(rootDir, isa)).exists(); 7365 } else { 7366 has32BitLibs = false; 7367 } 7368 } 7369 7370 if (has64BitLibs && !has32BitLibs) { 7371 // The package has 64 bit libs, but not 32 bit libs. Its primary 7372 // ABI should be 64 bit. We can safely assume here that the bundled 7373 // native libraries correspond to the most preferred ABI in the list. 7374 7375 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7376 pkg.applicationInfo.secondaryCpuAbi = null; 7377 } else if (has32BitLibs && !has64BitLibs) { 7378 // The package has 32 bit libs but not 64 bit libs. Its primary 7379 // ABI should be 32 bit. 7380 7381 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7382 pkg.applicationInfo.secondaryCpuAbi = null; 7383 } else if (has32BitLibs && has64BitLibs) { 7384 // The application has both 64 and 32 bit bundled libraries. We check 7385 // here that the app declares multiArch support, and warn if it doesn't. 7386 // 7387 // We will be lenient here and record both ABIs. The primary will be the 7388 // ABI that's higher on the list, i.e, a device that's configured to prefer 7389 // 64 bit apps will see a 64 bit primary ABI, 7390 7391 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7392 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7393 } 7394 7395 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7396 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7397 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7398 } else { 7399 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7400 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7401 } 7402 } else { 7403 pkg.applicationInfo.primaryCpuAbi = null; 7404 pkg.applicationInfo.secondaryCpuAbi = null; 7405 } 7406 } 7407 7408 private void killApplication(String pkgName, int appId, String reason) { 7409 // Request the ActivityManager to kill the process(only for existing packages) 7410 // so that we do not end up in a confused state while the user is still using the older 7411 // version of the application while the new one gets installed. 7412 IActivityManager am = ActivityManagerNative.getDefault(); 7413 if (am != null) { 7414 try { 7415 am.killApplicationWithAppId(pkgName, appId, reason); 7416 } catch (RemoteException e) { 7417 } 7418 } 7419 } 7420 7421 void removePackageLI(PackageSetting ps, boolean chatty) { 7422 if (DEBUG_INSTALL) { 7423 if (chatty) 7424 Log.d(TAG, "Removing package " + ps.name); 7425 } 7426 7427 // writer 7428 synchronized (mPackages) { 7429 mPackages.remove(ps.name); 7430 final PackageParser.Package pkg = ps.pkg; 7431 if (pkg != null) { 7432 cleanPackageDataStructuresLILPw(pkg, chatty); 7433 } 7434 } 7435 } 7436 7437 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7438 if (DEBUG_INSTALL) { 7439 if (chatty) 7440 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7441 } 7442 7443 // writer 7444 synchronized (mPackages) { 7445 mPackages.remove(pkg.applicationInfo.packageName); 7446 cleanPackageDataStructuresLILPw(pkg, chatty); 7447 } 7448 } 7449 7450 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7451 int N = pkg.providers.size(); 7452 StringBuilder r = null; 7453 int i; 7454 for (i=0; i<N; i++) { 7455 PackageParser.Provider p = pkg.providers.get(i); 7456 mProviders.removeProvider(p); 7457 if (p.info.authority == null) { 7458 7459 /* There was another ContentProvider with this authority when 7460 * this app was installed so this authority is null, 7461 * Ignore it as we don't have to unregister the provider. 7462 */ 7463 continue; 7464 } 7465 String names[] = p.info.authority.split(";"); 7466 for (int j = 0; j < names.length; j++) { 7467 if (mProvidersByAuthority.get(names[j]) == p) { 7468 mProvidersByAuthority.remove(names[j]); 7469 if (DEBUG_REMOVE) { 7470 if (chatty) 7471 Log.d(TAG, "Unregistered content provider: " + names[j] 7472 + ", className = " + p.info.name + ", isSyncable = " 7473 + p.info.isSyncable); 7474 } 7475 } 7476 } 7477 if (DEBUG_REMOVE && chatty) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append(p.info.name); 7484 } 7485 } 7486 if (r != null) { 7487 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7488 } 7489 7490 N = pkg.services.size(); 7491 r = null; 7492 for (i=0; i<N; i++) { 7493 PackageParser.Service s = pkg.services.get(i); 7494 mServices.removeService(s); 7495 if (chatty) { 7496 if (r == null) { 7497 r = new StringBuilder(256); 7498 } else { 7499 r.append(' '); 7500 } 7501 r.append(s.info.name); 7502 } 7503 } 7504 if (r != null) { 7505 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7506 } 7507 7508 N = pkg.receivers.size(); 7509 r = null; 7510 for (i=0; i<N; i++) { 7511 PackageParser.Activity a = pkg.receivers.get(i); 7512 mReceivers.removeActivity(a, "receiver"); 7513 if (DEBUG_REMOVE && chatty) { 7514 if (r == null) { 7515 r = new StringBuilder(256); 7516 } else { 7517 r.append(' '); 7518 } 7519 r.append(a.info.name); 7520 } 7521 } 7522 if (r != null) { 7523 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7524 } 7525 7526 N = pkg.activities.size(); 7527 r = null; 7528 for (i=0; i<N; i++) { 7529 PackageParser.Activity a = pkg.activities.get(i); 7530 mActivities.removeActivity(a, "activity"); 7531 if (DEBUG_REMOVE && chatty) { 7532 if (r == null) { 7533 r = new StringBuilder(256); 7534 } else { 7535 r.append(' '); 7536 } 7537 r.append(a.info.name); 7538 } 7539 } 7540 if (r != null) { 7541 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7542 } 7543 7544 N = pkg.permissions.size(); 7545 r = null; 7546 for (i=0; i<N; i++) { 7547 PackageParser.Permission p = pkg.permissions.get(i); 7548 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7549 if (bp == null) { 7550 bp = mSettings.mPermissionTrees.get(p.info.name); 7551 } 7552 if (bp != null && bp.perm == p) { 7553 bp.perm = null; 7554 if (DEBUG_REMOVE && chatty) { 7555 if (r == null) { 7556 r = new StringBuilder(256); 7557 } else { 7558 r.append(' '); 7559 } 7560 r.append(p.info.name); 7561 } 7562 } 7563 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7564 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7565 if (appOpPerms != null) { 7566 appOpPerms.remove(pkg.packageName); 7567 } 7568 } 7569 } 7570 if (r != null) { 7571 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7572 } 7573 7574 N = pkg.requestedPermissions.size(); 7575 r = null; 7576 for (i=0; i<N; i++) { 7577 String perm = pkg.requestedPermissions.get(i); 7578 BasePermission bp = mSettings.mPermissions.get(perm); 7579 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7580 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7581 if (appOpPerms != null) { 7582 appOpPerms.remove(pkg.packageName); 7583 if (appOpPerms.isEmpty()) { 7584 mAppOpPermissionPackages.remove(perm); 7585 } 7586 } 7587 } 7588 } 7589 if (r != null) { 7590 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7591 } 7592 7593 N = pkg.instrumentation.size(); 7594 r = null; 7595 for (i=0; i<N; i++) { 7596 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7597 mInstrumentation.remove(a.getComponentName()); 7598 if (DEBUG_REMOVE && chatty) { 7599 if (r == null) { 7600 r = new StringBuilder(256); 7601 } else { 7602 r.append(' '); 7603 } 7604 r.append(a.info.name); 7605 } 7606 } 7607 if (r != null) { 7608 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7609 } 7610 7611 r = null; 7612 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7613 // Only system apps can hold shared libraries. 7614 if (pkg.libraryNames != null) { 7615 for (i=0; i<pkg.libraryNames.size(); i++) { 7616 String name = pkg.libraryNames.get(i); 7617 SharedLibraryEntry cur = mSharedLibraries.get(name); 7618 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7619 mSharedLibraries.remove(name); 7620 if (DEBUG_REMOVE && chatty) { 7621 if (r == null) { 7622 r = new StringBuilder(256); 7623 } else { 7624 r.append(' '); 7625 } 7626 r.append(name); 7627 } 7628 } 7629 } 7630 } 7631 } 7632 if (r != null) { 7633 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7634 } 7635 } 7636 7637 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7638 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7639 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7640 return true; 7641 } 7642 } 7643 return false; 7644 } 7645 7646 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7647 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7648 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7649 7650 private void updatePermissionsLPw(String changingPkg, 7651 PackageParser.Package pkgInfo, int flags) { 7652 // Make sure there are no dangling permission trees. 7653 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7654 while (it.hasNext()) { 7655 final BasePermission bp = it.next(); 7656 if (bp.packageSetting == null) { 7657 // We may not yet have parsed the package, so just see if 7658 // we still know about its settings. 7659 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7660 } 7661 if (bp.packageSetting == null) { 7662 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7663 + " from package " + bp.sourcePackage); 7664 it.remove(); 7665 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7666 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7667 Slog.i(TAG, "Removing old permission tree: " + bp.name 7668 + " from package " + bp.sourcePackage); 7669 flags |= UPDATE_PERMISSIONS_ALL; 7670 it.remove(); 7671 } 7672 } 7673 } 7674 7675 // Make sure all dynamic permissions have been assigned to a package, 7676 // and make sure there are no dangling permissions. 7677 it = mSettings.mPermissions.values().iterator(); 7678 while (it.hasNext()) { 7679 final BasePermission bp = it.next(); 7680 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7681 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7682 + bp.name + " pkg=" + bp.sourcePackage 7683 + " info=" + bp.pendingInfo); 7684 if (bp.packageSetting == null && bp.pendingInfo != null) { 7685 final BasePermission tree = findPermissionTreeLP(bp.name); 7686 if (tree != null && tree.perm != null) { 7687 bp.packageSetting = tree.packageSetting; 7688 bp.perm = new PackageParser.Permission(tree.perm.owner, 7689 new PermissionInfo(bp.pendingInfo)); 7690 bp.perm.info.packageName = tree.perm.info.packageName; 7691 bp.perm.info.name = bp.name; 7692 bp.uid = tree.uid; 7693 } 7694 } 7695 } 7696 if (bp.packageSetting == null) { 7697 // We may not yet have parsed the package, so just see if 7698 // we still know about its settings. 7699 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7700 } 7701 if (bp.packageSetting == null) { 7702 Slog.w(TAG, "Removing dangling permission: " + bp.name 7703 + " from package " + bp.sourcePackage); 7704 it.remove(); 7705 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7706 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7707 Slog.i(TAG, "Removing old permission: " + bp.name 7708 + " from package " + bp.sourcePackage); 7709 flags |= UPDATE_PERMISSIONS_ALL; 7710 it.remove(); 7711 } 7712 } 7713 } 7714 7715 // Now update the permissions for all packages, in particular 7716 // replace the granted permissions of the system packages. 7717 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7718 for (PackageParser.Package pkg : mPackages.values()) { 7719 if (pkg != pkgInfo) { 7720 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7721 changingPkg); 7722 } 7723 } 7724 } 7725 7726 if (pkgInfo != null) { 7727 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7728 } 7729 } 7730 7731 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7732 String packageOfInterest) { 7733 // IMPORTANT: There are two types of permissions: install and runtime. 7734 // Install time permissions are granted when the app is installed to 7735 // all device users and users added in the future. Runtime permissions 7736 // are granted at runtime explicitly to specific users. Normal and signature 7737 // protected permissions are install time permissions. Dangerous permissions 7738 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7739 // otherwise they are runtime permissions. This function does not manage 7740 // runtime permissions except for the case an app targeting Lollipop MR1 7741 // being upgraded to target a newer SDK, in which case dangerous permissions 7742 // are transformed from install time to runtime ones. 7743 7744 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7745 if (ps == null) { 7746 return; 7747 } 7748 7749 PermissionsState permissionsState = ps.getPermissionsState(); 7750 PermissionsState origPermissions = permissionsState; 7751 7752 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7753 7754 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7755 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7756 7757 boolean changedInstallPermission = false; 7758 7759 if (replace) { 7760 ps.installPermissionsFixed = false; 7761 if (!ps.isSharedUser()) { 7762 origPermissions = new PermissionsState(permissionsState); 7763 permissionsState.reset(); 7764 } 7765 } 7766 7767 permissionsState.setGlobalGids(mGlobalGids); 7768 7769 final int N = pkg.requestedPermissions.size(); 7770 for (int i=0; i<N; i++) { 7771 final String name = pkg.requestedPermissions.get(i); 7772 final BasePermission bp = mSettings.mPermissions.get(name); 7773 7774 if (DEBUG_INSTALL) { 7775 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7776 } 7777 7778 if (bp == null || bp.packageSetting == null) { 7779 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7780 Slog.w(TAG, "Unknown permission " + name 7781 + " in package " + pkg.packageName); 7782 } 7783 continue; 7784 } 7785 7786 final String perm = bp.name; 7787 boolean allowedSig = false; 7788 int grant = GRANT_DENIED; 7789 7790 // Keep track of app op permissions. 7791 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7792 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7793 if (pkgs == null) { 7794 pkgs = new ArraySet<>(); 7795 mAppOpPermissionPackages.put(bp.name, pkgs); 7796 } 7797 pkgs.add(pkg.packageName); 7798 } 7799 7800 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7801 switch (level) { 7802 case PermissionInfo.PROTECTION_NORMAL: { 7803 // For all apps normal permissions are install time ones. 7804 grant = GRANT_INSTALL; 7805 } break; 7806 7807 case PermissionInfo.PROTECTION_DANGEROUS: { 7808 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7809 // For legacy apps dangerous permissions are install time ones. 7810 grant = GRANT_INSTALL_LEGACY; 7811 } else if (ps.isSystem()) { 7812 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7813 if (origPermissions.hasInstallPermission(bp.name)) { 7814 // If a system app had an install permission, then the app was 7815 // upgraded and we grant the permissions as runtime to all users. 7816 grant = GRANT_UPGRADE; 7817 upgradeUserIds = currentUserIds; 7818 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7819 // If users changed since the last permissions update for a 7820 // system app, we grant the permission as runtime to the new users. 7821 grant = GRANT_UPGRADE; 7822 upgradeUserIds = currentUserIds; 7823 for (int userId : updatedUserIds) { 7824 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7825 } 7826 } else { 7827 // Otherwise, we grant the permission as runtime if the app 7828 // already had it, i.e. we preserve runtime permissions. 7829 grant = GRANT_RUNTIME; 7830 } 7831 } else if (origPermissions.hasInstallPermission(bp.name)) { 7832 // For legacy apps that became modern, install becomes runtime. 7833 grant = GRANT_UPGRADE; 7834 upgradeUserIds = currentUserIds; 7835 } else if (replace) { 7836 // For upgraded modern apps keep runtime permissions unchanged. 7837 grant = GRANT_RUNTIME; 7838 } 7839 } break; 7840 7841 case PermissionInfo.PROTECTION_SIGNATURE: { 7842 // For all apps signature permissions are install time ones. 7843 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7844 if (allowedSig) { 7845 grant = GRANT_INSTALL; 7846 } 7847 } break; 7848 } 7849 7850 if (DEBUG_INSTALL) { 7851 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7852 } 7853 7854 if (grant != GRANT_DENIED) { 7855 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7856 // If this is an existing, non-system package, then 7857 // we can't add any new permissions to it. 7858 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7859 // Except... if this is a permission that was added 7860 // to the platform (note: need to only do this when 7861 // updating the platform). 7862 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7863 grant = GRANT_DENIED; 7864 } 7865 } 7866 } 7867 7868 switch (grant) { 7869 case GRANT_INSTALL: { 7870 // Revoke this as runtime permission to handle the case of 7871 // a runtime permssion being downgraded to an install one. 7872 for (int userId : UserManagerService.getInstance().getUserIds()) { 7873 if (origPermissions.getRuntimePermissionState( 7874 bp.name, userId) != null) { 7875 // Revoke the runtime permission and clear the flags. 7876 origPermissions.revokeRuntimePermission(bp, userId); 7877 origPermissions.updatePermissionFlags(bp, userId, 7878 PackageManager.MASK_PERMISSION_FLAGS, 0); 7879 // If we revoked a permission permission, we have to write. 7880 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7881 changedRuntimePermissionUserIds, userId); 7882 } 7883 } 7884 // Grant an install permission. 7885 if (permissionsState.grantInstallPermission(bp) != 7886 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7887 changedInstallPermission = true; 7888 } 7889 } break; 7890 7891 case GRANT_INSTALL_LEGACY: { 7892 // Grant an install permission. 7893 if (permissionsState.grantInstallPermission(bp) != 7894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7895 changedInstallPermission = true; 7896 } 7897 } break; 7898 7899 case GRANT_RUNTIME: { 7900 // Grant previously granted runtime permissions. 7901 for (int userId : UserManagerService.getInstance().getUserIds()) { 7902 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7903 PermissionState permissionState = origPermissions 7904 .getRuntimePermissionState(bp.name, userId); 7905 final int flags = permissionState.getFlags(); 7906 if (permissionsState.grantRuntimePermission(bp, userId) == 7907 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7908 // If we cannot put the permission as it was, we have to write. 7909 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7910 changedRuntimePermissionUserIds, userId); 7911 } else { 7912 // System components not only get the permissions but 7913 // they are also fixed, so nothing can change that. 7914 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7915 ? flags 7916 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7917 // Propagate the permission flags. 7918 permissionsState.updatePermissionFlags(bp, userId, 7919 newFlags, newFlags); 7920 } 7921 } 7922 } 7923 } break; 7924 7925 case GRANT_UPGRADE: { 7926 // Grant runtime permissions for a previously held install permission. 7927 PermissionState permissionState = origPermissions 7928 .getInstallPermissionState(bp.name); 7929 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7930 7931 origPermissions.revokeInstallPermission(bp); 7932 // We will be transferring the permission flags, so clear them. 7933 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7934 PackageManager.MASK_PERMISSION_FLAGS, 0); 7935 7936 // If the permission is not to be promoted to runtime we ignore it and 7937 // also its other flags as they are not applicable to install permissions. 7938 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7939 for (int userId : upgradeUserIds) { 7940 if (permissionsState.grantRuntimePermission(bp, userId) != 7941 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7942 // System components not only get the permissions but 7943 // they are also fixed so nothing can change that. 7944 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7945 ? flags 7946 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7947 // Transfer the permission flags. 7948 permissionsState.updatePermissionFlags(bp, userId, 7949 newFlags, newFlags); 7950 // If we granted the permission, we have to write. 7951 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7952 changedRuntimePermissionUserIds, userId); 7953 } 7954 } 7955 } 7956 } break; 7957 7958 default: { 7959 if (packageOfInterest == null 7960 || packageOfInterest.equals(pkg.packageName)) { 7961 Slog.w(TAG, "Not granting permission " + perm 7962 + " to package " + pkg.packageName 7963 + " because it was previously installed without"); 7964 } 7965 } break; 7966 } 7967 } else { 7968 if (permissionsState.revokeInstallPermission(bp) != 7969 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7970 // Also drop the permission flags. 7971 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7972 PackageManager.MASK_PERMISSION_FLAGS, 0); 7973 changedInstallPermission = true; 7974 Slog.i(TAG, "Un-granting permission " + perm 7975 + " from package " + pkg.packageName 7976 + " (protectionLevel=" + bp.protectionLevel 7977 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7978 + ")"); 7979 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7980 // Don't print warning for app op permissions, since it is fine for them 7981 // not to be granted, there is a UI for the user to decide. 7982 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7983 Slog.w(TAG, "Not granting permission " + perm 7984 + " to package " + pkg.packageName 7985 + " (protectionLevel=" + bp.protectionLevel 7986 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7987 + ")"); 7988 } 7989 } 7990 } 7991 } 7992 7993 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7994 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7995 // This is the first that we have heard about this package, so the 7996 // permissions we have now selected are fixed until explicitly 7997 // changed. 7998 ps.installPermissionsFixed = true; 7999 } 8000 8001 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8002 8003 // Persist the runtime permissions state for users with changes. 8004 for (int userId : changedRuntimePermissionUserIds) { 8005 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8006 } 8007 } 8008 8009 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8010 boolean allowed = false; 8011 final int NP = PackageParser.NEW_PERMISSIONS.length; 8012 for (int ip=0; ip<NP; ip++) { 8013 final PackageParser.NewPermissionInfo npi 8014 = PackageParser.NEW_PERMISSIONS[ip]; 8015 if (npi.name.equals(perm) 8016 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8017 allowed = true; 8018 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8019 + pkg.packageName); 8020 break; 8021 } 8022 } 8023 return allowed; 8024 } 8025 8026 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8027 BasePermission bp, PermissionsState origPermissions) { 8028 boolean allowed; 8029 allowed = (compareSignatures( 8030 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8031 == PackageManager.SIGNATURE_MATCH) 8032 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8033 == PackageManager.SIGNATURE_MATCH); 8034 if (!allowed && (bp.protectionLevel 8035 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8036 if (isSystemApp(pkg)) { 8037 // For updated system applications, a system permission 8038 // is granted only if it had been defined by the original application. 8039 if (pkg.isUpdatedSystemApp()) { 8040 final PackageSetting sysPs = mSettings 8041 .getDisabledSystemPkgLPr(pkg.packageName); 8042 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8043 // If the original was granted this permission, we take 8044 // that grant decision as read and propagate it to the 8045 // update. 8046 if (sysPs.isPrivileged()) { 8047 allowed = true; 8048 } 8049 } else { 8050 // The system apk may have been updated with an older 8051 // version of the one on the data partition, but which 8052 // granted a new system permission that it didn't have 8053 // before. In this case we do want to allow the app to 8054 // now get the new permission if the ancestral apk is 8055 // privileged to get it. 8056 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8057 for (int j=0; 8058 j<sysPs.pkg.requestedPermissions.size(); j++) { 8059 if (perm.equals( 8060 sysPs.pkg.requestedPermissions.get(j))) { 8061 allowed = true; 8062 break; 8063 } 8064 } 8065 } 8066 } 8067 } else { 8068 allowed = isPrivilegedApp(pkg); 8069 } 8070 } 8071 } 8072 if (!allowed && (bp.protectionLevel 8073 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8074 // For development permissions, a development permission 8075 // is granted only if it was already granted. 8076 allowed = origPermissions.hasInstallPermission(perm); 8077 } 8078 return allowed; 8079 } 8080 8081 final class ActivityIntentResolver 8082 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8084 boolean defaultOnly, int userId) { 8085 if (!sUserManager.exists(userId)) return null; 8086 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8087 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8088 } 8089 8090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8091 int userId) { 8092 if (!sUserManager.exists(userId)) return null; 8093 mFlags = flags; 8094 return super.queryIntent(intent, resolvedType, 8095 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8096 } 8097 8098 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8099 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8100 if (!sUserManager.exists(userId)) return null; 8101 if (packageActivities == null) { 8102 return null; 8103 } 8104 mFlags = flags; 8105 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8106 final int N = packageActivities.size(); 8107 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8108 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8109 8110 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8111 for (int i = 0; i < N; ++i) { 8112 intentFilters = packageActivities.get(i).intents; 8113 if (intentFilters != null && intentFilters.size() > 0) { 8114 PackageParser.ActivityIntentInfo[] array = 8115 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8116 intentFilters.toArray(array); 8117 listCut.add(array); 8118 } 8119 } 8120 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8121 } 8122 8123 public final void addActivity(PackageParser.Activity a, String type) { 8124 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8125 mActivities.put(a.getComponentName(), a); 8126 if (DEBUG_SHOW_INFO) 8127 Log.v( 8128 TAG, " " + type + " " + 8129 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8130 if (DEBUG_SHOW_INFO) 8131 Log.v(TAG, " Class=" + a.info.name); 8132 final int NI = a.intents.size(); 8133 for (int j=0; j<NI; j++) { 8134 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8135 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8136 intent.setPriority(0); 8137 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8138 + a.className + " with priority > 0, forcing to 0"); 8139 } 8140 if (DEBUG_SHOW_INFO) { 8141 Log.v(TAG, " IntentFilter:"); 8142 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8143 } 8144 if (!intent.debugCheck()) { 8145 Log.w(TAG, "==> For Activity " + a.info.name); 8146 } 8147 addFilter(intent); 8148 } 8149 } 8150 8151 public final void removeActivity(PackageParser.Activity a, String type) { 8152 mActivities.remove(a.getComponentName()); 8153 if (DEBUG_SHOW_INFO) { 8154 Log.v(TAG, " " + type + " " 8155 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8156 : a.info.name) + ":"); 8157 Log.v(TAG, " Class=" + a.info.name); 8158 } 8159 final int NI = a.intents.size(); 8160 for (int j=0; j<NI; j++) { 8161 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8162 if (DEBUG_SHOW_INFO) { 8163 Log.v(TAG, " IntentFilter:"); 8164 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8165 } 8166 removeFilter(intent); 8167 } 8168 } 8169 8170 @Override 8171 protected boolean allowFilterResult( 8172 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8173 ActivityInfo filterAi = filter.activity.info; 8174 for (int i=dest.size()-1; i>=0; i--) { 8175 ActivityInfo destAi = dest.get(i).activityInfo; 8176 if (destAi.name == filterAi.name 8177 && destAi.packageName == filterAi.packageName) { 8178 return false; 8179 } 8180 } 8181 return true; 8182 } 8183 8184 @Override 8185 protected ActivityIntentInfo[] newArray(int size) { 8186 return new ActivityIntentInfo[size]; 8187 } 8188 8189 @Override 8190 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8191 if (!sUserManager.exists(userId)) return true; 8192 PackageParser.Package p = filter.activity.owner; 8193 if (p != null) { 8194 PackageSetting ps = (PackageSetting)p.mExtras; 8195 if (ps != null) { 8196 // System apps are never considered stopped for purposes of 8197 // filtering, because there may be no way for the user to 8198 // actually re-launch them. 8199 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8200 && ps.getStopped(userId); 8201 } 8202 } 8203 return false; 8204 } 8205 8206 @Override 8207 protected boolean isPackageForFilter(String packageName, 8208 PackageParser.ActivityIntentInfo info) { 8209 return packageName.equals(info.activity.owner.packageName); 8210 } 8211 8212 @Override 8213 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8214 int match, int userId) { 8215 if (!sUserManager.exists(userId)) return null; 8216 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8217 return null; 8218 } 8219 final PackageParser.Activity activity = info.activity; 8220 if (mSafeMode && (activity.info.applicationInfo.flags 8221 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8222 return null; 8223 } 8224 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8225 if (ps == null) { 8226 return null; 8227 } 8228 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8229 ps.readUserState(userId), userId); 8230 if (ai == null) { 8231 return null; 8232 } 8233 final ResolveInfo res = new ResolveInfo(); 8234 res.activityInfo = ai; 8235 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8236 res.filter = info; 8237 } 8238 if (info != null) { 8239 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8240 } 8241 res.priority = info.getPriority(); 8242 res.preferredOrder = activity.owner.mPreferredOrder; 8243 //System.out.println("Result: " + res.activityInfo.className + 8244 // " = " + res.priority); 8245 res.match = match; 8246 res.isDefault = info.hasDefault; 8247 res.labelRes = info.labelRes; 8248 res.nonLocalizedLabel = info.nonLocalizedLabel; 8249 if (userNeedsBadging(userId)) { 8250 res.noResourceId = true; 8251 } else { 8252 res.icon = info.icon; 8253 } 8254 res.iconResourceId = info.icon; 8255 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8256 return res; 8257 } 8258 8259 @Override 8260 protected void sortResults(List<ResolveInfo> results) { 8261 Collections.sort(results, mResolvePrioritySorter); 8262 } 8263 8264 @Override 8265 protected void dumpFilter(PrintWriter out, String prefix, 8266 PackageParser.ActivityIntentInfo filter) { 8267 out.print(prefix); out.print( 8268 Integer.toHexString(System.identityHashCode(filter.activity))); 8269 out.print(' '); 8270 filter.activity.printComponentShortName(out); 8271 out.print(" filter "); 8272 out.println(Integer.toHexString(System.identityHashCode(filter))); 8273 } 8274 8275 @Override 8276 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8277 return filter.activity; 8278 } 8279 8280 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8281 PackageParser.Activity activity = (PackageParser.Activity)label; 8282 out.print(prefix); out.print( 8283 Integer.toHexString(System.identityHashCode(activity))); 8284 out.print(' '); 8285 activity.printComponentShortName(out); 8286 if (count > 1) { 8287 out.print(" ("); out.print(count); out.print(" filters)"); 8288 } 8289 out.println(); 8290 } 8291 8292// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8293// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8294// final List<ResolveInfo> retList = Lists.newArrayList(); 8295// while (i.hasNext()) { 8296// final ResolveInfo resolveInfo = i.next(); 8297// if (isEnabledLP(resolveInfo.activityInfo)) { 8298// retList.add(resolveInfo); 8299// } 8300// } 8301// return retList; 8302// } 8303 8304 // Keys are String (activity class name), values are Activity. 8305 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8306 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8307 private int mFlags; 8308 } 8309 8310 private final class ServiceIntentResolver 8311 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8312 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8313 boolean defaultOnly, int userId) { 8314 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8315 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8316 } 8317 8318 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8319 int userId) { 8320 if (!sUserManager.exists(userId)) return null; 8321 mFlags = flags; 8322 return super.queryIntent(intent, resolvedType, 8323 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8324 } 8325 8326 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8327 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8328 if (!sUserManager.exists(userId)) return null; 8329 if (packageServices == null) { 8330 return null; 8331 } 8332 mFlags = flags; 8333 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8334 final int N = packageServices.size(); 8335 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8336 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8337 8338 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8339 for (int i = 0; i < N; ++i) { 8340 intentFilters = packageServices.get(i).intents; 8341 if (intentFilters != null && intentFilters.size() > 0) { 8342 PackageParser.ServiceIntentInfo[] array = 8343 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8344 intentFilters.toArray(array); 8345 listCut.add(array); 8346 } 8347 } 8348 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8349 } 8350 8351 public final void addService(PackageParser.Service s) { 8352 mServices.put(s.getComponentName(), s); 8353 if (DEBUG_SHOW_INFO) { 8354 Log.v(TAG, " " 8355 + (s.info.nonLocalizedLabel != null 8356 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8357 Log.v(TAG, " Class=" + s.info.name); 8358 } 8359 final int NI = s.intents.size(); 8360 int j; 8361 for (j=0; j<NI; j++) { 8362 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8363 if (DEBUG_SHOW_INFO) { 8364 Log.v(TAG, " IntentFilter:"); 8365 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8366 } 8367 if (!intent.debugCheck()) { 8368 Log.w(TAG, "==> For Service " + s.info.name); 8369 } 8370 addFilter(intent); 8371 } 8372 } 8373 8374 public final void removeService(PackageParser.Service s) { 8375 mServices.remove(s.getComponentName()); 8376 if (DEBUG_SHOW_INFO) { 8377 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8378 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8379 Log.v(TAG, " Class=" + s.info.name); 8380 } 8381 final int NI = s.intents.size(); 8382 int j; 8383 for (j=0; j<NI; j++) { 8384 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8385 if (DEBUG_SHOW_INFO) { 8386 Log.v(TAG, " IntentFilter:"); 8387 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8388 } 8389 removeFilter(intent); 8390 } 8391 } 8392 8393 @Override 8394 protected boolean allowFilterResult( 8395 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8396 ServiceInfo filterSi = filter.service.info; 8397 for (int i=dest.size()-1; i>=0; i--) { 8398 ServiceInfo destAi = dest.get(i).serviceInfo; 8399 if (destAi.name == filterSi.name 8400 && destAi.packageName == filterSi.packageName) { 8401 return false; 8402 } 8403 } 8404 return true; 8405 } 8406 8407 @Override 8408 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8409 return new PackageParser.ServiceIntentInfo[size]; 8410 } 8411 8412 @Override 8413 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8414 if (!sUserManager.exists(userId)) return true; 8415 PackageParser.Package p = filter.service.owner; 8416 if (p != null) { 8417 PackageSetting ps = (PackageSetting)p.mExtras; 8418 if (ps != null) { 8419 // System apps are never considered stopped for purposes of 8420 // filtering, because there may be no way for the user to 8421 // actually re-launch them. 8422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8423 && ps.getStopped(userId); 8424 } 8425 } 8426 return false; 8427 } 8428 8429 @Override 8430 protected boolean isPackageForFilter(String packageName, 8431 PackageParser.ServiceIntentInfo info) { 8432 return packageName.equals(info.service.owner.packageName); 8433 } 8434 8435 @Override 8436 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8437 int match, int userId) { 8438 if (!sUserManager.exists(userId)) return null; 8439 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8440 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8441 return null; 8442 } 8443 final PackageParser.Service service = info.service; 8444 if (mSafeMode && (service.info.applicationInfo.flags 8445 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8446 return null; 8447 } 8448 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8449 if (ps == null) { 8450 return null; 8451 } 8452 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8453 ps.readUserState(userId), userId); 8454 if (si == null) { 8455 return null; 8456 } 8457 final ResolveInfo res = new ResolveInfo(); 8458 res.serviceInfo = si; 8459 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8460 res.filter = filter; 8461 } 8462 res.priority = info.getPriority(); 8463 res.preferredOrder = service.owner.mPreferredOrder; 8464 res.match = match; 8465 res.isDefault = info.hasDefault; 8466 res.labelRes = info.labelRes; 8467 res.nonLocalizedLabel = info.nonLocalizedLabel; 8468 res.icon = info.icon; 8469 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8470 return res; 8471 } 8472 8473 @Override 8474 protected void sortResults(List<ResolveInfo> results) { 8475 Collections.sort(results, mResolvePrioritySorter); 8476 } 8477 8478 @Override 8479 protected void dumpFilter(PrintWriter out, String prefix, 8480 PackageParser.ServiceIntentInfo filter) { 8481 out.print(prefix); out.print( 8482 Integer.toHexString(System.identityHashCode(filter.service))); 8483 out.print(' '); 8484 filter.service.printComponentShortName(out); 8485 out.print(" filter "); 8486 out.println(Integer.toHexString(System.identityHashCode(filter))); 8487 } 8488 8489 @Override 8490 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8491 return filter.service; 8492 } 8493 8494 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8495 PackageParser.Service service = (PackageParser.Service)label; 8496 out.print(prefix); out.print( 8497 Integer.toHexString(System.identityHashCode(service))); 8498 out.print(' '); 8499 service.printComponentShortName(out); 8500 if (count > 1) { 8501 out.print(" ("); out.print(count); out.print(" filters)"); 8502 } 8503 out.println(); 8504 } 8505 8506// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8507// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8508// final List<ResolveInfo> retList = Lists.newArrayList(); 8509// while (i.hasNext()) { 8510// final ResolveInfo resolveInfo = (ResolveInfo) i; 8511// if (isEnabledLP(resolveInfo.serviceInfo)) { 8512// retList.add(resolveInfo); 8513// } 8514// } 8515// return retList; 8516// } 8517 8518 // Keys are String (activity class name), values are Activity. 8519 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8520 = new ArrayMap<ComponentName, PackageParser.Service>(); 8521 private int mFlags; 8522 }; 8523 8524 private final class ProviderIntentResolver 8525 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8526 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8527 boolean defaultOnly, int userId) { 8528 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8529 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8530 } 8531 8532 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8533 int userId) { 8534 if (!sUserManager.exists(userId)) 8535 return null; 8536 mFlags = flags; 8537 return super.queryIntent(intent, resolvedType, 8538 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8539 } 8540 8541 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8542 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8543 if (!sUserManager.exists(userId)) 8544 return null; 8545 if (packageProviders == null) { 8546 return null; 8547 } 8548 mFlags = flags; 8549 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8550 final int N = packageProviders.size(); 8551 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8552 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8553 8554 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8555 for (int i = 0; i < N; ++i) { 8556 intentFilters = packageProviders.get(i).intents; 8557 if (intentFilters != null && intentFilters.size() > 0) { 8558 PackageParser.ProviderIntentInfo[] array = 8559 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8560 intentFilters.toArray(array); 8561 listCut.add(array); 8562 } 8563 } 8564 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8565 } 8566 8567 public final void addProvider(PackageParser.Provider p) { 8568 if (mProviders.containsKey(p.getComponentName())) { 8569 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8570 return; 8571 } 8572 8573 mProviders.put(p.getComponentName(), p); 8574 if (DEBUG_SHOW_INFO) { 8575 Log.v(TAG, " " 8576 + (p.info.nonLocalizedLabel != null 8577 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8578 Log.v(TAG, " Class=" + p.info.name); 8579 } 8580 final int NI = p.intents.size(); 8581 int j; 8582 for (j = 0; j < NI; j++) { 8583 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8584 if (DEBUG_SHOW_INFO) { 8585 Log.v(TAG, " IntentFilter:"); 8586 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8587 } 8588 if (!intent.debugCheck()) { 8589 Log.w(TAG, "==> For Provider " + p.info.name); 8590 } 8591 addFilter(intent); 8592 } 8593 } 8594 8595 public final void removeProvider(PackageParser.Provider p) { 8596 mProviders.remove(p.getComponentName()); 8597 if (DEBUG_SHOW_INFO) { 8598 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8599 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8600 Log.v(TAG, " Class=" + p.info.name); 8601 } 8602 final int NI = p.intents.size(); 8603 int j; 8604 for (j = 0; j < NI; j++) { 8605 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8606 if (DEBUG_SHOW_INFO) { 8607 Log.v(TAG, " IntentFilter:"); 8608 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8609 } 8610 removeFilter(intent); 8611 } 8612 } 8613 8614 @Override 8615 protected boolean allowFilterResult( 8616 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8617 ProviderInfo filterPi = filter.provider.info; 8618 for (int i = dest.size() - 1; i >= 0; i--) { 8619 ProviderInfo destPi = dest.get(i).providerInfo; 8620 if (destPi.name == filterPi.name 8621 && destPi.packageName == filterPi.packageName) { 8622 return false; 8623 } 8624 } 8625 return true; 8626 } 8627 8628 @Override 8629 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8630 return new PackageParser.ProviderIntentInfo[size]; 8631 } 8632 8633 @Override 8634 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8635 if (!sUserManager.exists(userId)) 8636 return true; 8637 PackageParser.Package p = filter.provider.owner; 8638 if (p != null) { 8639 PackageSetting ps = (PackageSetting) p.mExtras; 8640 if (ps != null) { 8641 // System apps are never considered stopped for purposes of 8642 // filtering, because there may be no way for the user to 8643 // actually re-launch them. 8644 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8645 && ps.getStopped(userId); 8646 } 8647 } 8648 return false; 8649 } 8650 8651 @Override 8652 protected boolean isPackageForFilter(String packageName, 8653 PackageParser.ProviderIntentInfo info) { 8654 return packageName.equals(info.provider.owner.packageName); 8655 } 8656 8657 @Override 8658 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8659 int match, int userId) { 8660 if (!sUserManager.exists(userId)) 8661 return null; 8662 final PackageParser.ProviderIntentInfo info = filter; 8663 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8664 return null; 8665 } 8666 final PackageParser.Provider provider = info.provider; 8667 if (mSafeMode && (provider.info.applicationInfo.flags 8668 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8669 return null; 8670 } 8671 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8672 if (ps == null) { 8673 return null; 8674 } 8675 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8676 ps.readUserState(userId), userId); 8677 if (pi == null) { 8678 return null; 8679 } 8680 final ResolveInfo res = new ResolveInfo(); 8681 res.providerInfo = pi; 8682 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8683 res.filter = filter; 8684 } 8685 res.priority = info.getPriority(); 8686 res.preferredOrder = provider.owner.mPreferredOrder; 8687 res.match = match; 8688 res.isDefault = info.hasDefault; 8689 res.labelRes = info.labelRes; 8690 res.nonLocalizedLabel = info.nonLocalizedLabel; 8691 res.icon = info.icon; 8692 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8693 return res; 8694 } 8695 8696 @Override 8697 protected void sortResults(List<ResolveInfo> results) { 8698 Collections.sort(results, mResolvePrioritySorter); 8699 } 8700 8701 @Override 8702 protected void dumpFilter(PrintWriter out, String prefix, 8703 PackageParser.ProviderIntentInfo filter) { 8704 out.print(prefix); 8705 out.print( 8706 Integer.toHexString(System.identityHashCode(filter.provider))); 8707 out.print(' '); 8708 filter.provider.printComponentShortName(out); 8709 out.print(" filter "); 8710 out.println(Integer.toHexString(System.identityHashCode(filter))); 8711 } 8712 8713 @Override 8714 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8715 return filter.provider; 8716 } 8717 8718 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8719 PackageParser.Provider provider = (PackageParser.Provider)label; 8720 out.print(prefix); out.print( 8721 Integer.toHexString(System.identityHashCode(provider))); 8722 out.print(' '); 8723 provider.printComponentShortName(out); 8724 if (count > 1) { 8725 out.print(" ("); out.print(count); out.print(" filters)"); 8726 } 8727 out.println(); 8728 } 8729 8730 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8731 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8732 private int mFlags; 8733 }; 8734 8735 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8736 new Comparator<ResolveInfo>() { 8737 public int compare(ResolveInfo r1, ResolveInfo r2) { 8738 int v1 = r1.priority; 8739 int v2 = r2.priority; 8740 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8741 if (v1 != v2) { 8742 return (v1 > v2) ? -1 : 1; 8743 } 8744 v1 = r1.preferredOrder; 8745 v2 = r2.preferredOrder; 8746 if (v1 != v2) { 8747 return (v1 > v2) ? -1 : 1; 8748 } 8749 if (r1.isDefault != r2.isDefault) { 8750 return r1.isDefault ? -1 : 1; 8751 } 8752 v1 = r1.match; 8753 v2 = r2.match; 8754 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8755 if (v1 != v2) { 8756 return (v1 > v2) ? -1 : 1; 8757 } 8758 if (r1.system != r2.system) { 8759 return r1.system ? -1 : 1; 8760 } 8761 return 0; 8762 } 8763 }; 8764 8765 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8766 new Comparator<ProviderInfo>() { 8767 public int compare(ProviderInfo p1, ProviderInfo p2) { 8768 final int v1 = p1.initOrder; 8769 final int v2 = p2.initOrder; 8770 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8771 } 8772 }; 8773 8774 final void sendPackageBroadcast(final String action, final String pkg, 8775 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8776 final int[] userIds) { 8777 mHandler.post(new Runnable() { 8778 @Override 8779 public void run() { 8780 try { 8781 final IActivityManager am = ActivityManagerNative.getDefault(); 8782 if (am == null) return; 8783 final int[] resolvedUserIds; 8784 if (userIds == null) { 8785 resolvedUserIds = am.getRunningUserIds(); 8786 } else { 8787 resolvedUserIds = userIds; 8788 } 8789 for (int id : resolvedUserIds) { 8790 final Intent intent = new Intent(action, 8791 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8792 if (extras != null) { 8793 intent.putExtras(extras); 8794 } 8795 if (targetPkg != null) { 8796 intent.setPackage(targetPkg); 8797 } 8798 // Modify the UID when posting to other users 8799 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8800 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8801 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8802 intent.putExtra(Intent.EXTRA_UID, uid); 8803 } 8804 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8805 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8806 if (DEBUG_BROADCASTS) { 8807 RuntimeException here = new RuntimeException("here"); 8808 here.fillInStackTrace(); 8809 Slog.d(TAG, "Sending to user " + id + ": " 8810 + intent.toShortString(false, true, false, false) 8811 + " " + intent.getExtras(), here); 8812 } 8813 am.broadcastIntent(null, intent, null, finishedReceiver, 8814 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8815 null, finishedReceiver != null, false, id); 8816 } 8817 } catch (RemoteException ex) { 8818 } 8819 } 8820 }); 8821 } 8822 8823 /** 8824 * Check if the external storage media is available. This is true if there 8825 * is a mounted external storage medium or if the external storage is 8826 * emulated. 8827 */ 8828 private boolean isExternalMediaAvailable() { 8829 return mMediaMounted || Environment.isExternalStorageEmulated(); 8830 } 8831 8832 @Override 8833 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8834 // writer 8835 synchronized (mPackages) { 8836 if (!isExternalMediaAvailable()) { 8837 // If the external storage is no longer mounted at this point, 8838 // the caller may not have been able to delete all of this 8839 // packages files and can not delete any more. Bail. 8840 return null; 8841 } 8842 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8843 if (lastPackage != null) { 8844 pkgs.remove(lastPackage); 8845 } 8846 if (pkgs.size() > 0) { 8847 return pkgs.get(0); 8848 } 8849 } 8850 return null; 8851 } 8852 8853 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8854 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8855 userId, andCode ? 1 : 0, packageName); 8856 if (mSystemReady) { 8857 msg.sendToTarget(); 8858 } else { 8859 if (mPostSystemReadyMessages == null) { 8860 mPostSystemReadyMessages = new ArrayList<>(); 8861 } 8862 mPostSystemReadyMessages.add(msg); 8863 } 8864 } 8865 8866 void startCleaningPackages() { 8867 // reader 8868 synchronized (mPackages) { 8869 if (!isExternalMediaAvailable()) { 8870 return; 8871 } 8872 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8873 return; 8874 } 8875 } 8876 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8877 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8878 IActivityManager am = ActivityManagerNative.getDefault(); 8879 if (am != null) { 8880 try { 8881 am.startService(null, intent, null, UserHandle.USER_OWNER); 8882 } catch (RemoteException e) { 8883 } 8884 } 8885 } 8886 8887 @Override 8888 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8889 int installFlags, String installerPackageName, VerificationParams verificationParams, 8890 String packageAbiOverride) { 8891 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8892 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8893 } 8894 8895 @Override 8896 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8897 int installFlags, String installerPackageName, VerificationParams verificationParams, 8898 String packageAbiOverride, int userId) { 8899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8900 8901 final int callingUid = Binder.getCallingUid(); 8902 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8903 8904 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8905 try { 8906 if (observer != null) { 8907 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8908 } 8909 } catch (RemoteException re) { 8910 } 8911 return; 8912 } 8913 8914 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8915 installFlags |= PackageManager.INSTALL_FROM_ADB; 8916 8917 } else { 8918 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8919 // about installerPackageName. 8920 8921 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8922 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8923 } 8924 8925 UserHandle user; 8926 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8927 user = UserHandle.ALL; 8928 } else { 8929 user = new UserHandle(userId); 8930 } 8931 8932 // Only system components can circumvent runtime permissions when installing. 8933 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8934 && mContext.checkCallingOrSelfPermission(Manifest.permission 8935 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8936 throw new SecurityException("You need the " 8937 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8938 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8939 } 8940 8941 verificationParams.setInstallerUid(callingUid); 8942 8943 final File originFile = new File(originPath); 8944 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8945 8946 final Message msg = mHandler.obtainMessage(INIT_COPY); 8947 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8948 null, verificationParams, user, packageAbiOverride); 8949 mHandler.sendMessage(msg); 8950 } 8951 8952 void installStage(String packageName, File stagedDir, String stagedCid, 8953 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8954 String installerPackageName, int installerUid, UserHandle user) { 8955 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8956 params.referrerUri, installerUid, null); 8957 8958 final OriginInfo origin; 8959 if (stagedDir != null) { 8960 origin = OriginInfo.fromStagedFile(stagedDir); 8961 } else { 8962 origin = OriginInfo.fromStagedContainer(stagedCid); 8963 } 8964 8965 final Message msg = mHandler.obtainMessage(INIT_COPY); 8966 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8967 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8968 mHandler.sendMessage(msg); 8969 } 8970 8971 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8972 Bundle extras = new Bundle(1); 8973 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8974 8975 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8976 packageName, extras, null, null, new int[] {userId}); 8977 try { 8978 IActivityManager am = ActivityManagerNative.getDefault(); 8979 final boolean isSystem = 8980 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8981 if (isSystem && am.isUserRunning(userId, false)) { 8982 // The just-installed/enabled app is bundled on the system, so presumed 8983 // to be able to run automatically without needing an explicit launch. 8984 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8985 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8986 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8987 .setPackage(packageName); 8988 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8989 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8990 } 8991 } catch (RemoteException e) { 8992 // shouldn't happen 8993 Slog.w(TAG, "Unable to bootstrap installed package", e); 8994 } 8995 } 8996 8997 @Override 8998 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8999 int userId) { 9000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9001 PackageSetting pkgSetting; 9002 final int uid = Binder.getCallingUid(); 9003 enforceCrossUserPermission(uid, userId, true, true, 9004 "setApplicationHiddenSetting for user " + userId); 9005 9006 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9007 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9008 return false; 9009 } 9010 9011 long callingId = Binder.clearCallingIdentity(); 9012 try { 9013 boolean sendAdded = false; 9014 boolean sendRemoved = false; 9015 // writer 9016 synchronized (mPackages) { 9017 pkgSetting = mSettings.mPackages.get(packageName); 9018 if (pkgSetting == null) { 9019 return false; 9020 } 9021 if (pkgSetting.getHidden(userId) != hidden) { 9022 pkgSetting.setHidden(hidden, userId); 9023 mSettings.writePackageRestrictionsLPr(userId); 9024 if (hidden) { 9025 sendRemoved = true; 9026 } else { 9027 sendAdded = true; 9028 } 9029 } 9030 } 9031 if (sendAdded) { 9032 sendPackageAddedForUser(packageName, pkgSetting, userId); 9033 return true; 9034 } 9035 if (sendRemoved) { 9036 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9037 "hiding pkg"); 9038 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9039 } 9040 } finally { 9041 Binder.restoreCallingIdentity(callingId); 9042 } 9043 return false; 9044 } 9045 9046 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9047 int userId) { 9048 final PackageRemovedInfo info = new PackageRemovedInfo(); 9049 info.removedPackage = packageName; 9050 info.removedUsers = new int[] {userId}; 9051 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9052 info.sendBroadcast(false, false, false); 9053 } 9054 9055 /** 9056 * Returns true if application is not found or there was an error. Otherwise it returns 9057 * the hidden state of the package for the given user. 9058 */ 9059 @Override 9060 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9062 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9063 false, "getApplicationHidden for user " + userId); 9064 PackageSetting pkgSetting; 9065 long callingId = Binder.clearCallingIdentity(); 9066 try { 9067 // writer 9068 synchronized (mPackages) { 9069 pkgSetting = mSettings.mPackages.get(packageName); 9070 if (pkgSetting == null) { 9071 return true; 9072 } 9073 return pkgSetting.getHidden(userId); 9074 } 9075 } finally { 9076 Binder.restoreCallingIdentity(callingId); 9077 } 9078 } 9079 9080 /** 9081 * @hide 9082 */ 9083 @Override 9084 public int installExistingPackageAsUser(String packageName, int userId) { 9085 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9086 null); 9087 PackageSetting pkgSetting; 9088 final int uid = Binder.getCallingUid(); 9089 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9090 + userId); 9091 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9092 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9093 } 9094 9095 long callingId = Binder.clearCallingIdentity(); 9096 try { 9097 boolean sendAdded = false; 9098 9099 // writer 9100 synchronized (mPackages) { 9101 pkgSetting = mSettings.mPackages.get(packageName); 9102 if (pkgSetting == null) { 9103 return PackageManager.INSTALL_FAILED_INVALID_URI; 9104 } 9105 if (!pkgSetting.getInstalled(userId)) { 9106 pkgSetting.setInstalled(true, userId); 9107 pkgSetting.setHidden(false, userId); 9108 mSettings.writePackageRestrictionsLPr(userId); 9109 sendAdded = true; 9110 } 9111 } 9112 9113 if (sendAdded) { 9114 sendPackageAddedForUser(packageName, pkgSetting, userId); 9115 } 9116 } finally { 9117 Binder.restoreCallingIdentity(callingId); 9118 } 9119 9120 return PackageManager.INSTALL_SUCCEEDED; 9121 } 9122 9123 boolean isUserRestricted(int userId, String restrictionKey) { 9124 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9125 if (restrictions.getBoolean(restrictionKey, false)) { 9126 Log.w(TAG, "User is restricted: " + restrictionKey); 9127 return true; 9128 } 9129 return false; 9130 } 9131 9132 @Override 9133 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9134 mContext.enforceCallingOrSelfPermission( 9135 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9136 "Only package verification agents can verify applications"); 9137 9138 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9139 final PackageVerificationResponse response = new PackageVerificationResponse( 9140 verificationCode, Binder.getCallingUid()); 9141 msg.arg1 = id; 9142 msg.obj = response; 9143 mHandler.sendMessage(msg); 9144 } 9145 9146 @Override 9147 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9148 long millisecondsToDelay) { 9149 mContext.enforceCallingOrSelfPermission( 9150 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9151 "Only package verification agents can extend verification timeouts"); 9152 9153 final PackageVerificationState state = mPendingVerification.get(id); 9154 final PackageVerificationResponse response = new PackageVerificationResponse( 9155 verificationCodeAtTimeout, Binder.getCallingUid()); 9156 9157 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9158 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9159 } 9160 if (millisecondsToDelay < 0) { 9161 millisecondsToDelay = 0; 9162 } 9163 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9164 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9165 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9166 } 9167 9168 if ((state != null) && !state.timeoutExtended()) { 9169 state.extendTimeout(); 9170 9171 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9172 msg.arg1 = id; 9173 msg.obj = response; 9174 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9175 } 9176 } 9177 9178 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9179 int verificationCode, UserHandle user) { 9180 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9181 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9182 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9183 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9184 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9185 9186 mContext.sendBroadcastAsUser(intent, user, 9187 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9188 } 9189 9190 private ComponentName matchComponentForVerifier(String packageName, 9191 List<ResolveInfo> receivers) { 9192 ActivityInfo targetReceiver = null; 9193 9194 final int NR = receivers.size(); 9195 for (int i = 0; i < NR; i++) { 9196 final ResolveInfo info = receivers.get(i); 9197 if (info.activityInfo == null) { 9198 continue; 9199 } 9200 9201 if (packageName.equals(info.activityInfo.packageName)) { 9202 targetReceiver = info.activityInfo; 9203 break; 9204 } 9205 } 9206 9207 if (targetReceiver == null) { 9208 return null; 9209 } 9210 9211 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9212 } 9213 9214 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9215 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9216 if (pkgInfo.verifiers.length == 0) { 9217 return null; 9218 } 9219 9220 final int N = pkgInfo.verifiers.length; 9221 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9222 for (int i = 0; i < N; i++) { 9223 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9224 9225 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9226 receivers); 9227 if (comp == null) { 9228 continue; 9229 } 9230 9231 final int verifierUid = getUidForVerifier(verifierInfo); 9232 if (verifierUid == -1) { 9233 continue; 9234 } 9235 9236 if (DEBUG_VERIFY) { 9237 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9238 + " with the correct signature"); 9239 } 9240 sufficientVerifiers.add(comp); 9241 verificationState.addSufficientVerifier(verifierUid); 9242 } 9243 9244 return sufficientVerifiers; 9245 } 9246 9247 private int getUidForVerifier(VerifierInfo verifierInfo) { 9248 synchronized (mPackages) { 9249 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9250 if (pkg == null) { 9251 return -1; 9252 } else if (pkg.mSignatures.length != 1) { 9253 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9254 + " has more than one signature; ignoring"); 9255 return -1; 9256 } 9257 9258 /* 9259 * If the public key of the package's signature does not match 9260 * our expected public key, then this is a different package and 9261 * we should skip. 9262 */ 9263 9264 final byte[] expectedPublicKey; 9265 try { 9266 final Signature verifierSig = pkg.mSignatures[0]; 9267 final PublicKey publicKey = verifierSig.getPublicKey(); 9268 expectedPublicKey = publicKey.getEncoded(); 9269 } catch (CertificateException e) { 9270 return -1; 9271 } 9272 9273 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9274 9275 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9276 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9277 + " does not have the expected public key; ignoring"); 9278 return -1; 9279 } 9280 9281 return pkg.applicationInfo.uid; 9282 } 9283 } 9284 9285 @Override 9286 public void finishPackageInstall(int token) { 9287 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9288 9289 if (DEBUG_INSTALL) { 9290 Slog.v(TAG, "BM finishing package install for " + token); 9291 } 9292 9293 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9294 mHandler.sendMessage(msg); 9295 } 9296 9297 /** 9298 * Get the verification agent timeout. 9299 * 9300 * @return verification timeout in milliseconds 9301 */ 9302 private long getVerificationTimeout() { 9303 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9304 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9305 DEFAULT_VERIFICATION_TIMEOUT); 9306 } 9307 9308 /** 9309 * Get the default verification agent response code. 9310 * 9311 * @return default verification response code 9312 */ 9313 private int getDefaultVerificationResponse() { 9314 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9315 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9316 DEFAULT_VERIFICATION_RESPONSE); 9317 } 9318 9319 /** 9320 * Check whether or not package verification has been enabled. 9321 * 9322 * @return true if verification should be performed 9323 */ 9324 private boolean isVerificationEnabled(int userId, int installFlags) { 9325 if (!DEFAULT_VERIFY_ENABLE) { 9326 return false; 9327 } 9328 9329 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9330 9331 // Check if installing from ADB 9332 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9333 // Do not run verification in a test harness environment 9334 if (ActivityManager.isRunningInTestHarness()) { 9335 return false; 9336 } 9337 if (ensureVerifyAppsEnabled) { 9338 return true; 9339 } 9340 // Check if the developer does not want package verification for ADB installs 9341 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9342 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9343 return false; 9344 } 9345 } 9346 9347 if (ensureVerifyAppsEnabled) { 9348 return true; 9349 } 9350 9351 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9352 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9353 } 9354 9355 @Override 9356 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9357 throws RemoteException { 9358 mContext.enforceCallingOrSelfPermission( 9359 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9360 "Only intentfilter verification agents can verify applications"); 9361 9362 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9363 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9364 Binder.getCallingUid(), verificationCode, failedDomains); 9365 msg.arg1 = id; 9366 msg.obj = response; 9367 mHandler.sendMessage(msg); 9368 } 9369 9370 @Override 9371 public int getIntentVerificationStatus(String packageName, int userId) { 9372 synchronized (mPackages) { 9373 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9374 } 9375 } 9376 9377 @Override 9378 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9379 boolean result = false; 9380 synchronized (mPackages) { 9381 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9382 } 9383 if (result) { 9384 scheduleWritePackageRestrictionsLocked(userId); 9385 } 9386 return result; 9387 } 9388 9389 @Override 9390 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9391 synchronized (mPackages) { 9392 return mSettings.getIntentFilterVerificationsLPr(packageName); 9393 } 9394 } 9395 9396 @Override 9397 public List<IntentFilter> getAllIntentFilters(String packageName) { 9398 if (TextUtils.isEmpty(packageName)) { 9399 return Collections.<IntentFilter>emptyList(); 9400 } 9401 synchronized (mPackages) { 9402 PackageParser.Package pkg = mPackages.get(packageName); 9403 if (pkg == null || pkg.activities == null) { 9404 return Collections.<IntentFilter>emptyList(); 9405 } 9406 final int count = pkg.activities.size(); 9407 ArrayList<IntentFilter> result = new ArrayList<>(); 9408 for (int n=0; n<count; n++) { 9409 PackageParser.Activity activity = pkg.activities.get(n); 9410 if (activity.intents != null || activity.intents.size() > 0) { 9411 result.addAll(activity.intents); 9412 } 9413 } 9414 return result; 9415 } 9416 } 9417 9418 @Override 9419 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9420 synchronized (mPackages) { 9421 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9422 if (packageName != null) { 9423 result |= updateIntentVerificationStatus(packageName, 9424 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9425 UserHandle.myUserId()); 9426 } 9427 return result; 9428 } 9429 } 9430 9431 @Override 9432 public String getDefaultBrowserPackageName(int userId) { 9433 synchronized (mPackages) { 9434 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9435 } 9436 } 9437 9438 /** 9439 * Get the "allow unknown sources" setting. 9440 * 9441 * @return the current "allow unknown sources" setting 9442 */ 9443 private int getUnknownSourcesSettings() { 9444 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9445 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9446 -1); 9447 } 9448 9449 @Override 9450 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9451 final int uid = Binder.getCallingUid(); 9452 // writer 9453 synchronized (mPackages) { 9454 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9455 if (targetPackageSetting == null) { 9456 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9457 } 9458 9459 PackageSetting installerPackageSetting; 9460 if (installerPackageName != null) { 9461 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9462 if (installerPackageSetting == null) { 9463 throw new IllegalArgumentException("Unknown installer package: " 9464 + installerPackageName); 9465 } 9466 } else { 9467 installerPackageSetting = null; 9468 } 9469 9470 Signature[] callerSignature; 9471 Object obj = mSettings.getUserIdLPr(uid); 9472 if (obj != null) { 9473 if (obj instanceof SharedUserSetting) { 9474 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9475 } else if (obj instanceof PackageSetting) { 9476 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9477 } else { 9478 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9479 } 9480 } else { 9481 throw new SecurityException("Unknown calling uid " + uid); 9482 } 9483 9484 // Verify: can't set installerPackageName to a package that is 9485 // not signed with the same cert as the caller. 9486 if (installerPackageSetting != null) { 9487 if (compareSignatures(callerSignature, 9488 installerPackageSetting.signatures.mSignatures) 9489 != PackageManager.SIGNATURE_MATCH) { 9490 throw new SecurityException( 9491 "Caller does not have same cert as new installer package " 9492 + installerPackageName); 9493 } 9494 } 9495 9496 // Verify: if target already has an installer package, it must 9497 // be signed with the same cert as the caller. 9498 if (targetPackageSetting.installerPackageName != null) { 9499 PackageSetting setting = mSettings.mPackages.get( 9500 targetPackageSetting.installerPackageName); 9501 // If the currently set package isn't valid, then it's always 9502 // okay to change it. 9503 if (setting != null) { 9504 if (compareSignatures(callerSignature, 9505 setting.signatures.mSignatures) 9506 != PackageManager.SIGNATURE_MATCH) { 9507 throw new SecurityException( 9508 "Caller does not have same cert as old installer package " 9509 + targetPackageSetting.installerPackageName); 9510 } 9511 } 9512 } 9513 9514 // Okay! 9515 targetPackageSetting.installerPackageName = installerPackageName; 9516 scheduleWriteSettingsLocked(); 9517 } 9518 } 9519 9520 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9521 // Queue up an async operation since the package installation may take a little while. 9522 mHandler.post(new Runnable() { 9523 public void run() { 9524 mHandler.removeCallbacks(this); 9525 // Result object to be returned 9526 PackageInstalledInfo res = new PackageInstalledInfo(); 9527 res.returnCode = currentStatus; 9528 res.uid = -1; 9529 res.pkg = null; 9530 res.removedInfo = new PackageRemovedInfo(); 9531 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9532 args.doPreInstall(res.returnCode); 9533 synchronized (mInstallLock) { 9534 installPackageLI(args, res); 9535 } 9536 args.doPostInstall(res.returnCode, res.uid); 9537 } 9538 9539 // A restore should be performed at this point if (a) the install 9540 // succeeded, (b) the operation is not an update, and (c) the new 9541 // package has not opted out of backup participation. 9542 final boolean update = res.removedInfo.removedPackage != null; 9543 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9544 boolean doRestore = !update 9545 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9546 9547 // Set up the post-install work request bookkeeping. This will be used 9548 // and cleaned up by the post-install event handling regardless of whether 9549 // there's a restore pass performed. Token values are >= 1. 9550 int token; 9551 if (mNextInstallToken < 0) mNextInstallToken = 1; 9552 token = mNextInstallToken++; 9553 9554 PostInstallData data = new PostInstallData(args, res); 9555 mRunningInstalls.put(token, data); 9556 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9557 9558 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9559 // Pass responsibility to the Backup Manager. It will perform a 9560 // restore if appropriate, then pass responsibility back to the 9561 // Package Manager to run the post-install observer callbacks 9562 // and broadcasts. 9563 IBackupManager bm = IBackupManager.Stub.asInterface( 9564 ServiceManager.getService(Context.BACKUP_SERVICE)); 9565 if (bm != null) { 9566 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9567 + " to BM for possible restore"); 9568 try { 9569 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9570 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9571 } else { 9572 doRestore = false; 9573 } 9574 } catch (RemoteException e) { 9575 // can't happen; the backup manager is local 9576 } catch (Exception e) { 9577 Slog.e(TAG, "Exception trying to enqueue restore", e); 9578 doRestore = false; 9579 } 9580 } else { 9581 Slog.e(TAG, "Backup Manager not found!"); 9582 doRestore = false; 9583 } 9584 } 9585 9586 if (!doRestore) { 9587 // No restore possible, or the Backup Manager was mysteriously not 9588 // available -- just fire the post-install work request directly. 9589 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9590 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9591 mHandler.sendMessage(msg); 9592 } 9593 } 9594 }); 9595 } 9596 9597 private abstract class HandlerParams { 9598 private static final int MAX_RETRIES = 4; 9599 9600 /** 9601 * Number of times startCopy() has been attempted and had a non-fatal 9602 * error. 9603 */ 9604 private int mRetries = 0; 9605 9606 /** User handle for the user requesting the information or installation. */ 9607 private final UserHandle mUser; 9608 9609 HandlerParams(UserHandle user) { 9610 mUser = user; 9611 } 9612 9613 UserHandle getUser() { 9614 return mUser; 9615 } 9616 9617 final boolean startCopy() { 9618 boolean res; 9619 try { 9620 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9621 9622 if (++mRetries > MAX_RETRIES) { 9623 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9624 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9625 handleServiceError(); 9626 return false; 9627 } else { 9628 handleStartCopy(); 9629 res = true; 9630 } 9631 } catch (RemoteException e) { 9632 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9633 mHandler.sendEmptyMessage(MCS_RECONNECT); 9634 res = false; 9635 } 9636 handleReturnCode(); 9637 return res; 9638 } 9639 9640 final void serviceError() { 9641 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9642 handleServiceError(); 9643 handleReturnCode(); 9644 } 9645 9646 abstract void handleStartCopy() throws RemoteException; 9647 abstract void handleServiceError(); 9648 abstract void handleReturnCode(); 9649 } 9650 9651 class MeasureParams extends HandlerParams { 9652 private final PackageStats mStats; 9653 private boolean mSuccess; 9654 9655 private final IPackageStatsObserver mObserver; 9656 9657 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9658 super(new UserHandle(stats.userHandle)); 9659 mObserver = observer; 9660 mStats = stats; 9661 } 9662 9663 @Override 9664 public String toString() { 9665 return "MeasureParams{" 9666 + Integer.toHexString(System.identityHashCode(this)) 9667 + " " + mStats.packageName + "}"; 9668 } 9669 9670 @Override 9671 void handleStartCopy() throws RemoteException { 9672 synchronized (mInstallLock) { 9673 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9674 } 9675 9676 if (mSuccess) { 9677 final boolean mounted; 9678 if (Environment.isExternalStorageEmulated()) { 9679 mounted = true; 9680 } else { 9681 final String status = Environment.getExternalStorageState(); 9682 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9683 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9684 } 9685 9686 if (mounted) { 9687 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9688 9689 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9690 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9691 9692 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9693 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9694 9695 // Always subtract cache size, since it's a subdirectory 9696 mStats.externalDataSize -= mStats.externalCacheSize; 9697 9698 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9699 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9700 9701 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9702 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9703 } 9704 } 9705 } 9706 9707 @Override 9708 void handleReturnCode() { 9709 if (mObserver != null) { 9710 try { 9711 mObserver.onGetStatsCompleted(mStats, mSuccess); 9712 } catch (RemoteException e) { 9713 Slog.i(TAG, "Observer no longer exists."); 9714 } 9715 } 9716 } 9717 9718 @Override 9719 void handleServiceError() { 9720 Slog.e(TAG, "Could not measure application " + mStats.packageName 9721 + " external storage"); 9722 } 9723 } 9724 9725 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9726 throws RemoteException { 9727 long result = 0; 9728 for (File path : paths) { 9729 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9730 } 9731 return result; 9732 } 9733 9734 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9735 for (File path : paths) { 9736 try { 9737 mcs.clearDirectory(path.getAbsolutePath()); 9738 } catch (RemoteException e) { 9739 } 9740 } 9741 } 9742 9743 static class OriginInfo { 9744 /** 9745 * Location where install is coming from, before it has been 9746 * copied/renamed into place. This could be a single monolithic APK 9747 * file, or a cluster directory. This location may be untrusted. 9748 */ 9749 final File file; 9750 final String cid; 9751 9752 /** 9753 * Flag indicating that {@link #file} or {@link #cid} has already been 9754 * staged, meaning downstream users don't need to defensively copy the 9755 * contents. 9756 */ 9757 final boolean staged; 9758 9759 /** 9760 * Flag indicating that {@link #file} or {@link #cid} is an already 9761 * installed app that is being moved. 9762 */ 9763 final boolean existing; 9764 9765 final String resolvedPath; 9766 final File resolvedFile; 9767 9768 static OriginInfo fromNothing() { 9769 return new OriginInfo(null, null, false, false); 9770 } 9771 9772 static OriginInfo fromUntrustedFile(File file) { 9773 return new OriginInfo(file, null, false, false); 9774 } 9775 9776 static OriginInfo fromExistingFile(File file) { 9777 return new OriginInfo(file, null, false, true); 9778 } 9779 9780 static OriginInfo fromStagedFile(File file) { 9781 return new OriginInfo(file, null, true, false); 9782 } 9783 9784 static OriginInfo fromStagedContainer(String cid) { 9785 return new OriginInfo(null, cid, true, false); 9786 } 9787 9788 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9789 this.file = file; 9790 this.cid = cid; 9791 this.staged = staged; 9792 this.existing = existing; 9793 9794 if (cid != null) { 9795 resolvedPath = PackageHelper.getSdDir(cid); 9796 resolvedFile = new File(resolvedPath); 9797 } else if (file != null) { 9798 resolvedPath = file.getAbsolutePath(); 9799 resolvedFile = file; 9800 } else { 9801 resolvedPath = null; 9802 resolvedFile = null; 9803 } 9804 } 9805 } 9806 9807 class MoveInfo { 9808 final int moveId; 9809 final String fromUuid; 9810 final String toUuid; 9811 final String packageName; 9812 final String dataAppName; 9813 final int appId; 9814 final String seinfo; 9815 9816 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9817 String dataAppName, int appId, String seinfo) { 9818 this.moveId = moveId; 9819 this.fromUuid = fromUuid; 9820 this.toUuid = toUuid; 9821 this.packageName = packageName; 9822 this.dataAppName = dataAppName; 9823 this.appId = appId; 9824 this.seinfo = seinfo; 9825 } 9826 } 9827 9828 class InstallParams extends HandlerParams { 9829 final OriginInfo origin; 9830 final MoveInfo move; 9831 final IPackageInstallObserver2 observer; 9832 int installFlags; 9833 final String installerPackageName; 9834 final String volumeUuid; 9835 final VerificationParams verificationParams; 9836 private InstallArgs mArgs; 9837 private int mRet; 9838 final String packageAbiOverride; 9839 9840 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9841 int installFlags, String installerPackageName, String volumeUuid, 9842 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9843 super(user); 9844 this.origin = origin; 9845 this.move = move; 9846 this.observer = observer; 9847 this.installFlags = installFlags; 9848 this.installerPackageName = installerPackageName; 9849 this.volumeUuid = volumeUuid; 9850 this.verificationParams = verificationParams; 9851 this.packageAbiOverride = packageAbiOverride; 9852 } 9853 9854 @Override 9855 public String toString() { 9856 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9857 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9858 } 9859 9860 public ManifestDigest getManifestDigest() { 9861 if (verificationParams == null) { 9862 return null; 9863 } 9864 return verificationParams.getManifestDigest(); 9865 } 9866 9867 private int installLocationPolicy(PackageInfoLite pkgLite) { 9868 String packageName = pkgLite.packageName; 9869 int installLocation = pkgLite.installLocation; 9870 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9871 // reader 9872 synchronized (mPackages) { 9873 PackageParser.Package pkg = mPackages.get(packageName); 9874 if (pkg != null) { 9875 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9876 // Check for downgrading. 9877 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9878 try { 9879 checkDowngrade(pkg, pkgLite); 9880 } catch (PackageManagerException e) { 9881 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9882 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9883 } 9884 } 9885 // Check for updated system application. 9886 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9887 if (onSd) { 9888 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9889 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9890 } 9891 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9892 } else { 9893 if (onSd) { 9894 // Install flag overrides everything. 9895 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9896 } 9897 // If current upgrade specifies particular preference 9898 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9899 // Application explicitly specified internal. 9900 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9901 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9902 // App explictly prefers external. Let policy decide 9903 } else { 9904 // Prefer previous location 9905 if (isExternal(pkg)) { 9906 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9907 } 9908 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9909 } 9910 } 9911 } else { 9912 // Invalid install. Return error code 9913 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9914 } 9915 } 9916 } 9917 // All the special cases have been taken care of. 9918 // Return result based on recommended install location. 9919 if (onSd) { 9920 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9921 } 9922 return pkgLite.recommendedInstallLocation; 9923 } 9924 9925 /* 9926 * Invoke remote method to get package information and install 9927 * location values. Override install location based on default 9928 * policy if needed and then create install arguments based 9929 * on the install location. 9930 */ 9931 public void handleStartCopy() throws RemoteException { 9932 int ret = PackageManager.INSTALL_SUCCEEDED; 9933 9934 // If we're already staged, we've firmly committed to an install location 9935 if (origin.staged) { 9936 if (origin.file != null) { 9937 installFlags |= PackageManager.INSTALL_INTERNAL; 9938 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9939 } else if (origin.cid != null) { 9940 installFlags |= PackageManager.INSTALL_EXTERNAL; 9941 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9942 } else { 9943 throw new IllegalStateException("Invalid stage location"); 9944 } 9945 } 9946 9947 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9948 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9949 9950 PackageInfoLite pkgLite = null; 9951 9952 if (onInt && onSd) { 9953 // Check if both bits are set. 9954 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9955 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9956 } else { 9957 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9958 packageAbiOverride); 9959 9960 /* 9961 * If we have too little free space, try to free cache 9962 * before giving up. 9963 */ 9964 if (!origin.staged && pkgLite.recommendedInstallLocation 9965 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9966 // TODO: focus freeing disk space on the target device 9967 final StorageManager storage = StorageManager.from(mContext); 9968 final long lowThreshold = storage.getStorageLowBytes( 9969 Environment.getDataDirectory()); 9970 9971 final long sizeBytes = mContainerService.calculateInstalledSize( 9972 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9973 9974 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9975 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9976 installFlags, packageAbiOverride); 9977 } 9978 9979 /* 9980 * The cache free must have deleted the file we 9981 * downloaded to install. 9982 * 9983 * TODO: fix the "freeCache" call to not delete 9984 * the file we care about. 9985 */ 9986 if (pkgLite.recommendedInstallLocation 9987 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9988 pkgLite.recommendedInstallLocation 9989 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9990 } 9991 } 9992 } 9993 9994 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9995 int loc = pkgLite.recommendedInstallLocation; 9996 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9997 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9998 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9999 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10000 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10001 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10002 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10003 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10004 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10005 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10006 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10007 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10008 } else { 10009 // Override with defaults if needed. 10010 loc = installLocationPolicy(pkgLite); 10011 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10012 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10013 } else if (!onSd && !onInt) { 10014 // Override install location with flags 10015 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10016 // Set the flag to install on external media. 10017 installFlags |= PackageManager.INSTALL_EXTERNAL; 10018 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10019 } else { 10020 // Make sure the flag for installing on external 10021 // media is unset 10022 installFlags |= PackageManager.INSTALL_INTERNAL; 10023 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10024 } 10025 } 10026 } 10027 } 10028 10029 final InstallArgs args = createInstallArgs(this); 10030 mArgs = args; 10031 10032 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10033 /* 10034 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10035 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10036 */ 10037 int userIdentifier = getUser().getIdentifier(); 10038 if (userIdentifier == UserHandle.USER_ALL 10039 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10040 userIdentifier = UserHandle.USER_OWNER; 10041 } 10042 10043 /* 10044 * Determine if we have any installed package verifiers. If we 10045 * do, then we'll defer to them to verify the packages. 10046 */ 10047 final int requiredUid = mRequiredVerifierPackage == null ? -1 10048 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10049 if (!origin.existing && requiredUid != -1 10050 && isVerificationEnabled(userIdentifier, installFlags)) { 10051 final Intent verification = new Intent( 10052 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10053 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10054 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10055 PACKAGE_MIME_TYPE); 10056 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10057 10058 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10059 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10060 0 /* TODO: Which userId? */); 10061 10062 if (DEBUG_VERIFY) { 10063 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10064 + verification.toString() + " with " + pkgLite.verifiers.length 10065 + " optional verifiers"); 10066 } 10067 10068 final int verificationId = mPendingVerificationToken++; 10069 10070 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10071 10072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10073 installerPackageName); 10074 10075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10076 installFlags); 10077 10078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10079 pkgLite.packageName); 10080 10081 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10082 pkgLite.versionCode); 10083 10084 if (verificationParams != null) { 10085 if (verificationParams.getVerificationURI() != null) { 10086 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10087 verificationParams.getVerificationURI()); 10088 } 10089 if (verificationParams.getOriginatingURI() != null) { 10090 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10091 verificationParams.getOriginatingURI()); 10092 } 10093 if (verificationParams.getReferrer() != null) { 10094 verification.putExtra(Intent.EXTRA_REFERRER, 10095 verificationParams.getReferrer()); 10096 } 10097 if (verificationParams.getOriginatingUid() >= 0) { 10098 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10099 verificationParams.getOriginatingUid()); 10100 } 10101 if (verificationParams.getInstallerUid() >= 0) { 10102 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10103 verificationParams.getInstallerUid()); 10104 } 10105 } 10106 10107 final PackageVerificationState verificationState = new PackageVerificationState( 10108 requiredUid, args); 10109 10110 mPendingVerification.append(verificationId, verificationState); 10111 10112 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10113 receivers, verificationState); 10114 10115 /* 10116 * If any sufficient verifiers were listed in the package 10117 * manifest, attempt to ask them. 10118 */ 10119 if (sufficientVerifiers != null) { 10120 final int N = sufficientVerifiers.size(); 10121 if (N == 0) { 10122 Slog.i(TAG, "Additional verifiers required, but none installed."); 10123 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10124 } else { 10125 for (int i = 0; i < N; i++) { 10126 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10127 10128 final Intent sufficientIntent = new Intent(verification); 10129 sufficientIntent.setComponent(verifierComponent); 10130 10131 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10132 } 10133 } 10134 } 10135 10136 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10137 mRequiredVerifierPackage, receivers); 10138 if (ret == PackageManager.INSTALL_SUCCEEDED 10139 && mRequiredVerifierPackage != null) { 10140 /* 10141 * Send the intent to the required verification agent, 10142 * but only start the verification timeout after the 10143 * target BroadcastReceivers have run. 10144 */ 10145 verification.setComponent(requiredVerifierComponent); 10146 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10147 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10148 new BroadcastReceiver() { 10149 @Override 10150 public void onReceive(Context context, Intent intent) { 10151 final Message msg = mHandler 10152 .obtainMessage(CHECK_PENDING_VERIFICATION); 10153 msg.arg1 = verificationId; 10154 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10155 } 10156 }, null, 0, null, null); 10157 10158 /* 10159 * We don't want the copy to proceed until verification 10160 * succeeds, so null out this field. 10161 */ 10162 mArgs = null; 10163 } 10164 } else { 10165 /* 10166 * No package verification is enabled, so immediately start 10167 * the remote call to initiate copy using temporary file. 10168 */ 10169 ret = args.copyApk(mContainerService, true); 10170 } 10171 } 10172 10173 mRet = ret; 10174 } 10175 10176 @Override 10177 void handleReturnCode() { 10178 // If mArgs is null, then MCS couldn't be reached. When it 10179 // reconnects, it will try again to install. At that point, this 10180 // will succeed. 10181 if (mArgs != null) { 10182 processPendingInstall(mArgs, mRet); 10183 } 10184 } 10185 10186 @Override 10187 void handleServiceError() { 10188 mArgs = createInstallArgs(this); 10189 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10190 } 10191 10192 public boolean isForwardLocked() { 10193 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10194 } 10195 } 10196 10197 /** 10198 * Used during creation of InstallArgs 10199 * 10200 * @param installFlags package installation flags 10201 * @return true if should be installed on external storage 10202 */ 10203 private static boolean installOnExternalAsec(int installFlags) { 10204 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10205 return false; 10206 } 10207 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10208 return true; 10209 } 10210 return false; 10211 } 10212 10213 /** 10214 * Used during creation of InstallArgs 10215 * 10216 * @param installFlags package installation flags 10217 * @return true if should be installed as forward locked 10218 */ 10219 private static boolean installForwardLocked(int installFlags) { 10220 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10221 } 10222 10223 private InstallArgs createInstallArgs(InstallParams params) { 10224 if (params.move != null) { 10225 return new MoveInstallArgs(params); 10226 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10227 return new AsecInstallArgs(params); 10228 } else { 10229 return new FileInstallArgs(params); 10230 } 10231 } 10232 10233 /** 10234 * Create args that describe an existing installed package. Typically used 10235 * when cleaning up old installs, or used as a move source. 10236 */ 10237 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10238 String resourcePath, String[] instructionSets) { 10239 final boolean isInAsec; 10240 if (installOnExternalAsec(installFlags)) { 10241 /* Apps on SD card are always in ASEC containers. */ 10242 isInAsec = true; 10243 } else if (installForwardLocked(installFlags) 10244 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10245 /* 10246 * Forward-locked apps are only in ASEC containers if they're the 10247 * new style 10248 */ 10249 isInAsec = true; 10250 } else { 10251 isInAsec = false; 10252 } 10253 10254 if (isInAsec) { 10255 return new AsecInstallArgs(codePath, instructionSets, 10256 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10257 } else { 10258 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10259 } 10260 } 10261 10262 static abstract class InstallArgs { 10263 /** @see InstallParams#origin */ 10264 final OriginInfo origin; 10265 /** @see InstallParams#move */ 10266 final MoveInfo move; 10267 10268 final IPackageInstallObserver2 observer; 10269 // Always refers to PackageManager flags only 10270 final int installFlags; 10271 final String installerPackageName; 10272 final String volumeUuid; 10273 final ManifestDigest manifestDigest; 10274 final UserHandle user; 10275 final String abiOverride; 10276 10277 // The list of instruction sets supported by this app. This is currently 10278 // only used during the rmdex() phase to clean up resources. We can get rid of this 10279 // if we move dex files under the common app path. 10280 /* nullable */ String[] instructionSets; 10281 10282 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10283 int installFlags, String installerPackageName, String volumeUuid, 10284 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10285 String abiOverride) { 10286 this.origin = origin; 10287 this.move = move; 10288 this.installFlags = installFlags; 10289 this.observer = observer; 10290 this.installerPackageName = installerPackageName; 10291 this.volumeUuid = volumeUuid; 10292 this.manifestDigest = manifestDigest; 10293 this.user = user; 10294 this.instructionSets = instructionSets; 10295 this.abiOverride = abiOverride; 10296 } 10297 10298 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10299 abstract int doPreInstall(int status); 10300 10301 /** 10302 * Rename package into final resting place. All paths on the given 10303 * scanned package should be updated to reflect the rename. 10304 */ 10305 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10306 abstract int doPostInstall(int status, int uid); 10307 10308 /** @see PackageSettingBase#codePathString */ 10309 abstract String getCodePath(); 10310 /** @see PackageSettingBase#resourcePathString */ 10311 abstract String getResourcePath(); 10312 10313 // Need installer lock especially for dex file removal. 10314 abstract void cleanUpResourcesLI(); 10315 abstract boolean doPostDeleteLI(boolean delete); 10316 10317 /** 10318 * Called before the source arguments are copied. This is used mostly 10319 * for MoveParams when it needs to read the source file to put it in the 10320 * destination. 10321 */ 10322 int doPreCopy() { 10323 return PackageManager.INSTALL_SUCCEEDED; 10324 } 10325 10326 /** 10327 * Called after the source arguments are copied. This is used mostly for 10328 * MoveParams when it needs to read the source file to put it in the 10329 * destination. 10330 * 10331 * @return 10332 */ 10333 int doPostCopy(int uid) { 10334 return PackageManager.INSTALL_SUCCEEDED; 10335 } 10336 10337 protected boolean isFwdLocked() { 10338 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10339 } 10340 10341 protected boolean isExternalAsec() { 10342 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10343 } 10344 10345 UserHandle getUser() { 10346 return user; 10347 } 10348 } 10349 10350 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10351 if (!allCodePaths.isEmpty()) { 10352 if (instructionSets == null) { 10353 throw new IllegalStateException("instructionSet == null"); 10354 } 10355 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10356 for (String codePath : allCodePaths) { 10357 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10358 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10359 if (retCode < 0) { 10360 Slog.w(TAG, "Couldn't remove dex file for package: " 10361 + " at location " + codePath + ", retcode=" + retCode); 10362 // we don't consider this to be a failure of the core package deletion 10363 } 10364 } 10365 } 10366 } 10367 } 10368 10369 /** 10370 * Logic to handle installation of non-ASEC applications, including copying 10371 * and renaming logic. 10372 */ 10373 class FileInstallArgs extends InstallArgs { 10374 private File codeFile; 10375 private File resourceFile; 10376 10377 // Example topology: 10378 // /data/app/com.example/base.apk 10379 // /data/app/com.example/split_foo.apk 10380 // /data/app/com.example/lib/arm/libfoo.so 10381 // /data/app/com.example/lib/arm64/libfoo.so 10382 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10383 10384 /** New install */ 10385 FileInstallArgs(InstallParams params) { 10386 super(params.origin, params.move, params.observer, params.installFlags, 10387 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10388 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10389 if (isFwdLocked()) { 10390 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10391 } 10392 } 10393 10394 /** Existing install */ 10395 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10396 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10397 null); 10398 this.codeFile = (codePath != null) ? new File(codePath) : null; 10399 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10400 } 10401 10402 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10403 if (origin.staged) { 10404 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10405 codeFile = origin.file; 10406 resourceFile = origin.file; 10407 return PackageManager.INSTALL_SUCCEEDED; 10408 } 10409 10410 try { 10411 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10412 codeFile = tempDir; 10413 resourceFile = tempDir; 10414 } catch (IOException e) { 10415 Slog.w(TAG, "Failed to create copy file: " + e); 10416 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10417 } 10418 10419 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10420 @Override 10421 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10422 if (!FileUtils.isValidExtFilename(name)) { 10423 throw new IllegalArgumentException("Invalid filename: " + name); 10424 } 10425 try { 10426 final File file = new File(codeFile, name); 10427 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10428 O_RDWR | O_CREAT, 0644); 10429 Os.chmod(file.getAbsolutePath(), 0644); 10430 return new ParcelFileDescriptor(fd); 10431 } catch (ErrnoException e) { 10432 throw new RemoteException("Failed to open: " + e.getMessage()); 10433 } 10434 } 10435 }; 10436 10437 int ret = PackageManager.INSTALL_SUCCEEDED; 10438 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10439 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10440 Slog.e(TAG, "Failed to copy package"); 10441 return ret; 10442 } 10443 10444 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10445 NativeLibraryHelper.Handle handle = null; 10446 try { 10447 handle = NativeLibraryHelper.Handle.create(codeFile); 10448 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10449 abiOverride); 10450 } catch (IOException e) { 10451 Slog.e(TAG, "Copying native libraries failed", e); 10452 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10453 } finally { 10454 IoUtils.closeQuietly(handle); 10455 } 10456 10457 return ret; 10458 } 10459 10460 int doPreInstall(int status) { 10461 if (status != PackageManager.INSTALL_SUCCEEDED) { 10462 cleanUp(); 10463 } 10464 return status; 10465 } 10466 10467 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10468 if (status != PackageManager.INSTALL_SUCCEEDED) { 10469 cleanUp(); 10470 return false; 10471 } 10472 10473 final File targetDir = codeFile.getParentFile(); 10474 final File beforeCodeFile = codeFile; 10475 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10476 10477 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10478 try { 10479 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10480 } catch (ErrnoException e) { 10481 Slog.w(TAG, "Failed to rename", e); 10482 return false; 10483 } 10484 10485 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10486 Slog.w(TAG, "Failed to restorecon"); 10487 return false; 10488 } 10489 10490 // Reflect the rename internally 10491 codeFile = afterCodeFile; 10492 resourceFile = afterCodeFile; 10493 10494 // Reflect the rename in scanned details 10495 pkg.codePath = afterCodeFile.getAbsolutePath(); 10496 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10497 pkg.baseCodePath); 10498 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10499 pkg.splitCodePaths); 10500 10501 // Reflect the rename in app info 10502 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10503 pkg.applicationInfo.setCodePath(pkg.codePath); 10504 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10505 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10506 pkg.applicationInfo.setResourcePath(pkg.codePath); 10507 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10508 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10509 10510 return true; 10511 } 10512 10513 int doPostInstall(int status, int uid) { 10514 if (status != PackageManager.INSTALL_SUCCEEDED) { 10515 cleanUp(); 10516 } 10517 return status; 10518 } 10519 10520 @Override 10521 String getCodePath() { 10522 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10523 } 10524 10525 @Override 10526 String getResourcePath() { 10527 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10528 } 10529 10530 private boolean cleanUp() { 10531 if (codeFile == null || !codeFile.exists()) { 10532 return false; 10533 } 10534 10535 if (codeFile.isDirectory()) { 10536 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10537 } else { 10538 codeFile.delete(); 10539 } 10540 10541 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10542 resourceFile.delete(); 10543 } 10544 10545 return true; 10546 } 10547 10548 void cleanUpResourcesLI() { 10549 // Try enumerating all code paths before deleting 10550 List<String> allCodePaths = Collections.EMPTY_LIST; 10551 if (codeFile != null && codeFile.exists()) { 10552 try { 10553 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10554 allCodePaths = pkg.getAllCodePaths(); 10555 } catch (PackageParserException e) { 10556 // Ignored; we tried our best 10557 } 10558 } 10559 10560 cleanUp(); 10561 removeDexFiles(allCodePaths, instructionSets); 10562 } 10563 10564 boolean doPostDeleteLI(boolean delete) { 10565 // XXX err, shouldn't we respect the delete flag? 10566 cleanUpResourcesLI(); 10567 return true; 10568 } 10569 } 10570 10571 private boolean isAsecExternal(String cid) { 10572 final String asecPath = PackageHelper.getSdFilesystem(cid); 10573 return !asecPath.startsWith(mAsecInternalPath); 10574 } 10575 10576 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10577 PackageManagerException { 10578 if (copyRet < 0) { 10579 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10580 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10581 throw new PackageManagerException(copyRet, message); 10582 } 10583 } 10584 } 10585 10586 /** 10587 * Extract the MountService "container ID" from the full code path of an 10588 * .apk. 10589 */ 10590 static String cidFromCodePath(String fullCodePath) { 10591 int eidx = fullCodePath.lastIndexOf("/"); 10592 String subStr1 = fullCodePath.substring(0, eidx); 10593 int sidx = subStr1.lastIndexOf("/"); 10594 return subStr1.substring(sidx+1, eidx); 10595 } 10596 10597 /** 10598 * Logic to handle installation of ASEC applications, including copying and 10599 * renaming logic. 10600 */ 10601 class AsecInstallArgs extends InstallArgs { 10602 static final String RES_FILE_NAME = "pkg.apk"; 10603 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10604 10605 String cid; 10606 String packagePath; 10607 String resourcePath; 10608 10609 /** New install */ 10610 AsecInstallArgs(InstallParams params) { 10611 super(params.origin, params.move, params.observer, params.installFlags, 10612 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10613 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10614 } 10615 10616 /** Existing install */ 10617 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10618 boolean isExternal, boolean isForwardLocked) { 10619 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10620 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10621 instructionSets, null); 10622 // Hackily pretend we're still looking at a full code path 10623 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10624 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10625 } 10626 10627 // Extract cid from fullCodePath 10628 int eidx = fullCodePath.lastIndexOf("/"); 10629 String subStr1 = fullCodePath.substring(0, eidx); 10630 int sidx = subStr1.lastIndexOf("/"); 10631 cid = subStr1.substring(sidx+1, eidx); 10632 setMountPath(subStr1); 10633 } 10634 10635 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10636 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10637 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10638 instructionSets, null); 10639 this.cid = cid; 10640 setMountPath(PackageHelper.getSdDir(cid)); 10641 } 10642 10643 void createCopyFile() { 10644 cid = mInstallerService.allocateExternalStageCidLegacy(); 10645 } 10646 10647 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10648 if (origin.staged) { 10649 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10650 cid = origin.cid; 10651 setMountPath(PackageHelper.getSdDir(cid)); 10652 return PackageManager.INSTALL_SUCCEEDED; 10653 } 10654 10655 if (temp) { 10656 createCopyFile(); 10657 } else { 10658 /* 10659 * Pre-emptively destroy the container since it's destroyed if 10660 * copying fails due to it existing anyway. 10661 */ 10662 PackageHelper.destroySdDir(cid); 10663 } 10664 10665 final String newMountPath = imcs.copyPackageToContainer( 10666 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10667 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10668 10669 if (newMountPath != null) { 10670 setMountPath(newMountPath); 10671 return PackageManager.INSTALL_SUCCEEDED; 10672 } else { 10673 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10674 } 10675 } 10676 10677 @Override 10678 String getCodePath() { 10679 return packagePath; 10680 } 10681 10682 @Override 10683 String getResourcePath() { 10684 return resourcePath; 10685 } 10686 10687 int doPreInstall(int status) { 10688 if (status != PackageManager.INSTALL_SUCCEEDED) { 10689 // Destroy container 10690 PackageHelper.destroySdDir(cid); 10691 } else { 10692 boolean mounted = PackageHelper.isContainerMounted(cid); 10693 if (!mounted) { 10694 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10695 Process.SYSTEM_UID); 10696 if (newMountPath != null) { 10697 setMountPath(newMountPath); 10698 } else { 10699 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10700 } 10701 } 10702 } 10703 return status; 10704 } 10705 10706 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10707 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10708 String newMountPath = null; 10709 if (PackageHelper.isContainerMounted(cid)) { 10710 // Unmount the container 10711 if (!PackageHelper.unMountSdDir(cid)) { 10712 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10713 return false; 10714 } 10715 } 10716 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10717 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10718 " which might be stale. Will try to clean up."); 10719 // Clean up the stale container and proceed to recreate. 10720 if (!PackageHelper.destroySdDir(newCacheId)) { 10721 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10722 return false; 10723 } 10724 // Successfully cleaned up stale container. Try to rename again. 10725 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10726 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10727 + " inspite of cleaning it up."); 10728 return false; 10729 } 10730 } 10731 if (!PackageHelper.isContainerMounted(newCacheId)) { 10732 Slog.w(TAG, "Mounting container " + newCacheId); 10733 newMountPath = PackageHelper.mountSdDir(newCacheId, 10734 getEncryptKey(), Process.SYSTEM_UID); 10735 } else { 10736 newMountPath = PackageHelper.getSdDir(newCacheId); 10737 } 10738 if (newMountPath == null) { 10739 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10740 return false; 10741 } 10742 Log.i(TAG, "Succesfully renamed " + cid + 10743 " to " + newCacheId + 10744 " at new path: " + newMountPath); 10745 cid = newCacheId; 10746 10747 final File beforeCodeFile = new File(packagePath); 10748 setMountPath(newMountPath); 10749 final File afterCodeFile = new File(packagePath); 10750 10751 // Reflect the rename in scanned details 10752 pkg.codePath = afterCodeFile.getAbsolutePath(); 10753 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10754 pkg.baseCodePath); 10755 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10756 pkg.splitCodePaths); 10757 10758 // Reflect the rename in app info 10759 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10760 pkg.applicationInfo.setCodePath(pkg.codePath); 10761 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10762 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10763 pkg.applicationInfo.setResourcePath(pkg.codePath); 10764 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10765 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10766 10767 return true; 10768 } 10769 10770 private void setMountPath(String mountPath) { 10771 final File mountFile = new File(mountPath); 10772 10773 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10774 if (monolithicFile.exists()) { 10775 packagePath = monolithicFile.getAbsolutePath(); 10776 if (isFwdLocked()) { 10777 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10778 } else { 10779 resourcePath = packagePath; 10780 } 10781 } else { 10782 packagePath = mountFile.getAbsolutePath(); 10783 resourcePath = packagePath; 10784 } 10785 } 10786 10787 int doPostInstall(int status, int uid) { 10788 if (status != PackageManager.INSTALL_SUCCEEDED) { 10789 cleanUp(); 10790 } else { 10791 final int groupOwner; 10792 final String protectedFile; 10793 if (isFwdLocked()) { 10794 groupOwner = UserHandle.getSharedAppGid(uid); 10795 protectedFile = RES_FILE_NAME; 10796 } else { 10797 groupOwner = -1; 10798 protectedFile = null; 10799 } 10800 10801 if (uid < Process.FIRST_APPLICATION_UID 10802 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10803 Slog.e(TAG, "Failed to finalize " + cid); 10804 PackageHelper.destroySdDir(cid); 10805 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10806 } 10807 10808 boolean mounted = PackageHelper.isContainerMounted(cid); 10809 if (!mounted) { 10810 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10811 } 10812 } 10813 return status; 10814 } 10815 10816 private void cleanUp() { 10817 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10818 10819 // Destroy secure container 10820 PackageHelper.destroySdDir(cid); 10821 } 10822 10823 private List<String> getAllCodePaths() { 10824 final File codeFile = new File(getCodePath()); 10825 if (codeFile != null && codeFile.exists()) { 10826 try { 10827 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10828 return pkg.getAllCodePaths(); 10829 } catch (PackageParserException e) { 10830 // Ignored; we tried our best 10831 } 10832 } 10833 return Collections.EMPTY_LIST; 10834 } 10835 10836 void cleanUpResourcesLI() { 10837 // Enumerate all code paths before deleting 10838 cleanUpResourcesLI(getAllCodePaths()); 10839 } 10840 10841 private void cleanUpResourcesLI(List<String> allCodePaths) { 10842 cleanUp(); 10843 removeDexFiles(allCodePaths, instructionSets); 10844 } 10845 10846 String getPackageName() { 10847 return getAsecPackageName(cid); 10848 } 10849 10850 boolean doPostDeleteLI(boolean delete) { 10851 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10852 final List<String> allCodePaths = getAllCodePaths(); 10853 boolean mounted = PackageHelper.isContainerMounted(cid); 10854 if (mounted) { 10855 // Unmount first 10856 if (PackageHelper.unMountSdDir(cid)) { 10857 mounted = false; 10858 } 10859 } 10860 if (!mounted && delete) { 10861 cleanUpResourcesLI(allCodePaths); 10862 } 10863 return !mounted; 10864 } 10865 10866 @Override 10867 int doPreCopy() { 10868 if (isFwdLocked()) { 10869 if (!PackageHelper.fixSdPermissions(cid, 10870 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10871 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10872 } 10873 } 10874 10875 return PackageManager.INSTALL_SUCCEEDED; 10876 } 10877 10878 @Override 10879 int doPostCopy(int uid) { 10880 if (isFwdLocked()) { 10881 if (uid < Process.FIRST_APPLICATION_UID 10882 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10883 RES_FILE_NAME)) { 10884 Slog.e(TAG, "Failed to finalize " + cid); 10885 PackageHelper.destroySdDir(cid); 10886 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10887 } 10888 } 10889 10890 return PackageManager.INSTALL_SUCCEEDED; 10891 } 10892 } 10893 10894 /** 10895 * Logic to handle movement of existing installed applications. 10896 */ 10897 class MoveInstallArgs extends InstallArgs { 10898 private File codeFile; 10899 private File resourceFile; 10900 10901 /** New install */ 10902 MoveInstallArgs(InstallParams params) { 10903 super(params.origin, params.move, params.observer, params.installFlags, 10904 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10905 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10906 } 10907 10908 int copyApk(IMediaContainerService imcs, boolean temp) { 10909 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10910 + move.fromUuid + " to " + move.toUuid); 10911 synchronized (mInstaller) { 10912 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10913 move.dataAppName, move.appId, move.seinfo) != 0) { 10914 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10915 } 10916 } 10917 10918 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10919 resourceFile = codeFile; 10920 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10921 10922 return PackageManager.INSTALL_SUCCEEDED; 10923 } 10924 10925 int doPreInstall(int status) { 10926 if (status != PackageManager.INSTALL_SUCCEEDED) { 10927 cleanUp(); 10928 } 10929 return status; 10930 } 10931 10932 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10933 if (status != PackageManager.INSTALL_SUCCEEDED) { 10934 cleanUp(); 10935 return false; 10936 } 10937 10938 // Reflect the move in app info 10939 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10940 pkg.applicationInfo.setCodePath(pkg.codePath); 10941 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10942 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10943 pkg.applicationInfo.setResourcePath(pkg.codePath); 10944 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10945 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10946 10947 return true; 10948 } 10949 10950 int doPostInstall(int status, int uid) { 10951 if (status != PackageManager.INSTALL_SUCCEEDED) { 10952 cleanUp(); 10953 } 10954 return status; 10955 } 10956 10957 @Override 10958 String getCodePath() { 10959 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10960 } 10961 10962 @Override 10963 String getResourcePath() { 10964 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10965 } 10966 10967 private boolean cleanUp() { 10968 if (codeFile == null || !codeFile.exists()) { 10969 return false; 10970 } 10971 10972 if (codeFile.isDirectory()) { 10973 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10974 } else { 10975 codeFile.delete(); 10976 } 10977 10978 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10979 resourceFile.delete(); 10980 } 10981 10982 return true; 10983 } 10984 10985 void cleanUpResourcesLI() { 10986 cleanUp(); 10987 } 10988 10989 boolean doPostDeleteLI(boolean delete) { 10990 // XXX err, shouldn't we respect the delete flag? 10991 cleanUpResourcesLI(); 10992 return true; 10993 } 10994 } 10995 10996 static String getAsecPackageName(String packageCid) { 10997 int idx = packageCid.lastIndexOf("-"); 10998 if (idx == -1) { 10999 return packageCid; 11000 } 11001 return packageCid.substring(0, idx); 11002 } 11003 11004 // Utility method used to create code paths based on package name and available index. 11005 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11006 String idxStr = ""; 11007 int idx = 1; 11008 // Fall back to default value of idx=1 if prefix is not 11009 // part of oldCodePath 11010 if (oldCodePath != null) { 11011 String subStr = oldCodePath; 11012 // Drop the suffix right away 11013 if (suffix != null && subStr.endsWith(suffix)) { 11014 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11015 } 11016 // If oldCodePath already contains prefix find out the 11017 // ending index to either increment or decrement. 11018 int sidx = subStr.lastIndexOf(prefix); 11019 if (sidx != -1) { 11020 subStr = subStr.substring(sidx + prefix.length()); 11021 if (subStr != null) { 11022 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11023 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11024 } 11025 try { 11026 idx = Integer.parseInt(subStr); 11027 if (idx <= 1) { 11028 idx++; 11029 } else { 11030 idx--; 11031 } 11032 } catch(NumberFormatException e) { 11033 } 11034 } 11035 } 11036 } 11037 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11038 return prefix + idxStr; 11039 } 11040 11041 private File getNextCodePath(File targetDir, String packageName) { 11042 int suffix = 1; 11043 File result; 11044 do { 11045 result = new File(targetDir, packageName + "-" + suffix); 11046 suffix++; 11047 } while (result.exists()); 11048 return result; 11049 } 11050 11051 // Utility method that returns the relative package path with respect 11052 // to the installation directory. Like say for /data/data/com.test-1.apk 11053 // string com.test-1 is returned. 11054 static String deriveCodePathName(String codePath) { 11055 if (codePath == null) { 11056 return null; 11057 } 11058 final File codeFile = new File(codePath); 11059 final String name = codeFile.getName(); 11060 if (codeFile.isDirectory()) { 11061 return name; 11062 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11063 final int lastDot = name.lastIndexOf('.'); 11064 return name.substring(0, lastDot); 11065 } else { 11066 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11067 return null; 11068 } 11069 } 11070 11071 class PackageInstalledInfo { 11072 String name; 11073 int uid; 11074 // The set of users that originally had this package installed. 11075 int[] origUsers; 11076 // The set of users that now have this package installed. 11077 int[] newUsers; 11078 PackageParser.Package pkg; 11079 int returnCode; 11080 String returnMsg; 11081 PackageRemovedInfo removedInfo; 11082 11083 public void setError(int code, String msg) { 11084 returnCode = code; 11085 returnMsg = msg; 11086 Slog.w(TAG, msg); 11087 } 11088 11089 public void setError(String msg, PackageParserException e) { 11090 returnCode = e.error; 11091 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11092 Slog.w(TAG, msg, e); 11093 } 11094 11095 public void setError(String msg, PackageManagerException e) { 11096 returnCode = e.error; 11097 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11098 Slog.w(TAG, msg, e); 11099 } 11100 11101 // In some error cases we want to convey more info back to the observer 11102 String origPackage; 11103 String origPermission; 11104 } 11105 11106 /* 11107 * Install a non-existing package. 11108 */ 11109 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11110 UserHandle user, String installerPackageName, String volumeUuid, 11111 PackageInstalledInfo res) { 11112 // Remember this for later, in case we need to rollback this install 11113 String pkgName = pkg.packageName; 11114 11115 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11116 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11117 UserHandle.USER_OWNER).exists(); 11118 synchronized(mPackages) { 11119 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11120 // A package with the same name is already installed, though 11121 // it has been renamed to an older name. The package we 11122 // are trying to install should be installed as an update to 11123 // the existing one, but that has not been requested, so bail. 11124 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11125 + " without first uninstalling package running as " 11126 + mSettings.mRenamedPackages.get(pkgName)); 11127 return; 11128 } 11129 if (mPackages.containsKey(pkgName)) { 11130 // Don't allow installation over an existing package with the same name. 11131 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11132 + " without first uninstalling."); 11133 return; 11134 } 11135 } 11136 11137 try { 11138 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11139 System.currentTimeMillis(), user); 11140 11141 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11142 // delete the partially installed application. the data directory will have to be 11143 // restored if it was already existing 11144 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11145 // remove package from internal structures. Note that we want deletePackageX to 11146 // delete the package data and cache directories that it created in 11147 // scanPackageLocked, unless those directories existed before we even tried to 11148 // install. 11149 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11150 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11151 res.removedInfo, true); 11152 } 11153 11154 } catch (PackageManagerException e) { 11155 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11156 } 11157 } 11158 11159 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11160 // Can't rotate keys during boot or if sharedUser. 11161 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11162 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11163 return false; 11164 } 11165 // app is using upgradeKeySets; make sure all are valid 11166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11167 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11168 for (int i = 0; i < upgradeKeySets.length; i++) { 11169 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11170 Slog.wtf(TAG, "Package " 11171 + (oldPs.name != null ? oldPs.name : "<null>") 11172 + " contains upgrade-key-set reference to unknown key-set: " 11173 + upgradeKeySets[i] 11174 + " reverting to signatures check."); 11175 return false; 11176 } 11177 } 11178 return true; 11179 } 11180 11181 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11182 // Upgrade keysets are being used. Determine if new package has a superset of the 11183 // required keys. 11184 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11185 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11186 for (int i = 0; i < upgradeKeySets.length; i++) { 11187 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11188 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11189 return true; 11190 } 11191 } 11192 return false; 11193 } 11194 11195 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11196 UserHandle user, String installerPackageName, String volumeUuid, 11197 PackageInstalledInfo res) { 11198 final PackageParser.Package oldPackage; 11199 final String pkgName = pkg.packageName; 11200 final int[] allUsers; 11201 final boolean[] perUserInstalled; 11202 final boolean weFroze; 11203 11204 // First find the old package info and check signatures 11205 synchronized(mPackages) { 11206 oldPackage = mPackages.get(pkgName); 11207 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11208 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11209 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11210 if(!checkUpgradeKeySetLP(ps, pkg)) { 11211 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11212 "New package not signed by keys specified by upgrade-keysets: " 11213 + pkgName); 11214 return; 11215 } 11216 } else { 11217 // default to original signature matching 11218 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11219 != PackageManager.SIGNATURE_MATCH) { 11220 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11221 "New package has a different signature: " + pkgName); 11222 return; 11223 } 11224 } 11225 11226 // In case of rollback, remember per-user/profile install state 11227 allUsers = sUserManager.getUserIds(); 11228 perUserInstalled = new boolean[allUsers.length]; 11229 for (int i = 0; i < allUsers.length; i++) { 11230 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11231 } 11232 11233 // Mark the app as frozen to prevent launching during the upgrade 11234 // process, and then kill all running instances 11235 if (!ps.frozen) { 11236 ps.frozen = true; 11237 weFroze = true; 11238 } else { 11239 weFroze = false; 11240 } 11241 } 11242 11243 // Now that we're guarded by frozen state, kill app during upgrade 11244 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11245 11246 try { 11247 boolean sysPkg = (isSystemApp(oldPackage)); 11248 if (sysPkg) { 11249 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11250 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11251 } else { 11252 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11253 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11254 } 11255 } finally { 11256 // Regardless of success or failure of upgrade steps above, always 11257 // unfreeze the package if we froze it 11258 if (weFroze) { 11259 unfreezePackage(pkgName); 11260 } 11261 } 11262 } 11263 11264 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11265 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11266 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11267 String volumeUuid, PackageInstalledInfo res) { 11268 String pkgName = deletedPackage.packageName; 11269 boolean deletedPkg = true; 11270 boolean updatedSettings = false; 11271 11272 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11273 + deletedPackage); 11274 long origUpdateTime; 11275 if (pkg.mExtras != null) { 11276 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11277 } else { 11278 origUpdateTime = 0; 11279 } 11280 11281 // First delete the existing package while retaining the data directory 11282 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11283 res.removedInfo, true)) { 11284 // If the existing package wasn't successfully deleted 11285 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11286 deletedPkg = false; 11287 } else { 11288 // Successfully deleted the old package; proceed with replace. 11289 11290 // If deleted package lived in a container, give users a chance to 11291 // relinquish resources before killing. 11292 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11293 if (DEBUG_INSTALL) { 11294 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11295 } 11296 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11297 final ArrayList<String> pkgList = new ArrayList<String>(1); 11298 pkgList.add(deletedPackage.applicationInfo.packageName); 11299 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11300 } 11301 11302 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11303 try { 11304 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11305 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11306 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11307 perUserInstalled, res, user); 11308 updatedSettings = true; 11309 } catch (PackageManagerException e) { 11310 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11311 } 11312 } 11313 11314 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11315 // remove package from internal structures. Note that we want deletePackageX to 11316 // delete the package data and cache directories that it created in 11317 // scanPackageLocked, unless those directories existed before we even tried to 11318 // install. 11319 if(updatedSettings) { 11320 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11321 deletePackageLI( 11322 pkgName, null, true, allUsers, perUserInstalled, 11323 PackageManager.DELETE_KEEP_DATA, 11324 res.removedInfo, true); 11325 } 11326 // Since we failed to install the new package we need to restore the old 11327 // package that we deleted. 11328 if (deletedPkg) { 11329 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11330 File restoreFile = new File(deletedPackage.codePath); 11331 // Parse old package 11332 boolean oldExternal = isExternal(deletedPackage); 11333 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11334 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11335 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11336 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11337 try { 11338 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11339 } catch (PackageManagerException e) { 11340 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11341 + e.getMessage()); 11342 return; 11343 } 11344 // Restore of old package succeeded. Update permissions. 11345 // writer 11346 synchronized (mPackages) { 11347 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11348 UPDATE_PERMISSIONS_ALL); 11349 // can downgrade to reader 11350 mSettings.writeLPr(); 11351 } 11352 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11353 } 11354 } 11355 } 11356 11357 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11358 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11359 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11360 String volumeUuid, PackageInstalledInfo res) { 11361 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11362 + ", old=" + deletedPackage); 11363 boolean disabledSystem = false; 11364 boolean updatedSettings = false; 11365 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11366 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11367 != 0) { 11368 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11369 } 11370 String packageName = deletedPackage.packageName; 11371 if (packageName == null) { 11372 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11373 "Attempt to delete null packageName."); 11374 return; 11375 } 11376 PackageParser.Package oldPkg; 11377 PackageSetting oldPkgSetting; 11378 // reader 11379 synchronized (mPackages) { 11380 oldPkg = mPackages.get(packageName); 11381 oldPkgSetting = mSettings.mPackages.get(packageName); 11382 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11383 (oldPkgSetting == null)) { 11384 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11385 "Couldn't find package:" + packageName + " information"); 11386 return; 11387 } 11388 } 11389 11390 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11391 res.removedInfo.removedPackage = packageName; 11392 // Remove existing system package 11393 removePackageLI(oldPkgSetting, true); 11394 // writer 11395 synchronized (mPackages) { 11396 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11397 if (!disabledSystem && deletedPackage != null) { 11398 // We didn't need to disable the .apk as a current system package, 11399 // which means we are replacing another update that is already 11400 // installed. We need to make sure to delete the older one's .apk. 11401 res.removedInfo.args = createInstallArgsForExisting(0, 11402 deletedPackage.applicationInfo.getCodePath(), 11403 deletedPackage.applicationInfo.getResourcePath(), 11404 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11405 } else { 11406 res.removedInfo.args = null; 11407 } 11408 } 11409 11410 // Successfully disabled the old package. Now proceed with re-installation 11411 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11412 11413 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11414 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11415 11416 PackageParser.Package newPackage = null; 11417 try { 11418 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11419 if (newPackage.mExtras != null) { 11420 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11421 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11422 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11423 11424 // is the update attempting to change shared user? that isn't going to work... 11425 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11426 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11427 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11428 + " to " + newPkgSetting.sharedUser); 11429 updatedSettings = true; 11430 } 11431 } 11432 11433 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11434 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11435 perUserInstalled, res, user); 11436 updatedSettings = true; 11437 } 11438 11439 } catch (PackageManagerException e) { 11440 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11441 } 11442 11443 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11444 // Re installation failed. Restore old information 11445 // Remove new pkg information 11446 if (newPackage != null) { 11447 removeInstalledPackageLI(newPackage, true); 11448 } 11449 // Add back the old system package 11450 try { 11451 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11452 } catch (PackageManagerException e) { 11453 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11454 } 11455 // Restore the old system information in Settings 11456 synchronized (mPackages) { 11457 if (disabledSystem) { 11458 mSettings.enableSystemPackageLPw(packageName); 11459 } 11460 if (updatedSettings) { 11461 mSettings.setInstallerPackageName(packageName, 11462 oldPkgSetting.installerPackageName); 11463 } 11464 mSettings.writeLPr(); 11465 } 11466 } 11467 } 11468 11469 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11470 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11471 UserHandle user) { 11472 String pkgName = newPackage.packageName; 11473 synchronized (mPackages) { 11474 //write settings. the installStatus will be incomplete at this stage. 11475 //note that the new package setting would have already been 11476 //added to mPackages. It hasn't been persisted yet. 11477 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11478 mSettings.writeLPr(); 11479 } 11480 11481 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11482 11483 synchronized (mPackages) { 11484 updatePermissionsLPw(newPackage.packageName, newPackage, 11485 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11486 ? UPDATE_PERMISSIONS_ALL : 0)); 11487 // For system-bundled packages, we assume that installing an upgraded version 11488 // of the package implies that the user actually wants to run that new code, 11489 // so we enable the package. 11490 PackageSetting ps = mSettings.mPackages.get(pkgName); 11491 if (ps != null) { 11492 if (isSystemApp(newPackage)) { 11493 // NB: implicit assumption that system package upgrades apply to all users 11494 if (DEBUG_INSTALL) { 11495 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11496 } 11497 if (res.origUsers != null) { 11498 for (int userHandle : res.origUsers) { 11499 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11500 userHandle, installerPackageName); 11501 } 11502 } 11503 // Also convey the prior install/uninstall state 11504 if (allUsers != null && perUserInstalled != null) { 11505 for (int i = 0; i < allUsers.length; i++) { 11506 if (DEBUG_INSTALL) { 11507 Slog.d(TAG, " user " + allUsers[i] 11508 + " => " + perUserInstalled[i]); 11509 } 11510 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11511 } 11512 // these install state changes will be persisted in the 11513 // upcoming call to mSettings.writeLPr(). 11514 } 11515 } 11516 // It's implied that when a user requests installation, they want the app to be 11517 // installed and enabled. 11518 int userId = user.getIdentifier(); 11519 if (userId != UserHandle.USER_ALL) { 11520 ps.setInstalled(true, userId); 11521 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11522 } 11523 } 11524 res.name = pkgName; 11525 res.uid = newPackage.applicationInfo.uid; 11526 res.pkg = newPackage; 11527 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11528 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11529 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11530 //to update install status 11531 mSettings.writeLPr(); 11532 } 11533 } 11534 11535 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11536 final int installFlags = args.installFlags; 11537 final String installerPackageName = args.installerPackageName; 11538 final String volumeUuid = args.volumeUuid; 11539 final File tmpPackageFile = new File(args.getCodePath()); 11540 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11541 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11542 || (args.volumeUuid != null)); 11543 boolean replace = false; 11544 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11545 // Result object to be returned 11546 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11547 11548 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11549 // Retrieve PackageSettings and parse package 11550 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11551 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11552 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11553 PackageParser pp = new PackageParser(); 11554 pp.setSeparateProcesses(mSeparateProcesses); 11555 pp.setDisplayMetrics(mMetrics); 11556 11557 final PackageParser.Package pkg; 11558 try { 11559 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11560 } catch (PackageParserException e) { 11561 res.setError("Failed parse during installPackageLI", e); 11562 return; 11563 } 11564 11565 // Mark that we have an install time CPU ABI override. 11566 pkg.cpuAbiOverride = args.abiOverride; 11567 11568 String pkgName = res.name = pkg.packageName; 11569 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11570 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11571 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11572 return; 11573 } 11574 } 11575 11576 try { 11577 pp.collectCertificates(pkg, parseFlags); 11578 pp.collectManifestDigest(pkg); 11579 } catch (PackageParserException e) { 11580 res.setError("Failed collect during installPackageLI", e); 11581 return; 11582 } 11583 11584 /* If the installer passed in a manifest digest, compare it now. */ 11585 if (args.manifestDigest != null) { 11586 if (DEBUG_INSTALL) { 11587 final String parsedManifest = pkg.manifestDigest == null ? "null" 11588 : pkg.manifestDigest.toString(); 11589 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11590 + parsedManifest); 11591 } 11592 11593 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11594 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11595 return; 11596 } 11597 } else if (DEBUG_INSTALL) { 11598 final String parsedManifest = pkg.manifestDigest == null 11599 ? "null" : pkg.manifestDigest.toString(); 11600 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11601 } 11602 11603 // Get rid of all references to package scan path via parser. 11604 pp = null; 11605 String oldCodePath = null; 11606 boolean systemApp = false; 11607 synchronized (mPackages) { 11608 // Check if installing already existing package 11609 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11610 String oldName = mSettings.mRenamedPackages.get(pkgName); 11611 if (pkg.mOriginalPackages != null 11612 && pkg.mOriginalPackages.contains(oldName) 11613 && mPackages.containsKey(oldName)) { 11614 // This package is derived from an original package, 11615 // and this device has been updating from that original 11616 // name. We must continue using the original name, so 11617 // rename the new package here. 11618 pkg.setPackageName(oldName); 11619 pkgName = pkg.packageName; 11620 replace = true; 11621 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11622 + oldName + " pkgName=" + pkgName); 11623 } else if (mPackages.containsKey(pkgName)) { 11624 // This package, under its official name, already exists 11625 // on the device; we should replace it. 11626 replace = true; 11627 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11628 } 11629 11630 // Prevent apps opting out from runtime permissions 11631 if (replace) { 11632 PackageParser.Package oldPackage = mPackages.get(pkgName); 11633 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11634 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11635 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11636 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11637 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11638 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11639 + " doesn't support runtime permissions but the old" 11640 + " target SDK " + oldTargetSdk + " does."); 11641 return; 11642 } 11643 } 11644 } 11645 11646 PackageSetting ps = mSettings.mPackages.get(pkgName); 11647 if (ps != null) { 11648 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11649 11650 // Quick sanity check that we're signed correctly if updating; 11651 // we'll check this again later when scanning, but we want to 11652 // bail early here before tripping over redefined permissions. 11653 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11654 if (!checkUpgradeKeySetLP(ps, pkg)) { 11655 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11656 + pkg.packageName + " upgrade keys do not match the " 11657 + "previously installed version"); 11658 return; 11659 } 11660 } else { 11661 try { 11662 verifySignaturesLP(ps, pkg); 11663 } catch (PackageManagerException e) { 11664 res.setError(e.error, e.getMessage()); 11665 return; 11666 } 11667 } 11668 11669 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11670 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11671 systemApp = (ps.pkg.applicationInfo.flags & 11672 ApplicationInfo.FLAG_SYSTEM) != 0; 11673 } 11674 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11675 } 11676 11677 // Check whether the newly-scanned package wants to define an already-defined perm 11678 int N = pkg.permissions.size(); 11679 for (int i = N-1; i >= 0; i--) { 11680 PackageParser.Permission perm = pkg.permissions.get(i); 11681 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11682 if (bp != null) { 11683 // If the defining package is signed with our cert, it's okay. This 11684 // also includes the "updating the same package" case, of course. 11685 // "updating same package" could also involve key-rotation. 11686 final boolean sigsOk; 11687 if (bp.sourcePackage.equals(pkg.packageName) 11688 && (bp.packageSetting instanceof PackageSetting) 11689 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11690 scanFlags))) { 11691 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11692 } else { 11693 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11694 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11695 } 11696 if (!sigsOk) { 11697 // If the owning package is the system itself, we log but allow 11698 // install to proceed; we fail the install on all other permission 11699 // redefinitions. 11700 if (!bp.sourcePackage.equals("android")) { 11701 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11702 + pkg.packageName + " attempting to redeclare permission " 11703 + perm.info.name + " already owned by " + bp.sourcePackage); 11704 res.origPermission = perm.info.name; 11705 res.origPackage = bp.sourcePackage; 11706 return; 11707 } else { 11708 Slog.w(TAG, "Package " + pkg.packageName 11709 + " attempting to redeclare system permission " 11710 + perm.info.name + "; ignoring new declaration"); 11711 pkg.permissions.remove(i); 11712 } 11713 } 11714 } 11715 } 11716 11717 } 11718 11719 if (systemApp && onExternal) { 11720 // Disable updates to system apps on sdcard 11721 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11722 "Cannot install updates to system apps on sdcard"); 11723 return; 11724 } 11725 11726 if (args.move != null) { 11727 // We did an in-place move, so dex is ready to roll 11728 scanFlags |= SCAN_NO_DEX; 11729 scanFlags |= SCAN_MOVE; 11730 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11731 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11732 scanFlags |= SCAN_NO_DEX; 11733 11734 try { 11735 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11736 true /* extract libs */); 11737 } catch (PackageManagerException pme) { 11738 Slog.e(TAG, "Error deriving application ABI", pme); 11739 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11740 return; 11741 } 11742 11743 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11744 int result = mPackageDexOptimizer 11745 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11746 false /* defer */, false /* inclDependencies */); 11747 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11748 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11749 return; 11750 } 11751 } 11752 11753 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11754 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11755 return; 11756 } 11757 11758 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11759 11760 if (replace) { 11761 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11762 installerPackageName, volumeUuid, res); 11763 } else { 11764 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11765 args.user, installerPackageName, volumeUuid, res); 11766 } 11767 synchronized (mPackages) { 11768 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11769 if (ps != null) { 11770 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11771 } 11772 } 11773 } 11774 11775 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11776 if (mIntentFilterVerifierComponent == null) { 11777 Slog.w(TAG, "No IntentFilter verification will not be done as " 11778 + "there is no IntentFilterVerifier available!"); 11779 return; 11780 } 11781 11782 final int verifierUid = getPackageUid( 11783 mIntentFilterVerifierComponent.getPackageName(), 11784 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11785 11786 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11787 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11788 msg.obj = pkg; 11789 msg.arg1 = userId; 11790 msg.arg2 = verifierUid; 11791 11792 mHandler.sendMessage(msg); 11793 } 11794 11795 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11796 PackageParser.Package pkg) { 11797 int size = pkg.activities.size(); 11798 if (size == 0) { 11799 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11800 "No activity, so no need to verify any IntentFilter!"); 11801 return; 11802 } 11803 11804 final boolean hasDomainURLs = hasDomainURLs(pkg); 11805 if (!hasDomainURLs) { 11806 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11807 "No domain URLs, so no need to verify any IntentFilter!"); 11808 return; 11809 } 11810 11811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11812 + " if any IntentFilter from the " + size 11813 + " Activities needs verification ..."); 11814 11815 final int verificationId = mIntentFilterVerificationToken++; 11816 int count = 0; 11817 final String packageName = pkg.packageName; 11818 boolean needToVerify = false; 11819 11820 synchronized (mPackages) { 11821 // If any filters need to be verified, then all need to be. 11822 for (PackageParser.Activity a : pkg.activities) { 11823 for (ActivityIntentInfo filter : a.intents) { 11824 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11825 if (DEBUG_DOMAIN_VERIFICATION) { 11826 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11827 } 11828 needToVerify = true; 11829 break; 11830 } 11831 } 11832 } 11833 if (needToVerify) { 11834 for (PackageParser.Activity a : pkg.activities) { 11835 for (ActivityIntentInfo filter : a.intents) { 11836 boolean needsFilterVerification = filter.hasWebDataURI(); 11837 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11839 "Verification needed for IntentFilter:" + filter.toString()); 11840 mIntentFilterVerifier.addOneIntentFilterVerification( 11841 verifierUid, userId, verificationId, filter, packageName); 11842 count++; 11843 } 11844 } 11845 } 11846 } 11847 } 11848 11849 if (count > 0) { 11850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11851 + " IntentFilter verification" + (count > 1 ? "s" : "") 11852 + " for userId:" + userId); 11853 mIntentFilterVerifier.startVerifications(userId); 11854 } else { 11855 if (DEBUG_DOMAIN_VERIFICATION) { 11856 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11857 } 11858 } 11859 } 11860 11861 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11862 final ComponentName cn = filter.activity.getComponentName(); 11863 final String packageName = cn.getPackageName(); 11864 11865 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11866 packageName); 11867 if (ivi == null) { 11868 return true; 11869 } 11870 int status = ivi.getStatus(); 11871 switch (status) { 11872 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11873 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11874 return true; 11875 11876 default: 11877 // Nothing to do 11878 return false; 11879 } 11880 } 11881 11882 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11883 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11884 || ((pkg.applicationInfo.privateFlags 11885 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11886 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11887 } 11888 11889 private static boolean isMultiArch(PackageSetting ps) { 11890 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11891 } 11892 11893 private static boolean isMultiArch(ApplicationInfo info) { 11894 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11895 } 11896 11897 private static boolean isExternal(PackageParser.Package pkg) { 11898 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11899 } 11900 11901 private static boolean isExternal(PackageSetting ps) { 11902 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11903 } 11904 11905 private static boolean isExternal(ApplicationInfo info) { 11906 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11907 } 11908 11909 private static boolean isSystemApp(PackageParser.Package pkg) { 11910 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11911 } 11912 11913 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11914 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11915 } 11916 11917 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11918 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11919 } 11920 11921 private static boolean isSystemApp(PackageSetting ps) { 11922 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11923 } 11924 11925 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11926 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11927 } 11928 11929 private int packageFlagsToInstallFlags(PackageSetting ps) { 11930 int installFlags = 0; 11931 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11932 // This existing package was an external ASEC install when we have 11933 // the external flag without a UUID 11934 installFlags |= PackageManager.INSTALL_EXTERNAL; 11935 } 11936 if (ps.isForwardLocked()) { 11937 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11938 } 11939 return installFlags; 11940 } 11941 11942 private void deleteTempPackageFiles() { 11943 final FilenameFilter filter = new FilenameFilter() { 11944 public boolean accept(File dir, String name) { 11945 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11946 } 11947 }; 11948 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11949 file.delete(); 11950 } 11951 } 11952 11953 @Override 11954 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11955 int flags) { 11956 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11957 flags); 11958 } 11959 11960 @Override 11961 public void deletePackage(final String packageName, 11962 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11963 mContext.enforceCallingOrSelfPermission( 11964 android.Manifest.permission.DELETE_PACKAGES, null); 11965 final int uid = Binder.getCallingUid(); 11966 if (UserHandle.getUserId(uid) != userId) { 11967 mContext.enforceCallingPermission( 11968 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11969 "deletePackage for user " + userId); 11970 } 11971 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11972 try { 11973 observer.onPackageDeleted(packageName, 11974 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11975 } catch (RemoteException re) { 11976 } 11977 return; 11978 } 11979 11980 boolean uninstallBlocked = false; 11981 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11982 int[] users = sUserManager.getUserIds(); 11983 for (int i = 0; i < users.length; ++i) { 11984 if (getBlockUninstallForUser(packageName, users[i])) { 11985 uninstallBlocked = true; 11986 break; 11987 } 11988 } 11989 } else { 11990 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11991 } 11992 if (uninstallBlocked) { 11993 try { 11994 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11995 null); 11996 } catch (RemoteException re) { 11997 } 11998 return; 11999 } 12000 12001 if (DEBUG_REMOVE) { 12002 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12003 } 12004 // Queue up an async operation since the package deletion may take a little while. 12005 mHandler.post(new Runnable() { 12006 public void run() { 12007 mHandler.removeCallbacks(this); 12008 final int returnCode = deletePackageX(packageName, userId, flags); 12009 if (observer != null) { 12010 try { 12011 observer.onPackageDeleted(packageName, returnCode, null); 12012 } catch (RemoteException e) { 12013 Log.i(TAG, "Observer no longer exists."); 12014 } //end catch 12015 } //end if 12016 } //end run 12017 }); 12018 } 12019 12020 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12021 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12022 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12023 try { 12024 if (dpm != null) { 12025 if (dpm.isDeviceOwner(packageName)) { 12026 return true; 12027 } 12028 int[] users; 12029 if (userId == UserHandle.USER_ALL) { 12030 users = sUserManager.getUserIds(); 12031 } else { 12032 users = new int[]{userId}; 12033 } 12034 for (int i = 0; i < users.length; ++i) { 12035 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12036 return true; 12037 } 12038 } 12039 } 12040 } catch (RemoteException e) { 12041 } 12042 return false; 12043 } 12044 12045 /** 12046 * This method is an internal method that could be get invoked either 12047 * to delete an installed package or to clean up a failed installation. 12048 * After deleting an installed package, a broadcast is sent to notify any 12049 * listeners that the package has been installed. For cleaning up a failed 12050 * installation, the broadcast is not necessary since the package's 12051 * installation wouldn't have sent the initial broadcast either 12052 * The key steps in deleting a package are 12053 * deleting the package information in internal structures like mPackages, 12054 * deleting the packages base directories through installd 12055 * updating mSettings to reflect current status 12056 * persisting settings for later use 12057 * sending a broadcast if necessary 12058 */ 12059 private int deletePackageX(String packageName, int userId, int flags) { 12060 final PackageRemovedInfo info = new PackageRemovedInfo(); 12061 final boolean res; 12062 12063 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12064 ? UserHandle.ALL : new UserHandle(userId); 12065 12066 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12067 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12068 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12069 } 12070 12071 boolean removedForAllUsers = false; 12072 boolean systemUpdate = false; 12073 12074 // for the uninstall-updates case and restricted profiles, remember the per- 12075 // userhandle installed state 12076 int[] allUsers; 12077 boolean[] perUserInstalled; 12078 synchronized (mPackages) { 12079 PackageSetting ps = mSettings.mPackages.get(packageName); 12080 allUsers = sUserManager.getUserIds(); 12081 perUserInstalled = new boolean[allUsers.length]; 12082 for (int i = 0; i < allUsers.length; i++) { 12083 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12084 } 12085 } 12086 12087 synchronized (mInstallLock) { 12088 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12089 res = deletePackageLI(packageName, removeForUser, 12090 true, allUsers, perUserInstalled, 12091 flags | REMOVE_CHATTY, info, true); 12092 systemUpdate = info.isRemovedPackageSystemUpdate; 12093 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12094 removedForAllUsers = true; 12095 } 12096 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12097 + " removedForAllUsers=" + removedForAllUsers); 12098 } 12099 12100 if (res) { 12101 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12102 12103 // If the removed package was a system update, the old system package 12104 // was re-enabled; we need to broadcast this information 12105 if (systemUpdate) { 12106 Bundle extras = new Bundle(1); 12107 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12108 ? info.removedAppId : info.uid); 12109 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12110 12111 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12112 extras, null, null, null); 12113 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12114 extras, null, null, null); 12115 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12116 null, packageName, null, null); 12117 } 12118 } 12119 // Force a gc here. 12120 Runtime.getRuntime().gc(); 12121 // Delete the resources here after sending the broadcast to let 12122 // other processes clean up before deleting resources. 12123 if (info.args != null) { 12124 synchronized (mInstallLock) { 12125 info.args.doPostDeleteLI(true); 12126 } 12127 } 12128 12129 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12130 } 12131 12132 class PackageRemovedInfo { 12133 String removedPackage; 12134 int uid = -1; 12135 int removedAppId = -1; 12136 int[] removedUsers = null; 12137 boolean isRemovedPackageSystemUpdate = false; 12138 // Clean up resources deleted packages. 12139 InstallArgs args = null; 12140 12141 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12142 Bundle extras = new Bundle(1); 12143 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12144 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12145 if (replacing) { 12146 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12147 } 12148 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12149 if (removedPackage != null) { 12150 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12151 extras, null, null, removedUsers); 12152 if (fullRemove && !replacing) { 12153 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12154 extras, null, null, removedUsers); 12155 } 12156 } 12157 if (removedAppId >= 0) { 12158 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12159 removedUsers); 12160 } 12161 } 12162 } 12163 12164 /* 12165 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12166 * flag is not set, the data directory is removed as well. 12167 * make sure this flag is set for partially installed apps. If not its meaningless to 12168 * delete a partially installed application. 12169 */ 12170 private void removePackageDataLI(PackageSetting ps, 12171 int[] allUserHandles, boolean[] perUserInstalled, 12172 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12173 String packageName = ps.name; 12174 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12175 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12176 // Retrieve object to delete permissions for shared user later on 12177 final PackageSetting deletedPs; 12178 // reader 12179 synchronized (mPackages) { 12180 deletedPs = mSettings.mPackages.get(packageName); 12181 if (outInfo != null) { 12182 outInfo.removedPackage = packageName; 12183 outInfo.removedUsers = deletedPs != null 12184 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12185 : null; 12186 } 12187 } 12188 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12189 removeDataDirsLI(ps.volumeUuid, packageName); 12190 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12191 } 12192 // writer 12193 synchronized (mPackages) { 12194 if (deletedPs != null) { 12195 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12196 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12197 clearDefaultBrowserIfNeeded(packageName); 12198 if (outInfo != null) { 12199 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12200 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12201 } 12202 updatePermissionsLPw(deletedPs.name, null, 0); 12203 if (deletedPs.sharedUser != null) { 12204 // Remove permissions associated with package. Since runtime 12205 // permissions are per user we have to kill the removed package 12206 // or packages running under the shared user of the removed 12207 // package if revoking the permissions requested only by the removed 12208 // package is successful and this causes a change in gids. 12209 for (int userId : UserManagerService.getInstance().getUserIds()) { 12210 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12211 userId); 12212 if (userIdToKill == UserHandle.USER_ALL 12213 || userIdToKill >= UserHandle.USER_OWNER) { 12214 // If gids changed for this user, kill all affected packages. 12215 mHandler.post(new Runnable() { 12216 @Override 12217 public void run() { 12218 // This has to happen with no lock held. 12219 killSettingPackagesForUser(deletedPs, userIdToKill, 12220 KILL_APP_REASON_GIDS_CHANGED); 12221 } 12222 }); 12223 break; 12224 } 12225 } 12226 } 12227 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12228 } 12229 // make sure to preserve per-user disabled state if this removal was just 12230 // a downgrade of a system app to the factory package 12231 if (allUserHandles != null && perUserInstalled != null) { 12232 if (DEBUG_REMOVE) { 12233 Slog.d(TAG, "Propagating install state across downgrade"); 12234 } 12235 for (int i = 0; i < allUserHandles.length; i++) { 12236 if (DEBUG_REMOVE) { 12237 Slog.d(TAG, " user " + allUserHandles[i] 12238 + " => " + perUserInstalled[i]); 12239 } 12240 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12241 } 12242 } 12243 } 12244 // can downgrade to reader 12245 if (writeSettings) { 12246 // Save settings now 12247 mSettings.writeLPr(); 12248 } 12249 } 12250 if (outInfo != null) { 12251 // A user ID was deleted here. Go through all users and remove it 12252 // from KeyStore. 12253 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12254 } 12255 } 12256 12257 static boolean locationIsPrivileged(File path) { 12258 try { 12259 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12260 .getCanonicalPath(); 12261 return path.getCanonicalPath().startsWith(privilegedAppDir); 12262 } catch (IOException e) { 12263 Slog.e(TAG, "Unable to access code path " + path); 12264 } 12265 return false; 12266 } 12267 12268 /* 12269 * Tries to delete system package. 12270 */ 12271 private boolean deleteSystemPackageLI(PackageSetting newPs, 12272 int[] allUserHandles, boolean[] perUserInstalled, 12273 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12274 final boolean applyUserRestrictions 12275 = (allUserHandles != null) && (perUserInstalled != null); 12276 PackageSetting disabledPs = null; 12277 // Confirm if the system package has been updated 12278 // An updated system app can be deleted. This will also have to restore 12279 // the system pkg from system partition 12280 // reader 12281 synchronized (mPackages) { 12282 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12283 } 12284 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12285 + " disabledPs=" + disabledPs); 12286 if (disabledPs == null) { 12287 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12288 return false; 12289 } else if (DEBUG_REMOVE) { 12290 Slog.d(TAG, "Deleting system pkg from data partition"); 12291 } 12292 if (DEBUG_REMOVE) { 12293 if (applyUserRestrictions) { 12294 Slog.d(TAG, "Remembering install states:"); 12295 for (int i = 0; i < allUserHandles.length; i++) { 12296 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12297 } 12298 } 12299 } 12300 // Delete the updated package 12301 outInfo.isRemovedPackageSystemUpdate = true; 12302 if (disabledPs.versionCode < newPs.versionCode) { 12303 // Delete data for downgrades 12304 flags &= ~PackageManager.DELETE_KEEP_DATA; 12305 } else { 12306 // Preserve data by setting flag 12307 flags |= PackageManager.DELETE_KEEP_DATA; 12308 } 12309 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12310 allUserHandles, perUserInstalled, outInfo, writeSettings); 12311 if (!ret) { 12312 return false; 12313 } 12314 // writer 12315 synchronized (mPackages) { 12316 // Reinstate the old system package 12317 mSettings.enableSystemPackageLPw(newPs.name); 12318 // Remove any native libraries from the upgraded package. 12319 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12320 } 12321 // Install the system package 12322 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12323 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12324 if (locationIsPrivileged(disabledPs.codePath)) { 12325 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12326 } 12327 12328 final PackageParser.Package newPkg; 12329 try { 12330 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12331 } catch (PackageManagerException e) { 12332 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12333 return false; 12334 } 12335 12336 // writer 12337 synchronized (mPackages) { 12338 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12339 updatePermissionsLPw(newPkg.packageName, newPkg, 12340 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12341 if (applyUserRestrictions) { 12342 if (DEBUG_REMOVE) { 12343 Slog.d(TAG, "Propagating install state across reinstall"); 12344 } 12345 for (int i = 0; i < allUserHandles.length; i++) { 12346 if (DEBUG_REMOVE) { 12347 Slog.d(TAG, " user " + allUserHandles[i] 12348 + " => " + perUserInstalled[i]); 12349 } 12350 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12351 } 12352 // Regardless of writeSettings we need to ensure that this restriction 12353 // state propagation is persisted 12354 mSettings.writeAllUsersPackageRestrictionsLPr(); 12355 } 12356 // can downgrade to reader here 12357 if (writeSettings) { 12358 mSettings.writeLPr(); 12359 } 12360 } 12361 return true; 12362 } 12363 12364 private boolean deleteInstalledPackageLI(PackageSetting ps, 12365 boolean deleteCodeAndResources, int flags, 12366 int[] allUserHandles, boolean[] perUserInstalled, 12367 PackageRemovedInfo outInfo, boolean writeSettings) { 12368 if (outInfo != null) { 12369 outInfo.uid = ps.appId; 12370 } 12371 12372 // Delete package data from internal structures and also remove data if flag is set 12373 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12374 12375 // Delete application code and resources 12376 if (deleteCodeAndResources && (outInfo != null)) { 12377 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12378 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12379 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12380 } 12381 return true; 12382 } 12383 12384 @Override 12385 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12386 int userId) { 12387 mContext.enforceCallingOrSelfPermission( 12388 android.Manifest.permission.DELETE_PACKAGES, null); 12389 synchronized (mPackages) { 12390 PackageSetting ps = mSettings.mPackages.get(packageName); 12391 if (ps == null) { 12392 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12393 return false; 12394 } 12395 if (!ps.getInstalled(userId)) { 12396 // Can't block uninstall for an app that is not installed or enabled. 12397 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12398 return false; 12399 } 12400 ps.setBlockUninstall(blockUninstall, userId); 12401 mSettings.writePackageRestrictionsLPr(userId); 12402 } 12403 return true; 12404 } 12405 12406 @Override 12407 public boolean getBlockUninstallForUser(String packageName, int userId) { 12408 synchronized (mPackages) { 12409 PackageSetting ps = mSettings.mPackages.get(packageName); 12410 if (ps == null) { 12411 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12412 return false; 12413 } 12414 return ps.getBlockUninstall(userId); 12415 } 12416 } 12417 12418 /* 12419 * This method handles package deletion in general 12420 */ 12421 private boolean deletePackageLI(String packageName, UserHandle user, 12422 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12423 int flags, PackageRemovedInfo outInfo, 12424 boolean writeSettings) { 12425 if (packageName == null) { 12426 Slog.w(TAG, "Attempt to delete null packageName."); 12427 return false; 12428 } 12429 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12430 PackageSetting ps; 12431 boolean dataOnly = false; 12432 int removeUser = -1; 12433 int appId = -1; 12434 synchronized (mPackages) { 12435 ps = mSettings.mPackages.get(packageName); 12436 if (ps == null) { 12437 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12438 return false; 12439 } 12440 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12441 && user.getIdentifier() != UserHandle.USER_ALL) { 12442 // The caller is asking that the package only be deleted for a single 12443 // user. To do this, we just mark its uninstalled state and delete 12444 // its data. If this is a system app, we only allow this to happen if 12445 // they have set the special DELETE_SYSTEM_APP which requests different 12446 // semantics than normal for uninstalling system apps. 12447 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12448 ps.setUserState(user.getIdentifier(), 12449 COMPONENT_ENABLED_STATE_DEFAULT, 12450 false, //installed 12451 true, //stopped 12452 true, //notLaunched 12453 false, //hidden 12454 null, null, null, 12455 false, // blockUninstall 12456 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12457 if (!isSystemApp(ps)) { 12458 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12459 // Other user still have this package installed, so all 12460 // we need to do is clear this user's data and save that 12461 // it is uninstalled. 12462 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12463 removeUser = user.getIdentifier(); 12464 appId = ps.appId; 12465 scheduleWritePackageRestrictionsLocked(removeUser); 12466 } else { 12467 // We need to set it back to 'installed' so the uninstall 12468 // broadcasts will be sent correctly. 12469 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12470 ps.setInstalled(true, user.getIdentifier()); 12471 } 12472 } else { 12473 // This is a system app, so we assume that the 12474 // other users still have this package installed, so all 12475 // we need to do is clear this user's data and save that 12476 // it is uninstalled. 12477 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12478 removeUser = user.getIdentifier(); 12479 appId = ps.appId; 12480 scheduleWritePackageRestrictionsLocked(removeUser); 12481 } 12482 } 12483 } 12484 12485 if (removeUser >= 0) { 12486 // From above, we determined that we are deleting this only 12487 // for a single user. Continue the work here. 12488 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12489 if (outInfo != null) { 12490 outInfo.removedPackage = packageName; 12491 outInfo.removedAppId = appId; 12492 outInfo.removedUsers = new int[] {removeUser}; 12493 } 12494 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12495 removeKeystoreDataIfNeeded(removeUser, appId); 12496 schedulePackageCleaning(packageName, removeUser, false); 12497 synchronized (mPackages) { 12498 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12499 scheduleWritePackageRestrictionsLocked(removeUser); 12500 } 12501 } 12502 return true; 12503 } 12504 12505 if (dataOnly) { 12506 // Delete application data first 12507 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12508 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12509 return true; 12510 } 12511 12512 boolean ret = false; 12513 if (isSystemApp(ps)) { 12514 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12515 // When an updated system application is deleted we delete the existing resources as well and 12516 // fall back to existing code in system partition 12517 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12518 flags, outInfo, writeSettings); 12519 } else { 12520 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12521 // Kill application pre-emptively especially for apps on sd. 12522 killApplication(packageName, ps.appId, "uninstall pkg"); 12523 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12524 allUserHandles, perUserInstalled, 12525 outInfo, writeSettings); 12526 } 12527 12528 return ret; 12529 } 12530 12531 private final class ClearStorageConnection implements ServiceConnection { 12532 IMediaContainerService mContainerService; 12533 12534 @Override 12535 public void onServiceConnected(ComponentName name, IBinder service) { 12536 synchronized (this) { 12537 mContainerService = IMediaContainerService.Stub.asInterface(service); 12538 notifyAll(); 12539 } 12540 } 12541 12542 @Override 12543 public void onServiceDisconnected(ComponentName name) { 12544 } 12545 } 12546 12547 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12548 final boolean mounted; 12549 if (Environment.isExternalStorageEmulated()) { 12550 mounted = true; 12551 } else { 12552 final String status = Environment.getExternalStorageState(); 12553 12554 mounted = status.equals(Environment.MEDIA_MOUNTED) 12555 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12556 } 12557 12558 if (!mounted) { 12559 return; 12560 } 12561 12562 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12563 int[] users; 12564 if (userId == UserHandle.USER_ALL) { 12565 users = sUserManager.getUserIds(); 12566 } else { 12567 users = new int[] { userId }; 12568 } 12569 final ClearStorageConnection conn = new ClearStorageConnection(); 12570 if (mContext.bindServiceAsUser( 12571 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12572 try { 12573 for (int curUser : users) { 12574 long timeout = SystemClock.uptimeMillis() + 5000; 12575 synchronized (conn) { 12576 long now = SystemClock.uptimeMillis(); 12577 while (conn.mContainerService == null && now < timeout) { 12578 try { 12579 conn.wait(timeout - now); 12580 } catch (InterruptedException e) { 12581 } 12582 } 12583 } 12584 if (conn.mContainerService == null) { 12585 return; 12586 } 12587 12588 final UserEnvironment userEnv = new UserEnvironment(curUser); 12589 clearDirectory(conn.mContainerService, 12590 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12591 if (allData) { 12592 clearDirectory(conn.mContainerService, 12593 userEnv.buildExternalStorageAppDataDirs(packageName)); 12594 clearDirectory(conn.mContainerService, 12595 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12596 } 12597 } 12598 } finally { 12599 mContext.unbindService(conn); 12600 } 12601 } 12602 } 12603 12604 @Override 12605 public void clearApplicationUserData(final String packageName, 12606 final IPackageDataObserver observer, final int userId) { 12607 mContext.enforceCallingOrSelfPermission( 12608 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12609 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12610 // Queue up an async operation since the package deletion may take a little while. 12611 mHandler.post(new Runnable() { 12612 public void run() { 12613 mHandler.removeCallbacks(this); 12614 final boolean succeeded; 12615 synchronized (mInstallLock) { 12616 succeeded = clearApplicationUserDataLI(packageName, userId); 12617 } 12618 clearExternalStorageDataSync(packageName, userId, true); 12619 if (succeeded) { 12620 // invoke DeviceStorageMonitor's update method to clear any notifications 12621 DeviceStorageMonitorInternal 12622 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12623 if (dsm != null) { 12624 dsm.checkMemory(); 12625 } 12626 } 12627 if(observer != null) { 12628 try { 12629 observer.onRemoveCompleted(packageName, succeeded); 12630 } catch (RemoteException e) { 12631 Log.i(TAG, "Observer no longer exists."); 12632 } 12633 } //end if observer 12634 } //end run 12635 }); 12636 } 12637 12638 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12639 if (packageName == null) { 12640 Slog.w(TAG, "Attempt to delete null packageName."); 12641 return false; 12642 } 12643 12644 // Try finding details about the requested package 12645 PackageParser.Package pkg; 12646 synchronized (mPackages) { 12647 pkg = mPackages.get(packageName); 12648 if (pkg == null) { 12649 final PackageSetting ps = mSettings.mPackages.get(packageName); 12650 if (ps != null) { 12651 pkg = ps.pkg; 12652 } 12653 } 12654 12655 if (pkg == null) { 12656 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12657 return false; 12658 } 12659 12660 PackageSetting ps = (PackageSetting) pkg.mExtras; 12661 PermissionsState permissionsState = ps.getPermissionsState(); 12662 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12663 } 12664 12665 // Always delete data directories for package, even if we found no other 12666 // record of app. This helps users recover from UID mismatches without 12667 // resorting to a full data wipe. 12668 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12669 if (retCode < 0) { 12670 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12671 return false; 12672 } 12673 12674 final int appId = pkg.applicationInfo.uid; 12675 removeKeystoreDataIfNeeded(userId, appId); 12676 12677 // Create a native library symlink only if we have native libraries 12678 // and if the native libraries are 32 bit libraries. We do not provide 12679 // this symlink for 64 bit libraries. 12680 if (pkg.applicationInfo.primaryCpuAbi != null && 12681 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12682 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12683 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12684 nativeLibPath, userId) < 0) { 12685 Slog.w(TAG, "Failed linking native library dir"); 12686 return false; 12687 } 12688 } 12689 12690 return true; 12691 } 12692 12693 12694 /** 12695 * Revokes granted runtime permissions and clears resettable flags 12696 * which are flags that can be set by a user interaction. 12697 * 12698 * @param permissionsState The permission state to reset. 12699 * @param userId The device user for which to do a reset. 12700 */ 12701 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12702 PermissionsState permissionsState, int userId) { 12703 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12704 | PackageManager.FLAG_PERMISSION_USER_FIXED 12705 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12706 12707 boolean needsWrite = false; 12708 12709 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12710 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12711 if (bp != null) { 12712 permissionsState.revokeRuntimePermission(bp, userId); 12713 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12714 needsWrite = true; 12715 } 12716 } 12717 12718 if (needsWrite) { 12719 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12720 } 12721 } 12722 12723 /** 12724 * Remove entries from the keystore daemon. Will only remove it if the 12725 * {@code appId} is valid. 12726 */ 12727 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12728 if (appId < 0) { 12729 return; 12730 } 12731 12732 final KeyStore keyStore = KeyStore.getInstance(); 12733 if (keyStore != null) { 12734 if (userId == UserHandle.USER_ALL) { 12735 for (final int individual : sUserManager.getUserIds()) { 12736 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12737 } 12738 } else { 12739 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12740 } 12741 } else { 12742 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12743 } 12744 } 12745 12746 @Override 12747 public void deleteApplicationCacheFiles(final String packageName, 12748 final IPackageDataObserver observer) { 12749 mContext.enforceCallingOrSelfPermission( 12750 android.Manifest.permission.DELETE_CACHE_FILES, null); 12751 // Queue up an async operation since the package deletion may take a little while. 12752 final int userId = UserHandle.getCallingUserId(); 12753 mHandler.post(new Runnable() { 12754 public void run() { 12755 mHandler.removeCallbacks(this); 12756 final boolean succeded; 12757 synchronized (mInstallLock) { 12758 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12759 } 12760 clearExternalStorageDataSync(packageName, userId, false); 12761 if (observer != null) { 12762 try { 12763 observer.onRemoveCompleted(packageName, succeded); 12764 } catch (RemoteException e) { 12765 Log.i(TAG, "Observer no longer exists."); 12766 } 12767 } //end if observer 12768 } //end run 12769 }); 12770 } 12771 12772 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12773 if (packageName == null) { 12774 Slog.w(TAG, "Attempt to delete null packageName."); 12775 return false; 12776 } 12777 PackageParser.Package p; 12778 synchronized (mPackages) { 12779 p = mPackages.get(packageName); 12780 } 12781 if (p == null) { 12782 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12783 return false; 12784 } 12785 final ApplicationInfo applicationInfo = p.applicationInfo; 12786 if (applicationInfo == null) { 12787 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12788 return false; 12789 } 12790 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12791 if (retCode < 0) { 12792 Slog.w(TAG, "Couldn't remove cache files for package: " 12793 + packageName + " u" + userId); 12794 return false; 12795 } 12796 return true; 12797 } 12798 12799 @Override 12800 public void getPackageSizeInfo(final String packageName, int userHandle, 12801 final IPackageStatsObserver observer) { 12802 mContext.enforceCallingOrSelfPermission( 12803 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12804 if (packageName == null) { 12805 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12806 } 12807 12808 PackageStats stats = new PackageStats(packageName, userHandle); 12809 12810 /* 12811 * Queue up an async operation since the package measurement may take a 12812 * little while. 12813 */ 12814 Message msg = mHandler.obtainMessage(INIT_COPY); 12815 msg.obj = new MeasureParams(stats, observer); 12816 mHandler.sendMessage(msg); 12817 } 12818 12819 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12820 PackageStats pStats) { 12821 if (packageName == null) { 12822 Slog.w(TAG, "Attempt to get size of null packageName."); 12823 return false; 12824 } 12825 PackageParser.Package p; 12826 boolean dataOnly = false; 12827 String libDirRoot = null; 12828 String asecPath = null; 12829 PackageSetting ps = null; 12830 synchronized (mPackages) { 12831 p = mPackages.get(packageName); 12832 ps = mSettings.mPackages.get(packageName); 12833 if(p == null) { 12834 dataOnly = true; 12835 if((ps == null) || (ps.pkg == null)) { 12836 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12837 return false; 12838 } 12839 p = ps.pkg; 12840 } 12841 if (ps != null) { 12842 libDirRoot = ps.legacyNativeLibraryPathString; 12843 } 12844 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12845 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12846 if (secureContainerId != null) { 12847 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12848 } 12849 } 12850 } 12851 String publicSrcDir = null; 12852 if(!dataOnly) { 12853 final ApplicationInfo applicationInfo = p.applicationInfo; 12854 if (applicationInfo == null) { 12855 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12856 return false; 12857 } 12858 if (p.isForwardLocked()) { 12859 publicSrcDir = applicationInfo.getBaseResourcePath(); 12860 } 12861 } 12862 // TODO: extend to measure size of split APKs 12863 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12864 // not just the first level. 12865 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12866 // just the primary. 12867 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12868 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12869 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12870 if (res < 0) { 12871 return false; 12872 } 12873 12874 // Fix-up for forward-locked applications in ASEC containers. 12875 if (!isExternal(p)) { 12876 pStats.codeSize += pStats.externalCodeSize; 12877 pStats.externalCodeSize = 0L; 12878 } 12879 12880 return true; 12881 } 12882 12883 12884 @Override 12885 public void addPackageToPreferred(String packageName) { 12886 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12887 } 12888 12889 @Override 12890 public void removePackageFromPreferred(String packageName) { 12891 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12892 } 12893 12894 @Override 12895 public List<PackageInfo> getPreferredPackages(int flags) { 12896 return new ArrayList<PackageInfo>(); 12897 } 12898 12899 private int getUidTargetSdkVersionLockedLPr(int uid) { 12900 Object obj = mSettings.getUserIdLPr(uid); 12901 if (obj instanceof SharedUserSetting) { 12902 final SharedUserSetting sus = (SharedUserSetting) obj; 12903 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12904 final Iterator<PackageSetting> it = sus.packages.iterator(); 12905 while (it.hasNext()) { 12906 final PackageSetting ps = it.next(); 12907 if (ps.pkg != null) { 12908 int v = ps.pkg.applicationInfo.targetSdkVersion; 12909 if (v < vers) vers = v; 12910 } 12911 } 12912 return vers; 12913 } else if (obj instanceof PackageSetting) { 12914 final PackageSetting ps = (PackageSetting) obj; 12915 if (ps.pkg != null) { 12916 return ps.pkg.applicationInfo.targetSdkVersion; 12917 } 12918 } 12919 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12920 } 12921 12922 @Override 12923 public void addPreferredActivity(IntentFilter filter, int match, 12924 ComponentName[] set, ComponentName activity, int userId) { 12925 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12926 "Adding preferred"); 12927 } 12928 12929 private void addPreferredActivityInternal(IntentFilter filter, int match, 12930 ComponentName[] set, ComponentName activity, boolean always, int userId, 12931 String opname) { 12932 // writer 12933 int callingUid = Binder.getCallingUid(); 12934 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12935 if (filter.countActions() == 0) { 12936 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12937 return; 12938 } 12939 synchronized (mPackages) { 12940 if (mContext.checkCallingOrSelfPermission( 12941 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12942 != PackageManager.PERMISSION_GRANTED) { 12943 if (getUidTargetSdkVersionLockedLPr(callingUid) 12944 < Build.VERSION_CODES.FROYO) { 12945 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12946 + callingUid); 12947 return; 12948 } 12949 mContext.enforceCallingOrSelfPermission( 12950 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12951 } 12952 12953 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12954 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12955 + userId + ":"); 12956 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12957 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12958 scheduleWritePackageRestrictionsLocked(userId); 12959 } 12960 } 12961 12962 @Override 12963 public void replacePreferredActivity(IntentFilter filter, int match, 12964 ComponentName[] set, ComponentName activity, int userId) { 12965 if (filter.countActions() != 1) { 12966 throw new IllegalArgumentException( 12967 "replacePreferredActivity expects filter to have only 1 action."); 12968 } 12969 if (filter.countDataAuthorities() != 0 12970 || filter.countDataPaths() != 0 12971 || filter.countDataSchemes() > 1 12972 || filter.countDataTypes() != 0) { 12973 throw new IllegalArgumentException( 12974 "replacePreferredActivity expects filter to have no data authorities, " + 12975 "paths, or types; and at most one scheme."); 12976 } 12977 12978 final int callingUid = Binder.getCallingUid(); 12979 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12980 synchronized (mPackages) { 12981 if (mContext.checkCallingOrSelfPermission( 12982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12983 != PackageManager.PERMISSION_GRANTED) { 12984 if (getUidTargetSdkVersionLockedLPr(callingUid) 12985 < Build.VERSION_CODES.FROYO) { 12986 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12987 + Binder.getCallingUid()); 12988 return; 12989 } 12990 mContext.enforceCallingOrSelfPermission( 12991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12992 } 12993 12994 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12995 if (pir != null) { 12996 // Get all of the existing entries that exactly match this filter. 12997 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12998 if (existing != null && existing.size() == 1) { 12999 PreferredActivity cur = existing.get(0); 13000 if (DEBUG_PREFERRED) { 13001 Slog.i(TAG, "Checking replace of preferred:"); 13002 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13003 if (!cur.mPref.mAlways) { 13004 Slog.i(TAG, " -- CUR; not mAlways!"); 13005 } else { 13006 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13007 Slog.i(TAG, " -- CUR: mSet=" 13008 + Arrays.toString(cur.mPref.mSetComponents)); 13009 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13010 Slog.i(TAG, " -- NEW: mMatch=" 13011 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13012 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13013 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13014 } 13015 } 13016 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13017 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13018 && cur.mPref.sameSet(set)) { 13019 // Setting the preferred activity to what it happens to be already 13020 if (DEBUG_PREFERRED) { 13021 Slog.i(TAG, "Replacing with same preferred activity " 13022 + cur.mPref.mShortComponent + " for user " 13023 + userId + ":"); 13024 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13025 } 13026 return; 13027 } 13028 } 13029 13030 if (existing != null) { 13031 if (DEBUG_PREFERRED) { 13032 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13033 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13034 } 13035 for (int i = 0; i < existing.size(); i++) { 13036 PreferredActivity pa = existing.get(i); 13037 if (DEBUG_PREFERRED) { 13038 Slog.i(TAG, "Removing existing preferred activity " 13039 + pa.mPref.mComponent + ":"); 13040 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13041 } 13042 pir.removeFilter(pa); 13043 } 13044 } 13045 } 13046 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13047 "Replacing preferred"); 13048 } 13049 } 13050 13051 @Override 13052 public void clearPackagePreferredActivities(String packageName) { 13053 final int uid = Binder.getCallingUid(); 13054 // writer 13055 synchronized (mPackages) { 13056 PackageParser.Package pkg = mPackages.get(packageName); 13057 if (pkg == null || pkg.applicationInfo.uid != uid) { 13058 if (mContext.checkCallingOrSelfPermission( 13059 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13060 != PackageManager.PERMISSION_GRANTED) { 13061 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13062 < Build.VERSION_CODES.FROYO) { 13063 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13064 + Binder.getCallingUid()); 13065 return; 13066 } 13067 mContext.enforceCallingOrSelfPermission( 13068 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13069 } 13070 } 13071 13072 int user = UserHandle.getCallingUserId(); 13073 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13074 scheduleWritePackageRestrictionsLocked(user); 13075 } 13076 } 13077 } 13078 13079 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13080 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13081 ArrayList<PreferredActivity> removed = null; 13082 boolean changed = false; 13083 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13084 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13085 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13086 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13087 continue; 13088 } 13089 Iterator<PreferredActivity> it = pir.filterIterator(); 13090 while (it.hasNext()) { 13091 PreferredActivity pa = it.next(); 13092 // Mark entry for removal only if it matches the package name 13093 // and the entry is of type "always". 13094 if (packageName == null || 13095 (pa.mPref.mComponent.getPackageName().equals(packageName) 13096 && pa.mPref.mAlways)) { 13097 if (removed == null) { 13098 removed = new ArrayList<PreferredActivity>(); 13099 } 13100 removed.add(pa); 13101 } 13102 } 13103 if (removed != null) { 13104 for (int j=0; j<removed.size(); j++) { 13105 PreferredActivity pa = removed.get(j); 13106 pir.removeFilter(pa); 13107 } 13108 changed = true; 13109 } 13110 } 13111 return changed; 13112 } 13113 13114 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13115 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13116 if (userId == UserHandle.USER_ALL) { 13117 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13118 sUserManager.getUserIds())) { 13119 for (int oneUserId : sUserManager.getUserIds()) { 13120 scheduleWritePackageRestrictionsLocked(oneUserId); 13121 } 13122 } 13123 } else { 13124 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13125 scheduleWritePackageRestrictionsLocked(userId); 13126 } 13127 } 13128 } 13129 13130 13131 void clearDefaultBrowserIfNeeded(String packageName) { 13132 for (int oneUserId : sUserManager.getUserIds()) { 13133 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13134 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13135 if (packageName.equals(defaultBrowserPackageName)) { 13136 setDefaultBrowserPackageName(null, oneUserId); 13137 } 13138 } 13139 } 13140 13141 @Override 13142 public void resetPreferredActivities(int userId) { 13143 /* TODO: Actually use userId. Why is it being passed in? */ 13144 mContext.enforceCallingOrSelfPermission( 13145 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13146 // writer 13147 synchronized (mPackages) { 13148 int user = UserHandle.getCallingUserId(); 13149 clearPackagePreferredActivitiesLPw(null, user); 13150 mSettings.readDefaultPreferredAppsLPw(this, user); 13151 scheduleWritePackageRestrictionsLocked(user); 13152 } 13153 } 13154 13155 @Override 13156 public int getPreferredActivities(List<IntentFilter> outFilters, 13157 List<ComponentName> outActivities, String packageName) { 13158 13159 int num = 0; 13160 final int userId = UserHandle.getCallingUserId(); 13161 // reader 13162 synchronized (mPackages) { 13163 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13164 if (pir != null) { 13165 final Iterator<PreferredActivity> it = pir.filterIterator(); 13166 while (it.hasNext()) { 13167 final PreferredActivity pa = it.next(); 13168 if (packageName == null 13169 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13170 && pa.mPref.mAlways)) { 13171 if (outFilters != null) { 13172 outFilters.add(new IntentFilter(pa)); 13173 } 13174 if (outActivities != null) { 13175 outActivities.add(pa.mPref.mComponent); 13176 } 13177 } 13178 } 13179 } 13180 } 13181 13182 return num; 13183 } 13184 13185 @Override 13186 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13187 int userId) { 13188 int callingUid = Binder.getCallingUid(); 13189 if (callingUid != Process.SYSTEM_UID) { 13190 throw new SecurityException( 13191 "addPersistentPreferredActivity can only be run by the system"); 13192 } 13193 if (filter.countActions() == 0) { 13194 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13195 return; 13196 } 13197 synchronized (mPackages) { 13198 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13199 " :"); 13200 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13201 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13202 new PersistentPreferredActivity(filter, activity)); 13203 scheduleWritePackageRestrictionsLocked(userId); 13204 } 13205 } 13206 13207 @Override 13208 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13209 int callingUid = Binder.getCallingUid(); 13210 if (callingUid != Process.SYSTEM_UID) { 13211 throw new SecurityException( 13212 "clearPackagePersistentPreferredActivities can only be run by the system"); 13213 } 13214 ArrayList<PersistentPreferredActivity> removed = null; 13215 boolean changed = false; 13216 synchronized (mPackages) { 13217 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13218 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13219 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13220 .valueAt(i); 13221 if (userId != thisUserId) { 13222 continue; 13223 } 13224 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13225 while (it.hasNext()) { 13226 PersistentPreferredActivity ppa = it.next(); 13227 // Mark entry for removal only if it matches the package name. 13228 if (ppa.mComponent.getPackageName().equals(packageName)) { 13229 if (removed == null) { 13230 removed = new ArrayList<PersistentPreferredActivity>(); 13231 } 13232 removed.add(ppa); 13233 } 13234 } 13235 if (removed != null) { 13236 for (int j=0; j<removed.size(); j++) { 13237 PersistentPreferredActivity ppa = removed.get(j); 13238 ppir.removeFilter(ppa); 13239 } 13240 changed = true; 13241 } 13242 } 13243 13244 if (changed) { 13245 scheduleWritePackageRestrictionsLocked(userId); 13246 } 13247 } 13248 } 13249 13250 /** 13251 * Non-Binder method, support for the backup/restore mechanism: write the 13252 * full set of preferred activities in its canonical XML format. Returns true 13253 * on success; false otherwise. 13254 */ 13255 @Override 13256 public byte[] getPreferredActivityBackup(int userId) { 13257 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13258 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13259 } 13260 13261 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13262 try { 13263 final XmlSerializer serializer = new FastXmlSerializer(); 13264 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13265 serializer.startDocument(null, true); 13266 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13267 13268 synchronized (mPackages) { 13269 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13270 } 13271 13272 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13273 serializer.endDocument(); 13274 serializer.flush(); 13275 } catch (Exception e) { 13276 if (DEBUG_BACKUP) { 13277 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13278 } 13279 return null; 13280 } 13281 13282 return dataStream.toByteArray(); 13283 } 13284 13285 @Override 13286 public void restorePreferredActivities(byte[] backup, int userId) { 13287 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13288 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13289 } 13290 13291 try { 13292 final XmlPullParser parser = Xml.newPullParser(); 13293 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13294 13295 int type; 13296 while ((type = parser.next()) != XmlPullParser.START_TAG 13297 && type != XmlPullParser.END_DOCUMENT) { 13298 } 13299 if (type != XmlPullParser.START_TAG) { 13300 // oops didn't find a start tag?! 13301 if (DEBUG_BACKUP) { 13302 Slog.e(TAG, "Didn't find start tag during restore"); 13303 } 13304 return; 13305 } 13306 13307 // this is supposed to be TAG_PREFERRED_BACKUP 13308 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13309 if (DEBUG_BACKUP) { 13310 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13311 } 13312 return; 13313 } 13314 13315 // skip interfering stuff, then we're aligned with the backing implementation 13316 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13317 synchronized (mPackages) { 13318 mSettings.readPreferredActivitiesLPw(parser, userId); 13319 } 13320 } catch (Exception e) { 13321 if (DEBUG_BACKUP) { 13322 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13323 } 13324 } 13325 } 13326 13327 @Override 13328 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13329 int sourceUserId, int targetUserId, int flags) { 13330 mContext.enforceCallingOrSelfPermission( 13331 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13332 int callingUid = Binder.getCallingUid(); 13333 enforceOwnerRights(ownerPackage, callingUid); 13334 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13335 if (intentFilter.countActions() == 0) { 13336 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13337 return; 13338 } 13339 synchronized (mPackages) { 13340 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13341 ownerPackage, targetUserId, flags); 13342 CrossProfileIntentResolver resolver = 13343 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13344 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13345 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13346 if (existing != null) { 13347 int size = existing.size(); 13348 for (int i = 0; i < size; i++) { 13349 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13350 return; 13351 } 13352 } 13353 } 13354 resolver.addFilter(newFilter); 13355 scheduleWritePackageRestrictionsLocked(sourceUserId); 13356 } 13357 } 13358 13359 @Override 13360 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13361 mContext.enforceCallingOrSelfPermission( 13362 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13363 int callingUid = Binder.getCallingUid(); 13364 enforceOwnerRights(ownerPackage, callingUid); 13365 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13366 synchronized (mPackages) { 13367 CrossProfileIntentResolver resolver = 13368 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13369 ArraySet<CrossProfileIntentFilter> set = 13370 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13371 for (CrossProfileIntentFilter filter : set) { 13372 if (filter.getOwnerPackage().equals(ownerPackage)) { 13373 resolver.removeFilter(filter); 13374 } 13375 } 13376 scheduleWritePackageRestrictionsLocked(sourceUserId); 13377 } 13378 } 13379 13380 // Enforcing that callingUid is owning pkg on userId 13381 private void enforceOwnerRights(String pkg, int callingUid) { 13382 // The system owns everything. 13383 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13384 return; 13385 } 13386 int callingUserId = UserHandle.getUserId(callingUid); 13387 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13388 if (pi == null) { 13389 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13390 + callingUserId); 13391 } 13392 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13393 throw new SecurityException("Calling uid " + callingUid 13394 + " does not own package " + pkg); 13395 } 13396 } 13397 13398 @Override 13399 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13400 Intent intent = new Intent(Intent.ACTION_MAIN); 13401 intent.addCategory(Intent.CATEGORY_HOME); 13402 13403 final int callingUserId = UserHandle.getCallingUserId(); 13404 List<ResolveInfo> list = queryIntentActivities(intent, null, 13405 PackageManager.GET_META_DATA, callingUserId); 13406 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13407 true, false, false, callingUserId); 13408 13409 allHomeCandidates.clear(); 13410 if (list != null) { 13411 for (ResolveInfo ri : list) { 13412 allHomeCandidates.add(ri); 13413 } 13414 } 13415 return (preferred == null || preferred.activityInfo == null) 13416 ? null 13417 : new ComponentName(preferred.activityInfo.packageName, 13418 preferred.activityInfo.name); 13419 } 13420 13421 @Override 13422 public void setApplicationEnabledSetting(String appPackageName, 13423 int newState, int flags, int userId, String callingPackage) { 13424 if (!sUserManager.exists(userId)) return; 13425 if (callingPackage == null) { 13426 callingPackage = Integer.toString(Binder.getCallingUid()); 13427 } 13428 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13429 } 13430 13431 @Override 13432 public void setComponentEnabledSetting(ComponentName componentName, 13433 int newState, int flags, int userId) { 13434 if (!sUserManager.exists(userId)) return; 13435 setEnabledSetting(componentName.getPackageName(), 13436 componentName.getClassName(), newState, flags, userId, null); 13437 } 13438 13439 private void setEnabledSetting(final String packageName, String className, int newState, 13440 final int flags, int userId, String callingPackage) { 13441 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13442 || newState == COMPONENT_ENABLED_STATE_ENABLED 13443 || newState == COMPONENT_ENABLED_STATE_DISABLED 13444 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13445 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13446 throw new IllegalArgumentException("Invalid new component state: " 13447 + newState); 13448 } 13449 PackageSetting pkgSetting; 13450 final int uid = Binder.getCallingUid(); 13451 final int permission = mContext.checkCallingOrSelfPermission( 13452 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13453 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13454 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13455 boolean sendNow = false; 13456 boolean isApp = (className == null); 13457 String componentName = isApp ? packageName : className; 13458 int packageUid = -1; 13459 ArrayList<String> components; 13460 13461 // writer 13462 synchronized (mPackages) { 13463 pkgSetting = mSettings.mPackages.get(packageName); 13464 if (pkgSetting == null) { 13465 if (className == null) { 13466 throw new IllegalArgumentException( 13467 "Unknown package: " + packageName); 13468 } 13469 throw new IllegalArgumentException( 13470 "Unknown component: " + packageName 13471 + "/" + className); 13472 } 13473 // Allow root and verify that userId is not being specified by a different user 13474 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13475 throw new SecurityException( 13476 "Permission Denial: attempt to change component state from pid=" 13477 + Binder.getCallingPid() 13478 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13479 } 13480 if (className == null) { 13481 // We're dealing with an application/package level state change 13482 if (pkgSetting.getEnabled(userId) == newState) { 13483 // Nothing to do 13484 return; 13485 } 13486 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13487 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13488 // Don't care about who enables an app. 13489 callingPackage = null; 13490 } 13491 pkgSetting.setEnabled(newState, userId, callingPackage); 13492 // pkgSetting.pkg.mSetEnabled = newState; 13493 } else { 13494 // We're dealing with a component level state change 13495 // First, verify that this is a valid class name. 13496 PackageParser.Package pkg = pkgSetting.pkg; 13497 if (pkg == null || !pkg.hasComponentClassName(className)) { 13498 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13499 throw new IllegalArgumentException("Component class " + className 13500 + " does not exist in " + packageName); 13501 } else { 13502 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13503 + className + " does not exist in " + packageName); 13504 } 13505 } 13506 switch (newState) { 13507 case COMPONENT_ENABLED_STATE_ENABLED: 13508 if (!pkgSetting.enableComponentLPw(className, userId)) { 13509 return; 13510 } 13511 break; 13512 case COMPONENT_ENABLED_STATE_DISABLED: 13513 if (!pkgSetting.disableComponentLPw(className, userId)) { 13514 return; 13515 } 13516 break; 13517 case COMPONENT_ENABLED_STATE_DEFAULT: 13518 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13519 return; 13520 } 13521 break; 13522 default: 13523 Slog.e(TAG, "Invalid new component state: " + newState); 13524 return; 13525 } 13526 } 13527 scheduleWritePackageRestrictionsLocked(userId); 13528 components = mPendingBroadcasts.get(userId, packageName); 13529 final boolean newPackage = components == null; 13530 if (newPackage) { 13531 components = new ArrayList<String>(); 13532 } 13533 if (!components.contains(componentName)) { 13534 components.add(componentName); 13535 } 13536 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13537 sendNow = true; 13538 // Purge entry from pending broadcast list if another one exists already 13539 // since we are sending one right away. 13540 mPendingBroadcasts.remove(userId, packageName); 13541 } else { 13542 if (newPackage) { 13543 mPendingBroadcasts.put(userId, packageName, components); 13544 } 13545 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13546 // Schedule a message 13547 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13548 } 13549 } 13550 } 13551 13552 long callingId = Binder.clearCallingIdentity(); 13553 try { 13554 if (sendNow) { 13555 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13556 sendPackageChangedBroadcast(packageName, 13557 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13558 } 13559 } finally { 13560 Binder.restoreCallingIdentity(callingId); 13561 } 13562 } 13563 13564 private void sendPackageChangedBroadcast(String packageName, 13565 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13566 if (DEBUG_INSTALL) 13567 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13568 + componentNames); 13569 Bundle extras = new Bundle(4); 13570 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13571 String nameList[] = new String[componentNames.size()]; 13572 componentNames.toArray(nameList); 13573 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13574 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13575 extras.putInt(Intent.EXTRA_UID, packageUid); 13576 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13577 new int[] {UserHandle.getUserId(packageUid)}); 13578 } 13579 13580 @Override 13581 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13582 if (!sUserManager.exists(userId)) return; 13583 final int uid = Binder.getCallingUid(); 13584 final int permission = mContext.checkCallingOrSelfPermission( 13585 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13586 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13587 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13588 // writer 13589 synchronized (mPackages) { 13590 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13591 allowedByPermission, uid, userId)) { 13592 scheduleWritePackageRestrictionsLocked(userId); 13593 } 13594 } 13595 } 13596 13597 @Override 13598 public String getInstallerPackageName(String packageName) { 13599 // reader 13600 synchronized (mPackages) { 13601 return mSettings.getInstallerPackageNameLPr(packageName); 13602 } 13603 } 13604 13605 @Override 13606 public int getApplicationEnabledSetting(String packageName, int userId) { 13607 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13608 int uid = Binder.getCallingUid(); 13609 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13610 // reader 13611 synchronized (mPackages) { 13612 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13613 } 13614 } 13615 13616 @Override 13617 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13618 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13619 int uid = Binder.getCallingUid(); 13620 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13621 // reader 13622 synchronized (mPackages) { 13623 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13624 } 13625 } 13626 13627 @Override 13628 public void enterSafeMode() { 13629 enforceSystemOrRoot("Only the system can request entering safe mode"); 13630 13631 if (!mSystemReady) { 13632 mSafeMode = true; 13633 } 13634 } 13635 13636 @Override 13637 public void systemReady() { 13638 mSystemReady = true; 13639 13640 // Read the compatibilty setting when the system is ready. 13641 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13642 mContext.getContentResolver(), 13643 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13644 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13645 if (DEBUG_SETTINGS) { 13646 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13647 } 13648 13649 synchronized (mPackages) { 13650 // Verify that all of the preferred activity components actually 13651 // exist. It is possible for applications to be updated and at 13652 // that point remove a previously declared activity component that 13653 // had been set as a preferred activity. We try to clean this up 13654 // the next time we encounter that preferred activity, but it is 13655 // possible for the user flow to never be able to return to that 13656 // situation so here we do a sanity check to make sure we haven't 13657 // left any junk around. 13658 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13659 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13660 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13661 removed.clear(); 13662 for (PreferredActivity pa : pir.filterSet()) { 13663 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13664 removed.add(pa); 13665 } 13666 } 13667 if (removed.size() > 0) { 13668 for (int r=0; r<removed.size(); r++) { 13669 PreferredActivity pa = removed.get(r); 13670 Slog.w(TAG, "Removing dangling preferred activity: " 13671 + pa.mPref.mComponent); 13672 pir.removeFilter(pa); 13673 } 13674 mSettings.writePackageRestrictionsLPr( 13675 mSettings.mPreferredActivities.keyAt(i)); 13676 } 13677 } 13678 } 13679 sUserManager.systemReady(); 13680 13681 // Kick off any messages waiting for system ready 13682 if (mPostSystemReadyMessages != null) { 13683 for (Message msg : mPostSystemReadyMessages) { 13684 msg.sendToTarget(); 13685 } 13686 mPostSystemReadyMessages = null; 13687 } 13688 13689 // Watch for external volumes that come and go over time 13690 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13691 storage.registerListener(mStorageListener); 13692 13693 mInstallerService.systemReady(); 13694 mPackageDexOptimizer.systemReady(); 13695 } 13696 13697 @Override 13698 public boolean isSafeMode() { 13699 return mSafeMode; 13700 } 13701 13702 @Override 13703 public boolean hasSystemUidErrors() { 13704 return mHasSystemUidErrors; 13705 } 13706 13707 static String arrayToString(int[] array) { 13708 StringBuffer buf = new StringBuffer(128); 13709 buf.append('['); 13710 if (array != null) { 13711 for (int i=0; i<array.length; i++) { 13712 if (i > 0) buf.append(", "); 13713 buf.append(array[i]); 13714 } 13715 } 13716 buf.append(']'); 13717 return buf.toString(); 13718 } 13719 13720 static class DumpState { 13721 public static final int DUMP_LIBS = 1 << 0; 13722 public static final int DUMP_FEATURES = 1 << 1; 13723 public static final int DUMP_RESOLVERS = 1 << 2; 13724 public static final int DUMP_PERMISSIONS = 1 << 3; 13725 public static final int DUMP_PACKAGES = 1 << 4; 13726 public static final int DUMP_SHARED_USERS = 1 << 5; 13727 public static final int DUMP_MESSAGES = 1 << 6; 13728 public static final int DUMP_PROVIDERS = 1 << 7; 13729 public static final int DUMP_VERIFIERS = 1 << 8; 13730 public static final int DUMP_PREFERRED = 1 << 9; 13731 public static final int DUMP_PREFERRED_XML = 1 << 10; 13732 public static final int DUMP_KEYSETS = 1 << 11; 13733 public static final int DUMP_VERSION = 1 << 12; 13734 public static final int DUMP_INSTALLS = 1 << 13; 13735 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13736 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13737 13738 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13739 13740 private int mTypes; 13741 13742 private int mOptions; 13743 13744 private boolean mTitlePrinted; 13745 13746 private SharedUserSetting mSharedUser; 13747 13748 public boolean isDumping(int type) { 13749 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13750 return true; 13751 } 13752 13753 return (mTypes & type) != 0; 13754 } 13755 13756 public void setDump(int type) { 13757 mTypes |= type; 13758 } 13759 13760 public boolean isOptionEnabled(int option) { 13761 return (mOptions & option) != 0; 13762 } 13763 13764 public void setOptionEnabled(int option) { 13765 mOptions |= option; 13766 } 13767 13768 public boolean onTitlePrinted() { 13769 final boolean printed = mTitlePrinted; 13770 mTitlePrinted = true; 13771 return printed; 13772 } 13773 13774 public boolean getTitlePrinted() { 13775 return mTitlePrinted; 13776 } 13777 13778 public void setTitlePrinted(boolean enabled) { 13779 mTitlePrinted = enabled; 13780 } 13781 13782 public SharedUserSetting getSharedUser() { 13783 return mSharedUser; 13784 } 13785 13786 public void setSharedUser(SharedUserSetting user) { 13787 mSharedUser = user; 13788 } 13789 } 13790 13791 @Override 13792 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13793 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13794 != PackageManager.PERMISSION_GRANTED) { 13795 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13796 + Binder.getCallingPid() 13797 + ", uid=" + Binder.getCallingUid() 13798 + " without permission " 13799 + android.Manifest.permission.DUMP); 13800 return; 13801 } 13802 13803 DumpState dumpState = new DumpState(); 13804 boolean fullPreferred = false; 13805 boolean checkin = false; 13806 13807 String packageName = null; 13808 13809 int opti = 0; 13810 while (opti < args.length) { 13811 String opt = args[opti]; 13812 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13813 break; 13814 } 13815 opti++; 13816 13817 if ("-a".equals(opt)) { 13818 // Right now we only know how to print all. 13819 } else if ("-h".equals(opt)) { 13820 pw.println("Package manager dump options:"); 13821 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13822 pw.println(" --checkin: dump for a checkin"); 13823 pw.println(" -f: print details of intent filters"); 13824 pw.println(" -h: print this help"); 13825 pw.println(" cmd may be one of:"); 13826 pw.println(" l[ibraries]: list known shared libraries"); 13827 pw.println(" f[ibraries]: list device features"); 13828 pw.println(" k[eysets]: print known keysets"); 13829 pw.println(" r[esolvers]: dump intent resolvers"); 13830 pw.println(" perm[issions]: dump permissions"); 13831 pw.println(" pref[erred]: print preferred package settings"); 13832 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13833 pw.println(" prov[iders]: dump content providers"); 13834 pw.println(" p[ackages]: dump installed packages"); 13835 pw.println(" s[hared-users]: dump shared user IDs"); 13836 pw.println(" m[essages]: print collected runtime messages"); 13837 pw.println(" v[erifiers]: print package verifier info"); 13838 pw.println(" version: print database version info"); 13839 pw.println(" write: write current settings now"); 13840 pw.println(" <package.name>: info about given package"); 13841 pw.println(" installs: details about install sessions"); 13842 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13843 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13844 return; 13845 } else if ("--checkin".equals(opt)) { 13846 checkin = true; 13847 } else if ("-f".equals(opt)) { 13848 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13849 } else { 13850 pw.println("Unknown argument: " + opt + "; use -h for help"); 13851 } 13852 } 13853 13854 // Is the caller requesting to dump a particular piece of data? 13855 if (opti < args.length) { 13856 String cmd = args[opti]; 13857 opti++; 13858 // Is this a package name? 13859 if ("android".equals(cmd) || cmd.contains(".")) { 13860 packageName = cmd; 13861 // When dumping a single package, we always dump all of its 13862 // filter information since the amount of data will be reasonable. 13863 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13864 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13865 dumpState.setDump(DumpState.DUMP_LIBS); 13866 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13867 dumpState.setDump(DumpState.DUMP_FEATURES); 13868 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13869 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13870 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13871 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13872 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13873 dumpState.setDump(DumpState.DUMP_PREFERRED); 13874 } else if ("preferred-xml".equals(cmd)) { 13875 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13876 if (opti < args.length && "--full".equals(args[opti])) { 13877 fullPreferred = true; 13878 opti++; 13879 } 13880 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13881 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13882 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13883 dumpState.setDump(DumpState.DUMP_PACKAGES); 13884 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13885 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13886 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13887 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13888 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13889 dumpState.setDump(DumpState.DUMP_MESSAGES); 13890 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13891 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13892 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13893 || "intent-filter-verifiers".equals(cmd)) { 13894 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13895 } else if ("version".equals(cmd)) { 13896 dumpState.setDump(DumpState.DUMP_VERSION); 13897 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13898 dumpState.setDump(DumpState.DUMP_KEYSETS); 13899 } else if ("installs".equals(cmd)) { 13900 dumpState.setDump(DumpState.DUMP_INSTALLS); 13901 } else if ("write".equals(cmd)) { 13902 synchronized (mPackages) { 13903 mSettings.writeLPr(); 13904 pw.println("Settings written."); 13905 return; 13906 } 13907 } 13908 } 13909 13910 if (checkin) { 13911 pw.println("vers,1"); 13912 } 13913 13914 // reader 13915 synchronized (mPackages) { 13916 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13917 if (!checkin) { 13918 if (dumpState.onTitlePrinted()) 13919 pw.println(); 13920 pw.println("Database versions:"); 13921 pw.print(" SDK Version:"); 13922 pw.print(" internal="); 13923 pw.print(mSettings.mInternalSdkPlatform); 13924 pw.print(" external="); 13925 pw.println(mSettings.mExternalSdkPlatform); 13926 pw.print(" DB Version:"); 13927 pw.print(" internal="); 13928 pw.print(mSettings.mInternalDatabaseVersion); 13929 pw.print(" external="); 13930 pw.println(mSettings.mExternalDatabaseVersion); 13931 } 13932 } 13933 13934 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13935 if (!checkin) { 13936 if (dumpState.onTitlePrinted()) 13937 pw.println(); 13938 pw.println("Verifiers:"); 13939 pw.print(" Required: "); 13940 pw.print(mRequiredVerifierPackage); 13941 pw.print(" (uid="); 13942 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13943 pw.println(")"); 13944 } else if (mRequiredVerifierPackage != null) { 13945 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13946 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13947 } 13948 } 13949 13950 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13951 packageName == null) { 13952 if (mIntentFilterVerifierComponent != null) { 13953 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13954 if (!checkin) { 13955 if (dumpState.onTitlePrinted()) 13956 pw.println(); 13957 pw.println("Intent Filter Verifier:"); 13958 pw.print(" Using: "); 13959 pw.print(verifierPackageName); 13960 pw.print(" (uid="); 13961 pw.print(getPackageUid(verifierPackageName, 0)); 13962 pw.println(")"); 13963 } else if (verifierPackageName != null) { 13964 pw.print("ifv,"); pw.print(verifierPackageName); 13965 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13966 } 13967 } else { 13968 pw.println(); 13969 pw.println("No Intent Filter Verifier available!"); 13970 } 13971 } 13972 13973 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13974 boolean printedHeader = false; 13975 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13976 while (it.hasNext()) { 13977 String name = it.next(); 13978 SharedLibraryEntry ent = mSharedLibraries.get(name); 13979 if (!checkin) { 13980 if (!printedHeader) { 13981 if (dumpState.onTitlePrinted()) 13982 pw.println(); 13983 pw.println("Libraries:"); 13984 printedHeader = true; 13985 } 13986 pw.print(" "); 13987 } else { 13988 pw.print("lib,"); 13989 } 13990 pw.print(name); 13991 if (!checkin) { 13992 pw.print(" -> "); 13993 } 13994 if (ent.path != null) { 13995 if (!checkin) { 13996 pw.print("(jar) "); 13997 pw.print(ent.path); 13998 } else { 13999 pw.print(",jar,"); 14000 pw.print(ent.path); 14001 } 14002 } else { 14003 if (!checkin) { 14004 pw.print("(apk) "); 14005 pw.print(ent.apk); 14006 } else { 14007 pw.print(",apk,"); 14008 pw.print(ent.apk); 14009 } 14010 } 14011 pw.println(); 14012 } 14013 } 14014 14015 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14016 if (dumpState.onTitlePrinted()) 14017 pw.println(); 14018 if (!checkin) { 14019 pw.println("Features:"); 14020 } 14021 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14022 while (it.hasNext()) { 14023 String name = it.next(); 14024 if (!checkin) { 14025 pw.print(" "); 14026 } else { 14027 pw.print("feat,"); 14028 } 14029 pw.println(name); 14030 } 14031 } 14032 14033 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14034 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14035 : "Activity Resolver Table:", " ", packageName, 14036 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14037 dumpState.setTitlePrinted(true); 14038 } 14039 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14040 : "Receiver Resolver Table:", " ", packageName, 14041 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14042 dumpState.setTitlePrinted(true); 14043 } 14044 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14045 : "Service Resolver Table:", " ", packageName, 14046 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14047 dumpState.setTitlePrinted(true); 14048 } 14049 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14050 : "Provider Resolver Table:", " ", packageName, 14051 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14052 dumpState.setTitlePrinted(true); 14053 } 14054 } 14055 14056 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14057 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14058 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14059 int user = mSettings.mPreferredActivities.keyAt(i); 14060 if (pir.dump(pw, 14061 dumpState.getTitlePrinted() 14062 ? "\nPreferred Activities User " + user + ":" 14063 : "Preferred Activities User " + user + ":", " ", 14064 packageName, true, false)) { 14065 dumpState.setTitlePrinted(true); 14066 } 14067 } 14068 } 14069 14070 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14071 pw.flush(); 14072 FileOutputStream fout = new FileOutputStream(fd); 14073 BufferedOutputStream str = new BufferedOutputStream(fout); 14074 XmlSerializer serializer = new FastXmlSerializer(); 14075 try { 14076 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14077 serializer.startDocument(null, true); 14078 serializer.setFeature( 14079 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14080 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14081 serializer.endDocument(); 14082 serializer.flush(); 14083 } catch (IllegalArgumentException e) { 14084 pw.println("Failed writing: " + e); 14085 } catch (IllegalStateException e) { 14086 pw.println("Failed writing: " + e); 14087 } catch (IOException e) { 14088 pw.println("Failed writing: " + e); 14089 } 14090 } 14091 14092 if (!checkin 14093 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14094 && packageName == null) { 14095 pw.println(); 14096 int count = mSettings.mPackages.size(); 14097 if (count == 0) { 14098 pw.println("No domain preferred apps!"); 14099 pw.println(); 14100 } else { 14101 final String prefix = " "; 14102 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14103 if (allPackageSettings.size() == 0) { 14104 pw.println("No domain preferred apps!"); 14105 pw.println(); 14106 } else { 14107 pw.println("Domain preferred apps status:"); 14108 pw.println(); 14109 count = 0; 14110 for (PackageSetting ps : allPackageSettings) { 14111 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14112 if (ivi == null || ivi.getPackageName() == null) continue; 14113 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14114 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14115 pw.println(prefix + "Status: " + ivi.getStatusString()); 14116 pw.println(); 14117 count++; 14118 } 14119 if (count == 0) { 14120 pw.println(prefix + "No domain preferred app status!"); 14121 pw.println(); 14122 } 14123 for (int userId : sUserManager.getUserIds()) { 14124 pw.println("Domain preferred apps for User " + userId + ":"); 14125 pw.println(); 14126 count = 0; 14127 for (PackageSetting ps : allPackageSettings) { 14128 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14129 if (ivi == null || ivi.getPackageName() == null) { 14130 continue; 14131 } 14132 final int status = ps.getDomainVerificationStatusForUser(userId); 14133 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14134 continue; 14135 } 14136 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14137 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14138 String statusStr = IntentFilterVerificationInfo. 14139 getStatusStringFromValue(status); 14140 pw.println(prefix + "Status: " + statusStr); 14141 pw.println(); 14142 count++; 14143 } 14144 if (count == 0) { 14145 pw.println(prefix + "No domain preferred apps!"); 14146 pw.println(); 14147 } 14148 } 14149 } 14150 } 14151 } 14152 14153 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14154 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14155 if (packageName == null) { 14156 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14157 if (iperm == 0) { 14158 if (dumpState.onTitlePrinted()) 14159 pw.println(); 14160 pw.println("AppOp Permissions:"); 14161 } 14162 pw.print(" AppOp Permission "); 14163 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14164 pw.println(":"); 14165 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14166 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14167 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14168 } 14169 } 14170 } 14171 } 14172 14173 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14174 boolean printedSomething = false; 14175 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14176 if (packageName != null && !packageName.equals(p.info.packageName)) { 14177 continue; 14178 } 14179 if (!printedSomething) { 14180 if (dumpState.onTitlePrinted()) 14181 pw.println(); 14182 pw.println("Registered ContentProviders:"); 14183 printedSomething = true; 14184 } 14185 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14186 pw.print(" "); pw.println(p.toString()); 14187 } 14188 printedSomething = false; 14189 for (Map.Entry<String, PackageParser.Provider> entry : 14190 mProvidersByAuthority.entrySet()) { 14191 PackageParser.Provider p = entry.getValue(); 14192 if (packageName != null && !packageName.equals(p.info.packageName)) { 14193 continue; 14194 } 14195 if (!printedSomething) { 14196 if (dumpState.onTitlePrinted()) 14197 pw.println(); 14198 pw.println("ContentProvider Authorities:"); 14199 printedSomething = true; 14200 } 14201 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14202 pw.print(" "); pw.println(p.toString()); 14203 if (p.info != null && p.info.applicationInfo != null) { 14204 final String appInfo = p.info.applicationInfo.toString(); 14205 pw.print(" applicationInfo="); pw.println(appInfo); 14206 } 14207 } 14208 } 14209 14210 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14211 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14212 } 14213 14214 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14215 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14216 } 14217 14218 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14219 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14220 } 14221 14222 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14223 // XXX should handle packageName != null by dumping only install data that 14224 // the given package is involved with. 14225 if (dumpState.onTitlePrinted()) pw.println(); 14226 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14227 } 14228 14229 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14230 if (dumpState.onTitlePrinted()) pw.println(); 14231 mSettings.dumpReadMessagesLPr(pw, dumpState); 14232 14233 pw.println(); 14234 pw.println("Package warning messages:"); 14235 BufferedReader in = null; 14236 String line = null; 14237 try { 14238 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14239 while ((line = in.readLine()) != null) { 14240 if (line.contains("ignored: updated version")) continue; 14241 pw.println(line); 14242 } 14243 } catch (IOException ignored) { 14244 } finally { 14245 IoUtils.closeQuietly(in); 14246 } 14247 } 14248 14249 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14250 BufferedReader in = null; 14251 String line = null; 14252 try { 14253 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14254 while ((line = in.readLine()) != null) { 14255 if (line.contains("ignored: updated version")) continue; 14256 pw.print("msg,"); 14257 pw.println(line); 14258 } 14259 } catch (IOException ignored) { 14260 } finally { 14261 IoUtils.closeQuietly(in); 14262 } 14263 } 14264 } 14265 } 14266 14267 // ------- apps on sdcard specific code ------- 14268 static final boolean DEBUG_SD_INSTALL = false; 14269 14270 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14271 14272 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14273 14274 private boolean mMediaMounted = false; 14275 14276 static String getEncryptKey() { 14277 try { 14278 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14279 SD_ENCRYPTION_KEYSTORE_NAME); 14280 if (sdEncKey == null) { 14281 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14282 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14283 if (sdEncKey == null) { 14284 Slog.e(TAG, "Failed to create encryption keys"); 14285 return null; 14286 } 14287 } 14288 return sdEncKey; 14289 } catch (NoSuchAlgorithmException nsae) { 14290 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14291 return null; 14292 } catch (IOException ioe) { 14293 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14294 return null; 14295 } 14296 } 14297 14298 /* 14299 * Update media status on PackageManager. 14300 */ 14301 @Override 14302 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14303 int callingUid = Binder.getCallingUid(); 14304 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14305 throw new SecurityException("Media status can only be updated by the system"); 14306 } 14307 // reader; this apparently protects mMediaMounted, but should probably 14308 // be a different lock in that case. 14309 synchronized (mPackages) { 14310 Log.i(TAG, "Updating external media status from " 14311 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14312 + (mediaStatus ? "mounted" : "unmounted")); 14313 if (DEBUG_SD_INSTALL) 14314 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14315 + ", mMediaMounted=" + mMediaMounted); 14316 if (mediaStatus == mMediaMounted) { 14317 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14318 : 0, -1); 14319 mHandler.sendMessage(msg); 14320 return; 14321 } 14322 mMediaMounted = mediaStatus; 14323 } 14324 // Queue up an async operation since the package installation may take a 14325 // little while. 14326 mHandler.post(new Runnable() { 14327 public void run() { 14328 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14329 } 14330 }); 14331 } 14332 14333 /** 14334 * Called by MountService when the initial ASECs to scan are available. 14335 * Should block until all the ASEC containers are finished being scanned. 14336 */ 14337 public void scanAvailableAsecs() { 14338 updateExternalMediaStatusInner(true, false, false); 14339 if (mShouldRestoreconData) { 14340 SELinuxMMAC.setRestoreconDone(); 14341 mShouldRestoreconData = false; 14342 } 14343 } 14344 14345 /* 14346 * Collect information of applications on external media, map them against 14347 * existing containers and update information based on current mount status. 14348 * Please note that we always have to report status if reportStatus has been 14349 * set to true especially when unloading packages. 14350 */ 14351 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14352 boolean externalStorage) { 14353 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14354 int[] uidArr = EmptyArray.INT; 14355 14356 final String[] list = PackageHelper.getSecureContainerList(); 14357 if (ArrayUtils.isEmpty(list)) { 14358 Log.i(TAG, "No secure containers found"); 14359 } else { 14360 // Process list of secure containers and categorize them 14361 // as active or stale based on their package internal state. 14362 14363 // reader 14364 synchronized (mPackages) { 14365 for (String cid : list) { 14366 // Leave stages untouched for now; installer service owns them 14367 if (PackageInstallerService.isStageName(cid)) continue; 14368 14369 if (DEBUG_SD_INSTALL) 14370 Log.i(TAG, "Processing container " + cid); 14371 String pkgName = getAsecPackageName(cid); 14372 if (pkgName == null) { 14373 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14374 continue; 14375 } 14376 if (DEBUG_SD_INSTALL) 14377 Log.i(TAG, "Looking for pkg : " + pkgName); 14378 14379 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14380 if (ps == null) { 14381 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14382 continue; 14383 } 14384 14385 /* 14386 * Skip packages that are not external if we're unmounting 14387 * external storage. 14388 */ 14389 if (externalStorage && !isMounted && !isExternal(ps)) { 14390 continue; 14391 } 14392 14393 final AsecInstallArgs args = new AsecInstallArgs(cid, 14394 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14395 // The package status is changed only if the code path 14396 // matches between settings and the container id. 14397 if (ps.codePathString != null 14398 && ps.codePathString.startsWith(args.getCodePath())) { 14399 if (DEBUG_SD_INSTALL) { 14400 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14401 + " at code path: " + ps.codePathString); 14402 } 14403 14404 // We do have a valid package installed on sdcard 14405 processCids.put(args, ps.codePathString); 14406 final int uid = ps.appId; 14407 if (uid != -1) { 14408 uidArr = ArrayUtils.appendInt(uidArr, uid); 14409 } 14410 } else { 14411 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14412 + ps.codePathString); 14413 } 14414 } 14415 } 14416 14417 Arrays.sort(uidArr); 14418 } 14419 14420 // Process packages with valid entries. 14421 if (isMounted) { 14422 if (DEBUG_SD_INSTALL) 14423 Log.i(TAG, "Loading packages"); 14424 loadMediaPackages(processCids, uidArr); 14425 startCleaningPackages(); 14426 mInstallerService.onSecureContainersAvailable(); 14427 } else { 14428 if (DEBUG_SD_INSTALL) 14429 Log.i(TAG, "Unloading packages"); 14430 unloadMediaPackages(processCids, uidArr, reportStatus); 14431 } 14432 } 14433 14434 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14435 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14436 final int size = infos.size(); 14437 final String[] packageNames = new String[size]; 14438 final int[] packageUids = new int[size]; 14439 for (int i = 0; i < size; i++) { 14440 final ApplicationInfo info = infos.get(i); 14441 packageNames[i] = info.packageName; 14442 packageUids[i] = info.uid; 14443 } 14444 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14445 finishedReceiver); 14446 } 14447 14448 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14449 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14450 sendResourcesChangedBroadcast(mediaStatus, replacing, 14451 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14452 } 14453 14454 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14455 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14456 int size = pkgList.length; 14457 if (size > 0) { 14458 // Send broadcasts here 14459 Bundle extras = new Bundle(); 14460 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14461 if (uidArr != null) { 14462 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14463 } 14464 if (replacing) { 14465 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14466 } 14467 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14468 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14469 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14470 } 14471 } 14472 14473 /* 14474 * Look at potentially valid container ids from processCids If package 14475 * information doesn't match the one on record or package scanning fails, 14476 * the cid is added to list of removeCids. We currently don't delete stale 14477 * containers. 14478 */ 14479 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14480 ArrayList<String> pkgList = new ArrayList<String>(); 14481 Set<AsecInstallArgs> keys = processCids.keySet(); 14482 14483 for (AsecInstallArgs args : keys) { 14484 String codePath = processCids.get(args); 14485 if (DEBUG_SD_INSTALL) 14486 Log.i(TAG, "Loading container : " + args.cid); 14487 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14488 try { 14489 // Make sure there are no container errors first. 14490 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14491 Slog.e(TAG, "Failed to mount cid : " + args.cid 14492 + " when installing from sdcard"); 14493 continue; 14494 } 14495 // Check code path here. 14496 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14497 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14498 + " does not match one in settings " + codePath); 14499 continue; 14500 } 14501 // Parse package 14502 int parseFlags = mDefParseFlags; 14503 if (args.isExternalAsec()) { 14504 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14505 } 14506 if (args.isFwdLocked()) { 14507 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14508 } 14509 14510 synchronized (mInstallLock) { 14511 PackageParser.Package pkg = null; 14512 try { 14513 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14514 } catch (PackageManagerException e) { 14515 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14516 } 14517 // Scan the package 14518 if (pkg != null) { 14519 /* 14520 * TODO why is the lock being held? doPostInstall is 14521 * called in other places without the lock. This needs 14522 * to be straightened out. 14523 */ 14524 // writer 14525 synchronized (mPackages) { 14526 retCode = PackageManager.INSTALL_SUCCEEDED; 14527 pkgList.add(pkg.packageName); 14528 // Post process args 14529 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14530 pkg.applicationInfo.uid); 14531 } 14532 } else { 14533 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14534 } 14535 } 14536 14537 } finally { 14538 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14539 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14540 } 14541 } 14542 } 14543 // writer 14544 synchronized (mPackages) { 14545 // If the platform SDK has changed since the last time we booted, 14546 // we need to re-grant app permission to catch any new ones that 14547 // appear. This is really a hack, and means that apps can in some 14548 // cases get permissions that the user didn't initially explicitly 14549 // allow... it would be nice to have some better way to handle 14550 // this situation. 14551 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14552 if (regrantPermissions) 14553 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14554 + mSdkVersion + "; regranting permissions for external storage"); 14555 mSettings.mExternalSdkPlatform = mSdkVersion; 14556 14557 // Make sure group IDs have been assigned, and any permission 14558 // changes in other apps are accounted for 14559 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14560 | (regrantPermissions 14561 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14562 : 0)); 14563 14564 mSettings.updateExternalDatabaseVersion(); 14565 14566 // can downgrade to reader 14567 // Persist settings 14568 mSettings.writeLPr(); 14569 } 14570 // Send a broadcast to let everyone know we are done processing 14571 if (pkgList.size() > 0) { 14572 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14573 } 14574 } 14575 14576 /* 14577 * Utility method to unload a list of specified containers 14578 */ 14579 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14580 // Just unmount all valid containers. 14581 for (AsecInstallArgs arg : cidArgs) { 14582 synchronized (mInstallLock) { 14583 arg.doPostDeleteLI(false); 14584 } 14585 } 14586 } 14587 14588 /* 14589 * Unload packages mounted on external media. This involves deleting package 14590 * data from internal structures, sending broadcasts about diabled packages, 14591 * gc'ing to free up references, unmounting all secure containers 14592 * corresponding to packages on external media, and posting a 14593 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14594 * that we always have to post this message if status has been requested no 14595 * matter what. 14596 */ 14597 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14598 final boolean reportStatus) { 14599 if (DEBUG_SD_INSTALL) 14600 Log.i(TAG, "unloading media packages"); 14601 ArrayList<String> pkgList = new ArrayList<String>(); 14602 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14603 final Set<AsecInstallArgs> keys = processCids.keySet(); 14604 for (AsecInstallArgs args : keys) { 14605 String pkgName = args.getPackageName(); 14606 if (DEBUG_SD_INSTALL) 14607 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14608 // Delete package internally 14609 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14610 synchronized (mInstallLock) { 14611 boolean res = deletePackageLI(pkgName, null, false, null, null, 14612 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14613 if (res) { 14614 pkgList.add(pkgName); 14615 } else { 14616 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14617 failedList.add(args); 14618 } 14619 } 14620 } 14621 14622 // reader 14623 synchronized (mPackages) { 14624 // We didn't update the settings after removing each package; 14625 // write them now for all packages. 14626 mSettings.writeLPr(); 14627 } 14628 14629 // We have to absolutely send UPDATED_MEDIA_STATUS only 14630 // after confirming that all the receivers processed the ordered 14631 // broadcast when packages get disabled, force a gc to clean things up. 14632 // and unload all the containers. 14633 if (pkgList.size() > 0) { 14634 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14635 new IIntentReceiver.Stub() { 14636 public void performReceive(Intent intent, int resultCode, String data, 14637 Bundle extras, boolean ordered, boolean sticky, 14638 int sendingUser) throws RemoteException { 14639 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14640 reportStatus ? 1 : 0, 1, keys); 14641 mHandler.sendMessage(msg); 14642 } 14643 }); 14644 } else { 14645 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14646 keys); 14647 mHandler.sendMessage(msg); 14648 } 14649 } 14650 14651 private void loadPrivatePackages(VolumeInfo vol) { 14652 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14653 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14654 synchronized (mInstallLock) { 14655 synchronized (mPackages) { 14656 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14657 for (PackageSetting ps : packages) { 14658 final PackageParser.Package pkg; 14659 try { 14660 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14661 loaded.add(pkg.applicationInfo); 14662 } catch (PackageManagerException e) { 14663 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14664 } 14665 } 14666 14667 // TODO: regrant any permissions that changed based since original install 14668 14669 mSettings.writeLPr(); 14670 } 14671 } 14672 14673 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14674 sendResourcesChangedBroadcast(true, false, loaded, null); 14675 } 14676 14677 private void unloadPrivatePackages(VolumeInfo vol) { 14678 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14679 synchronized (mInstallLock) { 14680 synchronized (mPackages) { 14681 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14682 for (PackageSetting ps : packages) { 14683 if (ps.pkg == null) continue; 14684 14685 final ApplicationInfo info = ps.pkg.applicationInfo; 14686 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14687 if (deletePackageLI(ps.name, null, false, null, null, 14688 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14689 unloaded.add(info); 14690 } else { 14691 Slog.w(TAG, "Failed to unload " + ps.codePath); 14692 } 14693 } 14694 14695 mSettings.writeLPr(); 14696 } 14697 } 14698 14699 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14700 sendResourcesChangedBroadcast(false, false, unloaded, null); 14701 } 14702 14703 private void unfreezePackage(String packageName) { 14704 synchronized (mPackages) { 14705 final PackageSetting ps = mSettings.mPackages.get(packageName); 14706 if (ps != null) { 14707 ps.frozen = false; 14708 } 14709 } 14710 } 14711 14712 @Override 14713 public int movePackage(final String packageName, final String volumeUuid) { 14714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14715 14716 final int moveId = mNextMoveId.getAndIncrement(); 14717 try { 14718 movePackageInternal(packageName, volumeUuid, moveId); 14719 } catch (PackageManagerException e) { 14720 Slog.w(TAG, "Failed to move " + packageName, e); 14721 mMoveCallbacks.notifyStatusChanged(moveId, 14722 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14723 } 14724 return moveId; 14725 } 14726 14727 private void movePackageInternal(final String packageName, final String volumeUuid, 14728 final int moveId) throws PackageManagerException { 14729 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14730 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14731 final PackageManager pm = mContext.getPackageManager(); 14732 14733 final boolean currentAsec; 14734 final String currentVolumeUuid; 14735 final File codeFile; 14736 final String installerPackageName; 14737 final String packageAbiOverride; 14738 final int appId; 14739 final String seinfo; 14740 final String label; 14741 14742 // reader 14743 synchronized (mPackages) { 14744 final PackageParser.Package pkg = mPackages.get(packageName); 14745 final PackageSetting ps = mSettings.mPackages.get(packageName); 14746 if (pkg == null || ps == null) { 14747 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14748 } 14749 14750 if (pkg.applicationInfo.isSystemApp()) { 14751 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14752 "Cannot move system application"); 14753 } 14754 14755 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14756 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14757 "Package already moved to " + volumeUuid); 14758 } 14759 14760 final File probe = new File(pkg.codePath); 14761 final File probeOat = new File(probe, "oat"); 14762 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14763 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14764 "Move only supported for modern cluster style installs"); 14765 } 14766 14767 if (ps.frozen) { 14768 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14769 "Failed to move already frozen package"); 14770 } 14771 ps.frozen = true; 14772 14773 currentAsec = pkg.applicationInfo.isForwardLocked() 14774 || pkg.applicationInfo.isExternalAsec(); 14775 currentVolumeUuid = ps.volumeUuid; 14776 codeFile = new File(pkg.codePath); 14777 installerPackageName = ps.installerPackageName; 14778 packageAbiOverride = ps.cpuAbiOverrideString; 14779 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14780 seinfo = pkg.applicationInfo.seinfo; 14781 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14782 } 14783 14784 // Now that we're guarded by frozen state, kill app during move 14785 killApplication(packageName, appId, "move pkg"); 14786 14787 final Bundle extras = new Bundle(); 14788 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14789 extras.putString(Intent.EXTRA_TITLE, label); 14790 mMoveCallbacks.notifyCreated(moveId, extras); 14791 14792 int installFlags; 14793 final boolean moveCompleteApp; 14794 final File measurePath; 14795 14796 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14797 installFlags = INSTALL_INTERNAL; 14798 moveCompleteApp = !currentAsec; 14799 measurePath = Environment.getDataAppDirectory(volumeUuid); 14800 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14801 installFlags = INSTALL_EXTERNAL; 14802 moveCompleteApp = false; 14803 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14804 } else { 14805 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14806 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14807 || !volume.isMountedWritable()) { 14808 unfreezePackage(packageName); 14809 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14810 "Move location not mounted private volume"); 14811 } 14812 14813 Preconditions.checkState(!currentAsec); 14814 14815 installFlags = INSTALL_INTERNAL; 14816 moveCompleteApp = true; 14817 measurePath = Environment.getDataAppDirectory(volumeUuid); 14818 } 14819 14820 final PackageStats stats = new PackageStats(null, -1); 14821 synchronized (mInstaller) { 14822 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14823 unfreezePackage(packageName); 14824 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14825 "Failed to measure package size"); 14826 } 14827 } 14828 14829 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14830 + stats.dataSize); 14831 14832 final long startFreeBytes = measurePath.getFreeSpace(); 14833 final long sizeBytes; 14834 if (moveCompleteApp) { 14835 sizeBytes = stats.codeSize + stats.dataSize; 14836 } else { 14837 sizeBytes = stats.codeSize; 14838 } 14839 14840 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14841 unfreezePackage(packageName); 14842 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14843 "Not enough free space to move"); 14844 } 14845 14846 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14847 14848 final CountDownLatch installedLatch = new CountDownLatch(1); 14849 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14850 @Override 14851 public void onUserActionRequired(Intent intent) throws RemoteException { 14852 throw new IllegalStateException(); 14853 } 14854 14855 @Override 14856 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14857 Bundle extras) throws RemoteException { 14858 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14859 + PackageManager.installStatusToString(returnCode, msg)); 14860 14861 installedLatch.countDown(); 14862 14863 // Regardless of success or failure of the move operation, 14864 // always unfreeze the package 14865 unfreezePackage(packageName); 14866 14867 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14868 switch (status) { 14869 case PackageInstaller.STATUS_SUCCESS: 14870 mMoveCallbacks.notifyStatusChanged(moveId, 14871 PackageManager.MOVE_SUCCEEDED); 14872 break; 14873 case PackageInstaller.STATUS_FAILURE_STORAGE: 14874 mMoveCallbacks.notifyStatusChanged(moveId, 14875 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14876 break; 14877 default: 14878 mMoveCallbacks.notifyStatusChanged(moveId, 14879 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14880 break; 14881 } 14882 } 14883 }; 14884 14885 final MoveInfo move; 14886 if (moveCompleteApp) { 14887 // Kick off a thread to report progress estimates 14888 new Thread() { 14889 @Override 14890 public void run() { 14891 while (true) { 14892 try { 14893 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14894 break; 14895 } 14896 } catch (InterruptedException ignored) { 14897 } 14898 14899 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14900 final int progress = 10 + (int) MathUtils.constrain( 14901 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14902 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14903 } 14904 } 14905 }.start(); 14906 14907 final String dataAppName = codeFile.getName(); 14908 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14909 dataAppName, appId, seinfo); 14910 } else { 14911 move = null; 14912 } 14913 14914 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14915 14916 final Message msg = mHandler.obtainMessage(INIT_COPY); 14917 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14918 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14919 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14920 mHandler.sendMessage(msg); 14921 } 14922 14923 @Override 14924 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14926 14927 final int realMoveId = mNextMoveId.getAndIncrement(); 14928 final Bundle extras = new Bundle(); 14929 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14930 mMoveCallbacks.notifyCreated(realMoveId, extras); 14931 14932 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14933 @Override 14934 public void onCreated(int moveId, Bundle extras) { 14935 // Ignored 14936 } 14937 14938 @Override 14939 public void onStatusChanged(int moveId, int status, long estMillis) { 14940 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14941 } 14942 }; 14943 14944 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14945 storage.setPrimaryStorageUuid(volumeUuid, callback); 14946 return realMoveId; 14947 } 14948 14949 @Override 14950 public int getMoveStatus(int moveId) { 14951 mContext.enforceCallingOrSelfPermission( 14952 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14953 return mMoveCallbacks.mLastStatus.get(moveId); 14954 } 14955 14956 @Override 14957 public void registerMoveCallback(IPackageMoveObserver callback) { 14958 mContext.enforceCallingOrSelfPermission( 14959 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14960 mMoveCallbacks.register(callback); 14961 } 14962 14963 @Override 14964 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14965 mContext.enforceCallingOrSelfPermission( 14966 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14967 mMoveCallbacks.unregister(callback); 14968 } 14969 14970 @Override 14971 public boolean setInstallLocation(int loc) { 14972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14973 null); 14974 if (getInstallLocation() == loc) { 14975 return true; 14976 } 14977 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14978 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14979 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14980 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14981 return true; 14982 } 14983 return false; 14984 } 14985 14986 @Override 14987 public int getInstallLocation() { 14988 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14989 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14990 PackageHelper.APP_INSTALL_AUTO); 14991 } 14992 14993 /** Called by UserManagerService */ 14994 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14995 mDirtyUsers.remove(userHandle); 14996 mSettings.removeUserLPw(userHandle); 14997 mPendingBroadcasts.remove(userHandle); 14998 if (mInstaller != null) { 14999 // Technically, we shouldn't be doing this with the package lock 15000 // held. However, this is very rare, and there is already so much 15001 // other disk I/O going on, that we'll let it slide for now. 15002 final StorageManager storage = StorageManager.from(mContext); 15003 final List<VolumeInfo> vols = storage.getVolumes(); 15004 for (VolumeInfo vol : vols) { 15005 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15006 final String volumeUuid = vol.getFsUuid(); 15007 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15008 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15009 } 15010 } 15011 } 15012 mUserNeedsBadging.delete(userHandle); 15013 removeUnusedPackagesLILPw(userManager, userHandle); 15014 } 15015 15016 /** 15017 * We're removing userHandle and would like to remove any downloaded packages 15018 * that are no longer in use by any other user. 15019 * @param userHandle the user being removed 15020 */ 15021 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15022 final boolean DEBUG_CLEAN_APKS = false; 15023 int [] users = userManager.getUserIdsLPr(); 15024 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15025 while (psit.hasNext()) { 15026 PackageSetting ps = psit.next(); 15027 if (ps.pkg == null) { 15028 continue; 15029 } 15030 final String packageName = ps.pkg.packageName; 15031 // Skip over if system app 15032 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15033 continue; 15034 } 15035 if (DEBUG_CLEAN_APKS) { 15036 Slog.i(TAG, "Checking package " + packageName); 15037 } 15038 boolean keep = false; 15039 for (int i = 0; i < users.length; i++) { 15040 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15041 keep = true; 15042 if (DEBUG_CLEAN_APKS) { 15043 Slog.i(TAG, " Keeping package " + packageName + " for user " 15044 + users[i]); 15045 } 15046 break; 15047 } 15048 } 15049 if (!keep) { 15050 if (DEBUG_CLEAN_APKS) { 15051 Slog.i(TAG, " Removing package " + packageName); 15052 } 15053 mHandler.post(new Runnable() { 15054 public void run() { 15055 deletePackageX(packageName, userHandle, 0); 15056 } //end run 15057 }); 15058 } 15059 } 15060 } 15061 15062 /** Called by UserManagerService */ 15063 void createNewUserLILPw(int userHandle, File path) { 15064 if (mInstaller != null) { 15065 mInstaller.createUserConfig(userHandle); 15066 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15067 } 15068 } 15069 15070 void newUserCreatedLILPw(int userHandle) { 15071 // Adding a user requires updating runtime permissions for system apps. 15072 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15073 } 15074 15075 @Override 15076 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15077 mContext.enforceCallingOrSelfPermission( 15078 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15079 "Only package verification agents can read the verifier device identity"); 15080 15081 synchronized (mPackages) { 15082 return mSettings.getVerifierDeviceIdentityLPw(); 15083 } 15084 } 15085 15086 @Override 15087 public void setPermissionEnforced(String permission, boolean enforced) { 15088 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15089 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15090 synchronized (mPackages) { 15091 if (mSettings.mReadExternalStorageEnforced == null 15092 || mSettings.mReadExternalStorageEnforced != enforced) { 15093 mSettings.mReadExternalStorageEnforced = enforced; 15094 mSettings.writeLPr(); 15095 } 15096 } 15097 // kill any non-foreground processes so we restart them and 15098 // grant/revoke the GID. 15099 final IActivityManager am = ActivityManagerNative.getDefault(); 15100 if (am != null) { 15101 final long token = Binder.clearCallingIdentity(); 15102 try { 15103 am.killProcessesBelowForeground("setPermissionEnforcement"); 15104 } catch (RemoteException e) { 15105 } finally { 15106 Binder.restoreCallingIdentity(token); 15107 } 15108 } 15109 } else { 15110 throw new IllegalArgumentException("No selective enforcement for " + permission); 15111 } 15112 } 15113 15114 @Override 15115 @Deprecated 15116 public boolean isPermissionEnforced(String permission) { 15117 return true; 15118 } 15119 15120 @Override 15121 public boolean isStorageLow() { 15122 final long token = Binder.clearCallingIdentity(); 15123 try { 15124 final DeviceStorageMonitorInternal 15125 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15126 if (dsm != null) { 15127 return dsm.isMemoryLow(); 15128 } else { 15129 return false; 15130 } 15131 } finally { 15132 Binder.restoreCallingIdentity(token); 15133 } 15134 } 15135 15136 @Override 15137 public IPackageInstaller getPackageInstaller() { 15138 return mInstallerService; 15139 } 15140 15141 private boolean userNeedsBadging(int userId) { 15142 int index = mUserNeedsBadging.indexOfKey(userId); 15143 if (index < 0) { 15144 final UserInfo userInfo; 15145 final long token = Binder.clearCallingIdentity(); 15146 try { 15147 userInfo = sUserManager.getUserInfo(userId); 15148 } finally { 15149 Binder.restoreCallingIdentity(token); 15150 } 15151 final boolean b; 15152 if (userInfo != null && userInfo.isManagedProfile()) { 15153 b = true; 15154 } else { 15155 b = false; 15156 } 15157 mUserNeedsBadging.put(userId, b); 15158 return b; 15159 } 15160 return mUserNeedsBadging.valueAt(index); 15161 } 15162 15163 @Override 15164 public KeySet getKeySetByAlias(String packageName, String alias) { 15165 if (packageName == null || alias == null) { 15166 return null; 15167 } 15168 synchronized(mPackages) { 15169 final PackageParser.Package pkg = mPackages.get(packageName); 15170 if (pkg == null) { 15171 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15172 throw new IllegalArgumentException("Unknown package: " + packageName); 15173 } 15174 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15175 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15176 } 15177 } 15178 15179 @Override 15180 public KeySet getSigningKeySet(String packageName) { 15181 if (packageName == null) { 15182 return null; 15183 } 15184 synchronized(mPackages) { 15185 final PackageParser.Package pkg = mPackages.get(packageName); 15186 if (pkg == null) { 15187 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15188 throw new IllegalArgumentException("Unknown package: " + packageName); 15189 } 15190 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15191 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15192 throw new SecurityException("May not access signing KeySet of other apps."); 15193 } 15194 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15195 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15196 } 15197 } 15198 15199 @Override 15200 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15201 if (packageName == null || ks == null) { 15202 return false; 15203 } 15204 synchronized(mPackages) { 15205 final PackageParser.Package pkg = mPackages.get(packageName); 15206 if (pkg == null) { 15207 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15208 throw new IllegalArgumentException("Unknown package: " + packageName); 15209 } 15210 IBinder ksh = ks.getToken(); 15211 if (ksh instanceof KeySetHandle) { 15212 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15213 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15214 } 15215 return false; 15216 } 15217 } 15218 15219 @Override 15220 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15221 if (packageName == null || ks == null) { 15222 return false; 15223 } 15224 synchronized(mPackages) { 15225 final PackageParser.Package pkg = mPackages.get(packageName); 15226 if (pkg == null) { 15227 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15228 throw new IllegalArgumentException("Unknown package: " + packageName); 15229 } 15230 IBinder ksh = ks.getToken(); 15231 if (ksh instanceof KeySetHandle) { 15232 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15233 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15234 } 15235 return false; 15236 } 15237 } 15238 15239 public void getUsageStatsIfNoPackageUsageInfo() { 15240 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15241 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15242 if (usm == null) { 15243 throw new IllegalStateException("UsageStatsManager must be initialized"); 15244 } 15245 long now = System.currentTimeMillis(); 15246 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15247 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15248 String packageName = entry.getKey(); 15249 PackageParser.Package pkg = mPackages.get(packageName); 15250 if (pkg == null) { 15251 continue; 15252 } 15253 UsageStats usage = entry.getValue(); 15254 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15255 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15256 } 15257 } 15258 } 15259 15260 /** 15261 * Check and throw if the given before/after packages would be considered a 15262 * downgrade. 15263 */ 15264 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15265 throws PackageManagerException { 15266 if (after.versionCode < before.mVersionCode) { 15267 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15268 "Update version code " + after.versionCode + " is older than current " 15269 + before.mVersionCode); 15270 } else if (after.versionCode == before.mVersionCode) { 15271 if (after.baseRevisionCode < before.baseRevisionCode) { 15272 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15273 "Update base revision code " + after.baseRevisionCode 15274 + " is older than current " + before.baseRevisionCode); 15275 } 15276 15277 if (!ArrayUtils.isEmpty(after.splitNames)) { 15278 for (int i = 0; i < after.splitNames.length; i++) { 15279 final String splitName = after.splitNames[i]; 15280 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15281 if (j != -1) { 15282 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15283 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15284 "Update split " + splitName + " revision code " 15285 + after.splitRevisionCodes[i] + " is older than current " 15286 + before.splitRevisionCodes[j]); 15287 } 15288 } 15289 } 15290 } 15291 } 15292 } 15293 15294 private static class MoveCallbacks extends Handler { 15295 private static final int MSG_CREATED = 1; 15296 private static final int MSG_STATUS_CHANGED = 2; 15297 15298 private final RemoteCallbackList<IPackageMoveObserver> 15299 mCallbacks = new RemoteCallbackList<>(); 15300 15301 private final SparseIntArray mLastStatus = new SparseIntArray(); 15302 15303 public MoveCallbacks(Looper looper) { 15304 super(looper); 15305 } 15306 15307 public void register(IPackageMoveObserver callback) { 15308 mCallbacks.register(callback); 15309 } 15310 15311 public void unregister(IPackageMoveObserver callback) { 15312 mCallbacks.unregister(callback); 15313 } 15314 15315 @Override 15316 public void handleMessage(Message msg) { 15317 final SomeArgs args = (SomeArgs) msg.obj; 15318 final int n = mCallbacks.beginBroadcast(); 15319 for (int i = 0; i < n; i++) { 15320 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15321 try { 15322 invokeCallback(callback, msg.what, args); 15323 } catch (RemoteException ignored) { 15324 } 15325 } 15326 mCallbacks.finishBroadcast(); 15327 args.recycle(); 15328 } 15329 15330 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15331 throws RemoteException { 15332 switch (what) { 15333 case MSG_CREATED: { 15334 callback.onCreated(args.argi1, (Bundle) args.arg2); 15335 break; 15336 } 15337 case MSG_STATUS_CHANGED: { 15338 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15339 break; 15340 } 15341 } 15342 } 15343 15344 private void notifyCreated(int moveId, Bundle extras) { 15345 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15346 15347 final SomeArgs args = SomeArgs.obtain(); 15348 args.argi1 = moveId; 15349 args.arg2 = extras; 15350 obtainMessage(MSG_CREATED, args).sendToTarget(); 15351 } 15352 15353 private void notifyStatusChanged(int moveId, int status) { 15354 notifyStatusChanged(moveId, status, -1); 15355 } 15356 15357 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15358 Slog.v(TAG, "Move " + moveId + " status " + status); 15359 15360 final SomeArgs args = SomeArgs.obtain(); 15361 args.argi1 = moveId; 15362 args.argi2 = status; 15363 args.arg3 = estMillis; 15364 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15365 15366 synchronized (mLastStatus) { 15367 mLastStatus.put(moveId, status); 15368 } 15369 } 15370 } 15371 15372 private final class OnPermissionChangeListeners extends Handler { 15373 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15374 15375 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15376 new RemoteCallbackList<>(); 15377 15378 public OnPermissionChangeListeners(Looper looper) { 15379 super(looper); 15380 } 15381 15382 @Override 15383 public void handleMessage(Message msg) { 15384 switch (msg.what) { 15385 case MSG_ON_PERMISSIONS_CHANGED: { 15386 final int uid = msg.arg1; 15387 handleOnPermissionsChanged(uid); 15388 } break; 15389 } 15390 } 15391 15392 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15393 mPermissionListeners.register(listener); 15394 15395 } 15396 15397 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15398 mPermissionListeners.unregister(listener); 15399 } 15400 15401 public void onPermissionsChanged(int uid) { 15402 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15403 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15404 } 15405 } 15406 15407 private void handleOnPermissionsChanged(int uid) { 15408 final int count = mPermissionListeners.beginBroadcast(); 15409 try { 15410 for (int i = 0; i < count; i++) { 15411 IOnPermissionsChangeListener callback = mPermissionListeners 15412 .getBroadcastItem(i); 15413 try { 15414 callback.onPermissionsChanged(uid); 15415 } catch (RemoteException e) { 15416 Log.e(TAG, "Permission listener is dead", e); 15417 } 15418 } 15419 } finally { 15420 mPermissionListeners.finishBroadcast(); 15421 } 15422 } 15423 } 15424} 15425