PackageManagerService.java revision 43469fd4a4e0d7b2fd387f74c0c7f23296553b23
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IOnPermissionsChangeListener; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.IPackagesProvider; 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.PackageManagerInternal; 115import android.content.pm.PackageParser; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Debug; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteCallbackList; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.os.storage.IMountService; 158import android.os.storage.StorageEventListener; 159import android.os.storage.StorageManager; 160import android.os.storage.VolumeInfo; 161import android.os.storage.VolumeRecord; 162import android.security.KeyStore; 163import android.security.SystemKeyStore; 164import android.system.ErrnoException; 165import android.system.Os; 166import android.system.StructStat; 167import android.text.TextUtils; 168import android.text.format.DateUtils; 169import android.util.ArrayMap; 170import android.util.ArraySet; 171import android.util.AtomicFile; 172import android.util.DisplayMetrics; 173import android.util.EventLog; 174import android.util.ExceptionUtils; 175import android.util.Log; 176import android.util.LogPrinter; 177import android.util.MathUtils; 178import android.util.PrintStreamPrinter; 179import android.util.Slog; 180import android.util.SparseArray; 181import android.util.SparseBooleanArray; 182import android.util.SparseIntArray; 183import android.util.Xml; 184import android.view.Display; 185 186import dalvik.system.DexFile; 187import dalvik.system.VMRuntime; 188 189import libcore.io.IoUtils; 190import libcore.util.EmptyArray; 191 192import com.android.internal.R; 193import com.android.internal.app.IMediaContainerService; 194import com.android.internal.app.ResolverActivity; 195import com.android.internal.content.NativeLibraryHelper; 196import com.android.internal.content.PackageHelper; 197import com.android.internal.os.IParcelFileDescriptorFactory; 198import com.android.internal.os.SomeArgs; 199import com.android.internal.util.ArrayUtils; 200import com.android.internal.util.FastPrintWriter; 201import com.android.internal.util.FastXmlSerializer; 202import com.android.internal.util.IndentingPrintWriter; 203import com.android.internal.util.Preconditions; 204import com.android.server.EventLogTags; 205import com.android.server.FgThread; 206import com.android.server.IntentResolver; 207import com.android.server.LocalServices; 208import com.android.server.ServiceThread; 209import com.android.server.SystemConfig; 210import com.android.server.Watchdog; 211import com.android.server.pm.Settings.DatabaseVersion; 212import com.android.server.pm.PermissionsState.PermissionState; 213import com.android.server.storage.DeviceStorageMonitorInternal; 214 215import org.xmlpull.v1.XmlPullParser; 216import org.xmlpull.v1.XmlPullParserException; 217import org.xmlpull.v1.XmlSerializer; 218 219import java.io.BufferedInputStream; 220import java.io.BufferedOutputStream; 221import java.io.BufferedReader; 222import java.io.ByteArrayInputStream; 223import java.io.ByteArrayOutputStream; 224import java.io.File; 225import java.io.FileDescriptor; 226import java.io.FileNotFoundException; 227import java.io.FileOutputStream; 228import java.io.FileReader; 229import java.io.FilenameFilter; 230import java.io.IOException; 231import java.io.InputStream; 232import java.io.PrintWriter; 233import java.nio.charset.StandardCharsets; 234import java.security.NoSuchAlgorithmException; 235import java.security.PublicKey; 236import java.security.cert.CertificateEncodingException; 237import java.security.cert.CertificateException; 238import java.text.SimpleDateFormat; 239import java.util.ArrayList; 240import java.util.Arrays; 241import java.util.Collection; 242import java.util.Collections; 243import java.util.Comparator; 244import java.util.Date; 245import java.util.Iterator; 246import java.util.List; 247import java.util.Map; 248import java.util.Objects; 249import java.util.Set; 250import java.util.concurrent.CountDownLatch; 251import java.util.concurrent.TimeUnit; 252import java.util.concurrent.atomic.AtomicBoolean; 253import java.util.concurrent.atomic.AtomicInteger; 254import java.util.concurrent.atomic.AtomicLong; 255 256/** 257 * Keep track of all those .apks everywhere. 258 * 259 * This is very central to the platform's security; please run the unit 260 * tests whenever making modifications here: 261 * 262runtest -c android.content.pm.PackageManagerTests frameworks-core 263 * 264 * {@hide} 265 */ 266public class PackageManagerService extends IPackageManager.Stub { 267 static final String TAG = "PackageManager"; 268 static final boolean DEBUG_SETTINGS = false; 269 static final boolean DEBUG_PREFERRED = false; 270 static final boolean DEBUG_UPGRADE = false; 271 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 272 private static final boolean DEBUG_BACKUP = true; 273 private static final boolean DEBUG_INSTALL = false; 274 private static final boolean DEBUG_REMOVE = false; 275 private static final boolean DEBUG_BROADCASTS = false; 276 private static final boolean DEBUG_SHOW_INFO = false; 277 private static final boolean DEBUG_PACKAGE_INFO = false; 278 private static final boolean DEBUG_INTENT_MATCHING = false; 279 private static final boolean DEBUG_PACKAGE_SCANNING = false; 280 private static final boolean DEBUG_VERIFY = false; 281 private static final boolean DEBUG_DEXOPT = false; 282 private static final boolean DEBUG_ABI_SELECTION = false; 283 284 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 285 286 private static final int RADIO_UID = Process.PHONE_UID; 287 private static final int LOG_UID = Process.LOG_UID; 288 private static final int NFC_UID = Process.NFC_UID; 289 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 290 private static final int SHELL_UID = Process.SHELL_UID; 291 292 // Cap the size of permission trees that 3rd party apps can define 293 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 294 295 // Suffix used during package installation when copying/moving 296 // package apks to install directory. 297 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 298 299 static final int SCAN_NO_DEX = 1<<1; 300 static final int SCAN_FORCE_DEX = 1<<2; 301 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 302 static final int SCAN_NEW_INSTALL = 1<<4; 303 static final int SCAN_NO_PATHS = 1<<5; 304 static final int SCAN_UPDATE_TIME = 1<<6; 305 static final int SCAN_DEFER_DEX = 1<<7; 306 static final int SCAN_BOOTING = 1<<8; 307 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 308 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 309 static final int SCAN_REQUIRE_KNOWN = 1<<12; 310 static final int SCAN_MOVE = 1<<13; 311 312 static final int REMOVE_CHATTY = 1<<16; 313 314 private static final int[] EMPTY_INT_ARRAY = new int[0]; 315 316 /** 317 * Timeout (in milliseconds) after which the watchdog should declare that 318 * our handler thread is wedged. The usual default for such things is one 319 * minute but we sometimes do very lengthy I/O operations on this thread, 320 * such as installing multi-gigabyte applications, so ours needs to be longer. 321 */ 322 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 323 324 /** 325 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 326 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 327 * settings entry if available, otherwise we use the hardcoded default. If it's been 328 * more than this long since the last fstrim, we force one during the boot sequence. 329 * 330 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 331 * one gets run at the next available charging+idle time. This final mandatory 332 * no-fstrim check kicks in only of the other scheduling criteria is never met. 333 */ 334 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 335 336 /** 337 * Whether verification is enabled by default. 338 */ 339 private static final boolean DEFAULT_VERIFY_ENABLE = true; 340 341 /** 342 * The default maximum time to wait for the verification agent to return in 343 * milliseconds. 344 */ 345 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 346 347 /** 348 * The default response for package verification timeout. 349 * 350 * This can be either PackageManager.VERIFICATION_ALLOW or 351 * PackageManager.VERIFICATION_REJECT. 352 */ 353 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 354 355 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 356 357 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 358 DEFAULT_CONTAINER_PACKAGE, 359 "com.android.defcontainer.DefaultContainerService"); 360 361 private static final String KILL_APP_REASON_GIDS_CHANGED = 362 "permission grant or revoke changed gids"; 363 364 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 365 "permissions revoked"; 366 367 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 368 369 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 370 371 /** Permission grant: not grant the permission. */ 372 private static final int GRANT_DENIED = 1; 373 374 /** Permission grant: grant the permission as an install permission. */ 375 private static final int GRANT_INSTALL = 2; 376 377 /** Permission grant: grant the permission as an install permission for a legacy app. */ 378 private static final int GRANT_INSTALL_LEGACY = 3; 379 380 /** Permission grant: grant the permission as a runtime one. */ 381 private static final int GRANT_RUNTIME = 4; 382 383 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 384 private static final int GRANT_UPGRADE = 5; 385 386 final ServiceThread mHandlerThread; 387 388 final PackageHandler mHandler; 389 390 /** 391 * Messages for {@link #mHandler} that need to wait for system ready before 392 * being dispatched. 393 */ 394 private ArrayList<Message> mPostSystemReadyMessages; 395 396 final int mSdkVersion = Build.VERSION.SDK_INT; 397 398 final Context mContext; 399 final boolean mFactoryTest; 400 final boolean mOnlyCore; 401 final boolean mLazyDexOpt; 402 final long mDexOptLRUThresholdInMills; 403 final DisplayMetrics mMetrics; 404 final int mDefParseFlags; 405 final String[] mSeparateProcesses; 406 final boolean mIsUpgrade; 407 408 // This is where all application persistent data goes. 409 final File mAppDataDir; 410 411 // This is where all application persistent data goes for secondary users. 412 final File mUserAppDataDir; 413 414 /** The location for ASEC container files on internal storage. */ 415 final String mAsecInternalPath; 416 417 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 418 // LOCK HELD. Can be called with mInstallLock held. 419 final Installer mInstaller; 420 421 /** Directory where installed third-party apps stored */ 422 final File mAppInstallDir; 423 424 /** 425 * Directory to which applications installed internally have their 426 * 32 bit native libraries copied. 427 */ 428 private File mAppLib32InstallDir; 429 430 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 431 // apps. 432 final File mDrmAppPrivateInstallDir; 433 434 // ---------------------------------------------------------------- 435 436 // Lock for state used when installing and doing other long running 437 // operations. Methods that must be called with this lock held have 438 // the suffix "LI". 439 final Object mInstallLock = new Object(); 440 441 // ---------------------------------------------------------------- 442 443 // Keys are String (package name), values are Package. This also serves 444 // as the lock for the global state. Methods that must be called with 445 // this lock held have the prefix "LP". 446 final ArrayMap<String, PackageParser.Package> mPackages = 447 new ArrayMap<String, PackageParser.Package>(); 448 449 // Tracks available target package names -> overlay package paths. 450 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 451 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 452 453 final Settings mSettings; 454 boolean mRestoredSettings; 455 456 // System configuration read by SystemConfig. 457 final int[] mGlobalGids; 458 final SparseArray<ArraySet<String>> mSystemPermissions; 459 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 460 461 // If mac_permissions.xml was found for seinfo labeling. 462 boolean mFoundPolicyFile; 463 464 // If a recursive restorecon of /data/data/<pkg> is needed. 465 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 466 467 public static final class SharedLibraryEntry { 468 public final String path; 469 public final String apk; 470 471 SharedLibraryEntry(String _path, String _apk) { 472 path = _path; 473 apk = _apk; 474 } 475 } 476 477 // Currently known shared libraries. 478 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 479 new ArrayMap<String, SharedLibraryEntry>(); 480 481 // All available activities, for your resolving pleasure. 482 final ActivityIntentResolver mActivities = 483 new ActivityIntentResolver(); 484 485 // All available receivers, for your resolving pleasure. 486 final ActivityIntentResolver mReceivers = 487 new ActivityIntentResolver(); 488 489 // All available services, for your resolving pleasure. 490 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 491 492 // All available providers, for your resolving pleasure. 493 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 494 495 // Mapping from provider base names (first directory in content URI codePath) 496 // to the provider information. 497 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 498 new ArrayMap<String, PackageParser.Provider>(); 499 500 // Mapping from instrumentation class names to info about them. 501 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 502 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 503 504 // Mapping from permission names to info about them. 505 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 506 new ArrayMap<String, PackageParser.PermissionGroup>(); 507 508 // Packages whose data we have transfered into another package, thus 509 // should no longer exist. 510 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 511 512 // Broadcast actions that are only available to the system. 513 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 514 515 /** List of packages waiting for verification. */ 516 final SparseArray<PackageVerificationState> mPendingVerification 517 = new SparseArray<PackageVerificationState>(); 518 519 /** Set of packages associated with each app op permission. */ 520 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 521 522 final PackageInstallerService mInstallerService; 523 524 private final PackageDexOptimizer mPackageDexOptimizer; 525 526 private AtomicInteger mNextMoveId = new AtomicInteger(); 527 private final MoveCallbacks mMoveCallbacks; 528 529 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 530 531 // Cache of users who need badging. 532 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 533 534 /** Token for keys in mPendingVerification. */ 535 private int mPendingVerificationToken = 0; 536 537 volatile boolean mSystemReady; 538 volatile boolean mSafeMode; 539 volatile boolean mHasSystemUidErrors; 540 541 ApplicationInfo mAndroidApplication; 542 final ActivityInfo mResolveActivity = new ActivityInfo(); 543 final ResolveInfo mResolveInfo = new ResolveInfo(); 544 ComponentName mResolveComponentName; 545 PackageParser.Package mPlatformPackage; 546 ComponentName mCustomResolverComponentName; 547 548 boolean mResolverReplaced = false; 549 550 private final ComponentName mIntentFilterVerifierComponent; 551 private int mIntentFilterVerificationToken = 0; 552 553 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 554 = new SparseArray<IntentFilterVerificationState>(); 555 556 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 557 new DefaultPermissionGrantPolicy(this); 558 559 private static class IFVerificationParams { 560 PackageParser.Package pkg; 561 boolean replacing; 562 int userId; 563 int verifierUid; 564 565 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 566 int _userId, int _verifierUid) { 567 pkg = _pkg; 568 replacing = _replacing; 569 userId = _userId; 570 replacing = _replacing; 571 verifierUid = _verifierUid; 572 } 573 } 574 575 private interface IntentFilterVerifier<T extends IntentFilter> { 576 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 577 T filter, String packageName); 578 void startVerifications(int userId); 579 void receiveVerificationResponse(int verificationId); 580 } 581 582 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 583 private Context mContext; 584 private ComponentName mIntentFilterVerifierComponent; 585 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 586 587 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 588 mContext = context; 589 mIntentFilterVerifierComponent = verifierComponent; 590 } 591 592 private String getDefaultScheme() { 593 return IntentFilter.SCHEME_HTTPS; 594 } 595 596 @Override 597 public void startVerifications(int userId) { 598 // Launch verifications requests 599 int count = mCurrentIntentFilterVerifications.size(); 600 for (int n=0; n<count; n++) { 601 int verificationId = mCurrentIntentFilterVerifications.get(n); 602 final IntentFilterVerificationState ivs = 603 mIntentFilterVerificationStates.get(verificationId); 604 605 String packageName = ivs.getPackageName(); 606 607 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 608 final int filterCount = filters.size(); 609 ArraySet<String> domainsSet = new ArraySet<>(); 610 for (int m=0; m<filterCount; m++) { 611 PackageParser.ActivityIntentInfo filter = filters.get(m); 612 domainsSet.addAll(filter.getHostsList()); 613 } 614 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 615 synchronized (mPackages) { 616 if (mSettings.createIntentFilterVerificationIfNeededLPw( 617 packageName, domainsList) != null) { 618 scheduleWriteSettingsLocked(); 619 } 620 } 621 sendVerificationRequest(userId, verificationId, ivs); 622 } 623 mCurrentIntentFilterVerifications.clear(); 624 } 625 626 private void sendVerificationRequest(int userId, int verificationId, 627 IntentFilterVerificationState ivs) { 628 629 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 630 verificationIntent.putExtra( 631 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 632 verificationId); 633 verificationIntent.putExtra( 634 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 635 getDefaultScheme()); 636 verificationIntent.putExtra( 637 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 638 ivs.getHostsString()); 639 verificationIntent.putExtra( 640 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 641 ivs.getPackageName()); 642 verificationIntent.setComponent(mIntentFilterVerifierComponent); 643 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 644 645 UserHandle user = new UserHandle(userId); 646 mContext.sendBroadcastAsUser(verificationIntent, user); 647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 648 "Sending IntentFilter verification broadcast"); 649 } 650 651 public void receiveVerificationResponse(int verificationId) { 652 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 653 654 final boolean verified = ivs.isVerified(); 655 656 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 657 final int count = filters.size(); 658 if (DEBUG_DOMAIN_VERIFICATION) { 659 Slog.i(TAG, "Received verification response " + verificationId 660 + " for " + count + " filters, verified=" + verified); 661 } 662 for (int n=0; n<count; n++) { 663 PackageParser.ActivityIntentInfo filter = filters.get(n); 664 filter.setVerified(verified); 665 666 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 667 + " verified with result:" + verified + " and hosts:" 668 + ivs.getHostsString()); 669 } 670 671 mIntentFilterVerificationStates.remove(verificationId); 672 673 final String packageName = ivs.getPackageName(); 674 IntentFilterVerificationInfo ivi = null; 675 676 synchronized (mPackages) { 677 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 678 } 679 if (ivi == null) { 680 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 681 + verificationId + " packageName:" + packageName); 682 return; 683 } 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 686 687 synchronized (mPackages) { 688 if (verified) { 689 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 690 } else { 691 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 692 } 693 scheduleWriteSettingsLocked(); 694 695 final int userId = ivs.getUserId(); 696 if (userId != UserHandle.USER_ALL) { 697 final int userStatus = 698 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 699 700 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 701 boolean needUpdate = false; 702 703 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 704 // already been set by the User thru the Disambiguation dialog 705 switch (userStatus) { 706 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 707 if (verified) { 708 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 709 } else { 710 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 711 } 712 needUpdate = true; 713 break; 714 715 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 716 if (verified) { 717 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 718 needUpdate = true; 719 } 720 break; 721 722 default: 723 // Nothing to do 724 } 725 726 if (needUpdate) { 727 mSettings.updateIntentFilterVerificationStatusLPw( 728 packageName, updatedStatus, userId); 729 scheduleWritePackageRestrictionsLocked(userId); 730 } 731 } 732 } 733 } 734 735 @Override 736 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 737 ActivityIntentInfo filter, String packageName) { 738 if (!hasValidDomains(filter)) { 739 return false; 740 } 741 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 742 if (ivs == null) { 743 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 744 packageName); 745 } 746 if (DEBUG_DOMAIN_VERIFICATION) { 747 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 748 } 749 ivs.addFilter(filter); 750 return true; 751 } 752 753 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 754 int userId, int verificationId, String packageName) { 755 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 756 verifierUid, userId, packageName); 757 ivs.setPendingState(); 758 synchronized (mPackages) { 759 mIntentFilterVerificationStates.append(verificationId, ivs); 760 mCurrentIntentFilterVerifications.add(verificationId); 761 } 762 return ivs; 763 } 764 } 765 766 private static boolean hasValidDomains(ActivityIntentInfo filter) { 767 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 768 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 769 if (!hasHTTPorHTTPS) { 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 771 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 772 return false; 773 } 774 return true; 775 } 776 777 private IntentFilterVerifier mIntentFilterVerifier; 778 779 // Set of pending broadcasts for aggregating enable/disable of components. 780 static class PendingPackageBroadcasts { 781 // for each user id, a map of <package name -> components within that package> 782 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 783 784 public PendingPackageBroadcasts() { 785 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 786 } 787 788 public ArrayList<String> get(int userId, String packageName) { 789 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 790 return packages.get(packageName); 791 } 792 793 public void put(int userId, String packageName, ArrayList<String> components) { 794 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 795 packages.put(packageName, components); 796 } 797 798 public void remove(int userId, String packageName) { 799 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 800 if (packages != null) { 801 packages.remove(packageName); 802 } 803 } 804 805 public void remove(int userId) { 806 mUidMap.remove(userId); 807 } 808 809 public int userIdCount() { 810 return mUidMap.size(); 811 } 812 813 public int userIdAt(int n) { 814 return mUidMap.keyAt(n); 815 } 816 817 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 818 return mUidMap.get(userId); 819 } 820 821 public int size() { 822 // total number of pending broadcast entries across all userIds 823 int num = 0; 824 for (int i = 0; i< mUidMap.size(); i++) { 825 num += mUidMap.valueAt(i).size(); 826 } 827 return num; 828 } 829 830 public void clear() { 831 mUidMap.clear(); 832 } 833 834 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 835 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 836 if (map == null) { 837 map = new ArrayMap<String, ArrayList<String>>(); 838 mUidMap.put(userId, map); 839 } 840 return map; 841 } 842 } 843 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 844 845 // Service Connection to remote media container service to copy 846 // package uri's from external media onto secure containers 847 // or internal storage. 848 private IMediaContainerService mContainerService = null; 849 850 static final int SEND_PENDING_BROADCAST = 1; 851 static final int MCS_BOUND = 3; 852 static final int END_COPY = 4; 853 static final int INIT_COPY = 5; 854 static final int MCS_UNBIND = 6; 855 static final int START_CLEANING_PACKAGE = 7; 856 static final int FIND_INSTALL_LOC = 8; 857 static final int POST_INSTALL = 9; 858 static final int MCS_RECONNECT = 10; 859 static final int MCS_GIVE_UP = 11; 860 static final int UPDATED_MEDIA_STATUS = 12; 861 static final int WRITE_SETTINGS = 13; 862 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 863 static final int PACKAGE_VERIFIED = 15; 864 static final int CHECK_PENDING_VERIFICATION = 16; 865 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 866 static final int INTENT_FILTER_VERIFIED = 18; 867 868 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 869 870 // Delay time in millisecs 871 static final int BROADCAST_DELAY = 10 * 1000; 872 873 static UserManagerService sUserManager; 874 875 // Stores a list of users whose package restrictions file needs to be updated 876 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 877 878 final private DefaultContainerConnection mDefContainerConn = 879 new DefaultContainerConnection(); 880 class DefaultContainerConnection implements ServiceConnection { 881 public void onServiceConnected(ComponentName name, IBinder service) { 882 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 883 IMediaContainerService imcs = 884 IMediaContainerService.Stub.asInterface(service); 885 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 886 } 887 888 public void onServiceDisconnected(ComponentName name) { 889 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 890 } 891 } 892 893 // Recordkeeping of restore-after-install operations that are currently in flight 894 // between the Package Manager and the Backup Manager 895 class PostInstallData { 896 public InstallArgs args; 897 public PackageInstalledInfo res; 898 899 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 900 args = _a; 901 res = _r; 902 } 903 } 904 905 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 906 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 907 908 // XML tags for backup/restore of various bits of state 909 private static final String TAG_PREFERRED_BACKUP = "pa"; 910 private static final String TAG_DEFAULT_APPS = "da"; 911 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 912 913 private final String mRequiredVerifierPackage; 914 915 private final PackageUsage mPackageUsage = new PackageUsage(); 916 917 private class PackageUsage { 918 private static final int WRITE_INTERVAL 919 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 920 921 private final Object mFileLock = new Object(); 922 private final AtomicLong mLastWritten = new AtomicLong(0); 923 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 924 925 private boolean mIsHistoricalPackageUsageAvailable = true; 926 927 boolean isHistoricalPackageUsageAvailable() { 928 return mIsHistoricalPackageUsageAvailable; 929 } 930 931 void write(boolean force) { 932 if (force) { 933 writeInternal(); 934 return; 935 } 936 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 937 && !DEBUG_DEXOPT) { 938 return; 939 } 940 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 941 new Thread("PackageUsage_DiskWriter") { 942 @Override 943 public void run() { 944 try { 945 writeInternal(); 946 } finally { 947 mBackgroundWriteRunning.set(false); 948 } 949 } 950 }.start(); 951 } 952 } 953 954 private void writeInternal() { 955 synchronized (mPackages) { 956 synchronized (mFileLock) { 957 AtomicFile file = getFile(); 958 FileOutputStream f = null; 959 try { 960 f = file.startWrite(); 961 BufferedOutputStream out = new BufferedOutputStream(f); 962 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 963 StringBuilder sb = new StringBuilder(); 964 for (PackageParser.Package pkg : mPackages.values()) { 965 if (pkg.mLastPackageUsageTimeInMills == 0) { 966 continue; 967 } 968 sb.setLength(0); 969 sb.append(pkg.packageName); 970 sb.append(' '); 971 sb.append((long)pkg.mLastPackageUsageTimeInMills); 972 sb.append('\n'); 973 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 974 } 975 out.flush(); 976 file.finishWrite(f); 977 } catch (IOException e) { 978 if (f != null) { 979 file.failWrite(f); 980 } 981 Log.e(TAG, "Failed to write package usage times", e); 982 } 983 } 984 } 985 mLastWritten.set(SystemClock.elapsedRealtime()); 986 } 987 988 void readLP() { 989 synchronized (mFileLock) { 990 AtomicFile file = getFile(); 991 BufferedInputStream in = null; 992 try { 993 in = new BufferedInputStream(file.openRead()); 994 StringBuffer sb = new StringBuffer(); 995 while (true) { 996 String packageName = readToken(in, sb, ' '); 997 if (packageName == null) { 998 break; 999 } 1000 String timeInMillisString = readToken(in, sb, '\n'); 1001 if (timeInMillisString == null) { 1002 throw new IOException("Failed to find last usage time for package " 1003 + packageName); 1004 } 1005 PackageParser.Package pkg = mPackages.get(packageName); 1006 if (pkg == null) { 1007 continue; 1008 } 1009 long timeInMillis; 1010 try { 1011 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1012 } catch (NumberFormatException e) { 1013 throw new IOException("Failed to parse " + timeInMillisString 1014 + " as a long.", e); 1015 } 1016 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1017 } 1018 } catch (FileNotFoundException expected) { 1019 mIsHistoricalPackageUsageAvailable = false; 1020 } catch (IOException e) { 1021 Log.w(TAG, "Failed to read package usage times", e); 1022 } finally { 1023 IoUtils.closeQuietly(in); 1024 } 1025 } 1026 mLastWritten.set(SystemClock.elapsedRealtime()); 1027 } 1028 1029 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1030 throws IOException { 1031 sb.setLength(0); 1032 while (true) { 1033 int ch = in.read(); 1034 if (ch == -1) { 1035 if (sb.length() == 0) { 1036 return null; 1037 } 1038 throw new IOException("Unexpected EOF"); 1039 } 1040 if (ch == endOfToken) { 1041 return sb.toString(); 1042 } 1043 sb.append((char)ch); 1044 } 1045 } 1046 1047 private AtomicFile getFile() { 1048 File dataDir = Environment.getDataDirectory(); 1049 File systemDir = new File(dataDir, "system"); 1050 File fname = new File(systemDir, "package-usage.list"); 1051 return new AtomicFile(fname); 1052 } 1053 } 1054 1055 class PackageHandler extends Handler { 1056 private boolean mBound = false; 1057 final ArrayList<HandlerParams> mPendingInstalls = 1058 new ArrayList<HandlerParams>(); 1059 1060 private boolean connectToService() { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1062 " DefaultContainerService"); 1063 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1064 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1065 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1066 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1068 mBound = true; 1069 return true; 1070 } 1071 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1072 return false; 1073 } 1074 1075 private void disconnectService() { 1076 mContainerService = null; 1077 mBound = false; 1078 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1079 mContext.unbindService(mDefContainerConn); 1080 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1081 } 1082 1083 PackageHandler(Looper looper) { 1084 super(looper); 1085 } 1086 1087 public void handleMessage(Message msg) { 1088 try { 1089 doHandleMessage(msg); 1090 } finally { 1091 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1092 } 1093 } 1094 1095 void doHandleMessage(Message msg) { 1096 switch (msg.what) { 1097 case INIT_COPY: { 1098 HandlerParams params = (HandlerParams) msg.obj; 1099 int idx = mPendingInstalls.size(); 1100 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1101 // If a bind was already initiated we dont really 1102 // need to do anything. The pending install 1103 // will be processed later on. 1104 if (!mBound) { 1105 // If this is the only one pending we might 1106 // have to bind to the service again. 1107 if (!connectToService()) { 1108 Slog.e(TAG, "Failed to bind to media container service"); 1109 params.serviceError(); 1110 return; 1111 } else { 1112 // Once we bind to the service, the first 1113 // pending request will be processed. 1114 mPendingInstalls.add(idx, params); 1115 } 1116 } else { 1117 mPendingInstalls.add(idx, params); 1118 // Already bound to the service. Just make 1119 // sure we trigger off processing the first request. 1120 if (idx == 0) { 1121 mHandler.sendEmptyMessage(MCS_BOUND); 1122 } 1123 } 1124 break; 1125 } 1126 case MCS_BOUND: { 1127 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1128 if (msg.obj != null) { 1129 mContainerService = (IMediaContainerService) msg.obj; 1130 } 1131 if (mContainerService == null) { 1132 if (!mBound) { 1133 // Something seriously wrong since we are not bound and we are not 1134 // waiting for connection. Bail out. 1135 Slog.e(TAG, "Cannot bind to media container service"); 1136 for (HandlerParams params : mPendingInstalls) { 1137 // Indicate service bind error 1138 params.serviceError(); 1139 } 1140 mPendingInstalls.clear(); 1141 } else { 1142 Slog.w(TAG, "Waiting to connect to media container service"); 1143 } 1144 } else if (mPendingInstalls.size() > 0) { 1145 HandlerParams params = mPendingInstalls.get(0); 1146 if (params != null) { 1147 if (params.startCopy()) { 1148 // We are done... look for more work or to 1149 // go idle. 1150 if (DEBUG_SD_INSTALL) Log.i(TAG, 1151 "Checking for more work or unbind..."); 1152 // Delete pending install 1153 if (mPendingInstalls.size() > 0) { 1154 mPendingInstalls.remove(0); 1155 } 1156 if (mPendingInstalls.size() == 0) { 1157 if (mBound) { 1158 if (DEBUG_SD_INSTALL) Log.i(TAG, 1159 "Posting delayed MCS_UNBIND"); 1160 removeMessages(MCS_UNBIND); 1161 Message ubmsg = obtainMessage(MCS_UNBIND); 1162 // Unbind after a little delay, to avoid 1163 // continual thrashing. 1164 sendMessageDelayed(ubmsg, 10000); 1165 } 1166 } else { 1167 // There are more pending requests in queue. 1168 // Just post MCS_BOUND message to trigger processing 1169 // of next pending install. 1170 if (DEBUG_SD_INSTALL) Log.i(TAG, 1171 "Posting MCS_BOUND for next work"); 1172 mHandler.sendEmptyMessage(MCS_BOUND); 1173 } 1174 } 1175 } 1176 } else { 1177 // Should never happen ideally. 1178 Slog.w(TAG, "Empty queue"); 1179 } 1180 break; 1181 } 1182 case MCS_RECONNECT: { 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1184 if (mPendingInstalls.size() > 0) { 1185 if (mBound) { 1186 disconnectService(); 1187 } 1188 if (!connectToService()) { 1189 Slog.e(TAG, "Failed to bind to media container service"); 1190 for (HandlerParams params : mPendingInstalls) { 1191 // Indicate service bind error 1192 params.serviceError(); 1193 } 1194 mPendingInstalls.clear(); 1195 } 1196 } 1197 break; 1198 } 1199 case MCS_UNBIND: { 1200 // If there is no actual work left, then time to unbind. 1201 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1202 1203 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1204 if (mBound) { 1205 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1206 1207 disconnectService(); 1208 } 1209 } else if (mPendingInstalls.size() > 0) { 1210 // There are more pending requests in queue. 1211 // Just post MCS_BOUND message to trigger processing 1212 // of next pending install. 1213 mHandler.sendEmptyMessage(MCS_BOUND); 1214 } 1215 1216 break; 1217 } 1218 case MCS_GIVE_UP: { 1219 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1220 mPendingInstalls.remove(0); 1221 break; 1222 } 1223 case SEND_PENDING_BROADCAST: { 1224 String packages[]; 1225 ArrayList<String> components[]; 1226 int size = 0; 1227 int uids[]; 1228 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1229 synchronized (mPackages) { 1230 if (mPendingBroadcasts == null) { 1231 return; 1232 } 1233 size = mPendingBroadcasts.size(); 1234 if (size <= 0) { 1235 // Nothing to be done. Just return 1236 return; 1237 } 1238 packages = new String[size]; 1239 components = new ArrayList[size]; 1240 uids = new int[size]; 1241 int i = 0; // filling out the above arrays 1242 1243 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1244 int packageUserId = mPendingBroadcasts.userIdAt(n); 1245 Iterator<Map.Entry<String, ArrayList<String>>> it 1246 = mPendingBroadcasts.packagesForUserId(packageUserId) 1247 .entrySet().iterator(); 1248 while (it.hasNext() && i < size) { 1249 Map.Entry<String, ArrayList<String>> ent = it.next(); 1250 packages[i] = ent.getKey(); 1251 components[i] = ent.getValue(); 1252 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1253 uids[i] = (ps != null) 1254 ? UserHandle.getUid(packageUserId, ps.appId) 1255 : -1; 1256 i++; 1257 } 1258 } 1259 size = i; 1260 mPendingBroadcasts.clear(); 1261 } 1262 // Send broadcasts 1263 for (int i = 0; i < size; i++) { 1264 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1265 } 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1267 break; 1268 } 1269 case START_CLEANING_PACKAGE: { 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 final String packageName = (String)msg.obj; 1272 final int userId = msg.arg1; 1273 final boolean andCode = msg.arg2 != 0; 1274 synchronized (mPackages) { 1275 if (userId == UserHandle.USER_ALL) { 1276 int[] users = sUserManager.getUserIds(); 1277 for (int user : users) { 1278 mSettings.addPackageToCleanLPw( 1279 new PackageCleanItem(user, packageName, andCode)); 1280 } 1281 } else { 1282 mSettings.addPackageToCleanLPw( 1283 new PackageCleanItem(userId, packageName, andCode)); 1284 } 1285 } 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1287 startCleaningPackages(); 1288 } break; 1289 case POST_INSTALL: { 1290 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1291 PostInstallData data = mRunningInstalls.get(msg.arg1); 1292 mRunningInstalls.delete(msg.arg1); 1293 boolean deleteOld = false; 1294 1295 if (data != null) { 1296 InstallArgs args = data.args; 1297 PackageInstalledInfo res = data.res; 1298 1299 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1300 res.removedInfo.sendBroadcast(false, true, false); 1301 Bundle extras = new Bundle(1); 1302 extras.putInt(Intent.EXTRA_UID, res.uid); 1303 1304 // Now that we successfully installed the package, grant runtime 1305 // permissions if requested before broadcasting the install. 1306 if ((args.installFlags 1307 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1308 grantRequestedRuntimePermissions(res.pkg, 1309 args.user.getIdentifier()); 1310 } 1311 1312 // Determine the set of users who are adding this 1313 // package for the first time vs. those who are seeing 1314 // an update. 1315 int[] firstUsers; 1316 int[] updateUsers = new int[0]; 1317 if (res.origUsers == null || res.origUsers.length == 0) { 1318 firstUsers = res.newUsers; 1319 } else { 1320 firstUsers = new int[0]; 1321 for (int i=0; i<res.newUsers.length; i++) { 1322 int user = res.newUsers[i]; 1323 boolean isNew = true; 1324 for (int j=0; j<res.origUsers.length; j++) { 1325 if (res.origUsers[j] == user) { 1326 isNew = false; 1327 break; 1328 } 1329 } 1330 if (isNew) { 1331 int[] newFirst = new int[firstUsers.length+1]; 1332 System.arraycopy(firstUsers, 0, newFirst, 0, 1333 firstUsers.length); 1334 newFirst[firstUsers.length] = user; 1335 firstUsers = newFirst; 1336 } else { 1337 int[] newUpdate = new int[updateUsers.length+1]; 1338 System.arraycopy(updateUsers, 0, newUpdate, 0, 1339 updateUsers.length); 1340 newUpdate[updateUsers.length] = user; 1341 updateUsers = newUpdate; 1342 } 1343 } 1344 } 1345 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1346 res.pkg.applicationInfo.packageName, 1347 extras, null, null, firstUsers); 1348 final boolean update = res.removedInfo.removedPackage != null; 1349 if (update) { 1350 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1351 } 1352 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1353 res.pkg.applicationInfo.packageName, 1354 extras, null, null, updateUsers); 1355 if (update) { 1356 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1357 res.pkg.applicationInfo.packageName, 1358 extras, null, null, updateUsers); 1359 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1360 null, null, 1361 res.pkg.applicationInfo.packageName, null, updateUsers); 1362 1363 // treat asec-hosted packages like removable media on upgrade 1364 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1365 if (DEBUG_INSTALL) { 1366 Slog.i(TAG, "upgrading pkg " + res.pkg 1367 + " is ASEC-hosted -> AVAILABLE"); 1368 } 1369 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1370 ArrayList<String> pkgList = new ArrayList<String>(1); 1371 pkgList.add(res.pkg.applicationInfo.packageName); 1372 sendResourcesChangedBroadcast(true, true, 1373 pkgList,uidArray, null); 1374 } 1375 } 1376 if (res.removedInfo.args != null) { 1377 // Remove the replaced package's older resources safely now 1378 deleteOld = true; 1379 } 1380 1381 // Log current value of "unknown sources" setting 1382 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1383 getUnknownSourcesSettings()); 1384 } 1385 // Force a gc to clear up things 1386 Runtime.getRuntime().gc(); 1387 // We delete after a gc for applications on sdcard. 1388 if (deleteOld) { 1389 synchronized (mInstallLock) { 1390 res.removedInfo.args.doPostDeleteLI(true); 1391 } 1392 } 1393 if (args.observer != null) { 1394 try { 1395 Bundle extras = extrasForInstallResult(res); 1396 args.observer.onPackageInstalled(res.name, res.returnCode, 1397 res.returnMsg, extras); 1398 } catch (RemoteException e) { 1399 Slog.i(TAG, "Observer no longer exists."); 1400 } 1401 } 1402 } else { 1403 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1404 } 1405 } break; 1406 case UPDATED_MEDIA_STATUS: { 1407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1408 boolean reportStatus = msg.arg1 == 1; 1409 boolean doGc = msg.arg2 == 1; 1410 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1411 if (doGc) { 1412 // Force a gc to clear up stale containers. 1413 Runtime.getRuntime().gc(); 1414 } 1415 if (msg.obj != null) { 1416 @SuppressWarnings("unchecked") 1417 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1418 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1419 // Unload containers 1420 unloadAllContainers(args); 1421 } 1422 if (reportStatus) { 1423 try { 1424 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1425 PackageHelper.getMountService().finishMediaUpdate(); 1426 } catch (RemoteException e) { 1427 Log.e(TAG, "MountService not running?"); 1428 } 1429 } 1430 } break; 1431 case WRITE_SETTINGS: { 1432 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1433 synchronized (mPackages) { 1434 removeMessages(WRITE_SETTINGS); 1435 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1436 mSettings.writeLPr(); 1437 mDirtyUsers.clear(); 1438 } 1439 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1440 } break; 1441 case WRITE_PACKAGE_RESTRICTIONS: { 1442 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1443 synchronized (mPackages) { 1444 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1445 for (int userId : mDirtyUsers) { 1446 mSettings.writePackageRestrictionsLPr(userId); 1447 } 1448 mDirtyUsers.clear(); 1449 } 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1451 } break; 1452 case CHECK_PENDING_VERIFICATION: { 1453 final int verificationId = msg.arg1; 1454 final PackageVerificationState state = mPendingVerification.get(verificationId); 1455 1456 if ((state != null) && !state.timeoutExtended()) { 1457 final InstallArgs args = state.getInstallArgs(); 1458 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1459 1460 Slog.i(TAG, "Verification timed out for " + originUri); 1461 mPendingVerification.remove(verificationId); 1462 1463 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1464 1465 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1466 Slog.i(TAG, "Continuing with installation of " + originUri); 1467 state.setVerifierResponse(Binder.getCallingUid(), 1468 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1469 broadcastPackageVerified(verificationId, originUri, 1470 PackageManager.VERIFICATION_ALLOW, 1471 state.getInstallArgs().getUser()); 1472 try { 1473 ret = args.copyApk(mContainerService, true); 1474 } catch (RemoteException e) { 1475 Slog.e(TAG, "Could not contact the ContainerService"); 1476 } 1477 } else { 1478 broadcastPackageVerified(verificationId, originUri, 1479 PackageManager.VERIFICATION_REJECT, 1480 state.getInstallArgs().getUser()); 1481 } 1482 1483 processPendingInstall(args, ret); 1484 mHandler.sendEmptyMessage(MCS_UNBIND); 1485 } 1486 break; 1487 } 1488 case PACKAGE_VERIFIED: { 1489 final int verificationId = msg.arg1; 1490 1491 final PackageVerificationState state = mPendingVerification.get(verificationId); 1492 if (state == null) { 1493 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1494 break; 1495 } 1496 1497 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1498 1499 state.setVerifierResponse(response.callerUid, response.code); 1500 1501 if (state.isVerificationComplete()) { 1502 mPendingVerification.remove(verificationId); 1503 1504 final InstallArgs args = state.getInstallArgs(); 1505 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1506 1507 int ret; 1508 if (state.isInstallAllowed()) { 1509 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1510 broadcastPackageVerified(verificationId, originUri, 1511 response.code, state.getInstallArgs().getUser()); 1512 try { 1513 ret = args.copyApk(mContainerService, true); 1514 } catch (RemoteException e) { 1515 Slog.e(TAG, "Could not contact the ContainerService"); 1516 } 1517 } else { 1518 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1519 } 1520 1521 processPendingInstall(args, ret); 1522 1523 mHandler.sendEmptyMessage(MCS_UNBIND); 1524 } 1525 1526 break; 1527 } 1528 case START_INTENT_FILTER_VERIFICATIONS: { 1529 IFVerificationParams params = (IFVerificationParams) msg.obj; 1530 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1531 params.replacing, params.pkg); 1532 break; 1533 } 1534 case INTENT_FILTER_VERIFIED: { 1535 final int verificationId = msg.arg1; 1536 1537 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1538 verificationId); 1539 if (state == null) { 1540 Slog.w(TAG, "Invalid IntentFilter verification token " 1541 + verificationId + " received"); 1542 break; 1543 } 1544 1545 final int userId = state.getUserId(); 1546 1547 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1548 "Processing IntentFilter verification with token:" 1549 + verificationId + " and userId:" + userId); 1550 1551 final IntentFilterVerificationResponse response = 1552 (IntentFilterVerificationResponse) msg.obj; 1553 1554 state.setVerifierResponse(response.callerUid, response.code); 1555 1556 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1557 "IntentFilter verification with token:" + verificationId 1558 + " and userId:" + userId 1559 + " is settings verifier response with response code:" 1560 + response.code); 1561 1562 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1563 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1564 + response.getFailedDomainsString()); 1565 } 1566 1567 if (state.isVerificationComplete()) { 1568 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1569 } else { 1570 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1571 "IntentFilter verification with token:" + verificationId 1572 + " was not said to be complete"); 1573 } 1574 1575 break; 1576 } 1577 } 1578 } 1579 } 1580 1581 private StorageEventListener mStorageListener = new StorageEventListener() { 1582 @Override 1583 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1584 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1585 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1586 // TODO: ensure that private directories exist for all active users 1587 // TODO: remove user data whose serial number doesn't match 1588 loadPrivatePackages(vol); 1589 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1590 unloadPrivatePackages(vol); 1591 } 1592 } 1593 1594 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1595 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1596 updateExternalMediaStatus(true, false); 1597 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1598 updateExternalMediaStatus(false, false); 1599 } 1600 } 1601 } 1602 1603 @Override 1604 public void onVolumeForgotten(String fsUuid) { 1605 // TODO: remove all packages hosted on this uuid 1606 } 1607 }; 1608 1609 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1610 if (userId >= UserHandle.USER_OWNER) { 1611 grantRequestedRuntimePermissionsForUser(pkg, userId); 1612 } else if (userId == UserHandle.USER_ALL) { 1613 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1614 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1615 } 1616 } 1617 1618 // We could have touched GID membership, so flush out packages.list 1619 synchronized (mPackages) { 1620 mSettings.writePackageListLPr(); 1621 } 1622 } 1623 1624 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1625 SettingBase sb = (SettingBase) pkg.mExtras; 1626 if (sb == null) { 1627 return; 1628 } 1629 1630 PermissionsState permissionsState = sb.getPermissionsState(); 1631 1632 for (String permission : pkg.requestedPermissions) { 1633 BasePermission bp = mSettings.mPermissions.get(permission); 1634 if (bp != null && bp.isRuntime()) { 1635 permissionsState.grantRuntimePermission(bp, userId); 1636 } 1637 } 1638 } 1639 1640 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1641 Bundle extras = null; 1642 switch (res.returnCode) { 1643 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1644 extras = new Bundle(); 1645 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1646 res.origPermission); 1647 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1648 res.origPackage); 1649 break; 1650 } 1651 case PackageManager.INSTALL_SUCCEEDED: { 1652 extras = new Bundle(); 1653 extras.putBoolean(Intent.EXTRA_REPLACING, 1654 res.removedInfo != null && res.removedInfo.removedPackage != null); 1655 break; 1656 } 1657 } 1658 return extras; 1659 } 1660 1661 void scheduleWriteSettingsLocked() { 1662 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1663 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1664 } 1665 } 1666 1667 void scheduleWritePackageRestrictionsLocked(int userId) { 1668 if (!sUserManager.exists(userId)) return; 1669 mDirtyUsers.add(userId); 1670 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1671 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1672 } 1673 } 1674 1675 public static PackageManagerService main(Context context, Installer installer, 1676 boolean factoryTest, boolean onlyCore) { 1677 PackageManagerService m = new PackageManagerService(context, installer, 1678 factoryTest, onlyCore); 1679 ServiceManager.addService("package", m); 1680 return m; 1681 } 1682 1683 static String[] splitString(String str, char sep) { 1684 int count = 1; 1685 int i = 0; 1686 while ((i=str.indexOf(sep, i)) >= 0) { 1687 count++; 1688 i++; 1689 } 1690 1691 String[] res = new String[count]; 1692 i=0; 1693 count = 0; 1694 int lastI=0; 1695 while ((i=str.indexOf(sep, i)) >= 0) { 1696 res[count] = str.substring(lastI, i); 1697 count++; 1698 i++; 1699 lastI = i; 1700 } 1701 res[count] = str.substring(lastI, str.length()); 1702 return res; 1703 } 1704 1705 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1706 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1707 Context.DISPLAY_SERVICE); 1708 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1709 } 1710 1711 public PackageManagerService(Context context, Installer installer, 1712 boolean factoryTest, boolean onlyCore) { 1713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1714 SystemClock.uptimeMillis()); 1715 1716 if (mSdkVersion <= 0) { 1717 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1718 } 1719 1720 mContext = context; 1721 mFactoryTest = factoryTest; 1722 mOnlyCore = onlyCore; 1723 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1724 mMetrics = new DisplayMetrics(); 1725 mSettings = new Settings(mPackages); 1726 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1727 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1728 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1729 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1730 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1731 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1732 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1733 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1734 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1735 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1736 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1737 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1738 1739 // TODO: add a property to control this? 1740 long dexOptLRUThresholdInMinutes; 1741 if (mLazyDexOpt) { 1742 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1743 } else { 1744 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1745 } 1746 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1747 1748 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1749 if (separateProcesses != null && separateProcesses.length() > 0) { 1750 if ("*".equals(separateProcesses)) { 1751 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1752 mSeparateProcesses = null; 1753 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1754 } else { 1755 mDefParseFlags = 0; 1756 mSeparateProcesses = separateProcesses.split(","); 1757 Slog.w(TAG, "Running with debug.separate_processes: " 1758 + separateProcesses); 1759 } 1760 } else { 1761 mDefParseFlags = 0; 1762 mSeparateProcesses = null; 1763 } 1764 1765 mInstaller = installer; 1766 mPackageDexOptimizer = new PackageDexOptimizer(this); 1767 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1768 1769 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1770 FgThread.get().getLooper()); 1771 1772 getDefaultDisplayMetrics(context, mMetrics); 1773 1774 SystemConfig systemConfig = SystemConfig.getInstance(); 1775 mGlobalGids = systemConfig.getGlobalGids(); 1776 mSystemPermissions = systemConfig.getSystemPermissions(); 1777 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1778 1779 synchronized (mInstallLock) { 1780 // writer 1781 synchronized (mPackages) { 1782 mHandlerThread = new ServiceThread(TAG, 1783 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1784 mHandlerThread.start(); 1785 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1786 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1787 1788 File dataDir = Environment.getDataDirectory(); 1789 mAppDataDir = new File(dataDir, "data"); 1790 mAppInstallDir = new File(dataDir, "app"); 1791 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1792 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1793 mUserAppDataDir = new File(dataDir, "user"); 1794 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1795 1796 sUserManager = new UserManagerService(context, this, 1797 mInstallLock, mPackages); 1798 1799 // Propagate permission configuration in to package manager. 1800 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1801 = systemConfig.getPermissions(); 1802 for (int i=0; i<permConfig.size(); i++) { 1803 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1804 BasePermission bp = mSettings.mPermissions.get(perm.name); 1805 if (bp == null) { 1806 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1807 mSettings.mPermissions.put(perm.name, bp); 1808 } 1809 if (perm.gids != null) { 1810 bp.setGids(perm.gids, perm.perUser); 1811 } 1812 } 1813 1814 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1815 for (int i=0; i<libConfig.size(); i++) { 1816 mSharedLibraries.put(libConfig.keyAt(i), 1817 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1818 } 1819 1820 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1821 1822 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1823 mSdkVersion, mOnlyCore); 1824 1825 String customResolverActivity = Resources.getSystem().getString( 1826 R.string.config_customResolverActivity); 1827 if (TextUtils.isEmpty(customResolverActivity)) { 1828 customResolverActivity = null; 1829 } else { 1830 mCustomResolverComponentName = ComponentName.unflattenFromString( 1831 customResolverActivity); 1832 } 1833 1834 long startTime = SystemClock.uptimeMillis(); 1835 1836 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1837 startTime); 1838 1839 // Set flag to monitor and not change apk file paths when 1840 // scanning install directories. 1841 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1842 1843 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1844 1845 /** 1846 * Add everything in the in the boot class path to the 1847 * list of process files because dexopt will have been run 1848 * if necessary during zygote startup. 1849 */ 1850 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1851 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1852 1853 if (bootClassPath != null) { 1854 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1855 for (String element : bootClassPathElements) { 1856 alreadyDexOpted.add(element); 1857 } 1858 } else { 1859 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1860 } 1861 1862 if (systemServerClassPath != null) { 1863 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1864 for (String element : systemServerClassPathElements) { 1865 alreadyDexOpted.add(element); 1866 } 1867 } else { 1868 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1869 } 1870 1871 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1872 final String[] dexCodeInstructionSets = 1873 getDexCodeInstructionSets( 1874 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1875 1876 /** 1877 * Ensure all external libraries have had dexopt run on them. 1878 */ 1879 if (mSharedLibraries.size() > 0) { 1880 // NOTE: For now, we're compiling these system "shared libraries" 1881 // (and framework jars) into all available architectures. It's possible 1882 // to compile them only when we come across an app that uses them (there's 1883 // already logic for that in scanPackageLI) but that adds some complexity. 1884 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1885 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1886 final String lib = libEntry.path; 1887 if (lib == null) { 1888 continue; 1889 } 1890 1891 try { 1892 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1893 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1894 alreadyDexOpted.add(lib); 1895 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1896 } 1897 } catch (FileNotFoundException e) { 1898 Slog.w(TAG, "Library not found: " + lib); 1899 } catch (IOException e) { 1900 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1901 + e.getMessage()); 1902 } 1903 } 1904 } 1905 } 1906 1907 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1908 1909 // Gross hack for now: we know this file doesn't contain any 1910 // code, so don't dexopt it to avoid the resulting log spew. 1911 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1912 1913 // Gross hack for now: we know this file is only part of 1914 // the boot class path for art, so don't dexopt it to 1915 // avoid the resulting log spew. 1916 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1917 1918 /** 1919 * There are a number of commands implemented in Java, which 1920 * we currently need to do the dexopt on so that they can be 1921 * run from a non-root shell. 1922 */ 1923 String[] frameworkFiles = frameworkDir.list(); 1924 if (frameworkFiles != null) { 1925 // TODO: We could compile these only for the most preferred ABI. We should 1926 // first double check that the dex files for these commands are not referenced 1927 // by other system apps. 1928 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1929 for (int i=0; i<frameworkFiles.length; i++) { 1930 File libPath = new File(frameworkDir, frameworkFiles[i]); 1931 String path = libPath.getPath(); 1932 // Skip the file if we already did it. 1933 if (alreadyDexOpted.contains(path)) { 1934 continue; 1935 } 1936 // Skip the file if it is not a type we want to dexopt. 1937 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1938 continue; 1939 } 1940 try { 1941 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1942 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1943 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1944 } 1945 } catch (FileNotFoundException e) { 1946 Slog.w(TAG, "Jar not found: " + path); 1947 } catch (IOException e) { 1948 Slog.w(TAG, "Exception reading jar: " + path, e); 1949 } 1950 } 1951 } 1952 } 1953 1954 // Collect vendor overlay packages. 1955 // (Do this before scanning any apps.) 1956 // For security and version matching reason, only consider 1957 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1958 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1959 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1960 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1961 1962 // Find base frameworks (resource packages without code). 1963 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1964 | PackageParser.PARSE_IS_SYSTEM_DIR 1965 | PackageParser.PARSE_IS_PRIVILEGED, 1966 scanFlags | SCAN_NO_DEX, 0); 1967 1968 // Collected privileged system packages. 1969 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1970 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1971 | PackageParser.PARSE_IS_SYSTEM_DIR 1972 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1973 1974 // Collect ordinary system packages. 1975 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1976 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1977 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1978 1979 // Collect all vendor packages. 1980 File vendorAppDir = new File("/vendor/app"); 1981 try { 1982 vendorAppDir = vendorAppDir.getCanonicalFile(); 1983 } catch (IOException e) { 1984 // failed to look up canonical path, continue with original one 1985 } 1986 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1987 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1988 1989 // Collect all OEM packages. 1990 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1991 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1992 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1993 1994 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1995 mInstaller.moveFiles(); 1996 1997 // Prune any system packages that no longer exist. 1998 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1999 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2000 if (!mOnlyCore) { 2001 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2002 while (psit.hasNext()) { 2003 PackageSetting ps = psit.next(); 2004 2005 /* 2006 * If this is not a system app, it can't be a 2007 * disable system app. 2008 */ 2009 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2010 continue; 2011 } 2012 2013 /* 2014 * If the package is scanned, it's not erased. 2015 */ 2016 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2017 if (scannedPkg != null) { 2018 /* 2019 * If the system app is both scanned and in the 2020 * disabled packages list, then it must have been 2021 * added via OTA. Remove it from the currently 2022 * scanned package so the previously user-installed 2023 * application can be scanned. 2024 */ 2025 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2026 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2027 + ps.name + "; removing system app. Last known codePath=" 2028 + ps.codePathString + ", installStatus=" + ps.installStatus 2029 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2030 + scannedPkg.mVersionCode); 2031 removePackageLI(ps, true); 2032 expectingBetter.put(ps.name, ps.codePath); 2033 } 2034 2035 continue; 2036 } 2037 2038 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2039 psit.remove(); 2040 logCriticalInfo(Log.WARN, "System package " + ps.name 2041 + " no longer exists; wiping its data"); 2042 removeDataDirsLI(null, ps.name); 2043 } else { 2044 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2045 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2046 possiblyDeletedUpdatedSystemApps.add(ps.name); 2047 } 2048 } 2049 } 2050 } 2051 2052 //look for any incomplete package installations 2053 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2054 //clean up list 2055 for(int i = 0; i < deletePkgsList.size(); i++) { 2056 //clean up here 2057 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2058 } 2059 //delete tmp files 2060 deleteTempPackageFiles(); 2061 2062 // Remove any shared userIDs that have no associated packages 2063 mSettings.pruneSharedUsersLPw(); 2064 2065 if (!mOnlyCore) { 2066 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2067 SystemClock.uptimeMillis()); 2068 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2069 2070 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2071 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2072 2073 /** 2074 * Remove disable package settings for any updated system 2075 * apps that were removed via an OTA. If they're not a 2076 * previously-updated app, remove them completely. 2077 * Otherwise, just revoke their system-level permissions. 2078 */ 2079 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2080 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2081 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2082 2083 String msg; 2084 if (deletedPkg == null) { 2085 msg = "Updated system package " + deletedAppName 2086 + " no longer exists; wiping its data"; 2087 removeDataDirsLI(null, deletedAppName); 2088 } else { 2089 msg = "Updated system app + " + deletedAppName 2090 + " no longer present; removing system privileges for " 2091 + deletedAppName; 2092 2093 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2094 2095 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2096 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2097 } 2098 logCriticalInfo(Log.WARN, msg); 2099 } 2100 2101 /** 2102 * Make sure all system apps that we expected to appear on 2103 * the userdata partition actually showed up. If they never 2104 * appeared, crawl back and revive the system version. 2105 */ 2106 for (int i = 0; i < expectingBetter.size(); i++) { 2107 final String packageName = expectingBetter.keyAt(i); 2108 if (!mPackages.containsKey(packageName)) { 2109 final File scanFile = expectingBetter.valueAt(i); 2110 2111 logCriticalInfo(Log.WARN, "Expected better " + packageName 2112 + " but never showed up; reverting to system"); 2113 2114 final int reparseFlags; 2115 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2116 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2117 | PackageParser.PARSE_IS_SYSTEM_DIR 2118 | PackageParser.PARSE_IS_PRIVILEGED; 2119 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2120 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR; 2122 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2123 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2124 | PackageParser.PARSE_IS_SYSTEM_DIR; 2125 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2126 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR; 2128 } else { 2129 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2130 continue; 2131 } 2132 2133 mSettings.enableSystemPackageLPw(packageName); 2134 2135 try { 2136 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2137 } catch (PackageManagerException e) { 2138 Slog.e(TAG, "Failed to parse original system package: " 2139 + e.getMessage()); 2140 } 2141 } 2142 } 2143 } 2144 2145 // Now that we know all of the shared libraries, update all clients to have 2146 // the correct library paths. 2147 updateAllSharedLibrariesLPw(); 2148 2149 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2150 // NOTE: We ignore potential failures here during a system scan (like 2151 // the rest of the commands above) because there's precious little we 2152 // can do about it. A settings error is reported, though. 2153 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2154 false /* force dexopt */, false /* defer dexopt */); 2155 } 2156 2157 // Now that we know all the packages we are keeping, 2158 // read and update their last usage times. 2159 mPackageUsage.readLP(); 2160 2161 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2162 SystemClock.uptimeMillis()); 2163 Slog.i(TAG, "Time to scan packages: " 2164 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2165 + " seconds"); 2166 2167 // If the platform SDK has changed since the last time we booted, 2168 // we need to re-grant app permission to catch any new ones that 2169 // appear. This is really a hack, and means that apps can in some 2170 // cases get permissions that the user didn't initially explicitly 2171 // allow... it would be nice to have some better way to handle 2172 // this situation. 2173 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2174 != mSdkVersion; 2175 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2176 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2177 + "; regranting permissions for internal storage"); 2178 mSettings.mInternalSdkPlatform = mSdkVersion; 2179 2180 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2181 | (regrantPermissions 2182 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2183 : 0)); 2184 2185 // If this is the first boot, and it is a normal boot, then 2186 // we need to initialize the default preferred apps. 2187 if (!mRestoredSettings && !onlyCore) { 2188 mSettings.readDefaultPreferredAppsLPw(this, 0); 2189 } 2190 2191 // If this is first boot after an OTA, and a normal boot, then 2192 // we need to clear code cache directories. 2193 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2194 if (mIsUpgrade && !onlyCore) { 2195 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2196 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2197 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2198 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2199 } 2200 mSettings.mFingerprint = Build.FINGERPRINT; 2201 } 2202 2203 primeDomainVerificationsLPw(); 2204 checkDefaultBrowser(); 2205 2206 // All the changes are done during package scanning. 2207 mSettings.updateInternalDatabaseVersion(); 2208 2209 // can downgrade to reader 2210 mSettings.writeLPr(); 2211 2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2213 SystemClock.uptimeMillis()); 2214 2215 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2216 2217 mInstallerService = new PackageInstallerService(context, this); 2218 2219 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2220 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2221 mIntentFilterVerifierComponent); 2222 2223 } // synchronized (mPackages) 2224 } // synchronized (mInstallLock) 2225 2226 // Now after opening every single application zip, make sure they 2227 // are all flushed. Not really needed, but keeps things nice and 2228 // tidy. 2229 Runtime.getRuntime().gc(); 2230 2231 // Expose private service for system components to use. 2232 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2233 } 2234 2235 @Override 2236 public boolean isFirstBoot() { 2237 return !mRestoredSettings; 2238 } 2239 2240 @Override 2241 public boolean isOnlyCoreApps() { 2242 return mOnlyCore; 2243 } 2244 2245 @Override 2246 public boolean isUpgrade() { 2247 return mIsUpgrade; 2248 } 2249 2250 private String getRequiredVerifierLPr() { 2251 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2252 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2253 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2254 2255 String requiredVerifier = null; 2256 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 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2268 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2269 continue; 2270 } 2271 2272 if (requiredVerifier != null) { 2273 throw new RuntimeException("There can be only one required verifier"); 2274 } 2275 2276 requiredVerifier = packageName; 2277 } 2278 2279 return requiredVerifier; 2280 } 2281 2282 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2283 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2284 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2285 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2286 2287 ComponentName verifierComponentName = null; 2288 2289 int priority = -1000; 2290 final int N = receivers.size(); 2291 for (int i = 0; i < N; i++) { 2292 final ResolveInfo info = receivers.get(i); 2293 2294 if (info.activityInfo == null) { 2295 continue; 2296 } 2297 2298 final String packageName = info.activityInfo.packageName; 2299 2300 final PackageSetting ps = mSettings.mPackages.get(packageName); 2301 if (ps == null) { 2302 continue; 2303 } 2304 2305 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2306 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2307 continue; 2308 } 2309 2310 // Select the IntentFilterVerifier with the highest priority 2311 if (priority < info.priority) { 2312 priority = info.priority; 2313 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2314 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2315 + verifierComponentName + " with priority: " + info.priority); 2316 } 2317 } 2318 2319 return verifierComponentName; 2320 } 2321 2322 private void primeDomainVerificationsLPw() { 2323 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2324 boolean updated = false; 2325 ArraySet<String> allHostsSet = new ArraySet<>(); 2326 for (PackageParser.Package pkg : mPackages.values()) { 2327 final String packageName = pkg.packageName; 2328 if (!hasDomainURLs(pkg)) { 2329 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2330 "package with no domain URLs: " + packageName); 2331 continue; 2332 } 2333 if (!pkg.isSystemApp()) { 2334 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2335 "No priming domain verifications for a non system package : " + 2336 packageName); 2337 continue; 2338 } 2339 for (PackageParser.Activity a : pkg.activities) { 2340 for (ActivityIntentInfo filter : a.intents) { 2341 if (hasValidDomains(filter)) { 2342 allHostsSet.addAll(filter.getHostsList()); 2343 } 2344 } 2345 } 2346 if (allHostsSet.size() == 0) { 2347 allHostsSet.add("*"); 2348 } 2349 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2350 IntentFilterVerificationInfo ivi = 2351 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2352 if (ivi != null) { 2353 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2354 "Priming domain verifications for package: " + packageName + 2355 " with hosts:" + ivi.getDomainsString()); 2356 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2357 updated = true; 2358 } 2359 else { 2360 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2361 "No priming domain verifications for package: " + packageName); 2362 } 2363 allHostsSet.clear(); 2364 } 2365 if (updated) { 2366 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2367 "Will need to write primed domain verifications"); 2368 } 2369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2370 } 2371 2372 private void checkDefaultBrowser() { 2373 final int myUserId = UserHandle.myUserId(); 2374 final String packageName = getDefaultBrowserPackageName(myUserId); 2375 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2376 if (info == null) { 2377 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2378 setDefaultBrowserPackageName(null, myUserId); 2379 } 2380 } 2381 2382 @Override 2383 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2384 throws RemoteException { 2385 try { 2386 return super.onTransact(code, data, reply, flags); 2387 } catch (RuntimeException e) { 2388 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2389 Slog.wtf(TAG, "Package Manager Crash", e); 2390 } 2391 throw e; 2392 } 2393 } 2394 2395 void cleanupInstallFailedPackage(PackageSetting ps) { 2396 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2397 2398 removeDataDirsLI(ps.volumeUuid, ps.name); 2399 if (ps.codePath != null) { 2400 if (ps.codePath.isDirectory()) { 2401 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2402 } else { 2403 ps.codePath.delete(); 2404 } 2405 } 2406 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2407 if (ps.resourcePath.isDirectory()) { 2408 FileUtils.deleteContents(ps.resourcePath); 2409 } 2410 ps.resourcePath.delete(); 2411 } 2412 mSettings.removePackageLPw(ps.name); 2413 } 2414 2415 static int[] appendInts(int[] cur, int[] add) { 2416 if (add == null) return cur; 2417 if (cur == null) return add; 2418 final int N = add.length; 2419 for (int i=0; i<N; i++) { 2420 cur = appendInt(cur, add[i]); 2421 } 2422 return cur; 2423 } 2424 2425 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2426 if (!sUserManager.exists(userId)) return null; 2427 final PackageSetting ps = (PackageSetting) p.mExtras; 2428 if (ps == null) { 2429 return null; 2430 } 2431 2432 final PermissionsState permissionsState = ps.getPermissionsState(); 2433 2434 final int[] gids = permissionsState.computeGids(userId); 2435 final Set<String> permissions = permissionsState.getPermissions(userId); 2436 final PackageUserState state = ps.readUserState(userId); 2437 2438 return PackageParser.generatePackageInfo(p, gids, flags, 2439 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2440 } 2441 2442 @Override 2443 public boolean isPackageFrozen(String packageName) { 2444 synchronized (mPackages) { 2445 final PackageSetting ps = mSettings.mPackages.get(packageName); 2446 if (ps != null) { 2447 return ps.frozen; 2448 } 2449 } 2450 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2451 return true; 2452 } 2453 2454 @Override 2455 public boolean isPackageAvailable(String packageName, int userId) { 2456 if (!sUserManager.exists(userId)) return false; 2457 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2458 synchronized (mPackages) { 2459 PackageParser.Package p = mPackages.get(packageName); 2460 if (p != null) { 2461 final PackageSetting ps = (PackageSetting) p.mExtras; 2462 if (ps != null) { 2463 final PackageUserState state = ps.readUserState(userId); 2464 if (state != null) { 2465 return PackageParser.isAvailable(state); 2466 } 2467 } 2468 } 2469 } 2470 return false; 2471 } 2472 2473 @Override 2474 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2475 if (!sUserManager.exists(userId)) return null; 2476 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2477 // reader 2478 synchronized (mPackages) { 2479 PackageParser.Package p = mPackages.get(packageName); 2480 if (DEBUG_PACKAGE_INFO) 2481 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2482 if (p != null) { 2483 return generatePackageInfo(p, flags, userId); 2484 } 2485 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2486 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2487 } 2488 } 2489 return null; 2490 } 2491 2492 @Override 2493 public String[] currentToCanonicalPackageNames(String[] names) { 2494 String[] out = new String[names.length]; 2495 // reader 2496 synchronized (mPackages) { 2497 for (int i=names.length-1; i>=0; i--) { 2498 PackageSetting ps = mSettings.mPackages.get(names[i]); 2499 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2500 } 2501 } 2502 return out; 2503 } 2504 2505 @Override 2506 public String[] canonicalToCurrentPackageNames(String[] names) { 2507 String[] out = new String[names.length]; 2508 // reader 2509 synchronized (mPackages) { 2510 for (int i=names.length-1; i>=0; i--) { 2511 String cur = mSettings.mRenamedPackages.get(names[i]); 2512 out[i] = cur != null ? cur : names[i]; 2513 } 2514 } 2515 return out; 2516 } 2517 2518 @Override 2519 public int getPackageUid(String packageName, int userId) { 2520 if (!sUserManager.exists(userId)) return -1; 2521 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2522 2523 // reader 2524 synchronized (mPackages) { 2525 PackageParser.Package p = mPackages.get(packageName); 2526 if(p != null) { 2527 return UserHandle.getUid(userId, p.applicationInfo.uid); 2528 } 2529 PackageSetting ps = mSettings.mPackages.get(packageName); 2530 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2531 return -1; 2532 } 2533 p = ps.pkg; 2534 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2535 } 2536 } 2537 2538 @Override 2539 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2540 if (!sUserManager.exists(userId)) { 2541 return null; 2542 } 2543 2544 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2545 "getPackageGids"); 2546 2547 // reader 2548 synchronized (mPackages) { 2549 PackageParser.Package p = mPackages.get(packageName); 2550 if (DEBUG_PACKAGE_INFO) { 2551 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2552 } 2553 if (p != null) { 2554 PackageSetting ps = (PackageSetting) p.mExtras; 2555 return ps.getPermissionsState().computeGids(userId); 2556 } 2557 } 2558 2559 return null; 2560 } 2561 2562 static PermissionInfo generatePermissionInfo( 2563 BasePermission bp, int flags) { 2564 if (bp.perm != null) { 2565 return PackageParser.generatePermissionInfo(bp.perm, flags); 2566 } 2567 PermissionInfo pi = new PermissionInfo(); 2568 pi.name = bp.name; 2569 pi.packageName = bp.sourcePackage; 2570 pi.nonLocalizedLabel = bp.name; 2571 pi.protectionLevel = bp.protectionLevel; 2572 return pi; 2573 } 2574 2575 @Override 2576 public PermissionInfo getPermissionInfo(String name, int flags) { 2577 // reader 2578 synchronized (mPackages) { 2579 final BasePermission p = mSettings.mPermissions.get(name); 2580 if (p != null) { 2581 return generatePermissionInfo(p, flags); 2582 } 2583 return null; 2584 } 2585 } 2586 2587 @Override 2588 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2589 // reader 2590 synchronized (mPackages) { 2591 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2592 for (BasePermission p : mSettings.mPermissions.values()) { 2593 if (group == null) { 2594 if (p.perm == null || p.perm.info.group == null) { 2595 out.add(generatePermissionInfo(p, flags)); 2596 } 2597 } else { 2598 if (p.perm != null && group.equals(p.perm.info.group)) { 2599 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2600 } 2601 } 2602 } 2603 2604 if (out.size() > 0) { 2605 return out; 2606 } 2607 return mPermissionGroups.containsKey(group) ? out : null; 2608 } 2609 } 2610 2611 @Override 2612 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2613 // reader 2614 synchronized (mPackages) { 2615 return PackageParser.generatePermissionGroupInfo( 2616 mPermissionGroups.get(name), flags); 2617 } 2618 } 2619 2620 @Override 2621 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2622 // reader 2623 synchronized (mPackages) { 2624 final int N = mPermissionGroups.size(); 2625 ArrayList<PermissionGroupInfo> out 2626 = new ArrayList<PermissionGroupInfo>(N); 2627 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2628 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2629 } 2630 return out; 2631 } 2632 } 2633 2634 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2635 int userId) { 2636 if (!sUserManager.exists(userId)) return null; 2637 PackageSetting ps = mSettings.mPackages.get(packageName); 2638 if (ps != null) { 2639 if (ps.pkg == null) { 2640 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2641 flags, userId); 2642 if (pInfo != null) { 2643 return pInfo.applicationInfo; 2644 } 2645 return null; 2646 } 2647 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2648 ps.readUserState(userId), userId); 2649 } 2650 return null; 2651 } 2652 2653 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2654 int userId) { 2655 if (!sUserManager.exists(userId)) return null; 2656 PackageSetting ps = mSettings.mPackages.get(packageName); 2657 if (ps != null) { 2658 PackageParser.Package pkg = ps.pkg; 2659 if (pkg == null) { 2660 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2661 return null; 2662 } 2663 // Only data remains, so we aren't worried about code paths 2664 pkg = new PackageParser.Package(packageName); 2665 pkg.applicationInfo.packageName = packageName; 2666 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2667 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2668 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2669 packageName, userId).getAbsolutePath(); 2670 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2671 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2672 } 2673 return generatePackageInfo(pkg, flags, userId); 2674 } 2675 return null; 2676 } 2677 2678 @Override 2679 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2680 if (!sUserManager.exists(userId)) return null; 2681 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2682 // writer 2683 synchronized (mPackages) { 2684 PackageParser.Package p = mPackages.get(packageName); 2685 if (DEBUG_PACKAGE_INFO) Log.v( 2686 TAG, "getApplicationInfo " + packageName 2687 + ": " + p); 2688 if (p != null) { 2689 PackageSetting ps = mSettings.mPackages.get(packageName); 2690 if (ps == null) return null; 2691 // Note: isEnabledLP() does not apply here - always return info 2692 return PackageParser.generateApplicationInfo( 2693 p, flags, ps.readUserState(userId), userId); 2694 } 2695 if ("android".equals(packageName)||"system".equals(packageName)) { 2696 return mAndroidApplication; 2697 } 2698 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2699 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2700 } 2701 } 2702 return null; 2703 } 2704 2705 @Override 2706 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2707 final IPackageDataObserver observer) { 2708 mContext.enforceCallingOrSelfPermission( 2709 android.Manifest.permission.CLEAR_APP_CACHE, null); 2710 // Queue up an async operation since clearing cache may take a little while. 2711 mHandler.post(new Runnable() { 2712 public void run() { 2713 mHandler.removeCallbacks(this); 2714 int retCode = -1; 2715 synchronized (mInstallLock) { 2716 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2717 if (retCode < 0) { 2718 Slog.w(TAG, "Couldn't clear application caches"); 2719 } 2720 } 2721 if (observer != null) { 2722 try { 2723 observer.onRemoveCompleted(null, (retCode >= 0)); 2724 } catch (RemoteException e) { 2725 Slog.w(TAG, "RemoveException when invoking call back"); 2726 } 2727 } 2728 } 2729 }); 2730 } 2731 2732 @Override 2733 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2734 final IntentSender pi) { 2735 mContext.enforceCallingOrSelfPermission( 2736 android.Manifest.permission.CLEAR_APP_CACHE, null); 2737 // Queue up an async operation since clearing cache may take a little while. 2738 mHandler.post(new Runnable() { 2739 public void run() { 2740 mHandler.removeCallbacks(this); 2741 int retCode = -1; 2742 synchronized (mInstallLock) { 2743 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2744 if (retCode < 0) { 2745 Slog.w(TAG, "Couldn't clear application caches"); 2746 } 2747 } 2748 if(pi != null) { 2749 try { 2750 // Callback via pending intent 2751 int code = (retCode >= 0) ? 1 : 0; 2752 pi.sendIntent(null, code, null, 2753 null, null); 2754 } catch (SendIntentException e1) { 2755 Slog.i(TAG, "Failed to send pending intent"); 2756 } 2757 } 2758 } 2759 }); 2760 } 2761 2762 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2763 synchronized (mInstallLock) { 2764 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2765 throw new IOException("Failed to free enough space"); 2766 } 2767 } 2768 } 2769 2770 @Override 2771 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2772 if (!sUserManager.exists(userId)) return null; 2773 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2774 synchronized (mPackages) { 2775 PackageParser.Activity a = mActivities.mActivities.get(component); 2776 2777 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2778 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2779 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2780 if (ps == null) return null; 2781 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2782 userId); 2783 } 2784 if (mResolveComponentName.equals(component)) { 2785 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2786 new PackageUserState(), userId); 2787 } 2788 } 2789 return null; 2790 } 2791 2792 @Override 2793 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2794 String resolvedType) { 2795 synchronized (mPackages) { 2796 PackageParser.Activity a = mActivities.mActivities.get(component); 2797 if (a == null) { 2798 return false; 2799 } 2800 for (int i=0; i<a.intents.size(); i++) { 2801 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2802 intent.getData(), intent.getCategories(), TAG) >= 0) { 2803 return true; 2804 } 2805 } 2806 return false; 2807 } 2808 } 2809 2810 @Override 2811 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2812 if (!sUserManager.exists(userId)) return null; 2813 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2814 synchronized (mPackages) { 2815 PackageParser.Activity a = mReceivers.mActivities.get(component); 2816 if (DEBUG_PACKAGE_INFO) Log.v( 2817 TAG, "getReceiverInfo " + component + ": " + a); 2818 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2819 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2820 if (ps == null) return null; 2821 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2822 userId); 2823 } 2824 } 2825 return null; 2826 } 2827 2828 @Override 2829 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2830 if (!sUserManager.exists(userId)) return null; 2831 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2832 synchronized (mPackages) { 2833 PackageParser.Service s = mServices.mServices.get(component); 2834 if (DEBUG_PACKAGE_INFO) Log.v( 2835 TAG, "getServiceInfo " + component + ": " + s); 2836 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2837 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2838 if (ps == null) return null; 2839 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2840 userId); 2841 } 2842 } 2843 return null; 2844 } 2845 2846 @Override 2847 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2848 if (!sUserManager.exists(userId)) return null; 2849 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2850 synchronized (mPackages) { 2851 PackageParser.Provider p = mProviders.mProviders.get(component); 2852 if (DEBUG_PACKAGE_INFO) Log.v( 2853 TAG, "getProviderInfo " + component + ": " + p); 2854 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2855 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2856 if (ps == null) return null; 2857 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2858 userId); 2859 } 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public String[] getSystemSharedLibraryNames() { 2866 Set<String> libSet; 2867 synchronized (mPackages) { 2868 libSet = mSharedLibraries.keySet(); 2869 int size = libSet.size(); 2870 if (size > 0) { 2871 String[] libs = new String[size]; 2872 libSet.toArray(libs); 2873 return libs; 2874 } 2875 } 2876 return null; 2877 } 2878 2879 /** 2880 * @hide 2881 */ 2882 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2883 synchronized (mPackages) { 2884 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2885 if (lib != null && lib.apk != null) { 2886 return mPackages.get(lib.apk); 2887 } 2888 } 2889 return null; 2890 } 2891 2892 @Override 2893 public FeatureInfo[] getSystemAvailableFeatures() { 2894 Collection<FeatureInfo> featSet; 2895 synchronized (mPackages) { 2896 featSet = mAvailableFeatures.values(); 2897 int size = featSet.size(); 2898 if (size > 0) { 2899 FeatureInfo[] features = new FeatureInfo[size+1]; 2900 featSet.toArray(features); 2901 FeatureInfo fi = new FeatureInfo(); 2902 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2903 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2904 features[size] = fi; 2905 return features; 2906 } 2907 } 2908 return null; 2909 } 2910 2911 @Override 2912 public boolean hasSystemFeature(String name) { 2913 synchronized (mPackages) { 2914 return mAvailableFeatures.containsKey(name); 2915 } 2916 } 2917 2918 private void checkValidCaller(int uid, int userId) { 2919 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2920 return; 2921 2922 throw new SecurityException("Caller uid=" + uid 2923 + " is not privileged to communicate with user=" + userId); 2924 } 2925 2926 @Override 2927 public int checkPermission(String permName, String pkgName, int userId) { 2928 if (!sUserManager.exists(userId)) { 2929 return PackageManager.PERMISSION_DENIED; 2930 } 2931 2932 synchronized (mPackages) { 2933 final PackageParser.Package p = mPackages.get(pkgName); 2934 if (p != null && p.mExtras != null) { 2935 final PackageSetting ps = (PackageSetting) p.mExtras; 2936 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2937 return PackageManager.PERMISSION_GRANTED; 2938 } 2939 } 2940 } 2941 2942 return PackageManager.PERMISSION_DENIED; 2943 } 2944 2945 @Override 2946 public int checkUidPermission(String permName, int uid) { 2947 final int userId = UserHandle.getUserId(uid); 2948 2949 if (!sUserManager.exists(userId)) { 2950 return PackageManager.PERMISSION_DENIED; 2951 } 2952 2953 synchronized (mPackages) { 2954 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2955 if (obj != null) { 2956 final SettingBase ps = (SettingBase) obj; 2957 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2958 return PackageManager.PERMISSION_GRANTED; 2959 } 2960 } else { 2961 ArraySet<String> perms = mSystemPermissions.get(uid); 2962 if (perms != null && perms.contains(permName)) { 2963 return PackageManager.PERMISSION_GRANTED; 2964 } 2965 } 2966 } 2967 2968 return PackageManager.PERMISSION_DENIED; 2969 } 2970 2971 /** 2972 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2973 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2974 * @param checkShell TODO(yamasani): 2975 * @param message the message to log on security exception 2976 */ 2977 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2978 boolean checkShell, String message) { 2979 if (userId < 0) { 2980 throw new IllegalArgumentException("Invalid userId " + userId); 2981 } 2982 if (checkShell) { 2983 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2984 } 2985 if (userId == UserHandle.getUserId(callingUid)) return; 2986 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2987 if (requireFullPermission) { 2988 mContext.enforceCallingOrSelfPermission( 2989 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2990 } else { 2991 try { 2992 mContext.enforceCallingOrSelfPermission( 2993 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2994 } catch (SecurityException se) { 2995 mContext.enforceCallingOrSelfPermission( 2996 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2997 } 2998 } 2999 } 3000 } 3001 3002 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3003 if (callingUid == Process.SHELL_UID) { 3004 if (userHandle >= 0 3005 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3006 throw new SecurityException("Shell does not have permission to access user " 3007 + userHandle); 3008 } else if (userHandle < 0) { 3009 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3010 + Debug.getCallers(3)); 3011 } 3012 } 3013 } 3014 3015 private BasePermission findPermissionTreeLP(String permName) { 3016 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3017 if (permName.startsWith(bp.name) && 3018 permName.length() > bp.name.length() && 3019 permName.charAt(bp.name.length()) == '.') { 3020 return bp; 3021 } 3022 } 3023 return null; 3024 } 3025 3026 private BasePermission checkPermissionTreeLP(String permName) { 3027 if (permName != null) { 3028 BasePermission bp = findPermissionTreeLP(permName); 3029 if (bp != null) { 3030 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3031 return bp; 3032 } 3033 throw new SecurityException("Calling uid " 3034 + Binder.getCallingUid() 3035 + " is not allowed to add to permission tree " 3036 + bp.name + " owned by uid " + bp.uid); 3037 } 3038 } 3039 throw new SecurityException("No permission tree found for " + permName); 3040 } 3041 3042 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3043 if (s1 == null) { 3044 return s2 == null; 3045 } 3046 if (s2 == null) { 3047 return false; 3048 } 3049 if (s1.getClass() != s2.getClass()) { 3050 return false; 3051 } 3052 return s1.equals(s2); 3053 } 3054 3055 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3056 if (pi1.icon != pi2.icon) return false; 3057 if (pi1.logo != pi2.logo) return false; 3058 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3059 if (!compareStrings(pi1.name, pi2.name)) return false; 3060 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3061 // We'll take care of setting this one. 3062 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3063 // These are not currently stored in settings. 3064 //if (!compareStrings(pi1.group, pi2.group)) return false; 3065 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3066 //if (pi1.labelRes != pi2.labelRes) return false; 3067 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3068 return true; 3069 } 3070 3071 int permissionInfoFootprint(PermissionInfo info) { 3072 int size = info.name.length(); 3073 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3074 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3075 return size; 3076 } 3077 3078 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3079 int size = 0; 3080 for (BasePermission perm : mSettings.mPermissions.values()) { 3081 if (perm.uid == tree.uid) { 3082 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3083 } 3084 } 3085 return size; 3086 } 3087 3088 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3089 // We calculate the max size of permissions defined by this uid and throw 3090 // if that plus the size of 'info' would exceed our stated maximum. 3091 if (tree.uid != Process.SYSTEM_UID) { 3092 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3093 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3094 throw new SecurityException("Permission tree size cap exceeded"); 3095 } 3096 } 3097 } 3098 3099 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3100 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3101 throw new SecurityException("Label must be specified in permission"); 3102 } 3103 BasePermission tree = checkPermissionTreeLP(info.name); 3104 BasePermission bp = mSettings.mPermissions.get(info.name); 3105 boolean added = bp == null; 3106 boolean changed = true; 3107 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3108 if (added) { 3109 enforcePermissionCapLocked(info, tree); 3110 bp = new BasePermission(info.name, tree.sourcePackage, 3111 BasePermission.TYPE_DYNAMIC); 3112 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3113 throw new SecurityException( 3114 "Not allowed to modify non-dynamic permission " 3115 + info.name); 3116 } else { 3117 if (bp.protectionLevel == fixedLevel 3118 && bp.perm.owner.equals(tree.perm.owner) 3119 && bp.uid == tree.uid 3120 && comparePermissionInfos(bp.perm.info, info)) { 3121 changed = false; 3122 } 3123 } 3124 bp.protectionLevel = fixedLevel; 3125 info = new PermissionInfo(info); 3126 info.protectionLevel = fixedLevel; 3127 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3128 bp.perm.info.packageName = tree.perm.info.packageName; 3129 bp.uid = tree.uid; 3130 if (added) { 3131 mSettings.mPermissions.put(info.name, bp); 3132 } 3133 if (changed) { 3134 if (!async) { 3135 mSettings.writeLPr(); 3136 } else { 3137 scheduleWriteSettingsLocked(); 3138 } 3139 } 3140 return added; 3141 } 3142 3143 @Override 3144 public boolean addPermission(PermissionInfo info) { 3145 synchronized (mPackages) { 3146 return addPermissionLocked(info, false); 3147 } 3148 } 3149 3150 @Override 3151 public boolean addPermissionAsync(PermissionInfo info) { 3152 synchronized (mPackages) { 3153 return addPermissionLocked(info, true); 3154 } 3155 } 3156 3157 @Override 3158 public void removePermission(String name) { 3159 synchronized (mPackages) { 3160 checkPermissionTreeLP(name); 3161 BasePermission bp = mSettings.mPermissions.get(name); 3162 if (bp != null) { 3163 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3164 throw new SecurityException( 3165 "Not allowed to modify non-dynamic permission " 3166 + name); 3167 } 3168 mSettings.mPermissions.remove(name); 3169 mSettings.writeLPr(); 3170 } 3171 } 3172 } 3173 3174 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3175 BasePermission bp) { 3176 int index = pkg.requestedPermissions.indexOf(bp.name); 3177 if (index == -1) { 3178 throw new SecurityException("Package " + pkg.packageName 3179 + " has not requested permission " + bp.name); 3180 } 3181 if (!bp.isRuntime()) { 3182 throw new SecurityException("Permission " + bp.name 3183 + " is not a changeable permission type"); 3184 } 3185 } 3186 3187 @Override 3188 public void grantRuntimePermission(String packageName, String name, final int userId) { 3189 if (!sUserManager.exists(userId)) { 3190 Log.e(TAG, "No such user:" + userId); 3191 return; 3192 } 3193 3194 mContext.enforceCallingOrSelfPermission( 3195 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3196 "grantRuntimePermission"); 3197 3198 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3199 "grantRuntimePermission"); 3200 3201 final SettingBase sb; 3202 3203 synchronized (mPackages) { 3204 final PackageParser.Package pkg = mPackages.get(packageName); 3205 if (pkg == null) { 3206 throw new IllegalArgumentException("Unknown package: " + packageName); 3207 } 3208 3209 final BasePermission bp = mSettings.mPermissions.get(name); 3210 if (bp == null) { 3211 throw new IllegalArgumentException("Unknown permission: " + name); 3212 } 3213 3214 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3215 3216 sb = (SettingBase) pkg.mExtras; 3217 if (sb == null) { 3218 throw new IllegalArgumentException("Unknown package: " + packageName); 3219 } 3220 3221 final PermissionsState permissionsState = sb.getPermissionsState(); 3222 3223 final int flags = permissionsState.getPermissionFlags(name, userId); 3224 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3225 throw new SecurityException("Cannot grant system fixed permission: " 3226 + name + " for package: " + packageName); 3227 } 3228 3229 final int result = permissionsState.grantRuntimePermission(bp, userId); 3230 switch (result) { 3231 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3232 return; 3233 } 3234 3235 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3236 mHandler.post(new Runnable() { 3237 @Override 3238 public void run() { 3239 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3240 } 3241 }); 3242 } break; 3243 } 3244 3245 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3246 3247 // Not critical if that is lost - app has to request again. 3248 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3249 } 3250 } 3251 3252 @Override 3253 public void revokeRuntimePermission(String packageName, String name, int userId) { 3254 if (!sUserManager.exists(userId)) { 3255 Log.e(TAG, "No such user:" + userId); 3256 return; 3257 } 3258 3259 mContext.enforceCallingOrSelfPermission( 3260 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3261 "revokeRuntimePermission"); 3262 3263 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3264 "revokeRuntimePermission"); 3265 3266 final SettingBase sb; 3267 3268 synchronized (mPackages) { 3269 final PackageParser.Package pkg = mPackages.get(packageName); 3270 if (pkg == null) { 3271 throw new IllegalArgumentException("Unknown package: " + packageName); 3272 } 3273 3274 final BasePermission bp = mSettings.mPermissions.get(name); 3275 if (bp == null) { 3276 throw new IllegalArgumentException("Unknown permission: " + name); 3277 } 3278 3279 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3280 3281 sb = (SettingBase) pkg.mExtras; 3282 if (sb == null) { 3283 throw new IllegalArgumentException("Unknown package: " + packageName); 3284 } 3285 3286 final PermissionsState permissionsState = sb.getPermissionsState(); 3287 3288 final int flags = permissionsState.getPermissionFlags(name, userId); 3289 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3290 throw new SecurityException("Cannot revoke system fixed permission: " 3291 + name + " for package: " + packageName); 3292 } 3293 3294 if (permissionsState.revokeRuntimePermission(bp, userId) == 3295 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3296 return; 3297 } 3298 3299 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3300 3301 // Critical, after this call app should never have the permission. 3302 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3303 } 3304 3305 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3306 } 3307 3308 @Override 3309 public int getPermissionFlags(String name, String packageName, int userId) { 3310 if (!sUserManager.exists(userId)) { 3311 return 0; 3312 } 3313 3314 mContext.enforceCallingOrSelfPermission( 3315 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3316 "getPermissionFlags"); 3317 3318 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3319 "getPermissionFlags"); 3320 3321 synchronized (mPackages) { 3322 final PackageParser.Package pkg = mPackages.get(packageName); 3323 if (pkg == null) { 3324 throw new IllegalArgumentException("Unknown package: " + packageName); 3325 } 3326 3327 final BasePermission bp = mSettings.mPermissions.get(name); 3328 if (bp == null) { 3329 throw new IllegalArgumentException("Unknown permission: " + name); 3330 } 3331 3332 SettingBase sb = (SettingBase) pkg.mExtras; 3333 if (sb == null) { 3334 throw new IllegalArgumentException("Unknown package: " + packageName); 3335 } 3336 3337 PermissionsState permissionsState = sb.getPermissionsState(); 3338 return permissionsState.getPermissionFlags(name, userId); 3339 } 3340 } 3341 3342 @Override 3343 public void updatePermissionFlags(String name, String packageName, int flagMask, 3344 int flagValues, int userId) { 3345 if (!sUserManager.exists(userId)) { 3346 return; 3347 } 3348 3349 mContext.enforceCallingOrSelfPermission( 3350 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3351 "updatePermissionFlags"); 3352 3353 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3354 "updatePermissionFlags"); 3355 3356 // Only the system can change system fixed flags. 3357 if (getCallingUid() != Process.SYSTEM_UID) { 3358 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3359 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3360 } 3361 3362 synchronized (mPackages) { 3363 final PackageParser.Package pkg = mPackages.get(packageName); 3364 if (pkg == null) { 3365 throw new IllegalArgumentException("Unknown package: " + packageName); 3366 } 3367 3368 final BasePermission bp = mSettings.mPermissions.get(name); 3369 if (bp == null) { 3370 throw new IllegalArgumentException("Unknown permission: " + name); 3371 } 3372 3373 SettingBase sb = (SettingBase) pkg.mExtras; 3374 if (sb == null) { 3375 throw new IllegalArgumentException("Unknown package: " + packageName); 3376 } 3377 3378 PermissionsState permissionsState = sb.getPermissionsState(); 3379 3380 // Only the package manager can change flags for system component permissions. 3381 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3382 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3383 return; 3384 } 3385 3386 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3387 3388 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3389 // Install and runtime permissions are stored in different places, 3390 // so figure out what permission changed and persist the change. 3391 if (permissionsState.getInstallPermissionState(name) != null) { 3392 scheduleWriteSettingsLocked(); 3393 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3394 || hadState) { 3395 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3396 } 3397 } 3398 } 3399 } 3400 3401 /** 3402 * Update the permission flags for all packages and runtime permissions of a user in order 3403 * to allow device or profile owner to remove POLICY_FIXED. 3404 */ 3405 @Override 3406 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3407 if (!sUserManager.exists(userId)) { 3408 return; 3409 } 3410 3411 mContext.enforceCallingOrSelfPermission( 3412 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3413 "updatePermissionFlagsForAllApps"); 3414 3415 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3416 "updatePermissionFlagsForAllApps"); 3417 3418 // Only the system can change system fixed flags. 3419 if (getCallingUid() != Process.SYSTEM_UID) { 3420 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3421 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3422 } 3423 3424 synchronized (mPackages) { 3425 boolean changed = false; 3426 final int packageCount = mPackages.size(); 3427 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3428 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3429 SettingBase sb = (SettingBase) pkg.mExtras; 3430 if (sb == null) { 3431 continue; 3432 } 3433 PermissionsState permissionsState = sb.getPermissionsState(); 3434 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3435 userId, flagMask, flagValues); 3436 } 3437 if (changed) { 3438 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3439 } 3440 } 3441 } 3442 3443 @Override 3444 public boolean shouldShowRequestPermissionRationale(String permissionName, 3445 String packageName, int userId) { 3446 if (UserHandle.getCallingUserId() != userId) { 3447 mContext.enforceCallingPermission( 3448 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3449 "canShowRequestPermissionRationale for user " + userId); 3450 } 3451 3452 final int uid = getPackageUid(packageName, userId); 3453 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3454 return false; 3455 } 3456 3457 if (checkPermission(permissionName, packageName, userId) 3458 == PackageManager.PERMISSION_GRANTED) { 3459 return false; 3460 } 3461 3462 final int flags; 3463 3464 final long identity = Binder.clearCallingIdentity(); 3465 try { 3466 flags = getPermissionFlags(permissionName, 3467 packageName, userId); 3468 } finally { 3469 Binder.restoreCallingIdentity(identity); 3470 } 3471 3472 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3473 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3474 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3475 3476 if ((flags & fixedFlags) != 0) { 3477 return false; 3478 } 3479 3480 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3481 } 3482 3483 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3484 BasePermission bp = mSettings.mPermissions.get(permission); 3485 if (bp == null) { 3486 throw new SecurityException("Missing " + permission + " permission"); 3487 } 3488 3489 SettingBase sb = (SettingBase) pkg.mExtras; 3490 PermissionsState permissionsState = sb.getPermissionsState(); 3491 3492 if (permissionsState.grantInstallPermission(bp) != 3493 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3494 scheduleWriteSettingsLocked(); 3495 } 3496 } 3497 3498 @Override 3499 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3500 mContext.enforceCallingOrSelfPermission( 3501 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3502 "addOnPermissionsChangeListener"); 3503 3504 synchronized (mPackages) { 3505 mOnPermissionChangeListeners.addListenerLocked(listener); 3506 } 3507 } 3508 3509 @Override 3510 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3511 synchronized (mPackages) { 3512 mOnPermissionChangeListeners.removeListenerLocked(listener); 3513 } 3514 } 3515 3516 @Override 3517 public boolean isProtectedBroadcast(String actionName) { 3518 synchronized (mPackages) { 3519 return mProtectedBroadcasts.contains(actionName); 3520 } 3521 } 3522 3523 @Override 3524 public int checkSignatures(String pkg1, String pkg2) { 3525 synchronized (mPackages) { 3526 final PackageParser.Package p1 = mPackages.get(pkg1); 3527 final PackageParser.Package p2 = mPackages.get(pkg2); 3528 if (p1 == null || p1.mExtras == null 3529 || p2 == null || p2.mExtras == null) { 3530 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3531 } 3532 return compareSignatures(p1.mSignatures, p2.mSignatures); 3533 } 3534 } 3535 3536 @Override 3537 public int checkUidSignatures(int uid1, int uid2) { 3538 // Map to base uids. 3539 uid1 = UserHandle.getAppId(uid1); 3540 uid2 = UserHandle.getAppId(uid2); 3541 // reader 3542 synchronized (mPackages) { 3543 Signature[] s1; 3544 Signature[] s2; 3545 Object obj = mSettings.getUserIdLPr(uid1); 3546 if (obj != null) { 3547 if (obj instanceof SharedUserSetting) { 3548 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3549 } else if (obj instanceof PackageSetting) { 3550 s1 = ((PackageSetting)obj).signatures.mSignatures; 3551 } else { 3552 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3553 } 3554 } else { 3555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3556 } 3557 obj = mSettings.getUserIdLPr(uid2); 3558 if (obj != null) { 3559 if (obj instanceof SharedUserSetting) { 3560 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3561 } else if (obj instanceof PackageSetting) { 3562 s2 = ((PackageSetting)obj).signatures.mSignatures; 3563 } else { 3564 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3565 } 3566 } else { 3567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3568 } 3569 return compareSignatures(s1, s2); 3570 } 3571 } 3572 3573 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3574 final long identity = Binder.clearCallingIdentity(); 3575 try { 3576 if (sb instanceof SharedUserSetting) { 3577 SharedUserSetting sus = (SharedUserSetting) sb; 3578 final int packageCount = sus.packages.size(); 3579 for (int i = 0; i < packageCount; i++) { 3580 PackageSetting susPs = sus.packages.valueAt(i); 3581 if (userId == UserHandle.USER_ALL) { 3582 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3583 } else { 3584 final int uid = UserHandle.getUid(userId, susPs.appId); 3585 killUid(uid, reason); 3586 } 3587 } 3588 } else if (sb instanceof PackageSetting) { 3589 PackageSetting ps = (PackageSetting) sb; 3590 if (userId == UserHandle.USER_ALL) { 3591 killApplication(ps.pkg.packageName, ps.appId, reason); 3592 } else { 3593 final int uid = UserHandle.getUid(userId, ps.appId); 3594 killUid(uid, reason); 3595 } 3596 } 3597 } finally { 3598 Binder.restoreCallingIdentity(identity); 3599 } 3600 } 3601 3602 private static void killUid(int uid, String reason) { 3603 IActivityManager am = ActivityManagerNative.getDefault(); 3604 if (am != null) { 3605 try { 3606 am.killUid(uid, reason); 3607 } catch (RemoteException e) { 3608 /* ignore - same process */ 3609 } 3610 } 3611 } 3612 3613 /** 3614 * Compares two sets of signatures. Returns: 3615 * <br /> 3616 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3617 * <br /> 3618 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3619 * <br /> 3620 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3621 * <br /> 3622 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3623 * <br /> 3624 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3625 */ 3626 static int compareSignatures(Signature[] s1, Signature[] s2) { 3627 if (s1 == null) { 3628 return s2 == null 3629 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3630 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3631 } 3632 3633 if (s2 == null) { 3634 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3635 } 3636 3637 if (s1.length != s2.length) { 3638 return PackageManager.SIGNATURE_NO_MATCH; 3639 } 3640 3641 // Since both signature sets are of size 1, we can compare without HashSets. 3642 if (s1.length == 1) { 3643 return s1[0].equals(s2[0]) ? 3644 PackageManager.SIGNATURE_MATCH : 3645 PackageManager.SIGNATURE_NO_MATCH; 3646 } 3647 3648 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3649 for (Signature sig : s1) { 3650 set1.add(sig); 3651 } 3652 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3653 for (Signature sig : s2) { 3654 set2.add(sig); 3655 } 3656 // Make sure s2 contains all signatures in s1. 3657 if (set1.equals(set2)) { 3658 return PackageManager.SIGNATURE_MATCH; 3659 } 3660 return PackageManager.SIGNATURE_NO_MATCH; 3661 } 3662 3663 /** 3664 * If the database version for this type of package (internal storage or 3665 * external storage) is less than the version where package signatures 3666 * were updated, return true. 3667 */ 3668 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3669 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3670 DatabaseVersion.SIGNATURE_END_ENTITY)) 3671 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3672 DatabaseVersion.SIGNATURE_END_ENTITY)); 3673 } 3674 3675 /** 3676 * Used for backward compatibility to make sure any packages with 3677 * certificate chains get upgraded to the new style. {@code existingSigs} 3678 * will be in the old format (since they were stored on disk from before the 3679 * system upgrade) and {@code scannedSigs} will be in the newer format. 3680 */ 3681 private int compareSignaturesCompat(PackageSignatures existingSigs, 3682 PackageParser.Package scannedPkg) { 3683 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3684 return PackageManager.SIGNATURE_NO_MATCH; 3685 } 3686 3687 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3688 for (Signature sig : existingSigs.mSignatures) { 3689 existingSet.add(sig); 3690 } 3691 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3692 for (Signature sig : scannedPkg.mSignatures) { 3693 try { 3694 Signature[] chainSignatures = sig.getChainSignatures(); 3695 for (Signature chainSig : chainSignatures) { 3696 scannedCompatSet.add(chainSig); 3697 } 3698 } catch (CertificateEncodingException e) { 3699 scannedCompatSet.add(sig); 3700 } 3701 } 3702 /* 3703 * Make sure the expanded scanned set contains all signatures in the 3704 * existing one. 3705 */ 3706 if (scannedCompatSet.equals(existingSet)) { 3707 // Migrate the old signatures to the new scheme. 3708 existingSigs.assignSignatures(scannedPkg.mSignatures); 3709 // The new KeySets will be re-added later in the scanning process. 3710 synchronized (mPackages) { 3711 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3712 } 3713 return PackageManager.SIGNATURE_MATCH; 3714 } 3715 return PackageManager.SIGNATURE_NO_MATCH; 3716 } 3717 3718 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3719 if (isExternal(scannedPkg)) { 3720 return mSettings.isExternalDatabaseVersionOlderThan( 3721 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3722 } else { 3723 return mSettings.isInternalDatabaseVersionOlderThan( 3724 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3725 } 3726 } 3727 3728 private int compareSignaturesRecover(PackageSignatures existingSigs, 3729 PackageParser.Package scannedPkg) { 3730 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3731 return PackageManager.SIGNATURE_NO_MATCH; 3732 } 3733 3734 String msg = null; 3735 try { 3736 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3737 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3738 + scannedPkg.packageName); 3739 return PackageManager.SIGNATURE_MATCH; 3740 } 3741 } catch (CertificateException e) { 3742 msg = e.getMessage(); 3743 } 3744 3745 logCriticalInfo(Log.INFO, 3746 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3747 return PackageManager.SIGNATURE_NO_MATCH; 3748 } 3749 3750 @Override 3751 public String[] getPackagesForUid(int uid) { 3752 uid = UserHandle.getAppId(uid); 3753 // reader 3754 synchronized (mPackages) { 3755 Object obj = mSettings.getUserIdLPr(uid); 3756 if (obj instanceof SharedUserSetting) { 3757 final SharedUserSetting sus = (SharedUserSetting) obj; 3758 final int N = sus.packages.size(); 3759 final String[] res = new String[N]; 3760 final Iterator<PackageSetting> it = sus.packages.iterator(); 3761 int i = 0; 3762 while (it.hasNext()) { 3763 res[i++] = it.next().name; 3764 } 3765 return res; 3766 } else if (obj instanceof PackageSetting) { 3767 final PackageSetting ps = (PackageSetting) obj; 3768 return new String[] { ps.name }; 3769 } 3770 } 3771 return null; 3772 } 3773 3774 @Override 3775 public String getNameForUid(int uid) { 3776 // reader 3777 synchronized (mPackages) { 3778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3779 if (obj instanceof SharedUserSetting) { 3780 final SharedUserSetting sus = (SharedUserSetting) obj; 3781 return sus.name + ":" + sus.userId; 3782 } else if (obj instanceof PackageSetting) { 3783 final PackageSetting ps = (PackageSetting) obj; 3784 return ps.name; 3785 } 3786 } 3787 return null; 3788 } 3789 3790 @Override 3791 public int getUidForSharedUser(String sharedUserName) { 3792 if(sharedUserName == null) { 3793 return -1; 3794 } 3795 // reader 3796 synchronized (mPackages) { 3797 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3798 if (suid == null) { 3799 return -1; 3800 } 3801 return suid.userId; 3802 } 3803 } 3804 3805 @Override 3806 public int getFlagsForUid(int uid) { 3807 synchronized (mPackages) { 3808 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3809 if (obj instanceof SharedUserSetting) { 3810 final SharedUserSetting sus = (SharedUserSetting) obj; 3811 return sus.pkgFlags; 3812 } else if (obj instanceof PackageSetting) { 3813 final PackageSetting ps = (PackageSetting) obj; 3814 return ps.pkgFlags; 3815 } 3816 } 3817 return 0; 3818 } 3819 3820 @Override 3821 public int getPrivateFlagsForUid(int uid) { 3822 synchronized (mPackages) { 3823 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3824 if (obj instanceof SharedUserSetting) { 3825 final SharedUserSetting sus = (SharedUserSetting) obj; 3826 return sus.pkgPrivateFlags; 3827 } else if (obj instanceof PackageSetting) { 3828 final PackageSetting ps = (PackageSetting) obj; 3829 return ps.pkgPrivateFlags; 3830 } 3831 } 3832 return 0; 3833 } 3834 3835 @Override 3836 public boolean isUidPrivileged(int uid) { 3837 uid = UserHandle.getAppId(uid); 3838 // reader 3839 synchronized (mPackages) { 3840 Object obj = mSettings.getUserIdLPr(uid); 3841 if (obj instanceof SharedUserSetting) { 3842 final SharedUserSetting sus = (SharedUserSetting) obj; 3843 final Iterator<PackageSetting> it = sus.packages.iterator(); 3844 while (it.hasNext()) { 3845 if (it.next().isPrivileged()) { 3846 return true; 3847 } 3848 } 3849 } else if (obj instanceof PackageSetting) { 3850 final PackageSetting ps = (PackageSetting) obj; 3851 return ps.isPrivileged(); 3852 } 3853 } 3854 return false; 3855 } 3856 3857 @Override 3858 public String[] getAppOpPermissionPackages(String permissionName) { 3859 synchronized (mPackages) { 3860 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3861 if (pkgs == null) { 3862 return null; 3863 } 3864 return pkgs.toArray(new String[pkgs.size()]); 3865 } 3866 } 3867 3868 @Override 3869 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3870 int flags, int userId) { 3871 if (!sUserManager.exists(userId)) return null; 3872 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3873 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3874 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3875 } 3876 3877 @Override 3878 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3879 IntentFilter filter, int match, ComponentName activity) { 3880 final int userId = UserHandle.getCallingUserId(); 3881 if (DEBUG_PREFERRED) { 3882 Log.v(TAG, "setLastChosenActivity intent=" + intent 3883 + " resolvedType=" + resolvedType 3884 + " flags=" + flags 3885 + " filter=" + filter 3886 + " match=" + match 3887 + " activity=" + activity); 3888 filter.dump(new PrintStreamPrinter(System.out), " "); 3889 } 3890 intent.setComponent(null); 3891 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3892 // Find any earlier preferred or last chosen entries and nuke them 3893 findPreferredActivity(intent, resolvedType, 3894 flags, query, 0, false, true, false, userId); 3895 // Add the new activity as the last chosen for this filter 3896 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3897 "Setting last chosen"); 3898 } 3899 3900 @Override 3901 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3902 final int userId = UserHandle.getCallingUserId(); 3903 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3904 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3905 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3906 false, false, false, userId); 3907 } 3908 3909 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3910 int flags, List<ResolveInfo> query, int userId) { 3911 if (query != null) { 3912 final int N = query.size(); 3913 if (N == 1) { 3914 return query.get(0); 3915 } else if (N > 1) { 3916 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3917 // If there is more than one activity with the same priority, 3918 // then let the user decide between them. 3919 ResolveInfo r0 = query.get(0); 3920 ResolveInfo r1 = query.get(1); 3921 if (DEBUG_INTENT_MATCHING || debug) { 3922 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3923 + r1.activityInfo.name + "=" + r1.priority); 3924 } 3925 // If the first activity has a higher priority, or a different 3926 // default, then it is always desireable to pick it. 3927 if (r0.priority != r1.priority 3928 || r0.preferredOrder != r1.preferredOrder 3929 || r0.isDefault != r1.isDefault) { 3930 return query.get(0); 3931 } 3932 // If we have saved a preference for a preferred activity for 3933 // this Intent, use that. 3934 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3935 flags, query, r0.priority, true, false, debug, userId); 3936 if (ri != null) { 3937 return ri; 3938 } 3939 if (userId != 0) { 3940 ri = new ResolveInfo(mResolveInfo); 3941 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3942 ri.activityInfo.applicationInfo = new ApplicationInfo( 3943 ri.activityInfo.applicationInfo); 3944 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3945 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3946 return ri; 3947 } 3948 return mResolveInfo; 3949 } 3950 } 3951 return null; 3952 } 3953 3954 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3955 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3956 final int N = query.size(); 3957 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3958 .get(userId); 3959 // Get the list of persistent preferred activities that handle the intent 3960 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3961 List<PersistentPreferredActivity> pprefs = ppir != null 3962 ? ppir.queryIntent(intent, resolvedType, 3963 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3964 : null; 3965 if (pprefs != null && pprefs.size() > 0) { 3966 final int M = pprefs.size(); 3967 for (int i=0; i<M; i++) { 3968 final PersistentPreferredActivity ppa = pprefs.get(i); 3969 if (DEBUG_PREFERRED || debug) { 3970 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3971 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3972 + "\n component=" + ppa.mComponent); 3973 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3974 } 3975 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3976 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3977 if (DEBUG_PREFERRED || debug) { 3978 Slog.v(TAG, "Found persistent preferred activity:"); 3979 if (ai != null) { 3980 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3981 } else { 3982 Slog.v(TAG, " null"); 3983 } 3984 } 3985 if (ai == null) { 3986 // This previously registered persistent preferred activity 3987 // component is no longer known. Ignore it and do NOT remove it. 3988 continue; 3989 } 3990 for (int j=0; j<N; j++) { 3991 final ResolveInfo ri = query.get(j); 3992 if (!ri.activityInfo.applicationInfo.packageName 3993 .equals(ai.applicationInfo.packageName)) { 3994 continue; 3995 } 3996 if (!ri.activityInfo.name.equals(ai.name)) { 3997 continue; 3998 } 3999 // Found a persistent preference that can handle the intent. 4000 if (DEBUG_PREFERRED || debug) { 4001 Slog.v(TAG, "Returning persistent preferred activity: " + 4002 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4003 } 4004 return ri; 4005 } 4006 } 4007 } 4008 return null; 4009 } 4010 4011 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4012 List<ResolveInfo> query, int priority, boolean always, 4013 boolean removeMatches, boolean debug, int userId) { 4014 if (!sUserManager.exists(userId)) return null; 4015 // writer 4016 synchronized (mPackages) { 4017 if (intent.getSelector() != null) { 4018 intent = intent.getSelector(); 4019 } 4020 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4021 4022 // Try to find a matching persistent preferred activity. 4023 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4024 debug, userId); 4025 4026 // If a persistent preferred activity matched, use it. 4027 if (pri != null) { 4028 return pri; 4029 } 4030 4031 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4032 // Get the list of preferred activities that handle the intent 4033 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4034 List<PreferredActivity> prefs = pir != null 4035 ? pir.queryIntent(intent, resolvedType, 4036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4037 : null; 4038 if (prefs != null && prefs.size() > 0) { 4039 boolean changed = false; 4040 try { 4041 // First figure out how good the original match set is. 4042 // We will only allow preferred activities that came 4043 // from the same match quality. 4044 int match = 0; 4045 4046 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4047 4048 final int N = query.size(); 4049 for (int j=0; j<N; j++) { 4050 final ResolveInfo ri = query.get(j); 4051 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4052 + ": 0x" + Integer.toHexString(match)); 4053 if (ri.match > match) { 4054 match = ri.match; 4055 } 4056 } 4057 4058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4059 + Integer.toHexString(match)); 4060 4061 match &= IntentFilter.MATCH_CATEGORY_MASK; 4062 final int M = prefs.size(); 4063 for (int i=0; i<M; i++) { 4064 final PreferredActivity pa = prefs.get(i); 4065 if (DEBUG_PREFERRED || debug) { 4066 Slog.v(TAG, "Checking PreferredActivity ds=" 4067 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4068 + "\n component=" + pa.mPref.mComponent); 4069 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4070 } 4071 if (pa.mPref.mMatch != match) { 4072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4073 + Integer.toHexString(pa.mPref.mMatch)); 4074 continue; 4075 } 4076 // If it's not an "always" type preferred activity and that's what we're 4077 // looking for, skip it. 4078 if (always && !pa.mPref.mAlways) { 4079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4080 continue; 4081 } 4082 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4083 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4084 if (DEBUG_PREFERRED || debug) { 4085 Slog.v(TAG, "Found preferred activity:"); 4086 if (ai != null) { 4087 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4088 } else { 4089 Slog.v(TAG, " null"); 4090 } 4091 } 4092 if (ai == null) { 4093 // This previously registered preferred activity 4094 // component is no longer known. Most likely an update 4095 // to the app was installed and in the new version this 4096 // component no longer exists. Clean it up by removing 4097 // it from the preferred activities list, and skip it. 4098 Slog.w(TAG, "Removing dangling preferred activity: " 4099 + pa.mPref.mComponent); 4100 pir.removeFilter(pa); 4101 changed = true; 4102 continue; 4103 } 4104 for (int j=0; j<N; j++) { 4105 final ResolveInfo ri = query.get(j); 4106 if (!ri.activityInfo.applicationInfo.packageName 4107 .equals(ai.applicationInfo.packageName)) { 4108 continue; 4109 } 4110 if (!ri.activityInfo.name.equals(ai.name)) { 4111 continue; 4112 } 4113 4114 if (removeMatches) { 4115 pir.removeFilter(pa); 4116 changed = true; 4117 if (DEBUG_PREFERRED) { 4118 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4119 } 4120 break; 4121 } 4122 4123 // Okay we found a previously set preferred or last chosen app. 4124 // If the result set is different from when this 4125 // was created, we need to clear it and re-ask the 4126 // user their preference, if we're looking for an "always" type entry. 4127 if (always && !pa.mPref.sameSet(query)) { 4128 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4129 + intent + " type " + resolvedType); 4130 if (DEBUG_PREFERRED) { 4131 Slog.v(TAG, "Removing preferred activity since set changed " 4132 + pa.mPref.mComponent); 4133 } 4134 pir.removeFilter(pa); 4135 // Re-add the filter as a "last chosen" entry (!always) 4136 PreferredActivity lastChosen = new PreferredActivity( 4137 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4138 pir.addFilter(lastChosen); 4139 changed = true; 4140 return null; 4141 } 4142 4143 // Yay! Either the set matched or we're looking for the last chosen 4144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4145 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4146 return ri; 4147 } 4148 } 4149 } finally { 4150 if (changed) { 4151 if (DEBUG_PREFERRED) { 4152 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4153 } 4154 scheduleWritePackageRestrictionsLocked(userId); 4155 } 4156 } 4157 } 4158 } 4159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4160 return null; 4161 } 4162 4163 /* 4164 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4165 */ 4166 @Override 4167 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4168 int targetUserId) { 4169 mContext.enforceCallingOrSelfPermission( 4170 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4171 List<CrossProfileIntentFilter> matches = 4172 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4173 if (matches != null) { 4174 int size = matches.size(); 4175 for (int i = 0; i < size; i++) { 4176 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4177 } 4178 } 4179 if (hasWebURI(intent)) { 4180 // cross-profile app linking works only towards the parent. 4181 final UserInfo parent = getProfileParent(sourceUserId); 4182 synchronized(mPackages) { 4183 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4184 parent.id) != null; 4185 } 4186 } 4187 return false; 4188 } 4189 4190 private UserInfo getProfileParent(int userId) { 4191 final long identity = Binder.clearCallingIdentity(); 4192 try { 4193 return sUserManager.getProfileParent(userId); 4194 } finally { 4195 Binder.restoreCallingIdentity(identity); 4196 } 4197 } 4198 4199 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4200 String resolvedType, int userId) { 4201 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4202 if (resolver != null) { 4203 return resolver.queryIntent(intent, resolvedType, false, userId); 4204 } 4205 return null; 4206 } 4207 4208 @Override 4209 public List<ResolveInfo> queryIntentActivities(Intent intent, 4210 String resolvedType, int flags, int userId) { 4211 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4212 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4213 ComponentName comp = intent.getComponent(); 4214 if (comp == null) { 4215 if (intent.getSelector() != null) { 4216 intent = intent.getSelector(); 4217 comp = intent.getComponent(); 4218 } 4219 } 4220 4221 if (comp != null) { 4222 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4223 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4224 if (ai != null) { 4225 final ResolveInfo ri = new ResolveInfo(); 4226 ri.activityInfo = ai; 4227 list.add(ri); 4228 } 4229 return list; 4230 } 4231 4232 // reader 4233 synchronized (mPackages) { 4234 final String pkgName = intent.getPackage(); 4235 if (pkgName == null) { 4236 List<CrossProfileIntentFilter> matchingFilters = 4237 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4238 // Check for results that need to skip the current profile. 4239 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4240 resolvedType, flags, userId); 4241 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4242 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4243 result.add(xpResolveInfo); 4244 return filterIfNotPrimaryUser(result, userId); 4245 } 4246 4247 // Check for results in the current profile. 4248 List<ResolveInfo> result = mActivities.queryIntent( 4249 intent, resolvedType, flags, userId); 4250 4251 // Check for cross profile results. 4252 xpResolveInfo = queryCrossProfileIntents( 4253 matchingFilters, intent, resolvedType, flags, userId); 4254 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4255 result.add(xpResolveInfo); 4256 Collections.sort(result, mResolvePrioritySorter); 4257 } 4258 result = filterIfNotPrimaryUser(result, userId); 4259 if (hasWebURI(intent)) { 4260 CrossProfileDomainInfo xpDomainInfo = null; 4261 final UserInfo parent = getProfileParent(userId); 4262 if (parent != null) { 4263 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4264 flags, userId, parent.id); 4265 } 4266 if (xpDomainInfo != null) { 4267 if (xpResolveInfo != null) { 4268 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4269 // in the result. 4270 result.remove(xpResolveInfo); 4271 } 4272 if (result.size() == 0) { 4273 result.add(xpDomainInfo.resolveInfo); 4274 return result; 4275 } 4276 } else if (result.size() <= 1) { 4277 return result; 4278 } 4279 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4280 xpDomainInfo); 4281 Collections.sort(result, mResolvePrioritySorter); 4282 } 4283 return result; 4284 } 4285 final PackageParser.Package pkg = mPackages.get(pkgName); 4286 if (pkg != null) { 4287 return filterIfNotPrimaryUser( 4288 mActivities.queryIntentForPackage( 4289 intent, resolvedType, flags, pkg.activities, userId), 4290 userId); 4291 } 4292 return new ArrayList<ResolveInfo>(); 4293 } 4294 } 4295 4296 private static class CrossProfileDomainInfo { 4297 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4298 ResolveInfo resolveInfo; 4299 /* Best domain verification status of the activities found in the other profile */ 4300 int bestDomainVerificationStatus; 4301 } 4302 4303 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4304 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4305 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING, 4306 sourceUserId)) { 4307 return null; 4308 } 4309 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4310 resolvedType, flags, parentUserId); 4311 4312 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4313 return null; 4314 } 4315 CrossProfileDomainInfo result = null; 4316 int size = resultTargetUser.size(); 4317 for (int i = 0; i < size; i++) { 4318 ResolveInfo riTargetUser = resultTargetUser.get(i); 4319 // Intent filter verification is only for filters that specify a host. So don't return 4320 // those that handle all web uris. 4321 if (riTargetUser.handleAllWebDataURI) { 4322 continue; 4323 } 4324 String packageName = riTargetUser.activityInfo.packageName; 4325 PackageSetting ps = mSettings.mPackages.get(packageName); 4326 if (ps == null) { 4327 continue; 4328 } 4329 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4330 if (result == null) { 4331 result = new CrossProfileDomainInfo(); 4332 result.resolveInfo = 4333 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4334 result.bestDomainVerificationStatus = status; 4335 } else { 4336 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4337 result.bestDomainVerificationStatus); 4338 } 4339 } 4340 return result; 4341 } 4342 4343 /** 4344 * Verification statuses are ordered from the worse to the best, except for 4345 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4346 */ 4347 private int bestDomainVerificationStatus(int status1, int status2) { 4348 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4349 return status2; 4350 } 4351 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4352 return status1; 4353 } 4354 return (int) MathUtils.max(status1, status2); 4355 } 4356 4357 private boolean isUserEnabled(int userId) { 4358 long callingId = Binder.clearCallingIdentity(); 4359 try { 4360 UserInfo userInfo = sUserManager.getUserInfo(userId); 4361 return userInfo != null && userInfo.isEnabled(); 4362 } finally { 4363 Binder.restoreCallingIdentity(callingId); 4364 } 4365 } 4366 4367 /** 4368 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4369 * 4370 * @return filtered list 4371 */ 4372 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4373 if (userId == UserHandle.USER_OWNER) { 4374 return resolveInfos; 4375 } 4376 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4377 ResolveInfo info = resolveInfos.get(i); 4378 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4379 resolveInfos.remove(i); 4380 } 4381 } 4382 return resolveInfos; 4383 } 4384 4385 private static boolean hasWebURI(Intent intent) { 4386 if (intent.getData() == null) { 4387 return false; 4388 } 4389 final String scheme = intent.getScheme(); 4390 if (TextUtils.isEmpty(scheme)) { 4391 return false; 4392 } 4393 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4394 } 4395 4396 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4397 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4398 if (DEBUG_PREFERRED) { 4399 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4400 candidates.size()); 4401 } 4402 4403 final int userId = UserHandle.getCallingUserId(); 4404 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4405 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4406 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4407 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4408 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4409 4410 synchronized (mPackages) { 4411 final int count = candidates.size(); 4412 // First, try to use the domain prefered App. Partition the candidates into four lists: 4413 // one for the final results, one for the "do not use ever", one for "undefined status" 4414 // and finally one for "Browser App type". 4415 for (int n=0; n<count; n++) { 4416 ResolveInfo info = candidates.get(n); 4417 String packageName = info.activityInfo.packageName; 4418 PackageSetting ps = mSettings.mPackages.get(packageName); 4419 if (ps != null) { 4420 // Add to the special match all list (Browser use case) 4421 if (info.handleAllWebDataURI) { 4422 matchAllList.add(info); 4423 continue; 4424 } 4425 // Try to get the status from User settings first 4426 int status = getDomainVerificationStatusLPr(ps, userId); 4427 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4428 alwaysList.add(info); 4429 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4430 neverList.add(info); 4431 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4432 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4433 undefinedList.add(info); 4434 } 4435 } 4436 } 4437 // First try to add the "always" resolution for the current user if there is any 4438 if (alwaysList.size() > 0) { 4439 result.addAll(alwaysList); 4440 // if there is an "always" for the parent user, add it. 4441 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4442 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4443 result.add(xpDomainInfo.resolveInfo); 4444 } else { 4445 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4446 result.addAll(undefinedList); 4447 if (xpDomainInfo != null && ( 4448 xpDomainInfo.bestDomainVerificationStatus 4449 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4450 || xpDomainInfo.bestDomainVerificationStatus 4451 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4452 result.add(xpDomainInfo.resolveInfo); 4453 } 4454 // Also add Browsers (all of them or only the default one) 4455 if ((flags & MATCH_ALL) != 0) { 4456 result.addAll(matchAllList); 4457 } else { 4458 // Try to add the Default Browser if we can 4459 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4460 UserHandle.myUserId()); 4461 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4462 boolean defaultBrowserFound = false; 4463 final int browserCount = matchAllList.size(); 4464 for (int n=0; n<browserCount; n++) { 4465 ResolveInfo browser = matchAllList.get(n); 4466 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4467 result.add(browser); 4468 defaultBrowserFound = true; 4469 break; 4470 } 4471 } 4472 if (!defaultBrowserFound) { 4473 result.addAll(matchAllList); 4474 } 4475 } else { 4476 result.addAll(matchAllList); 4477 } 4478 } 4479 4480 // If there is nothing selected, add all candidates and remove the ones that the User 4481 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4482 if (result.size() == 0) { 4483 result.addAll(candidates); 4484 result.removeAll(neverList); 4485 } 4486 } 4487 } 4488 if (DEBUG_PREFERRED) { 4489 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4490 result.size()); 4491 } 4492 return result; 4493 } 4494 4495 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4496 int status = ps.getDomainVerificationStatusForUser(userId); 4497 // if none available, get the master status 4498 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4499 if (ps.getIntentFilterVerificationInfo() != null) { 4500 status = ps.getIntentFilterVerificationInfo().getStatus(); 4501 } 4502 } 4503 return status; 4504 } 4505 4506 private ResolveInfo querySkipCurrentProfileIntents( 4507 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4508 int flags, int sourceUserId) { 4509 if (matchingFilters != null) { 4510 int size = matchingFilters.size(); 4511 for (int i = 0; i < size; i ++) { 4512 CrossProfileIntentFilter filter = matchingFilters.get(i); 4513 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4514 // Checking if there are activities in the target user that can handle the 4515 // intent. 4516 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4517 flags, sourceUserId); 4518 if (resolveInfo != null) { 4519 return resolveInfo; 4520 } 4521 } 4522 } 4523 } 4524 return null; 4525 } 4526 4527 // Return matching ResolveInfo if any for skip current profile intent filters. 4528 private ResolveInfo queryCrossProfileIntents( 4529 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4530 int flags, int sourceUserId) { 4531 if (matchingFilters != null) { 4532 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4533 // match the same intent. For performance reasons, it is better not to 4534 // run queryIntent twice for the same userId 4535 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4536 int size = matchingFilters.size(); 4537 for (int i = 0; i < size; i++) { 4538 CrossProfileIntentFilter filter = matchingFilters.get(i); 4539 int targetUserId = filter.getTargetUserId(); 4540 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4541 && !alreadyTriedUserIds.get(targetUserId)) { 4542 // Checking if there are activities in the target user that can handle the 4543 // intent. 4544 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4545 flags, sourceUserId); 4546 if (resolveInfo != null) return resolveInfo; 4547 alreadyTriedUserIds.put(targetUserId, true); 4548 } 4549 } 4550 } 4551 return null; 4552 } 4553 4554 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4555 String resolvedType, int flags, int sourceUserId) { 4556 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4557 resolvedType, flags, filter.getTargetUserId()); 4558 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4559 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4560 } 4561 return null; 4562 } 4563 4564 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4565 int sourceUserId, int targetUserId) { 4566 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4567 String className; 4568 if (targetUserId == UserHandle.USER_OWNER) { 4569 className = FORWARD_INTENT_TO_USER_OWNER; 4570 } else { 4571 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4572 } 4573 ComponentName forwardingActivityComponentName = new ComponentName( 4574 mAndroidApplication.packageName, className); 4575 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4576 sourceUserId); 4577 if (targetUserId == UserHandle.USER_OWNER) { 4578 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4579 forwardingResolveInfo.noResourceId = true; 4580 } 4581 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4582 forwardingResolveInfo.priority = 0; 4583 forwardingResolveInfo.preferredOrder = 0; 4584 forwardingResolveInfo.match = 0; 4585 forwardingResolveInfo.isDefault = true; 4586 forwardingResolveInfo.filter = filter; 4587 forwardingResolveInfo.targetUserId = targetUserId; 4588 return forwardingResolveInfo; 4589 } 4590 4591 @Override 4592 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4593 Intent[] specifics, String[] specificTypes, Intent intent, 4594 String resolvedType, int flags, int userId) { 4595 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4596 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4597 false, "query intent activity options"); 4598 final String resultsAction = intent.getAction(); 4599 4600 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4601 | PackageManager.GET_RESOLVED_FILTER, userId); 4602 4603 if (DEBUG_INTENT_MATCHING) { 4604 Log.v(TAG, "Query " + intent + ": " + results); 4605 } 4606 4607 int specificsPos = 0; 4608 int N; 4609 4610 // todo: note that the algorithm used here is O(N^2). This 4611 // isn't a problem in our current environment, but if we start running 4612 // into situations where we have more than 5 or 10 matches then this 4613 // should probably be changed to something smarter... 4614 4615 // First we go through and resolve each of the specific items 4616 // that were supplied, taking care of removing any corresponding 4617 // duplicate items in the generic resolve list. 4618 if (specifics != null) { 4619 for (int i=0; i<specifics.length; i++) { 4620 final Intent sintent = specifics[i]; 4621 if (sintent == null) { 4622 continue; 4623 } 4624 4625 if (DEBUG_INTENT_MATCHING) { 4626 Log.v(TAG, "Specific #" + i + ": " + sintent); 4627 } 4628 4629 String action = sintent.getAction(); 4630 if (resultsAction != null && resultsAction.equals(action)) { 4631 // If this action was explicitly requested, then don't 4632 // remove things that have it. 4633 action = null; 4634 } 4635 4636 ResolveInfo ri = null; 4637 ActivityInfo ai = null; 4638 4639 ComponentName comp = sintent.getComponent(); 4640 if (comp == null) { 4641 ri = resolveIntent( 4642 sintent, 4643 specificTypes != null ? specificTypes[i] : null, 4644 flags, userId); 4645 if (ri == null) { 4646 continue; 4647 } 4648 if (ri == mResolveInfo) { 4649 // ACK! Must do something better with this. 4650 } 4651 ai = ri.activityInfo; 4652 comp = new ComponentName(ai.applicationInfo.packageName, 4653 ai.name); 4654 } else { 4655 ai = getActivityInfo(comp, flags, userId); 4656 if (ai == null) { 4657 continue; 4658 } 4659 } 4660 4661 // Look for any generic query activities that are duplicates 4662 // of this specific one, and remove them from the results. 4663 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4664 N = results.size(); 4665 int j; 4666 for (j=specificsPos; j<N; j++) { 4667 ResolveInfo sri = results.get(j); 4668 if ((sri.activityInfo.name.equals(comp.getClassName()) 4669 && sri.activityInfo.applicationInfo.packageName.equals( 4670 comp.getPackageName())) 4671 || (action != null && sri.filter.matchAction(action))) { 4672 results.remove(j); 4673 if (DEBUG_INTENT_MATCHING) Log.v( 4674 TAG, "Removing duplicate item from " + j 4675 + " due to specific " + specificsPos); 4676 if (ri == null) { 4677 ri = sri; 4678 } 4679 j--; 4680 N--; 4681 } 4682 } 4683 4684 // Add this specific item to its proper place. 4685 if (ri == null) { 4686 ri = new ResolveInfo(); 4687 ri.activityInfo = ai; 4688 } 4689 results.add(specificsPos, ri); 4690 ri.specificIndex = i; 4691 specificsPos++; 4692 } 4693 } 4694 4695 // Now we go through the remaining generic results and remove any 4696 // duplicate actions that are found here. 4697 N = results.size(); 4698 for (int i=specificsPos; i<N-1; i++) { 4699 final ResolveInfo rii = results.get(i); 4700 if (rii.filter == null) { 4701 continue; 4702 } 4703 4704 // Iterate over all of the actions of this result's intent 4705 // filter... typically this should be just one. 4706 final Iterator<String> it = rii.filter.actionsIterator(); 4707 if (it == null) { 4708 continue; 4709 } 4710 while (it.hasNext()) { 4711 final String action = it.next(); 4712 if (resultsAction != null && resultsAction.equals(action)) { 4713 // If this action was explicitly requested, then don't 4714 // remove things that have it. 4715 continue; 4716 } 4717 for (int j=i+1; j<N; j++) { 4718 final ResolveInfo rij = results.get(j); 4719 if (rij.filter != null && rij.filter.hasAction(action)) { 4720 results.remove(j); 4721 if (DEBUG_INTENT_MATCHING) Log.v( 4722 TAG, "Removing duplicate item from " + j 4723 + " due to action " + action + " at " + i); 4724 j--; 4725 N--; 4726 } 4727 } 4728 } 4729 4730 // If the caller didn't request filter information, drop it now 4731 // so we don't have to marshall/unmarshall it. 4732 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4733 rii.filter = null; 4734 } 4735 } 4736 4737 // Filter out the caller activity if so requested. 4738 if (caller != null) { 4739 N = results.size(); 4740 for (int i=0; i<N; i++) { 4741 ActivityInfo ainfo = results.get(i).activityInfo; 4742 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4743 && caller.getClassName().equals(ainfo.name)) { 4744 results.remove(i); 4745 break; 4746 } 4747 } 4748 } 4749 4750 // If the caller didn't request filter information, 4751 // drop them now so we don't have to 4752 // marshall/unmarshall it. 4753 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4754 N = results.size(); 4755 for (int i=0; i<N; i++) { 4756 results.get(i).filter = null; 4757 } 4758 } 4759 4760 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4761 return results; 4762 } 4763 4764 @Override 4765 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4766 int userId) { 4767 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4768 ComponentName comp = intent.getComponent(); 4769 if (comp == null) { 4770 if (intent.getSelector() != null) { 4771 intent = intent.getSelector(); 4772 comp = intent.getComponent(); 4773 } 4774 } 4775 if (comp != null) { 4776 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4777 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4778 if (ai != null) { 4779 ResolveInfo ri = new ResolveInfo(); 4780 ri.activityInfo = ai; 4781 list.add(ri); 4782 } 4783 return list; 4784 } 4785 4786 // reader 4787 synchronized (mPackages) { 4788 String pkgName = intent.getPackage(); 4789 if (pkgName == null) { 4790 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4791 } 4792 final PackageParser.Package pkg = mPackages.get(pkgName); 4793 if (pkg != null) { 4794 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4795 userId); 4796 } 4797 return null; 4798 } 4799 } 4800 4801 @Override 4802 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4803 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4804 if (!sUserManager.exists(userId)) return null; 4805 if (query != null) { 4806 if (query.size() >= 1) { 4807 // If there is more than one service with the same priority, 4808 // just arbitrarily pick the first one. 4809 return query.get(0); 4810 } 4811 } 4812 return null; 4813 } 4814 4815 @Override 4816 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4817 int userId) { 4818 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4819 ComponentName comp = intent.getComponent(); 4820 if (comp == null) { 4821 if (intent.getSelector() != null) { 4822 intent = intent.getSelector(); 4823 comp = intent.getComponent(); 4824 } 4825 } 4826 if (comp != null) { 4827 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4828 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4829 if (si != null) { 4830 final ResolveInfo ri = new ResolveInfo(); 4831 ri.serviceInfo = si; 4832 list.add(ri); 4833 } 4834 return list; 4835 } 4836 4837 // reader 4838 synchronized (mPackages) { 4839 String pkgName = intent.getPackage(); 4840 if (pkgName == null) { 4841 return mServices.queryIntent(intent, resolvedType, flags, userId); 4842 } 4843 final PackageParser.Package pkg = mPackages.get(pkgName); 4844 if (pkg != null) { 4845 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4846 userId); 4847 } 4848 return null; 4849 } 4850 } 4851 4852 @Override 4853 public List<ResolveInfo> queryIntentContentProviders( 4854 Intent intent, String resolvedType, int flags, int userId) { 4855 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4856 ComponentName comp = intent.getComponent(); 4857 if (comp == null) { 4858 if (intent.getSelector() != null) { 4859 intent = intent.getSelector(); 4860 comp = intent.getComponent(); 4861 } 4862 } 4863 if (comp != null) { 4864 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4865 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4866 if (pi != null) { 4867 final ResolveInfo ri = new ResolveInfo(); 4868 ri.providerInfo = pi; 4869 list.add(ri); 4870 } 4871 return list; 4872 } 4873 4874 // reader 4875 synchronized (mPackages) { 4876 String pkgName = intent.getPackage(); 4877 if (pkgName == null) { 4878 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4879 } 4880 final PackageParser.Package pkg = mPackages.get(pkgName); 4881 if (pkg != null) { 4882 return mProviders.queryIntentForPackage( 4883 intent, resolvedType, flags, pkg.providers, userId); 4884 } 4885 return null; 4886 } 4887 } 4888 4889 @Override 4890 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4891 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4892 4893 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4894 4895 // writer 4896 synchronized (mPackages) { 4897 ArrayList<PackageInfo> list; 4898 if (listUninstalled) { 4899 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4900 for (PackageSetting ps : mSettings.mPackages.values()) { 4901 PackageInfo pi; 4902 if (ps.pkg != null) { 4903 pi = generatePackageInfo(ps.pkg, flags, userId); 4904 } else { 4905 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4906 } 4907 if (pi != null) { 4908 list.add(pi); 4909 } 4910 } 4911 } else { 4912 list = new ArrayList<PackageInfo>(mPackages.size()); 4913 for (PackageParser.Package p : mPackages.values()) { 4914 PackageInfo pi = generatePackageInfo(p, flags, userId); 4915 if (pi != null) { 4916 list.add(pi); 4917 } 4918 } 4919 } 4920 4921 return new ParceledListSlice<PackageInfo>(list); 4922 } 4923 } 4924 4925 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4926 String[] permissions, boolean[] tmp, int flags, int userId) { 4927 int numMatch = 0; 4928 final PermissionsState permissionsState = ps.getPermissionsState(); 4929 for (int i=0; i<permissions.length; i++) { 4930 final String permission = permissions[i]; 4931 if (permissionsState.hasPermission(permission, userId)) { 4932 tmp[i] = true; 4933 numMatch++; 4934 } else { 4935 tmp[i] = false; 4936 } 4937 } 4938 if (numMatch == 0) { 4939 return; 4940 } 4941 PackageInfo pi; 4942 if (ps.pkg != null) { 4943 pi = generatePackageInfo(ps.pkg, flags, userId); 4944 } else { 4945 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4946 } 4947 // The above might return null in cases of uninstalled apps or install-state 4948 // skew across users/profiles. 4949 if (pi != null) { 4950 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4951 if (numMatch == permissions.length) { 4952 pi.requestedPermissions = permissions; 4953 } else { 4954 pi.requestedPermissions = new String[numMatch]; 4955 numMatch = 0; 4956 for (int i=0; i<permissions.length; i++) { 4957 if (tmp[i]) { 4958 pi.requestedPermissions[numMatch] = permissions[i]; 4959 numMatch++; 4960 } 4961 } 4962 } 4963 } 4964 list.add(pi); 4965 } 4966 } 4967 4968 @Override 4969 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4970 String[] permissions, int flags, int userId) { 4971 if (!sUserManager.exists(userId)) return null; 4972 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4973 4974 // writer 4975 synchronized (mPackages) { 4976 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4977 boolean[] tmpBools = new boolean[permissions.length]; 4978 if (listUninstalled) { 4979 for (PackageSetting ps : mSettings.mPackages.values()) { 4980 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4981 } 4982 } else { 4983 for (PackageParser.Package pkg : mPackages.values()) { 4984 PackageSetting ps = (PackageSetting)pkg.mExtras; 4985 if (ps != null) { 4986 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4987 userId); 4988 } 4989 } 4990 } 4991 4992 return new ParceledListSlice<PackageInfo>(list); 4993 } 4994 } 4995 4996 @Override 4997 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4998 if (!sUserManager.exists(userId)) return null; 4999 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5000 5001 // writer 5002 synchronized (mPackages) { 5003 ArrayList<ApplicationInfo> list; 5004 if (listUninstalled) { 5005 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5006 for (PackageSetting ps : mSettings.mPackages.values()) { 5007 ApplicationInfo ai; 5008 if (ps.pkg != null) { 5009 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5010 ps.readUserState(userId), userId); 5011 } else { 5012 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5013 } 5014 if (ai != null) { 5015 list.add(ai); 5016 } 5017 } 5018 } else { 5019 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5020 for (PackageParser.Package p : mPackages.values()) { 5021 if (p.mExtras != null) { 5022 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5023 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5024 if (ai != null) { 5025 list.add(ai); 5026 } 5027 } 5028 } 5029 } 5030 5031 return new ParceledListSlice<ApplicationInfo>(list); 5032 } 5033 } 5034 5035 public List<ApplicationInfo> getPersistentApplications(int flags) { 5036 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5037 5038 // reader 5039 synchronized (mPackages) { 5040 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5041 final int userId = UserHandle.getCallingUserId(); 5042 while (i.hasNext()) { 5043 final PackageParser.Package p = i.next(); 5044 if (p.applicationInfo != null 5045 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5046 && (!mSafeMode || isSystemApp(p))) { 5047 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5048 if (ps != null) { 5049 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5050 ps.readUserState(userId), userId); 5051 if (ai != null) { 5052 finalList.add(ai); 5053 } 5054 } 5055 } 5056 } 5057 } 5058 5059 return finalList; 5060 } 5061 5062 @Override 5063 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5064 if (!sUserManager.exists(userId)) return null; 5065 // reader 5066 synchronized (mPackages) { 5067 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5068 PackageSetting ps = provider != null 5069 ? mSettings.mPackages.get(provider.owner.packageName) 5070 : null; 5071 return ps != null 5072 && mSettings.isEnabledLPr(provider.info, flags, userId) 5073 && (!mSafeMode || (provider.info.applicationInfo.flags 5074 &ApplicationInfo.FLAG_SYSTEM) != 0) 5075 ? PackageParser.generateProviderInfo(provider, flags, 5076 ps.readUserState(userId), userId) 5077 : null; 5078 } 5079 } 5080 5081 /** 5082 * @deprecated 5083 */ 5084 @Deprecated 5085 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5086 // reader 5087 synchronized (mPackages) { 5088 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5089 .entrySet().iterator(); 5090 final int userId = UserHandle.getCallingUserId(); 5091 while (i.hasNext()) { 5092 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5093 PackageParser.Provider p = entry.getValue(); 5094 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5095 5096 if (ps != null && p.syncable 5097 && (!mSafeMode || (p.info.applicationInfo.flags 5098 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5099 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5100 ps.readUserState(userId), userId); 5101 if (info != null) { 5102 outNames.add(entry.getKey()); 5103 outInfo.add(info); 5104 } 5105 } 5106 } 5107 } 5108 } 5109 5110 @Override 5111 public List<ProviderInfo> queryContentProviders(String processName, 5112 int uid, int flags) { 5113 ArrayList<ProviderInfo> finalList = null; 5114 // reader 5115 synchronized (mPackages) { 5116 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5117 final int userId = processName != null ? 5118 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5119 while (i.hasNext()) { 5120 final PackageParser.Provider p = i.next(); 5121 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5122 if (ps != null && p.info.authority != null 5123 && (processName == null 5124 || (p.info.processName.equals(processName) 5125 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5126 && mSettings.isEnabledLPr(p.info, flags, userId) 5127 && (!mSafeMode 5128 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5129 if (finalList == null) { 5130 finalList = new ArrayList<ProviderInfo>(3); 5131 } 5132 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5133 ps.readUserState(userId), userId); 5134 if (info != null) { 5135 finalList.add(info); 5136 } 5137 } 5138 } 5139 } 5140 5141 if (finalList != null) { 5142 Collections.sort(finalList, mProviderInitOrderSorter); 5143 } 5144 5145 return finalList; 5146 } 5147 5148 @Override 5149 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5150 int flags) { 5151 // reader 5152 synchronized (mPackages) { 5153 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5154 return PackageParser.generateInstrumentationInfo(i, flags); 5155 } 5156 } 5157 5158 @Override 5159 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5160 int flags) { 5161 ArrayList<InstrumentationInfo> finalList = 5162 new ArrayList<InstrumentationInfo>(); 5163 5164 // reader 5165 synchronized (mPackages) { 5166 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5167 while (i.hasNext()) { 5168 final PackageParser.Instrumentation p = i.next(); 5169 if (targetPackage == null 5170 || targetPackage.equals(p.info.targetPackage)) { 5171 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5172 flags); 5173 if (ii != null) { 5174 finalList.add(ii); 5175 } 5176 } 5177 } 5178 } 5179 5180 return finalList; 5181 } 5182 5183 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5184 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5185 if (overlays == null) { 5186 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5187 return; 5188 } 5189 for (PackageParser.Package opkg : overlays.values()) { 5190 // Not much to do if idmap fails: we already logged the error 5191 // and we certainly don't want to abort installation of pkg simply 5192 // because an overlay didn't fit properly. For these reasons, 5193 // ignore the return value of createIdmapForPackagePairLI. 5194 createIdmapForPackagePairLI(pkg, opkg); 5195 } 5196 } 5197 5198 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5199 PackageParser.Package opkg) { 5200 if (!opkg.mTrustedOverlay) { 5201 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5202 opkg.baseCodePath + ": overlay not trusted"); 5203 return false; 5204 } 5205 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5206 if (overlaySet == null) { 5207 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5208 opkg.baseCodePath + " but target package has no known overlays"); 5209 return false; 5210 } 5211 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5212 // TODO: generate idmap for split APKs 5213 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5214 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5215 + opkg.baseCodePath); 5216 return false; 5217 } 5218 PackageParser.Package[] overlayArray = 5219 overlaySet.values().toArray(new PackageParser.Package[0]); 5220 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5221 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5222 return p1.mOverlayPriority - p2.mOverlayPriority; 5223 } 5224 }; 5225 Arrays.sort(overlayArray, cmp); 5226 5227 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5228 int i = 0; 5229 for (PackageParser.Package p : overlayArray) { 5230 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5231 } 5232 return true; 5233 } 5234 5235 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5236 final File[] files = dir.listFiles(); 5237 if (ArrayUtils.isEmpty(files)) { 5238 Log.d(TAG, "No files in app dir " + dir); 5239 return; 5240 } 5241 5242 if (DEBUG_PACKAGE_SCANNING) { 5243 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5244 + " flags=0x" + Integer.toHexString(parseFlags)); 5245 } 5246 5247 for (File file : files) { 5248 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5249 && !PackageInstallerService.isStageName(file.getName()); 5250 if (!isPackage) { 5251 // Ignore entries which are not packages 5252 continue; 5253 } 5254 try { 5255 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5256 scanFlags, currentTime, null); 5257 } catch (PackageManagerException e) { 5258 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5259 5260 // Delete invalid userdata apps 5261 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5262 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5263 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5264 if (file.isDirectory()) { 5265 mInstaller.rmPackageDir(file.getAbsolutePath()); 5266 } else { 5267 file.delete(); 5268 } 5269 } 5270 } 5271 } 5272 } 5273 5274 private static File getSettingsProblemFile() { 5275 File dataDir = Environment.getDataDirectory(); 5276 File systemDir = new File(dataDir, "system"); 5277 File fname = new File(systemDir, "uiderrors.txt"); 5278 return fname; 5279 } 5280 5281 static void reportSettingsProblem(int priority, String msg) { 5282 logCriticalInfo(priority, msg); 5283 } 5284 5285 static void logCriticalInfo(int priority, String msg) { 5286 Slog.println(priority, TAG, msg); 5287 EventLogTags.writePmCriticalInfo(msg); 5288 try { 5289 File fname = getSettingsProblemFile(); 5290 FileOutputStream out = new FileOutputStream(fname, true); 5291 PrintWriter pw = new FastPrintWriter(out); 5292 SimpleDateFormat formatter = new SimpleDateFormat(); 5293 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5294 pw.println(dateString + ": " + msg); 5295 pw.close(); 5296 FileUtils.setPermissions( 5297 fname.toString(), 5298 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5299 -1, -1); 5300 } catch (java.io.IOException e) { 5301 } 5302 } 5303 5304 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5305 PackageParser.Package pkg, File srcFile, int parseFlags) 5306 throws PackageManagerException { 5307 if (ps != null 5308 && ps.codePath.equals(srcFile) 5309 && ps.timeStamp == srcFile.lastModified() 5310 && !isCompatSignatureUpdateNeeded(pkg) 5311 && !isRecoverSignatureUpdateNeeded(pkg)) { 5312 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5313 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5314 ArraySet<PublicKey> signingKs; 5315 synchronized (mPackages) { 5316 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5317 } 5318 if (ps.signatures.mSignatures != null 5319 && ps.signatures.mSignatures.length != 0 5320 && signingKs != null) { 5321 // Optimization: reuse the existing cached certificates 5322 // if the package appears to be unchanged. 5323 pkg.mSignatures = ps.signatures.mSignatures; 5324 pkg.mSigningKeys = signingKs; 5325 return; 5326 } 5327 5328 Slog.w(TAG, "PackageSetting for " + ps.name 5329 + " is missing signatures. Collecting certs again to recover them."); 5330 } else { 5331 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5332 } 5333 5334 try { 5335 pp.collectCertificates(pkg, parseFlags); 5336 pp.collectManifestDigest(pkg); 5337 } catch (PackageParserException e) { 5338 throw PackageManagerException.from(e); 5339 } 5340 } 5341 5342 /* 5343 * Scan a package and return the newly parsed package. 5344 * Returns null in case of errors and the error code is stored in mLastScanError 5345 */ 5346 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5347 long currentTime, UserHandle user) throws PackageManagerException { 5348 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5349 parseFlags |= mDefParseFlags; 5350 PackageParser pp = new PackageParser(); 5351 pp.setSeparateProcesses(mSeparateProcesses); 5352 pp.setOnlyCoreApps(mOnlyCore); 5353 pp.setDisplayMetrics(mMetrics); 5354 5355 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5356 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5357 } 5358 5359 final PackageParser.Package pkg; 5360 try { 5361 pkg = pp.parsePackage(scanFile, parseFlags); 5362 } catch (PackageParserException e) { 5363 throw PackageManagerException.from(e); 5364 } 5365 5366 PackageSetting ps = null; 5367 PackageSetting updatedPkg; 5368 // reader 5369 synchronized (mPackages) { 5370 // Look to see if we already know about this package. 5371 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5372 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5373 // This package has been renamed to its original name. Let's 5374 // use that. 5375 ps = mSettings.peekPackageLPr(oldName); 5376 } 5377 // If there was no original package, see one for the real package name. 5378 if (ps == null) { 5379 ps = mSettings.peekPackageLPr(pkg.packageName); 5380 } 5381 // Check to see if this package could be hiding/updating a system 5382 // package. Must look for it either under the original or real 5383 // package name depending on our state. 5384 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5385 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5386 } 5387 boolean updatedPkgBetter = false; 5388 // First check if this is a system package that may involve an update 5389 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5390 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5391 // it needs to drop FLAG_PRIVILEGED. 5392 if (locationIsPrivileged(scanFile)) { 5393 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5394 } else { 5395 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5396 } 5397 5398 if (ps != null && !ps.codePath.equals(scanFile)) { 5399 // The path has changed from what was last scanned... check the 5400 // version of the new path against what we have stored to determine 5401 // what to do. 5402 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5403 if (pkg.mVersionCode <= ps.versionCode) { 5404 // The system package has been updated and the code path does not match 5405 // Ignore entry. Skip it. 5406 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5407 + " ignored: updated version " + ps.versionCode 5408 + " better than this " + pkg.mVersionCode); 5409 if (!updatedPkg.codePath.equals(scanFile)) { 5410 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5411 + ps.name + " changing from " + updatedPkg.codePathString 5412 + " to " + scanFile); 5413 updatedPkg.codePath = scanFile; 5414 updatedPkg.codePathString = scanFile.toString(); 5415 updatedPkg.resourcePath = scanFile; 5416 updatedPkg.resourcePathString = scanFile.toString(); 5417 } 5418 updatedPkg.pkg = pkg; 5419 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5420 } else { 5421 // The current app on the system partition is better than 5422 // what we have updated to on the data partition; switch 5423 // back to the system partition version. 5424 // At this point, its safely assumed that package installation for 5425 // apps in system partition will go through. If not there won't be a working 5426 // version of the app 5427 // writer 5428 synchronized (mPackages) { 5429 // Just remove the loaded entries from package lists. 5430 mPackages.remove(ps.name); 5431 } 5432 5433 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5434 + " reverting from " + ps.codePathString 5435 + ": new version " + pkg.mVersionCode 5436 + " better than installed " + ps.versionCode); 5437 5438 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5439 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5440 synchronized (mInstallLock) { 5441 args.cleanUpResourcesLI(); 5442 } 5443 synchronized (mPackages) { 5444 mSettings.enableSystemPackageLPw(ps.name); 5445 } 5446 updatedPkgBetter = true; 5447 } 5448 } 5449 } 5450 5451 if (updatedPkg != null) { 5452 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5453 // initially 5454 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5455 5456 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5457 // flag set initially 5458 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5459 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5460 } 5461 } 5462 5463 // Verify certificates against what was last scanned 5464 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5465 5466 /* 5467 * A new system app appeared, but we already had a non-system one of the 5468 * same name installed earlier. 5469 */ 5470 boolean shouldHideSystemApp = false; 5471 if (updatedPkg == null && ps != null 5472 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5473 /* 5474 * Check to make sure the signatures match first. If they don't, 5475 * wipe the installed application and its data. 5476 */ 5477 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5478 != PackageManager.SIGNATURE_MATCH) { 5479 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5480 + " signatures don't match existing userdata copy; removing"); 5481 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5482 ps = null; 5483 } else { 5484 /* 5485 * If the newly-added system app is an older version than the 5486 * already installed version, hide it. It will be scanned later 5487 * and re-added like an update. 5488 */ 5489 if (pkg.mVersionCode <= ps.versionCode) { 5490 shouldHideSystemApp = true; 5491 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5492 + " but new version " + pkg.mVersionCode + " better than installed " 5493 + ps.versionCode + "; hiding system"); 5494 } else { 5495 /* 5496 * The newly found system app is a newer version that the 5497 * one previously installed. Simply remove the 5498 * already-installed application and replace it with our own 5499 * while keeping the application data. 5500 */ 5501 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5502 + " reverting from " + ps.codePathString + ": new version " 5503 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5504 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5505 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5506 synchronized (mInstallLock) { 5507 args.cleanUpResourcesLI(); 5508 } 5509 } 5510 } 5511 } 5512 5513 // The apk is forward locked (not public) if its code and resources 5514 // are kept in different files. (except for app in either system or 5515 // vendor path). 5516 // TODO grab this value from PackageSettings 5517 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5518 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5519 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5520 } 5521 } 5522 5523 // TODO: extend to support forward-locked splits 5524 String resourcePath = null; 5525 String baseResourcePath = null; 5526 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5527 if (ps != null && ps.resourcePathString != null) { 5528 resourcePath = ps.resourcePathString; 5529 baseResourcePath = ps.resourcePathString; 5530 } else { 5531 // Should not happen at all. Just log an error. 5532 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5533 } 5534 } else { 5535 resourcePath = pkg.codePath; 5536 baseResourcePath = pkg.baseCodePath; 5537 } 5538 5539 // Set application objects path explicitly. 5540 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5541 pkg.applicationInfo.setCodePath(pkg.codePath); 5542 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5543 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5544 pkg.applicationInfo.setResourcePath(resourcePath); 5545 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5546 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5547 5548 // Note that we invoke the following method only if we are about to unpack an application 5549 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5550 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5551 5552 /* 5553 * If the system app should be overridden by a previously installed 5554 * data, hide the system app now and let the /data/app scan pick it up 5555 * again. 5556 */ 5557 if (shouldHideSystemApp) { 5558 synchronized (mPackages) { 5559 /* 5560 * We have to grant systems permissions before we hide, because 5561 * grantPermissions will assume the package update is trying to 5562 * expand its permissions. 5563 */ 5564 grantPermissionsLPw(pkg, true, pkg.packageName); 5565 mSettings.disableSystemPackageLPw(pkg.packageName); 5566 } 5567 } 5568 5569 return scannedPkg; 5570 } 5571 5572 private static String fixProcessName(String defProcessName, 5573 String processName, int uid) { 5574 if (processName == null) { 5575 return defProcessName; 5576 } 5577 return processName; 5578 } 5579 5580 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5581 throws PackageManagerException { 5582 if (pkgSetting.signatures.mSignatures != null) { 5583 // Already existing package. Make sure signatures match 5584 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5585 == PackageManager.SIGNATURE_MATCH; 5586 if (!match) { 5587 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5588 == PackageManager.SIGNATURE_MATCH; 5589 } 5590 if (!match) { 5591 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5592 == PackageManager.SIGNATURE_MATCH; 5593 } 5594 if (!match) { 5595 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5596 + pkg.packageName + " signatures do not match the " 5597 + "previously installed version; ignoring!"); 5598 } 5599 } 5600 5601 // Check for shared user signatures 5602 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5603 // Already existing package. Make sure signatures match 5604 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5605 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5606 if (!match) { 5607 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5608 == PackageManager.SIGNATURE_MATCH; 5609 } 5610 if (!match) { 5611 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5612 == PackageManager.SIGNATURE_MATCH; 5613 } 5614 if (!match) { 5615 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5616 "Package " + pkg.packageName 5617 + " has no signatures that match those in shared user " 5618 + pkgSetting.sharedUser.name + "; ignoring!"); 5619 } 5620 } 5621 } 5622 5623 /** 5624 * Enforces that only the system UID or root's UID can call a method exposed 5625 * via Binder. 5626 * 5627 * @param message used as message if SecurityException is thrown 5628 * @throws SecurityException if the caller is not system or root 5629 */ 5630 private static final void enforceSystemOrRoot(String message) { 5631 final int uid = Binder.getCallingUid(); 5632 if (uid != Process.SYSTEM_UID && uid != 0) { 5633 throw new SecurityException(message); 5634 } 5635 } 5636 5637 @Override 5638 public void performBootDexOpt() { 5639 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5640 5641 // Before everything else, see whether we need to fstrim. 5642 try { 5643 IMountService ms = PackageHelper.getMountService(); 5644 if (ms != null) { 5645 final boolean isUpgrade = isUpgrade(); 5646 boolean doTrim = isUpgrade; 5647 if (doTrim) { 5648 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5649 } else { 5650 final long interval = android.provider.Settings.Global.getLong( 5651 mContext.getContentResolver(), 5652 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5653 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5654 if (interval > 0) { 5655 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5656 if (timeSinceLast > interval) { 5657 doTrim = true; 5658 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5659 + "; running immediately"); 5660 } 5661 } 5662 } 5663 if (doTrim) { 5664 if (!isFirstBoot()) { 5665 try { 5666 ActivityManagerNative.getDefault().showBootMessage( 5667 mContext.getResources().getString( 5668 R.string.android_upgrading_fstrim), true); 5669 } catch (RemoteException e) { 5670 } 5671 } 5672 ms.runMaintenance(); 5673 } 5674 } else { 5675 Slog.e(TAG, "Mount service unavailable!"); 5676 } 5677 } catch (RemoteException e) { 5678 // Can't happen; MountService is local 5679 } 5680 5681 final ArraySet<PackageParser.Package> pkgs; 5682 synchronized (mPackages) { 5683 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5684 } 5685 5686 if (pkgs != null) { 5687 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5688 // in case the device runs out of space. 5689 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5690 // Give priority to core apps. 5691 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5692 PackageParser.Package pkg = it.next(); 5693 if (pkg.coreApp) { 5694 if (DEBUG_DEXOPT) { 5695 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5696 } 5697 sortedPkgs.add(pkg); 5698 it.remove(); 5699 } 5700 } 5701 // Give priority to system apps that listen for pre boot complete. 5702 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5703 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5704 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5705 PackageParser.Package pkg = it.next(); 5706 if (pkgNames.contains(pkg.packageName)) { 5707 if (DEBUG_DEXOPT) { 5708 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5709 } 5710 sortedPkgs.add(pkg); 5711 it.remove(); 5712 } 5713 } 5714 // Give priority to system apps. 5715 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5716 PackageParser.Package pkg = it.next(); 5717 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5718 if (DEBUG_DEXOPT) { 5719 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5720 } 5721 sortedPkgs.add(pkg); 5722 it.remove(); 5723 } 5724 } 5725 // Give priority to updated system apps. 5726 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5727 PackageParser.Package pkg = it.next(); 5728 if (pkg.isUpdatedSystemApp()) { 5729 if (DEBUG_DEXOPT) { 5730 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5731 } 5732 sortedPkgs.add(pkg); 5733 it.remove(); 5734 } 5735 } 5736 // Give priority to apps that listen for boot complete. 5737 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5738 pkgNames = getPackageNamesForIntent(intent); 5739 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5740 PackageParser.Package pkg = it.next(); 5741 if (pkgNames.contains(pkg.packageName)) { 5742 if (DEBUG_DEXOPT) { 5743 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5744 } 5745 sortedPkgs.add(pkg); 5746 it.remove(); 5747 } 5748 } 5749 // Filter out packages that aren't recently used. 5750 filterRecentlyUsedApps(pkgs); 5751 // Add all remaining apps. 5752 for (PackageParser.Package pkg : pkgs) { 5753 if (DEBUG_DEXOPT) { 5754 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5755 } 5756 sortedPkgs.add(pkg); 5757 } 5758 5759 // If we want to be lazy, filter everything that wasn't recently used. 5760 if (mLazyDexOpt) { 5761 filterRecentlyUsedApps(sortedPkgs); 5762 } 5763 5764 int i = 0; 5765 int total = sortedPkgs.size(); 5766 File dataDir = Environment.getDataDirectory(); 5767 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5768 if (lowThreshold == 0) { 5769 throw new IllegalStateException("Invalid low memory threshold"); 5770 } 5771 for (PackageParser.Package pkg : sortedPkgs) { 5772 long usableSpace = dataDir.getUsableSpace(); 5773 if (usableSpace < lowThreshold) { 5774 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5775 break; 5776 } 5777 performBootDexOpt(pkg, ++i, total); 5778 } 5779 } 5780 } 5781 5782 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5783 // Filter out packages that aren't recently used. 5784 // 5785 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5786 // should do a full dexopt. 5787 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5788 int total = pkgs.size(); 5789 int skipped = 0; 5790 long now = System.currentTimeMillis(); 5791 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5792 PackageParser.Package pkg = i.next(); 5793 long then = pkg.mLastPackageUsageTimeInMills; 5794 if (then + mDexOptLRUThresholdInMills < now) { 5795 if (DEBUG_DEXOPT) { 5796 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5797 ((then == 0) ? "never" : new Date(then))); 5798 } 5799 i.remove(); 5800 skipped++; 5801 } 5802 } 5803 if (DEBUG_DEXOPT) { 5804 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5805 } 5806 } 5807 } 5808 5809 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5810 List<ResolveInfo> ris = null; 5811 try { 5812 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5813 intent, null, 0, UserHandle.USER_OWNER); 5814 } catch (RemoteException e) { 5815 } 5816 ArraySet<String> pkgNames = new ArraySet<String>(); 5817 if (ris != null) { 5818 for (ResolveInfo ri : ris) { 5819 pkgNames.add(ri.activityInfo.packageName); 5820 } 5821 } 5822 return pkgNames; 5823 } 5824 5825 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5826 if (DEBUG_DEXOPT) { 5827 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5828 } 5829 if (!isFirstBoot()) { 5830 try { 5831 ActivityManagerNative.getDefault().showBootMessage( 5832 mContext.getResources().getString(R.string.android_upgrading_apk, 5833 curr, total), true); 5834 } catch (RemoteException e) { 5835 } 5836 } 5837 PackageParser.Package p = pkg; 5838 synchronized (mInstallLock) { 5839 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5840 false /* force dex */, false /* defer */, true /* include dependencies */); 5841 } 5842 } 5843 5844 @Override 5845 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5846 return performDexOpt(packageName, instructionSet, false); 5847 } 5848 5849 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5850 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5851 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5852 if (!dexopt && !updateUsage) { 5853 // We aren't going to dexopt or update usage, so bail early. 5854 return false; 5855 } 5856 PackageParser.Package p; 5857 final String targetInstructionSet; 5858 synchronized (mPackages) { 5859 p = mPackages.get(packageName); 5860 if (p == null) { 5861 return false; 5862 } 5863 if (updateUsage) { 5864 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5865 } 5866 mPackageUsage.write(false); 5867 if (!dexopt) { 5868 // We aren't going to dexopt, so bail early. 5869 return false; 5870 } 5871 5872 targetInstructionSet = instructionSet != null ? instructionSet : 5873 getPrimaryInstructionSet(p.applicationInfo); 5874 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5875 return false; 5876 } 5877 } 5878 5879 synchronized (mInstallLock) { 5880 final String[] instructionSets = new String[] { targetInstructionSet }; 5881 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5882 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5883 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5884 } 5885 } 5886 5887 public ArraySet<String> getPackagesThatNeedDexOpt() { 5888 ArraySet<String> pkgs = null; 5889 synchronized (mPackages) { 5890 for (PackageParser.Package p : mPackages.values()) { 5891 if (DEBUG_DEXOPT) { 5892 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5893 } 5894 if (!p.mDexOptPerformed.isEmpty()) { 5895 continue; 5896 } 5897 if (pkgs == null) { 5898 pkgs = new ArraySet<String>(); 5899 } 5900 pkgs.add(p.packageName); 5901 } 5902 } 5903 return pkgs; 5904 } 5905 5906 public void shutdown() { 5907 mPackageUsage.write(true); 5908 } 5909 5910 @Override 5911 public void forceDexOpt(String packageName) { 5912 enforceSystemOrRoot("forceDexOpt"); 5913 5914 PackageParser.Package pkg; 5915 synchronized (mPackages) { 5916 pkg = mPackages.get(packageName); 5917 if (pkg == null) { 5918 throw new IllegalArgumentException("Missing package: " + packageName); 5919 } 5920 } 5921 5922 synchronized (mInstallLock) { 5923 final String[] instructionSets = new String[] { 5924 getPrimaryInstructionSet(pkg.applicationInfo) }; 5925 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5926 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5927 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5928 throw new IllegalStateException("Failed to dexopt: " + res); 5929 } 5930 } 5931 } 5932 5933 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5934 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5935 Slog.w(TAG, "Unable to update from " + oldPkg.name 5936 + " to " + newPkg.packageName 5937 + ": old package not in system partition"); 5938 return false; 5939 } else if (mPackages.get(oldPkg.name) != null) { 5940 Slog.w(TAG, "Unable to update from " + oldPkg.name 5941 + " to " + newPkg.packageName 5942 + ": old package still exists"); 5943 return false; 5944 } 5945 return true; 5946 } 5947 5948 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5949 int[] users = sUserManager.getUserIds(); 5950 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5951 if (res < 0) { 5952 return res; 5953 } 5954 for (int user : users) { 5955 if (user != 0) { 5956 res = mInstaller.createUserData(volumeUuid, packageName, 5957 UserHandle.getUid(user, uid), user, seinfo); 5958 if (res < 0) { 5959 return res; 5960 } 5961 } 5962 } 5963 return res; 5964 } 5965 5966 private int removeDataDirsLI(String volumeUuid, String packageName) { 5967 int[] users = sUserManager.getUserIds(); 5968 int res = 0; 5969 for (int user : users) { 5970 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5971 if (resInner < 0) { 5972 res = resInner; 5973 } 5974 } 5975 5976 return res; 5977 } 5978 5979 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5980 int[] users = sUserManager.getUserIds(); 5981 int res = 0; 5982 for (int user : users) { 5983 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5984 if (resInner < 0) { 5985 res = resInner; 5986 } 5987 } 5988 return res; 5989 } 5990 5991 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5992 PackageParser.Package changingLib) { 5993 if (file.path != null) { 5994 usesLibraryFiles.add(file.path); 5995 return; 5996 } 5997 PackageParser.Package p = mPackages.get(file.apk); 5998 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5999 // If we are doing this while in the middle of updating a library apk, 6000 // then we need to make sure to use that new apk for determining the 6001 // dependencies here. (We haven't yet finished committing the new apk 6002 // to the package manager state.) 6003 if (p == null || p.packageName.equals(changingLib.packageName)) { 6004 p = changingLib; 6005 } 6006 } 6007 if (p != null) { 6008 usesLibraryFiles.addAll(p.getAllCodePaths()); 6009 } 6010 } 6011 6012 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6013 PackageParser.Package changingLib) throws PackageManagerException { 6014 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6015 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6016 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6017 for (int i=0; i<N; i++) { 6018 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6019 if (file == null) { 6020 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6021 "Package " + pkg.packageName + " requires unavailable shared library " 6022 + pkg.usesLibraries.get(i) + "; failing!"); 6023 } 6024 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6025 } 6026 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6027 for (int i=0; i<N; i++) { 6028 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6029 if (file == null) { 6030 Slog.w(TAG, "Package " + pkg.packageName 6031 + " desires unavailable shared library " 6032 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6033 } else { 6034 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6035 } 6036 } 6037 N = usesLibraryFiles.size(); 6038 if (N > 0) { 6039 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6040 } else { 6041 pkg.usesLibraryFiles = null; 6042 } 6043 } 6044 } 6045 6046 private static boolean hasString(List<String> list, List<String> which) { 6047 if (list == null) { 6048 return false; 6049 } 6050 for (int i=list.size()-1; i>=0; i--) { 6051 for (int j=which.size()-1; j>=0; j--) { 6052 if (which.get(j).equals(list.get(i))) { 6053 return true; 6054 } 6055 } 6056 } 6057 return false; 6058 } 6059 6060 private void updateAllSharedLibrariesLPw() { 6061 for (PackageParser.Package pkg : mPackages.values()) { 6062 try { 6063 updateSharedLibrariesLPw(pkg, null); 6064 } catch (PackageManagerException e) { 6065 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6066 } 6067 } 6068 } 6069 6070 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6071 PackageParser.Package changingPkg) { 6072 ArrayList<PackageParser.Package> res = null; 6073 for (PackageParser.Package pkg : mPackages.values()) { 6074 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6075 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6076 if (res == null) { 6077 res = new ArrayList<PackageParser.Package>(); 6078 } 6079 res.add(pkg); 6080 try { 6081 updateSharedLibrariesLPw(pkg, changingPkg); 6082 } catch (PackageManagerException e) { 6083 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6084 } 6085 } 6086 } 6087 return res; 6088 } 6089 6090 /** 6091 * Derive the value of the {@code cpuAbiOverride} based on the provided 6092 * value and an optional stored value from the package settings. 6093 */ 6094 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6095 String cpuAbiOverride = null; 6096 6097 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6098 cpuAbiOverride = null; 6099 } else if (abiOverride != null) { 6100 cpuAbiOverride = abiOverride; 6101 } else if (settings != null) { 6102 cpuAbiOverride = settings.cpuAbiOverrideString; 6103 } 6104 6105 return cpuAbiOverride; 6106 } 6107 6108 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6109 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6110 boolean success = false; 6111 try { 6112 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6113 currentTime, user); 6114 success = true; 6115 return res; 6116 } finally { 6117 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6118 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6119 } 6120 } 6121 } 6122 6123 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6124 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6125 final File scanFile = new File(pkg.codePath); 6126 if (pkg.applicationInfo.getCodePath() == null || 6127 pkg.applicationInfo.getResourcePath() == null) { 6128 // Bail out. The resource and code paths haven't been set. 6129 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6130 "Code and resource paths haven't been set correctly"); 6131 } 6132 6133 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6134 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6135 } else { 6136 // Only allow system apps to be flagged as core apps. 6137 pkg.coreApp = false; 6138 } 6139 6140 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6141 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6142 } 6143 6144 if (mCustomResolverComponentName != null && 6145 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6146 setUpCustomResolverActivity(pkg); 6147 } 6148 6149 if (pkg.packageName.equals("android")) { 6150 synchronized (mPackages) { 6151 if (mAndroidApplication != null) { 6152 Slog.w(TAG, "*************************************************"); 6153 Slog.w(TAG, "Core android package being redefined. Skipping."); 6154 Slog.w(TAG, " file=" + scanFile); 6155 Slog.w(TAG, "*************************************************"); 6156 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6157 "Core android package being redefined. Skipping."); 6158 } 6159 6160 // Set up information for our fall-back user intent resolution activity. 6161 mPlatformPackage = pkg; 6162 pkg.mVersionCode = mSdkVersion; 6163 mAndroidApplication = pkg.applicationInfo; 6164 6165 if (!mResolverReplaced) { 6166 mResolveActivity.applicationInfo = mAndroidApplication; 6167 mResolveActivity.name = ResolverActivity.class.getName(); 6168 mResolveActivity.packageName = mAndroidApplication.packageName; 6169 mResolveActivity.processName = "system:ui"; 6170 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6171 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6172 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6173 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6174 mResolveActivity.exported = true; 6175 mResolveActivity.enabled = true; 6176 mResolveInfo.activityInfo = mResolveActivity; 6177 mResolveInfo.priority = 0; 6178 mResolveInfo.preferredOrder = 0; 6179 mResolveInfo.match = 0; 6180 mResolveComponentName = new ComponentName( 6181 mAndroidApplication.packageName, mResolveActivity.name); 6182 } 6183 } 6184 } 6185 6186 if (DEBUG_PACKAGE_SCANNING) { 6187 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6188 Log.d(TAG, "Scanning package " + pkg.packageName); 6189 } 6190 6191 if (mPackages.containsKey(pkg.packageName) 6192 || mSharedLibraries.containsKey(pkg.packageName)) { 6193 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6194 "Application package " + pkg.packageName 6195 + " already installed. Skipping duplicate."); 6196 } 6197 6198 // If we're only installing presumed-existing packages, require that the 6199 // scanned APK is both already known and at the path previously established 6200 // for it. Previously unknown packages we pick up normally, but if we have an 6201 // a priori expectation about this package's install presence, enforce it. 6202 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6203 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6204 if (known != null) { 6205 if (DEBUG_PACKAGE_SCANNING) { 6206 Log.d(TAG, "Examining " + pkg.codePath 6207 + " and requiring known paths " + known.codePathString 6208 + " & " + known.resourcePathString); 6209 } 6210 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6211 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6212 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6213 "Application package " + pkg.packageName 6214 + " found at " + pkg.applicationInfo.getCodePath() 6215 + " but expected at " + known.codePathString + "; ignoring."); 6216 } 6217 } 6218 } 6219 6220 // Initialize package source and resource directories 6221 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6222 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6223 6224 SharedUserSetting suid = null; 6225 PackageSetting pkgSetting = null; 6226 6227 if (!isSystemApp(pkg)) { 6228 // Only system apps can use these features. 6229 pkg.mOriginalPackages = null; 6230 pkg.mRealPackage = null; 6231 pkg.mAdoptPermissions = null; 6232 } 6233 6234 // writer 6235 synchronized (mPackages) { 6236 if (pkg.mSharedUserId != null) { 6237 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6238 if (suid == null) { 6239 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6240 "Creating application package " + pkg.packageName 6241 + " for shared user failed"); 6242 } 6243 if (DEBUG_PACKAGE_SCANNING) { 6244 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6245 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6246 + "): packages=" + suid.packages); 6247 } 6248 } 6249 6250 // Check if we are renaming from an original package name. 6251 PackageSetting origPackage = null; 6252 String realName = null; 6253 if (pkg.mOriginalPackages != null) { 6254 // This package may need to be renamed to a previously 6255 // installed name. Let's check on that... 6256 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6257 if (pkg.mOriginalPackages.contains(renamed)) { 6258 // This package had originally been installed as the 6259 // original name, and we have already taken care of 6260 // transitioning to the new one. Just update the new 6261 // one to continue using the old name. 6262 realName = pkg.mRealPackage; 6263 if (!pkg.packageName.equals(renamed)) { 6264 // Callers into this function may have already taken 6265 // care of renaming the package; only do it here if 6266 // it is not already done. 6267 pkg.setPackageName(renamed); 6268 } 6269 6270 } else { 6271 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6272 if ((origPackage = mSettings.peekPackageLPr( 6273 pkg.mOriginalPackages.get(i))) != null) { 6274 // We do have the package already installed under its 6275 // original name... should we use it? 6276 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6277 // New package is not compatible with original. 6278 origPackage = null; 6279 continue; 6280 } else if (origPackage.sharedUser != null) { 6281 // Make sure uid is compatible between packages. 6282 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6283 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6284 + " to " + pkg.packageName + ": old uid " 6285 + origPackage.sharedUser.name 6286 + " differs from " + pkg.mSharedUserId); 6287 origPackage = null; 6288 continue; 6289 } 6290 } else { 6291 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6292 + pkg.packageName + " to old name " + origPackage.name); 6293 } 6294 break; 6295 } 6296 } 6297 } 6298 } 6299 6300 if (mTransferedPackages.contains(pkg.packageName)) { 6301 Slog.w(TAG, "Package " + pkg.packageName 6302 + " was transferred to another, but its .apk remains"); 6303 } 6304 6305 // Just create the setting, don't add it yet. For already existing packages 6306 // the PkgSetting exists already and doesn't have to be created. 6307 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6308 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6309 pkg.applicationInfo.primaryCpuAbi, 6310 pkg.applicationInfo.secondaryCpuAbi, 6311 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6312 user, false); 6313 if (pkgSetting == null) { 6314 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6315 "Creating application package " + pkg.packageName + " failed"); 6316 } 6317 6318 if (pkgSetting.origPackage != null) { 6319 // If we are first transitioning from an original package, 6320 // fix up the new package's name now. We need to do this after 6321 // looking up the package under its new name, so getPackageLP 6322 // can take care of fiddling things correctly. 6323 pkg.setPackageName(origPackage.name); 6324 6325 // File a report about this. 6326 String msg = "New package " + pkgSetting.realName 6327 + " renamed to replace old package " + pkgSetting.name; 6328 reportSettingsProblem(Log.WARN, msg); 6329 6330 // Make a note of it. 6331 mTransferedPackages.add(origPackage.name); 6332 6333 // No longer need to retain this. 6334 pkgSetting.origPackage = null; 6335 } 6336 6337 if (realName != null) { 6338 // Make a note of it. 6339 mTransferedPackages.add(pkg.packageName); 6340 } 6341 6342 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6343 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6344 } 6345 6346 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6347 // Check all shared libraries and map to their actual file path. 6348 // We only do this here for apps not on a system dir, because those 6349 // are the only ones that can fail an install due to this. We 6350 // will take care of the system apps by updating all of their 6351 // library paths after the scan is done. 6352 updateSharedLibrariesLPw(pkg, null); 6353 } 6354 6355 if (mFoundPolicyFile) { 6356 SELinuxMMAC.assignSeinfoValue(pkg); 6357 } 6358 6359 pkg.applicationInfo.uid = pkgSetting.appId; 6360 pkg.mExtras = pkgSetting; 6361 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6362 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6363 // We just determined the app is signed correctly, so bring 6364 // over the latest parsed certs. 6365 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6366 } else { 6367 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6368 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6369 "Package " + pkg.packageName + " upgrade keys do not match the " 6370 + "previously installed version"); 6371 } else { 6372 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6373 String msg = "System package " + pkg.packageName 6374 + " signature changed; retaining data."; 6375 reportSettingsProblem(Log.WARN, msg); 6376 } 6377 } 6378 } else { 6379 try { 6380 verifySignaturesLP(pkgSetting, pkg); 6381 // We just determined the app is signed correctly, so bring 6382 // over the latest parsed certs. 6383 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6384 } catch (PackageManagerException e) { 6385 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6386 throw e; 6387 } 6388 // The signature has changed, but this package is in the system 6389 // image... let's recover! 6390 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6391 // However... if this package is part of a shared user, but it 6392 // doesn't match the signature of the shared user, let's fail. 6393 // What this means is that you can't change the signatures 6394 // associated with an overall shared user, which doesn't seem all 6395 // that unreasonable. 6396 if (pkgSetting.sharedUser != null) { 6397 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6398 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6399 throw new PackageManagerException( 6400 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6401 "Signature mismatch for shared user : " 6402 + pkgSetting.sharedUser); 6403 } 6404 } 6405 // File a report about this. 6406 String msg = "System package " + pkg.packageName 6407 + " signature changed; retaining data."; 6408 reportSettingsProblem(Log.WARN, msg); 6409 } 6410 } 6411 // Verify that this new package doesn't have any content providers 6412 // that conflict with existing packages. Only do this if the 6413 // package isn't already installed, since we don't want to break 6414 // things that are installed. 6415 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6416 final int N = pkg.providers.size(); 6417 int i; 6418 for (i=0; i<N; i++) { 6419 PackageParser.Provider p = pkg.providers.get(i); 6420 if (p.info.authority != null) { 6421 String names[] = p.info.authority.split(";"); 6422 for (int j = 0; j < names.length; j++) { 6423 if (mProvidersByAuthority.containsKey(names[j])) { 6424 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6425 final String otherPackageName = 6426 ((other != null && other.getComponentName() != null) ? 6427 other.getComponentName().getPackageName() : "?"); 6428 throw new PackageManagerException( 6429 INSTALL_FAILED_CONFLICTING_PROVIDER, 6430 "Can't install because provider name " + names[j] 6431 + " (in package " + pkg.applicationInfo.packageName 6432 + ") is already used by " + otherPackageName); 6433 } 6434 } 6435 } 6436 } 6437 } 6438 6439 if (pkg.mAdoptPermissions != null) { 6440 // This package wants to adopt ownership of permissions from 6441 // another package. 6442 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6443 final String origName = pkg.mAdoptPermissions.get(i); 6444 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6445 if (orig != null) { 6446 if (verifyPackageUpdateLPr(orig, pkg)) { 6447 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6448 + pkg.packageName); 6449 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6450 } 6451 } 6452 } 6453 } 6454 } 6455 6456 final String pkgName = pkg.packageName; 6457 6458 final long scanFileTime = scanFile.lastModified(); 6459 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6460 pkg.applicationInfo.processName = fixProcessName( 6461 pkg.applicationInfo.packageName, 6462 pkg.applicationInfo.processName, 6463 pkg.applicationInfo.uid); 6464 6465 File dataPath; 6466 if (mPlatformPackage == pkg) { 6467 // The system package is special. 6468 dataPath = new File(Environment.getDataDirectory(), "system"); 6469 6470 pkg.applicationInfo.dataDir = dataPath.getPath(); 6471 6472 } else { 6473 // This is a normal package, need to make its data directory. 6474 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6475 UserHandle.USER_OWNER); 6476 6477 boolean uidError = false; 6478 if (dataPath.exists()) { 6479 int currentUid = 0; 6480 try { 6481 StructStat stat = Os.stat(dataPath.getPath()); 6482 currentUid = stat.st_uid; 6483 } catch (ErrnoException e) { 6484 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6485 } 6486 6487 // If we have mismatched owners for the data path, we have a problem. 6488 if (currentUid != pkg.applicationInfo.uid) { 6489 boolean recovered = false; 6490 if (currentUid == 0) { 6491 // The directory somehow became owned by root. Wow. 6492 // This is probably because the system was stopped while 6493 // installd was in the middle of messing with its libs 6494 // directory. Ask installd to fix that. 6495 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6496 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6497 if (ret >= 0) { 6498 recovered = true; 6499 String msg = "Package " + pkg.packageName 6500 + " unexpectedly changed to uid 0; recovered to " + 6501 + pkg.applicationInfo.uid; 6502 reportSettingsProblem(Log.WARN, msg); 6503 } 6504 } 6505 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6506 || (scanFlags&SCAN_BOOTING) != 0)) { 6507 // If this is a system app, we can at least delete its 6508 // current data so the application will still work. 6509 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6510 if (ret >= 0) { 6511 // TODO: Kill the processes first 6512 // Old data gone! 6513 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6514 ? "System package " : "Third party package "; 6515 String msg = prefix + pkg.packageName 6516 + " has changed from uid: " 6517 + currentUid + " to " 6518 + pkg.applicationInfo.uid + "; old data erased"; 6519 reportSettingsProblem(Log.WARN, msg); 6520 recovered = true; 6521 6522 // And now re-install the app. 6523 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6524 pkg.applicationInfo.seinfo); 6525 if (ret == -1) { 6526 // Ack should not happen! 6527 msg = prefix + pkg.packageName 6528 + " could not have data directory re-created after delete."; 6529 reportSettingsProblem(Log.WARN, msg); 6530 throw new PackageManagerException( 6531 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6532 } 6533 } 6534 if (!recovered) { 6535 mHasSystemUidErrors = true; 6536 } 6537 } else if (!recovered) { 6538 // If we allow this install to proceed, we will be broken. 6539 // Abort, abort! 6540 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6541 "scanPackageLI"); 6542 } 6543 if (!recovered) { 6544 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6545 + pkg.applicationInfo.uid + "/fs_" 6546 + currentUid; 6547 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6548 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6549 String msg = "Package " + pkg.packageName 6550 + " has mismatched uid: " 6551 + currentUid + " on disk, " 6552 + pkg.applicationInfo.uid + " in settings"; 6553 // writer 6554 synchronized (mPackages) { 6555 mSettings.mReadMessages.append(msg); 6556 mSettings.mReadMessages.append('\n'); 6557 uidError = true; 6558 if (!pkgSetting.uidError) { 6559 reportSettingsProblem(Log.ERROR, msg); 6560 } 6561 } 6562 } 6563 } 6564 pkg.applicationInfo.dataDir = dataPath.getPath(); 6565 if (mShouldRestoreconData) { 6566 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6567 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6568 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6569 } 6570 } else { 6571 if (DEBUG_PACKAGE_SCANNING) { 6572 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6573 Log.v(TAG, "Want this data dir: " + dataPath); 6574 } 6575 //invoke installer to do the actual installation 6576 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6577 pkg.applicationInfo.seinfo); 6578 if (ret < 0) { 6579 // Error from installer 6580 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6581 "Unable to create data dirs [errorCode=" + ret + "]"); 6582 } 6583 6584 if (dataPath.exists()) { 6585 pkg.applicationInfo.dataDir = dataPath.getPath(); 6586 } else { 6587 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6588 pkg.applicationInfo.dataDir = null; 6589 } 6590 } 6591 6592 pkgSetting.uidError = uidError; 6593 } 6594 6595 final String path = scanFile.getPath(); 6596 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6597 6598 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6599 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6600 6601 // Some system apps still use directory structure for native libraries 6602 // in which case we might end up not detecting abi solely based on apk 6603 // structure. Try to detect abi based on directory structure. 6604 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6605 pkg.applicationInfo.primaryCpuAbi == null) { 6606 setBundledAppAbisAndRoots(pkg, pkgSetting); 6607 setNativeLibraryPaths(pkg); 6608 } 6609 6610 } else { 6611 if ((scanFlags & SCAN_MOVE) != 0) { 6612 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6613 // but we already have this packages package info in the PackageSetting. We just 6614 // use that and derive the native library path based on the new codepath. 6615 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6616 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6617 } 6618 6619 // Set native library paths again. For moves, the path will be updated based on the 6620 // ABIs we've determined above. For non-moves, the path will be updated based on the 6621 // ABIs we determined during compilation, but the path will depend on the final 6622 // package path (after the rename away from the stage path). 6623 setNativeLibraryPaths(pkg); 6624 } 6625 6626 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6627 final int[] userIds = sUserManager.getUserIds(); 6628 synchronized (mInstallLock) { 6629 // Create a native library symlink only if we have native libraries 6630 // and if the native libraries are 32 bit libraries. We do not provide 6631 // this symlink for 64 bit libraries. 6632 if (pkg.applicationInfo.primaryCpuAbi != null && 6633 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6634 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6635 for (int userId : userIds) { 6636 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6637 nativeLibPath, userId) < 0) { 6638 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6639 "Failed linking native library dir (user=" + userId + ")"); 6640 } 6641 } 6642 } 6643 } 6644 6645 // This is a special case for the "system" package, where the ABI is 6646 // dictated by the zygote configuration (and init.rc). We should keep track 6647 // of this ABI so that we can deal with "normal" applications that run under 6648 // the same UID correctly. 6649 if (mPlatformPackage == pkg) { 6650 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6651 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6652 } 6653 6654 // If there's a mismatch between the abi-override in the package setting 6655 // and the abiOverride specified for the install. Warn about this because we 6656 // would've already compiled the app without taking the package setting into 6657 // account. 6658 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6659 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6660 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6661 " for package: " + pkg.packageName); 6662 } 6663 } 6664 6665 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6666 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6667 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6668 6669 // Copy the derived override back to the parsed package, so that we can 6670 // update the package settings accordingly. 6671 pkg.cpuAbiOverride = cpuAbiOverride; 6672 6673 if (DEBUG_ABI_SELECTION) { 6674 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6675 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6676 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6677 } 6678 6679 // Push the derived path down into PackageSettings so we know what to 6680 // clean up at uninstall time. 6681 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6682 6683 if (DEBUG_ABI_SELECTION) { 6684 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6685 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6686 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6687 } 6688 6689 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6690 // We don't do this here during boot because we can do it all 6691 // at once after scanning all existing packages. 6692 // 6693 // We also do this *before* we perform dexopt on this package, so that 6694 // we can avoid redundant dexopts, and also to make sure we've got the 6695 // code and package path correct. 6696 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6697 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6698 } 6699 6700 if ((scanFlags & SCAN_NO_DEX) == 0) { 6701 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6702 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6703 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6704 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6705 } 6706 } 6707 if (mFactoryTest && pkg.requestedPermissions.contains( 6708 android.Manifest.permission.FACTORY_TEST)) { 6709 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6710 } 6711 6712 ArrayList<PackageParser.Package> clientLibPkgs = null; 6713 6714 // writer 6715 synchronized (mPackages) { 6716 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6717 // Only system apps can add new shared libraries. 6718 if (pkg.libraryNames != null) { 6719 for (int i=0; i<pkg.libraryNames.size(); i++) { 6720 String name = pkg.libraryNames.get(i); 6721 boolean allowed = false; 6722 if (pkg.isUpdatedSystemApp()) { 6723 // New library entries can only be added through the 6724 // system image. This is important to get rid of a lot 6725 // of nasty edge cases: for example if we allowed a non- 6726 // system update of the app to add a library, then uninstalling 6727 // the update would make the library go away, and assumptions 6728 // we made such as through app install filtering would now 6729 // have allowed apps on the device which aren't compatible 6730 // with it. Better to just have the restriction here, be 6731 // conservative, and create many fewer cases that can negatively 6732 // impact the user experience. 6733 final PackageSetting sysPs = mSettings 6734 .getDisabledSystemPkgLPr(pkg.packageName); 6735 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6736 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6737 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6738 allowed = true; 6739 allowed = true; 6740 break; 6741 } 6742 } 6743 } 6744 } else { 6745 allowed = true; 6746 } 6747 if (allowed) { 6748 if (!mSharedLibraries.containsKey(name)) { 6749 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6750 } else if (!name.equals(pkg.packageName)) { 6751 Slog.w(TAG, "Package " + pkg.packageName + " library " 6752 + name + " already exists; skipping"); 6753 } 6754 } else { 6755 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6756 + name + " that is not declared on system image; skipping"); 6757 } 6758 } 6759 if ((scanFlags&SCAN_BOOTING) == 0) { 6760 // If we are not booting, we need to update any applications 6761 // that are clients of our shared library. If we are booting, 6762 // this will all be done once the scan is complete. 6763 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6764 } 6765 } 6766 } 6767 } 6768 6769 // We also need to dexopt any apps that are dependent on this library. Note that 6770 // if these fail, we should abort the install since installing the library will 6771 // result in some apps being broken. 6772 if (clientLibPkgs != null) { 6773 if ((scanFlags & SCAN_NO_DEX) == 0) { 6774 for (int i = 0; i < clientLibPkgs.size(); i++) { 6775 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6776 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6777 null /* instruction sets */, forceDex, 6778 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6779 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6780 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6781 "scanPackageLI failed to dexopt clientLibPkgs"); 6782 } 6783 } 6784 } 6785 } 6786 6787 // Also need to kill any apps that are dependent on the library. 6788 if (clientLibPkgs != null) { 6789 for (int i=0; i<clientLibPkgs.size(); i++) { 6790 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6791 killApplication(clientPkg.applicationInfo.packageName, 6792 clientPkg.applicationInfo.uid, "update lib"); 6793 } 6794 } 6795 6796 // Make sure we're not adding any bogus keyset info 6797 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6798 ksms.assertScannedPackageValid(pkg); 6799 6800 // writer 6801 synchronized (mPackages) { 6802 // We don't expect installation to fail beyond this point 6803 6804 // Add the new setting to mSettings 6805 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6806 // Add the new setting to mPackages 6807 mPackages.put(pkg.applicationInfo.packageName, pkg); 6808 // Make sure we don't accidentally delete its data. 6809 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6810 while (iter.hasNext()) { 6811 PackageCleanItem item = iter.next(); 6812 if (pkgName.equals(item.packageName)) { 6813 iter.remove(); 6814 } 6815 } 6816 6817 // Take care of first install / last update times. 6818 if (currentTime != 0) { 6819 if (pkgSetting.firstInstallTime == 0) { 6820 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6821 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6822 pkgSetting.lastUpdateTime = currentTime; 6823 } 6824 } else if (pkgSetting.firstInstallTime == 0) { 6825 // We need *something*. Take time time stamp of the file. 6826 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6827 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6828 if (scanFileTime != pkgSetting.timeStamp) { 6829 // A package on the system image has changed; consider this 6830 // to be an update. 6831 pkgSetting.lastUpdateTime = scanFileTime; 6832 } 6833 } 6834 6835 // Add the package's KeySets to the global KeySetManagerService 6836 ksms.addScannedPackageLPw(pkg); 6837 6838 int N = pkg.providers.size(); 6839 StringBuilder r = null; 6840 int i; 6841 for (i=0; i<N; i++) { 6842 PackageParser.Provider p = pkg.providers.get(i); 6843 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6844 p.info.processName, pkg.applicationInfo.uid); 6845 mProviders.addProvider(p); 6846 p.syncable = p.info.isSyncable; 6847 if (p.info.authority != null) { 6848 String names[] = p.info.authority.split(";"); 6849 p.info.authority = null; 6850 for (int j = 0; j < names.length; j++) { 6851 if (j == 1 && p.syncable) { 6852 // We only want the first authority for a provider to possibly be 6853 // syncable, so if we already added this provider using a different 6854 // authority clear the syncable flag. We copy the provider before 6855 // changing it because the mProviders object contains a reference 6856 // to a provider that we don't want to change. 6857 // Only do this for the second authority since the resulting provider 6858 // object can be the same for all future authorities for this provider. 6859 p = new PackageParser.Provider(p); 6860 p.syncable = false; 6861 } 6862 if (!mProvidersByAuthority.containsKey(names[j])) { 6863 mProvidersByAuthority.put(names[j], p); 6864 if (p.info.authority == null) { 6865 p.info.authority = names[j]; 6866 } else { 6867 p.info.authority = p.info.authority + ";" + names[j]; 6868 } 6869 if (DEBUG_PACKAGE_SCANNING) { 6870 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6871 Log.d(TAG, "Registered content provider: " + names[j] 6872 + ", className = " + p.info.name + ", isSyncable = " 6873 + p.info.isSyncable); 6874 } 6875 } else { 6876 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6877 Slog.w(TAG, "Skipping provider name " + names[j] + 6878 " (in package " + pkg.applicationInfo.packageName + 6879 "): name already used by " 6880 + ((other != null && other.getComponentName() != null) 6881 ? other.getComponentName().getPackageName() : "?")); 6882 } 6883 } 6884 } 6885 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6886 if (r == null) { 6887 r = new StringBuilder(256); 6888 } else { 6889 r.append(' '); 6890 } 6891 r.append(p.info.name); 6892 } 6893 } 6894 if (r != null) { 6895 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6896 } 6897 6898 N = pkg.services.size(); 6899 r = null; 6900 for (i=0; i<N; i++) { 6901 PackageParser.Service s = pkg.services.get(i); 6902 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6903 s.info.processName, pkg.applicationInfo.uid); 6904 mServices.addService(s); 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(s.info.name); 6912 } 6913 } 6914 if (r != null) { 6915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6916 } 6917 6918 N = pkg.receivers.size(); 6919 r = null; 6920 for (i=0; i<N; i++) { 6921 PackageParser.Activity a = pkg.receivers.get(i); 6922 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6923 a.info.processName, pkg.applicationInfo.uid); 6924 mReceivers.addActivity(a, "receiver"); 6925 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6926 if (r == null) { 6927 r = new StringBuilder(256); 6928 } else { 6929 r.append(' '); 6930 } 6931 r.append(a.info.name); 6932 } 6933 } 6934 if (r != null) { 6935 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6936 } 6937 6938 N = pkg.activities.size(); 6939 r = null; 6940 for (i=0; i<N; i++) { 6941 PackageParser.Activity a = pkg.activities.get(i); 6942 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6943 a.info.processName, pkg.applicationInfo.uid); 6944 mActivities.addActivity(a, "activity"); 6945 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6946 if (r == null) { 6947 r = new StringBuilder(256); 6948 } else { 6949 r.append(' '); 6950 } 6951 r.append(a.info.name); 6952 } 6953 } 6954 if (r != null) { 6955 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6956 } 6957 6958 N = pkg.permissionGroups.size(); 6959 r = null; 6960 for (i=0; i<N; i++) { 6961 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6962 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6963 if (cur == null) { 6964 mPermissionGroups.put(pg.info.name, pg); 6965 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6966 if (r == null) { 6967 r = new StringBuilder(256); 6968 } else { 6969 r.append(' '); 6970 } 6971 r.append(pg.info.name); 6972 } 6973 } else { 6974 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6975 + pg.info.packageName + " ignored: original from " 6976 + cur.info.packageName); 6977 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6978 if (r == null) { 6979 r = new StringBuilder(256); 6980 } else { 6981 r.append(' '); 6982 } 6983 r.append("DUP:"); 6984 r.append(pg.info.name); 6985 } 6986 } 6987 } 6988 if (r != null) { 6989 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6990 } 6991 6992 N = pkg.permissions.size(); 6993 r = null; 6994 for (i=0; i<N; i++) { 6995 PackageParser.Permission p = pkg.permissions.get(i); 6996 6997 // Now that permission groups have a special meaning, we ignore permission 6998 // groups for legacy apps to prevent unexpected behavior. In particular, 6999 // permissions for one app being granted to someone just becuase they happen 7000 // to be in a group defined by another app (before this had no implications). 7001 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7002 p.group = mPermissionGroups.get(p.info.group); 7003 // Warn for a permission in an unknown group. 7004 if (p.info.group != null && p.group == null) { 7005 Slog.w(TAG, "Permission " + p.info.name + " from package " 7006 + p.info.packageName + " in an unknown group " + p.info.group); 7007 } 7008 } 7009 7010 ArrayMap<String, BasePermission> permissionMap = 7011 p.tree ? mSettings.mPermissionTrees 7012 : mSettings.mPermissions; 7013 BasePermission bp = permissionMap.get(p.info.name); 7014 7015 // Allow system apps to redefine non-system permissions 7016 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7017 final boolean currentOwnerIsSystem = (bp.perm != null 7018 && isSystemApp(bp.perm.owner)); 7019 if (isSystemApp(p.owner)) { 7020 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7021 // It's a built-in permission and no owner, take ownership now 7022 bp.packageSetting = pkgSetting; 7023 bp.perm = p; 7024 bp.uid = pkg.applicationInfo.uid; 7025 bp.sourcePackage = p.info.packageName; 7026 } else if (!currentOwnerIsSystem) { 7027 String msg = "New decl " + p.owner + " of permission " 7028 + p.info.name + " is system; overriding " + bp.sourcePackage; 7029 reportSettingsProblem(Log.WARN, msg); 7030 bp = null; 7031 } 7032 } 7033 } 7034 7035 if (bp == null) { 7036 bp = new BasePermission(p.info.name, p.info.packageName, 7037 BasePermission.TYPE_NORMAL); 7038 permissionMap.put(p.info.name, bp); 7039 } 7040 7041 if (bp.perm == null) { 7042 if (bp.sourcePackage == null 7043 || bp.sourcePackage.equals(p.info.packageName)) { 7044 BasePermission tree = findPermissionTreeLP(p.info.name); 7045 if (tree == null 7046 || tree.sourcePackage.equals(p.info.packageName)) { 7047 bp.packageSetting = pkgSetting; 7048 bp.perm = p; 7049 bp.uid = pkg.applicationInfo.uid; 7050 bp.sourcePackage = p.info.packageName; 7051 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7052 if (r == null) { 7053 r = new StringBuilder(256); 7054 } else { 7055 r.append(' '); 7056 } 7057 r.append(p.info.name); 7058 } 7059 } else { 7060 Slog.w(TAG, "Permission " + p.info.name + " from package " 7061 + p.info.packageName + " ignored: base tree " 7062 + tree.name + " is from package " 7063 + tree.sourcePackage); 7064 } 7065 } else { 7066 Slog.w(TAG, "Permission " + p.info.name + " from package " 7067 + p.info.packageName + " ignored: original from " 7068 + bp.sourcePackage); 7069 } 7070 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7071 if (r == null) { 7072 r = new StringBuilder(256); 7073 } else { 7074 r.append(' '); 7075 } 7076 r.append("DUP:"); 7077 r.append(p.info.name); 7078 } 7079 if (bp.perm == p) { 7080 bp.protectionLevel = p.info.protectionLevel; 7081 } 7082 } 7083 7084 if (r != null) { 7085 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7086 } 7087 7088 N = pkg.instrumentation.size(); 7089 r = null; 7090 for (i=0; i<N; i++) { 7091 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7092 a.info.packageName = pkg.applicationInfo.packageName; 7093 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7094 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7095 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7096 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7097 a.info.dataDir = pkg.applicationInfo.dataDir; 7098 7099 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7100 // need other information about the application, like the ABI and what not ? 7101 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7102 mInstrumentation.put(a.getComponentName(), a); 7103 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7104 if (r == null) { 7105 r = new StringBuilder(256); 7106 } else { 7107 r.append(' '); 7108 } 7109 r.append(a.info.name); 7110 } 7111 } 7112 if (r != null) { 7113 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7114 } 7115 7116 if (pkg.protectedBroadcasts != null) { 7117 N = pkg.protectedBroadcasts.size(); 7118 for (i=0; i<N; i++) { 7119 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7120 } 7121 } 7122 7123 pkgSetting.setTimeStamp(scanFileTime); 7124 7125 // Create idmap files for pairs of (packages, overlay packages). 7126 // Note: "android", ie framework-res.apk, is handled by native layers. 7127 if (pkg.mOverlayTarget != null) { 7128 // This is an overlay package. 7129 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7130 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7131 mOverlays.put(pkg.mOverlayTarget, 7132 new ArrayMap<String, PackageParser.Package>()); 7133 } 7134 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7135 map.put(pkg.packageName, pkg); 7136 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7137 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7138 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7139 "scanPackageLI failed to createIdmap"); 7140 } 7141 } 7142 } else if (mOverlays.containsKey(pkg.packageName) && 7143 !pkg.packageName.equals("android")) { 7144 // This is a regular package, with one or more known overlay packages. 7145 createIdmapsForPackageLI(pkg); 7146 } 7147 } 7148 7149 return pkg; 7150 } 7151 7152 /** 7153 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7154 * is derived purely on the basis of the contents of {@code scanFile} and 7155 * {@code cpuAbiOverride}. 7156 * 7157 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7158 */ 7159 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7160 String cpuAbiOverride, boolean extractLibs) 7161 throws PackageManagerException { 7162 // TODO: We can probably be smarter about this stuff. For installed apps, 7163 // we can calculate this information at install time once and for all. For 7164 // system apps, we can probably assume that this information doesn't change 7165 // after the first boot scan. As things stand, we do lots of unnecessary work. 7166 7167 // Give ourselves some initial paths; we'll come back for another 7168 // pass once we've determined ABI below. 7169 setNativeLibraryPaths(pkg); 7170 7171 // We would never need to extract libs for forward-locked and external packages, 7172 // since the container service will do it for us. We shouldn't attempt to 7173 // extract libs from system app when it was not updated. 7174 if (pkg.isForwardLocked() || isExternal(pkg) || 7175 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7176 extractLibs = false; 7177 } 7178 7179 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7180 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7181 7182 NativeLibraryHelper.Handle handle = null; 7183 try { 7184 handle = NativeLibraryHelper.Handle.create(scanFile); 7185 // TODO(multiArch): This can be null for apps that didn't go through the 7186 // usual installation process. We can calculate it again, like we 7187 // do during install time. 7188 // 7189 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7190 // unnecessary. 7191 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7192 7193 // Null out the abis so that they can be recalculated. 7194 pkg.applicationInfo.primaryCpuAbi = null; 7195 pkg.applicationInfo.secondaryCpuAbi = null; 7196 if (isMultiArch(pkg.applicationInfo)) { 7197 // Warn if we've set an abiOverride for multi-lib packages.. 7198 // By definition, we need to copy both 32 and 64 bit libraries for 7199 // such packages. 7200 if (pkg.cpuAbiOverride != null 7201 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7202 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7203 } 7204 7205 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7206 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7207 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7208 if (extractLibs) { 7209 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7210 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7211 useIsaSpecificSubdirs); 7212 } else { 7213 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7214 } 7215 } 7216 7217 maybeThrowExceptionForMultiArchCopy( 7218 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7219 7220 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7221 if (extractLibs) { 7222 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7223 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7224 useIsaSpecificSubdirs); 7225 } else { 7226 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7227 } 7228 } 7229 7230 maybeThrowExceptionForMultiArchCopy( 7231 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7232 7233 if (abi64 >= 0) { 7234 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7235 } 7236 7237 if (abi32 >= 0) { 7238 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7239 if (abi64 >= 0) { 7240 pkg.applicationInfo.secondaryCpuAbi = abi; 7241 } else { 7242 pkg.applicationInfo.primaryCpuAbi = abi; 7243 } 7244 } 7245 } else { 7246 String[] abiList = (cpuAbiOverride != null) ? 7247 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7248 7249 // Enable gross and lame hacks for apps that are built with old 7250 // SDK tools. We must scan their APKs for renderscript bitcode and 7251 // not launch them if it's present. Don't bother checking on devices 7252 // that don't have 64 bit support. 7253 boolean needsRenderScriptOverride = false; 7254 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7255 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7256 abiList = Build.SUPPORTED_32_BIT_ABIS; 7257 needsRenderScriptOverride = true; 7258 } 7259 7260 final int copyRet; 7261 if (extractLibs) { 7262 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7263 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7264 } else { 7265 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7266 } 7267 7268 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7269 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7270 "Error unpackaging native libs for app, errorCode=" + copyRet); 7271 } 7272 7273 if (copyRet >= 0) { 7274 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7275 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7276 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7277 } else if (needsRenderScriptOverride) { 7278 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7279 } 7280 } 7281 } catch (IOException ioe) { 7282 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7283 } finally { 7284 IoUtils.closeQuietly(handle); 7285 } 7286 7287 // Now that we've calculated the ABIs and determined if it's an internal app, 7288 // we will go ahead and populate the nativeLibraryPath. 7289 setNativeLibraryPaths(pkg); 7290 } 7291 7292 /** 7293 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7294 * i.e, so that all packages can be run inside a single process if required. 7295 * 7296 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7297 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7298 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7299 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7300 * updating a package that belongs to a shared user. 7301 * 7302 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7303 * adds unnecessary complexity. 7304 */ 7305 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7306 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7307 String requiredInstructionSet = null; 7308 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7309 requiredInstructionSet = VMRuntime.getInstructionSet( 7310 scannedPackage.applicationInfo.primaryCpuAbi); 7311 } 7312 7313 PackageSetting requirer = null; 7314 for (PackageSetting ps : packagesForUser) { 7315 // If packagesForUser contains scannedPackage, we skip it. This will happen 7316 // when scannedPackage is an update of an existing package. Without this check, 7317 // we will never be able to change the ABI of any package belonging to a shared 7318 // user, even if it's compatible with other packages. 7319 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7320 if (ps.primaryCpuAbiString == null) { 7321 continue; 7322 } 7323 7324 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7325 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7326 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7327 // this but there's not much we can do. 7328 String errorMessage = "Instruction set mismatch, " 7329 + ((requirer == null) ? "[caller]" : requirer) 7330 + " requires " + requiredInstructionSet + " whereas " + ps 7331 + " requires " + instructionSet; 7332 Slog.w(TAG, errorMessage); 7333 } 7334 7335 if (requiredInstructionSet == null) { 7336 requiredInstructionSet = instructionSet; 7337 requirer = ps; 7338 } 7339 } 7340 } 7341 7342 if (requiredInstructionSet != null) { 7343 String adjustedAbi; 7344 if (requirer != null) { 7345 // requirer != null implies that either scannedPackage was null or that scannedPackage 7346 // did not require an ABI, in which case we have to adjust scannedPackage to match 7347 // the ABI of the set (which is the same as requirer's ABI) 7348 adjustedAbi = requirer.primaryCpuAbiString; 7349 if (scannedPackage != null) { 7350 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7351 } 7352 } else { 7353 // requirer == null implies that we're updating all ABIs in the set to 7354 // match scannedPackage. 7355 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7356 } 7357 7358 for (PackageSetting ps : packagesForUser) { 7359 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7360 if (ps.primaryCpuAbiString != null) { 7361 continue; 7362 } 7363 7364 ps.primaryCpuAbiString = adjustedAbi; 7365 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7366 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7367 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7368 7369 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7370 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7371 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7372 ps.primaryCpuAbiString = null; 7373 ps.pkg.applicationInfo.primaryCpuAbi = null; 7374 return; 7375 } else { 7376 mInstaller.rmdex(ps.codePathString, 7377 getDexCodeInstructionSet(getPreferredInstructionSet())); 7378 } 7379 } 7380 } 7381 } 7382 } 7383 } 7384 7385 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7386 synchronized (mPackages) { 7387 mResolverReplaced = true; 7388 // Set up information for custom user intent resolution activity. 7389 mResolveActivity.applicationInfo = pkg.applicationInfo; 7390 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7391 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7392 mResolveActivity.processName = pkg.applicationInfo.packageName; 7393 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7394 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7395 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7396 mResolveActivity.theme = 0; 7397 mResolveActivity.exported = true; 7398 mResolveActivity.enabled = true; 7399 mResolveInfo.activityInfo = mResolveActivity; 7400 mResolveInfo.priority = 0; 7401 mResolveInfo.preferredOrder = 0; 7402 mResolveInfo.match = 0; 7403 mResolveComponentName = mCustomResolverComponentName; 7404 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7405 mResolveComponentName); 7406 } 7407 } 7408 7409 private static String calculateBundledApkRoot(final String codePathString) { 7410 final File codePath = new File(codePathString); 7411 final File codeRoot; 7412 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7413 codeRoot = Environment.getRootDirectory(); 7414 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7415 codeRoot = Environment.getOemDirectory(); 7416 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7417 codeRoot = Environment.getVendorDirectory(); 7418 } else { 7419 // Unrecognized code path; take its top real segment as the apk root: 7420 // e.g. /something/app/blah.apk => /something 7421 try { 7422 File f = codePath.getCanonicalFile(); 7423 File parent = f.getParentFile(); // non-null because codePath is a file 7424 File tmp; 7425 while ((tmp = parent.getParentFile()) != null) { 7426 f = parent; 7427 parent = tmp; 7428 } 7429 codeRoot = f; 7430 Slog.w(TAG, "Unrecognized code path " 7431 + codePath + " - using " + codeRoot); 7432 } catch (IOException e) { 7433 // Can't canonicalize the code path -- shenanigans? 7434 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7435 return Environment.getRootDirectory().getPath(); 7436 } 7437 } 7438 return codeRoot.getPath(); 7439 } 7440 7441 /** 7442 * Derive and set the location of native libraries for the given package, 7443 * which varies depending on where and how the package was installed. 7444 */ 7445 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7446 final ApplicationInfo info = pkg.applicationInfo; 7447 final String codePath = pkg.codePath; 7448 final File codeFile = new File(codePath); 7449 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7450 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7451 7452 info.nativeLibraryRootDir = null; 7453 info.nativeLibraryRootRequiresIsa = false; 7454 info.nativeLibraryDir = null; 7455 info.secondaryNativeLibraryDir = null; 7456 7457 if (isApkFile(codeFile)) { 7458 // Monolithic install 7459 if (bundledApp) { 7460 // If "/system/lib64/apkname" exists, assume that is the per-package 7461 // native library directory to use; otherwise use "/system/lib/apkname". 7462 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7463 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7464 getPrimaryInstructionSet(info)); 7465 7466 // This is a bundled system app so choose the path based on the ABI. 7467 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7468 // is just the default path. 7469 final String apkName = deriveCodePathName(codePath); 7470 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7471 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7472 apkName).getAbsolutePath(); 7473 7474 if (info.secondaryCpuAbi != null) { 7475 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7476 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7477 secondaryLibDir, apkName).getAbsolutePath(); 7478 } 7479 } else if (asecApp) { 7480 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7481 .getAbsolutePath(); 7482 } else { 7483 final String apkName = deriveCodePathName(codePath); 7484 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7485 .getAbsolutePath(); 7486 } 7487 7488 info.nativeLibraryRootRequiresIsa = false; 7489 info.nativeLibraryDir = info.nativeLibraryRootDir; 7490 } else { 7491 // Cluster install 7492 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7493 info.nativeLibraryRootRequiresIsa = true; 7494 7495 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7496 getPrimaryInstructionSet(info)).getAbsolutePath(); 7497 7498 if (info.secondaryCpuAbi != null) { 7499 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7500 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7501 } 7502 } 7503 } 7504 7505 /** 7506 * Calculate the abis and roots for a bundled app. These can uniquely 7507 * be determined from the contents of the system partition, i.e whether 7508 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7509 * of this information, and instead assume that the system was built 7510 * sensibly. 7511 */ 7512 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7513 PackageSetting pkgSetting) { 7514 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7515 7516 // If "/system/lib64/apkname" exists, assume that is the per-package 7517 // native library directory to use; otherwise use "/system/lib/apkname". 7518 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7519 setBundledAppAbi(pkg, apkRoot, apkName); 7520 // pkgSetting might be null during rescan following uninstall of updates 7521 // to a bundled app, so accommodate that possibility. The settings in 7522 // that case will be established later from the parsed package. 7523 // 7524 // If the settings aren't null, sync them up with what we've just derived. 7525 // note that apkRoot isn't stored in the package settings. 7526 if (pkgSetting != null) { 7527 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7528 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7529 } 7530 } 7531 7532 /** 7533 * Deduces the ABI of a bundled app and sets the relevant fields on the 7534 * parsed pkg object. 7535 * 7536 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7537 * under which system libraries are installed. 7538 * @param apkName the name of the installed package. 7539 */ 7540 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7541 final File codeFile = new File(pkg.codePath); 7542 7543 final boolean has64BitLibs; 7544 final boolean has32BitLibs; 7545 if (isApkFile(codeFile)) { 7546 // Monolithic install 7547 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7548 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7549 } else { 7550 // Cluster install 7551 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7552 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7553 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7554 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7555 has64BitLibs = (new File(rootDir, isa)).exists(); 7556 } else { 7557 has64BitLibs = false; 7558 } 7559 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7560 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7561 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7562 has32BitLibs = (new File(rootDir, isa)).exists(); 7563 } else { 7564 has32BitLibs = false; 7565 } 7566 } 7567 7568 if (has64BitLibs && !has32BitLibs) { 7569 // The package has 64 bit libs, but not 32 bit libs. Its primary 7570 // ABI should be 64 bit. We can safely assume here that the bundled 7571 // native libraries correspond to the most preferred ABI in the list. 7572 7573 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7574 pkg.applicationInfo.secondaryCpuAbi = null; 7575 } else if (has32BitLibs && !has64BitLibs) { 7576 // The package has 32 bit libs but not 64 bit libs. Its primary 7577 // ABI should be 32 bit. 7578 7579 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7580 pkg.applicationInfo.secondaryCpuAbi = null; 7581 } else if (has32BitLibs && has64BitLibs) { 7582 // The application has both 64 and 32 bit bundled libraries. We check 7583 // here that the app declares multiArch support, and warn if it doesn't. 7584 // 7585 // We will be lenient here and record both ABIs. The primary will be the 7586 // ABI that's higher on the list, i.e, a device that's configured to prefer 7587 // 64 bit apps will see a 64 bit primary ABI, 7588 7589 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7590 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7591 } 7592 7593 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7594 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7595 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7596 } else { 7597 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7598 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7599 } 7600 } else { 7601 pkg.applicationInfo.primaryCpuAbi = null; 7602 pkg.applicationInfo.secondaryCpuAbi = null; 7603 } 7604 } 7605 7606 private void killApplication(String pkgName, int appId, String reason) { 7607 // Request the ActivityManager to kill the process(only for existing packages) 7608 // so that we do not end up in a confused state while the user is still using the older 7609 // version of the application while the new one gets installed. 7610 IActivityManager am = ActivityManagerNative.getDefault(); 7611 if (am != null) { 7612 try { 7613 am.killApplicationWithAppId(pkgName, appId, reason); 7614 } catch (RemoteException e) { 7615 } 7616 } 7617 } 7618 7619 void removePackageLI(PackageSetting ps, boolean chatty) { 7620 if (DEBUG_INSTALL) { 7621 if (chatty) 7622 Log.d(TAG, "Removing package " + ps.name); 7623 } 7624 7625 // writer 7626 synchronized (mPackages) { 7627 mPackages.remove(ps.name); 7628 final PackageParser.Package pkg = ps.pkg; 7629 if (pkg != null) { 7630 cleanPackageDataStructuresLILPw(pkg, chatty); 7631 } 7632 } 7633 } 7634 7635 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7636 if (DEBUG_INSTALL) { 7637 if (chatty) 7638 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7639 } 7640 7641 // writer 7642 synchronized (mPackages) { 7643 mPackages.remove(pkg.applicationInfo.packageName); 7644 cleanPackageDataStructuresLILPw(pkg, chatty); 7645 } 7646 } 7647 7648 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7649 int N = pkg.providers.size(); 7650 StringBuilder r = null; 7651 int i; 7652 for (i=0; i<N; i++) { 7653 PackageParser.Provider p = pkg.providers.get(i); 7654 mProviders.removeProvider(p); 7655 if (p.info.authority == null) { 7656 7657 /* There was another ContentProvider with this authority when 7658 * this app was installed so this authority is null, 7659 * Ignore it as we don't have to unregister the provider. 7660 */ 7661 continue; 7662 } 7663 String names[] = p.info.authority.split(";"); 7664 for (int j = 0; j < names.length; j++) { 7665 if (mProvidersByAuthority.get(names[j]) == p) { 7666 mProvidersByAuthority.remove(names[j]); 7667 if (DEBUG_REMOVE) { 7668 if (chatty) 7669 Log.d(TAG, "Unregistered content provider: " + names[j] 7670 + ", className = " + p.info.name + ", isSyncable = " 7671 + p.info.isSyncable); 7672 } 7673 } 7674 } 7675 if (DEBUG_REMOVE && chatty) { 7676 if (r == null) { 7677 r = new StringBuilder(256); 7678 } else { 7679 r.append(' '); 7680 } 7681 r.append(p.info.name); 7682 } 7683 } 7684 if (r != null) { 7685 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7686 } 7687 7688 N = pkg.services.size(); 7689 r = null; 7690 for (i=0; i<N; i++) { 7691 PackageParser.Service s = pkg.services.get(i); 7692 mServices.removeService(s); 7693 if (chatty) { 7694 if (r == null) { 7695 r = new StringBuilder(256); 7696 } else { 7697 r.append(' '); 7698 } 7699 r.append(s.info.name); 7700 } 7701 } 7702 if (r != null) { 7703 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7704 } 7705 7706 N = pkg.receivers.size(); 7707 r = null; 7708 for (i=0; i<N; i++) { 7709 PackageParser.Activity a = pkg.receivers.get(i); 7710 mReceivers.removeActivity(a, "receiver"); 7711 if (DEBUG_REMOVE && chatty) { 7712 if (r == null) { 7713 r = new StringBuilder(256); 7714 } else { 7715 r.append(' '); 7716 } 7717 r.append(a.info.name); 7718 } 7719 } 7720 if (r != null) { 7721 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7722 } 7723 7724 N = pkg.activities.size(); 7725 r = null; 7726 for (i=0; i<N; i++) { 7727 PackageParser.Activity a = pkg.activities.get(i); 7728 mActivities.removeActivity(a, "activity"); 7729 if (DEBUG_REMOVE && chatty) { 7730 if (r == null) { 7731 r = new StringBuilder(256); 7732 } else { 7733 r.append(' '); 7734 } 7735 r.append(a.info.name); 7736 } 7737 } 7738 if (r != null) { 7739 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7740 } 7741 7742 N = pkg.permissions.size(); 7743 r = null; 7744 for (i=0; i<N; i++) { 7745 PackageParser.Permission p = pkg.permissions.get(i); 7746 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7747 if (bp == null) { 7748 bp = mSettings.mPermissionTrees.get(p.info.name); 7749 } 7750 if (bp != null && bp.perm == p) { 7751 bp.perm = null; 7752 if (DEBUG_REMOVE && chatty) { 7753 if (r == null) { 7754 r = new StringBuilder(256); 7755 } else { 7756 r.append(' '); 7757 } 7758 r.append(p.info.name); 7759 } 7760 } 7761 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7762 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7763 if (appOpPerms != null) { 7764 appOpPerms.remove(pkg.packageName); 7765 } 7766 } 7767 } 7768 if (r != null) { 7769 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7770 } 7771 7772 N = pkg.requestedPermissions.size(); 7773 r = null; 7774 for (i=0; i<N; i++) { 7775 String perm = pkg.requestedPermissions.get(i); 7776 BasePermission bp = mSettings.mPermissions.get(perm); 7777 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7778 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7779 if (appOpPerms != null) { 7780 appOpPerms.remove(pkg.packageName); 7781 if (appOpPerms.isEmpty()) { 7782 mAppOpPermissionPackages.remove(perm); 7783 } 7784 } 7785 } 7786 } 7787 if (r != null) { 7788 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7789 } 7790 7791 N = pkg.instrumentation.size(); 7792 r = null; 7793 for (i=0; i<N; i++) { 7794 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7795 mInstrumentation.remove(a.getComponentName()); 7796 if (DEBUG_REMOVE && chatty) { 7797 if (r == null) { 7798 r = new StringBuilder(256); 7799 } else { 7800 r.append(' '); 7801 } 7802 r.append(a.info.name); 7803 } 7804 } 7805 if (r != null) { 7806 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7807 } 7808 7809 r = null; 7810 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7811 // Only system apps can hold shared libraries. 7812 if (pkg.libraryNames != null) { 7813 for (i=0; i<pkg.libraryNames.size(); i++) { 7814 String name = pkg.libraryNames.get(i); 7815 SharedLibraryEntry cur = mSharedLibraries.get(name); 7816 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7817 mSharedLibraries.remove(name); 7818 if (DEBUG_REMOVE && chatty) { 7819 if (r == null) { 7820 r = new StringBuilder(256); 7821 } else { 7822 r.append(' '); 7823 } 7824 r.append(name); 7825 } 7826 } 7827 } 7828 } 7829 } 7830 if (r != null) { 7831 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7832 } 7833 } 7834 7835 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7836 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7837 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7838 return true; 7839 } 7840 } 7841 return false; 7842 } 7843 7844 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7845 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7846 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7847 7848 private void updatePermissionsLPw(String changingPkg, 7849 PackageParser.Package pkgInfo, int flags) { 7850 // Make sure there are no dangling permission trees. 7851 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7852 while (it.hasNext()) { 7853 final BasePermission bp = it.next(); 7854 if (bp.packageSetting == null) { 7855 // We may not yet have parsed the package, so just see if 7856 // we still know about its settings. 7857 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7858 } 7859 if (bp.packageSetting == null) { 7860 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7861 + " from package " + bp.sourcePackage); 7862 it.remove(); 7863 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7864 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7865 Slog.i(TAG, "Removing old permission tree: " + bp.name 7866 + " from package " + bp.sourcePackage); 7867 flags |= UPDATE_PERMISSIONS_ALL; 7868 it.remove(); 7869 } 7870 } 7871 } 7872 7873 // Make sure all dynamic permissions have been assigned to a package, 7874 // and make sure there are no dangling permissions. 7875 it = mSettings.mPermissions.values().iterator(); 7876 while (it.hasNext()) { 7877 final BasePermission bp = it.next(); 7878 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7879 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7880 + bp.name + " pkg=" + bp.sourcePackage 7881 + " info=" + bp.pendingInfo); 7882 if (bp.packageSetting == null && bp.pendingInfo != null) { 7883 final BasePermission tree = findPermissionTreeLP(bp.name); 7884 if (tree != null && tree.perm != null) { 7885 bp.packageSetting = tree.packageSetting; 7886 bp.perm = new PackageParser.Permission(tree.perm.owner, 7887 new PermissionInfo(bp.pendingInfo)); 7888 bp.perm.info.packageName = tree.perm.info.packageName; 7889 bp.perm.info.name = bp.name; 7890 bp.uid = tree.uid; 7891 } 7892 } 7893 } 7894 if (bp.packageSetting == null) { 7895 // We may not yet have parsed the package, so just see if 7896 // we still know about its settings. 7897 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7898 } 7899 if (bp.packageSetting == null) { 7900 Slog.w(TAG, "Removing dangling permission: " + bp.name 7901 + " from package " + bp.sourcePackage); 7902 it.remove(); 7903 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7904 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7905 Slog.i(TAG, "Removing old permission: " + bp.name 7906 + " from package " + bp.sourcePackage); 7907 flags |= UPDATE_PERMISSIONS_ALL; 7908 it.remove(); 7909 } 7910 } 7911 } 7912 7913 // Now update the permissions for all packages, in particular 7914 // replace the granted permissions of the system packages. 7915 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7916 for (PackageParser.Package pkg : mPackages.values()) { 7917 if (pkg != pkgInfo) { 7918 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7919 changingPkg); 7920 } 7921 } 7922 } 7923 7924 if (pkgInfo != null) { 7925 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7926 } 7927 } 7928 7929 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7930 String packageOfInterest) { 7931 // IMPORTANT: There are two types of permissions: install and runtime. 7932 // Install time permissions are granted when the app is installed to 7933 // all device users and users added in the future. Runtime permissions 7934 // are granted at runtime explicitly to specific users. Normal and signature 7935 // protected permissions are install time permissions. Dangerous permissions 7936 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7937 // otherwise they are runtime permissions. This function does not manage 7938 // runtime permissions except for the case an app targeting Lollipop MR1 7939 // being upgraded to target a newer SDK, in which case dangerous permissions 7940 // are transformed from install time to runtime ones. 7941 7942 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7943 if (ps == null) { 7944 return; 7945 } 7946 7947 PermissionsState permissionsState = ps.getPermissionsState(); 7948 PermissionsState origPermissions = permissionsState; 7949 7950 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7951 7952 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7953 7954 boolean changedInstallPermission = false; 7955 7956 if (replace) { 7957 ps.installPermissionsFixed = false; 7958 if (!ps.isSharedUser()) { 7959 origPermissions = new PermissionsState(permissionsState); 7960 permissionsState.reset(); 7961 } 7962 } 7963 7964 permissionsState.setGlobalGids(mGlobalGids); 7965 7966 final int N = pkg.requestedPermissions.size(); 7967 for (int i=0; i<N; i++) { 7968 final String name = pkg.requestedPermissions.get(i); 7969 final BasePermission bp = mSettings.mPermissions.get(name); 7970 7971 if (DEBUG_INSTALL) { 7972 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7973 } 7974 7975 if (bp == null || bp.packageSetting == null) { 7976 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7977 Slog.w(TAG, "Unknown permission " + name 7978 + " in package " + pkg.packageName); 7979 } 7980 continue; 7981 } 7982 7983 final String perm = bp.name; 7984 boolean allowedSig = false; 7985 int grant = GRANT_DENIED; 7986 7987 // Keep track of app op permissions. 7988 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7989 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7990 if (pkgs == null) { 7991 pkgs = new ArraySet<>(); 7992 mAppOpPermissionPackages.put(bp.name, pkgs); 7993 } 7994 pkgs.add(pkg.packageName); 7995 } 7996 7997 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7998 switch (level) { 7999 case PermissionInfo.PROTECTION_NORMAL: { 8000 // For all apps normal permissions are install time ones. 8001 grant = GRANT_INSTALL; 8002 } break; 8003 8004 case PermissionInfo.PROTECTION_DANGEROUS: { 8005 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8006 // For legacy apps dangerous permissions are install time ones. 8007 grant = GRANT_INSTALL_LEGACY; 8008 } else if (origPermissions.hasInstallPermission(bp.name)) { 8009 // For legacy apps that became modern, install becomes runtime. 8010 grant = GRANT_UPGRADE; 8011 } else { 8012 // For modern apps keep runtime permissions unchanged. 8013 grant = GRANT_RUNTIME; 8014 } 8015 } break; 8016 8017 case PermissionInfo.PROTECTION_SIGNATURE: { 8018 // For all apps signature permissions are install time ones. 8019 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8020 if (allowedSig) { 8021 grant = GRANT_INSTALL; 8022 } 8023 } break; 8024 } 8025 8026 if (DEBUG_INSTALL) { 8027 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8028 } 8029 8030 if (grant != GRANT_DENIED) { 8031 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8032 // If this is an existing, non-system package, then 8033 // we can't add any new permissions to it. 8034 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8035 // Except... if this is a permission that was added 8036 // to the platform (note: need to only do this when 8037 // updating the platform). 8038 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8039 grant = GRANT_DENIED; 8040 } 8041 } 8042 } 8043 8044 switch (grant) { 8045 case GRANT_INSTALL: { 8046 // Revoke this as runtime permission to handle the case of 8047 // a runtime permission being downgraded to an install one. 8048 for (int userId : UserManagerService.getInstance().getUserIds()) { 8049 if (origPermissions.getRuntimePermissionState( 8050 bp.name, userId) != null) { 8051 // Revoke the runtime permission and clear the flags. 8052 origPermissions.revokeRuntimePermission(bp, userId); 8053 origPermissions.updatePermissionFlags(bp, userId, 8054 PackageManager.MASK_PERMISSION_FLAGS, 0); 8055 // If we revoked a permission permission, we have to write. 8056 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8057 changedRuntimePermissionUserIds, userId); 8058 } 8059 } 8060 // Grant an install permission. 8061 if (permissionsState.grantInstallPermission(bp) != 8062 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8063 changedInstallPermission = true; 8064 } 8065 } break; 8066 8067 case GRANT_INSTALL_LEGACY: { 8068 // Grant an install permission. 8069 if (permissionsState.grantInstallPermission(bp) != 8070 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8071 changedInstallPermission = true; 8072 } 8073 } break; 8074 8075 case GRANT_RUNTIME: { 8076 // Grant previously granted runtime permissions. 8077 for (int userId : UserManagerService.getInstance().getUserIds()) { 8078 PermissionState permissionState = origPermissions 8079 .getRuntimePermissionState(bp.name, userId); 8080 final int flags = permissionState != null 8081 ? permissionState.getFlags() : 0; 8082 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8083 if (permissionsState.grantRuntimePermission(bp, userId) == 8084 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8085 // If we cannot put the permission as it was, we have to write. 8086 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8087 changedRuntimePermissionUserIds, userId); 8088 } 8089 } 8090 // Propagate the permission flags. 8091 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8092 } 8093 } break; 8094 8095 case GRANT_UPGRADE: { 8096 // Grant runtime permissions for a previously held install permission. 8097 PermissionState permissionState = origPermissions 8098 .getInstallPermissionState(bp.name); 8099 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8100 8101 if (origPermissions.revokeInstallPermission(bp) 8102 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8103 // We will be transferring the permission flags, so clear them. 8104 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8105 PackageManager.MASK_PERMISSION_FLAGS, 0); 8106 changedInstallPermission = true; 8107 } 8108 8109 // If the permission is not to be promoted to runtime we ignore it and 8110 // also its other flags as they are not applicable to install permissions. 8111 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8112 for (int userId : currentUserIds) { 8113 if (permissionsState.grantRuntimePermission(bp, userId) != 8114 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8115 // Transfer the permission flags. 8116 permissionsState.updatePermissionFlags(bp, userId, 8117 flags, flags); 8118 // If we granted the permission, we have to write. 8119 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8120 changedRuntimePermissionUserIds, userId); 8121 } 8122 } 8123 } 8124 } break; 8125 8126 default: { 8127 if (packageOfInterest == null 8128 || packageOfInterest.equals(pkg.packageName)) { 8129 Slog.w(TAG, "Not granting permission " + perm 8130 + " to package " + pkg.packageName 8131 + " because it was previously installed without"); 8132 } 8133 } break; 8134 } 8135 } else { 8136 if (permissionsState.revokeInstallPermission(bp) != 8137 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8138 // Also drop the permission flags. 8139 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8140 PackageManager.MASK_PERMISSION_FLAGS, 0); 8141 changedInstallPermission = true; 8142 Slog.i(TAG, "Un-granting permission " + perm 8143 + " from package " + pkg.packageName 8144 + " (protectionLevel=" + bp.protectionLevel 8145 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8146 + ")"); 8147 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8148 // Don't print warning for app op permissions, since it is fine for them 8149 // not to be granted, there is a UI for the user to decide. 8150 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8151 Slog.w(TAG, "Not granting permission " + perm 8152 + " to package " + pkg.packageName 8153 + " (protectionLevel=" + bp.protectionLevel 8154 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8155 + ")"); 8156 } 8157 } 8158 } 8159 } 8160 8161 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8162 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8163 // This is the first that we have heard about this package, so the 8164 // permissions we have now selected are fixed until explicitly 8165 // changed. 8166 ps.installPermissionsFixed = true; 8167 } 8168 8169 // Persist the runtime permissions state for users with changes. 8170 for (int userId : changedRuntimePermissionUserIds) { 8171 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8172 } 8173 } 8174 8175 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8176 boolean allowed = false; 8177 final int NP = PackageParser.NEW_PERMISSIONS.length; 8178 for (int ip=0; ip<NP; ip++) { 8179 final PackageParser.NewPermissionInfo npi 8180 = PackageParser.NEW_PERMISSIONS[ip]; 8181 if (npi.name.equals(perm) 8182 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8183 allowed = true; 8184 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8185 + pkg.packageName); 8186 break; 8187 } 8188 } 8189 return allowed; 8190 } 8191 8192 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8193 BasePermission bp, PermissionsState origPermissions) { 8194 boolean allowed; 8195 allowed = (compareSignatures( 8196 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8197 == PackageManager.SIGNATURE_MATCH) 8198 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8199 == PackageManager.SIGNATURE_MATCH); 8200 if (!allowed && (bp.protectionLevel 8201 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8202 if (isSystemApp(pkg)) { 8203 // For updated system applications, a system permission 8204 // is granted only if it had been defined by the original application. 8205 if (pkg.isUpdatedSystemApp()) { 8206 final PackageSetting sysPs = mSettings 8207 .getDisabledSystemPkgLPr(pkg.packageName); 8208 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8209 // If the original was granted this permission, we take 8210 // that grant decision as read and propagate it to the 8211 // update. 8212 if (sysPs.isPrivileged()) { 8213 allowed = true; 8214 } 8215 } else { 8216 // The system apk may have been updated with an older 8217 // version of the one on the data partition, but which 8218 // granted a new system permission that it didn't have 8219 // before. In this case we do want to allow the app to 8220 // now get the new permission if the ancestral apk is 8221 // privileged to get it. 8222 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8223 for (int j=0; 8224 j<sysPs.pkg.requestedPermissions.size(); j++) { 8225 if (perm.equals( 8226 sysPs.pkg.requestedPermissions.get(j))) { 8227 allowed = true; 8228 break; 8229 } 8230 } 8231 } 8232 } 8233 } else { 8234 allowed = isPrivilegedApp(pkg); 8235 } 8236 } 8237 } 8238 if (!allowed && (bp.protectionLevel 8239 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8240 // For development permissions, a development permission 8241 // is granted only if it was already granted. 8242 allowed = origPermissions.hasInstallPermission(perm); 8243 } 8244 return allowed; 8245 } 8246 8247 final class ActivityIntentResolver 8248 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8249 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8250 boolean defaultOnly, int userId) { 8251 if (!sUserManager.exists(userId)) return null; 8252 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8253 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8254 } 8255 8256 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8257 int userId) { 8258 if (!sUserManager.exists(userId)) return null; 8259 mFlags = flags; 8260 return super.queryIntent(intent, resolvedType, 8261 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8262 } 8263 8264 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8265 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8266 if (!sUserManager.exists(userId)) return null; 8267 if (packageActivities == null) { 8268 return null; 8269 } 8270 mFlags = flags; 8271 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8272 final int N = packageActivities.size(); 8273 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8274 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8275 8276 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8277 for (int i = 0; i < N; ++i) { 8278 intentFilters = packageActivities.get(i).intents; 8279 if (intentFilters != null && intentFilters.size() > 0) { 8280 PackageParser.ActivityIntentInfo[] array = 8281 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8282 intentFilters.toArray(array); 8283 listCut.add(array); 8284 } 8285 } 8286 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8287 } 8288 8289 public final void addActivity(PackageParser.Activity a, String type) { 8290 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8291 mActivities.put(a.getComponentName(), a); 8292 if (DEBUG_SHOW_INFO) 8293 Log.v( 8294 TAG, " " + type + " " + 8295 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8296 if (DEBUG_SHOW_INFO) 8297 Log.v(TAG, " Class=" + a.info.name); 8298 final int NI = a.intents.size(); 8299 for (int j=0; j<NI; j++) { 8300 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8301 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8302 intent.setPriority(0); 8303 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8304 + a.className + " with priority > 0, forcing to 0"); 8305 } 8306 if (DEBUG_SHOW_INFO) { 8307 Log.v(TAG, " IntentFilter:"); 8308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8309 } 8310 if (!intent.debugCheck()) { 8311 Log.w(TAG, "==> For Activity " + a.info.name); 8312 } 8313 addFilter(intent); 8314 } 8315 } 8316 8317 public final void removeActivity(PackageParser.Activity a, String type) { 8318 mActivities.remove(a.getComponentName()); 8319 if (DEBUG_SHOW_INFO) { 8320 Log.v(TAG, " " + type + " " 8321 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8322 : a.info.name) + ":"); 8323 Log.v(TAG, " Class=" + a.info.name); 8324 } 8325 final int NI = a.intents.size(); 8326 for (int j=0; j<NI; j++) { 8327 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8328 if (DEBUG_SHOW_INFO) { 8329 Log.v(TAG, " IntentFilter:"); 8330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8331 } 8332 removeFilter(intent); 8333 } 8334 } 8335 8336 @Override 8337 protected boolean allowFilterResult( 8338 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8339 ActivityInfo filterAi = filter.activity.info; 8340 for (int i=dest.size()-1; i>=0; i--) { 8341 ActivityInfo destAi = dest.get(i).activityInfo; 8342 if (destAi.name == filterAi.name 8343 && destAi.packageName == filterAi.packageName) { 8344 return false; 8345 } 8346 } 8347 return true; 8348 } 8349 8350 @Override 8351 protected ActivityIntentInfo[] newArray(int size) { 8352 return new ActivityIntentInfo[size]; 8353 } 8354 8355 @Override 8356 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8357 if (!sUserManager.exists(userId)) return true; 8358 PackageParser.Package p = filter.activity.owner; 8359 if (p != null) { 8360 PackageSetting ps = (PackageSetting)p.mExtras; 8361 if (ps != null) { 8362 // System apps are never considered stopped for purposes of 8363 // filtering, because there may be no way for the user to 8364 // actually re-launch them. 8365 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8366 && ps.getStopped(userId); 8367 } 8368 } 8369 return false; 8370 } 8371 8372 @Override 8373 protected boolean isPackageForFilter(String packageName, 8374 PackageParser.ActivityIntentInfo info) { 8375 return packageName.equals(info.activity.owner.packageName); 8376 } 8377 8378 @Override 8379 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8380 int match, int userId) { 8381 if (!sUserManager.exists(userId)) return null; 8382 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8383 return null; 8384 } 8385 final PackageParser.Activity activity = info.activity; 8386 if (mSafeMode && (activity.info.applicationInfo.flags 8387 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8388 return null; 8389 } 8390 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8391 if (ps == null) { 8392 return null; 8393 } 8394 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8395 ps.readUserState(userId), userId); 8396 if (ai == null) { 8397 return null; 8398 } 8399 final ResolveInfo res = new ResolveInfo(); 8400 res.activityInfo = ai; 8401 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8402 res.filter = info; 8403 } 8404 if (info != null) { 8405 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8406 } 8407 res.priority = info.getPriority(); 8408 res.preferredOrder = activity.owner.mPreferredOrder; 8409 //System.out.println("Result: " + res.activityInfo.className + 8410 // " = " + res.priority); 8411 res.match = match; 8412 res.isDefault = info.hasDefault; 8413 res.labelRes = info.labelRes; 8414 res.nonLocalizedLabel = info.nonLocalizedLabel; 8415 if (userNeedsBadging(userId)) { 8416 res.noResourceId = true; 8417 } else { 8418 res.icon = info.icon; 8419 } 8420 res.iconResourceId = info.icon; 8421 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8422 return res; 8423 } 8424 8425 @Override 8426 protected void sortResults(List<ResolveInfo> results) { 8427 Collections.sort(results, mResolvePrioritySorter); 8428 } 8429 8430 @Override 8431 protected void dumpFilter(PrintWriter out, String prefix, 8432 PackageParser.ActivityIntentInfo filter) { 8433 out.print(prefix); out.print( 8434 Integer.toHexString(System.identityHashCode(filter.activity))); 8435 out.print(' '); 8436 filter.activity.printComponentShortName(out); 8437 out.print(" filter "); 8438 out.println(Integer.toHexString(System.identityHashCode(filter))); 8439 } 8440 8441 @Override 8442 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8443 return filter.activity; 8444 } 8445 8446 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8447 PackageParser.Activity activity = (PackageParser.Activity)label; 8448 out.print(prefix); out.print( 8449 Integer.toHexString(System.identityHashCode(activity))); 8450 out.print(' '); 8451 activity.printComponentShortName(out); 8452 if (count > 1) { 8453 out.print(" ("); out.print(count); out.print(" filters)"); 8454 } 8455 out.println(); 8456 } 8457 8458// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8459// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8460// final List<ResolveInfo> retList = Lists.newArrayList(); 8461// while (i.hasNext()) { 8462// final ResolveInfo resolveInfo = i.next(); 8463// if (isEnabledLP(resolveInfo.activityInfo)) { 8464// retList.add(resolveInfo); 8465// } 8466// } 8467// return retList; 8468// } 8469 8470 // Keys are String (activity class name), values are Activity. 8471 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8472 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8473 private int mFlags; 8474 } 8475 8476 private final class ServiceIntentResolver 8477 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8478 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8479 boolean defaultOnly, int userId) { 8480 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8481 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8482 } 8483 8484 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8485 int userId) { 8486 if (!sUserManager.exists(userId)) return null; 8487 mFlags = flags; 8488 return super.queryIntent(intent, resolvedType, 8489 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8490 } 8491 8492 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8493 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8494 if (!sUserManager.exists(userId)) return null; 8495 if (packageServices == null) { 8496 return null; 8497 } 8498 mFlags = flags; 8499 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8500 final int N = packageServices.size(); 8501 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8502 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8503 8504 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8505 for (int i = 0; i < N; ++i) { 8506 intentFilters = packageServices.get(i).intents; 8507 if (intentFilters != null && intentFilters.size() > 0) { 8508 PackageParser.ServiceIntentInfo[] array = 8509 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8510 intentFilters.toArray(array); 8511 listCut.add(array); 8512 } 8513 } 8514 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8515 } 8516 8517 public final void addService(PackageParser.Service s) { 8518 mServices.put(s.getComponentName(), s); 8519 if (DEBUG_SHOW_INFO) { 8520 Log.v(TAG, " " 8521 + (s.info.nonLocalizedLabel != null 8522 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8523 Log.v(TAG, " Class=" + s.info.name); 8524 } 8525 final int NI = s.intents.size(); 8526 int j; 8527 for (j=0; j<NI; j++) { 8528 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8529 if (DEBUG_SHOW_INFO) { 8530 Log.v(TAG, " IntentFilter:"); 8531 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8532 } 8533 if (!intent.debugCheck()) { 8534 Log.w(TAG, "==> For Service " + s.info.name); 8535 } 8536 addFilter(intent); 8537 } 8538 } 8539 8540 public final void removeService(PackageParser.Service s) { 8541 mServices.remove(s.getComponentName()); 8542 if (DEBUG_SHOW_INFO) { 8543 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8544 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8545 Log.v(TAG, " Class=" + s.info.name); 8546 } 8547 final int NI = s.intents.size(); 8548 int j; 8549 for (j=0; j<NI; j++) { 8550 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8551 if (DEBUG_SHOW_INFO) { 8552 Log.v(TAG, " IntentFilter:"); 8553 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8554 } 8555 removeFilter(intent); 8556 } 8557 } 8558 8559 @Override 8560 protected boolean allowFilterResult( 8561 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8562 ServiceInfo filterSi = filter.service.info; 8563 for (int i=dest.size()-1; i>=0; i--) { 8564 ServiceInfo destAi = dest.get(i).serviceInfo; 8565 if (destAi.name == filterSi.name 8566 && destAi.packageName == filterSi.packageName) { 8567 return false; 8568 } 8569 } 8570 return true; 8571 } 8572 8573 @Override 8574 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8575 return new PackageParser.ServiceIntentInfo[size]; 8576 } 8577 8578 @Override 8579 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8580 if (!sUserManager.exists(userId)) return true; 8581 PackageParser.Package p = filter.service.owner; 8582 if (p != null) { 8583 PackageSetting ps = (PackageSetting)p.mExtras; 8584 if (ps != null) { 8585 // System apps are never considered stopped for purposes of 8586 // filtering, because there may be no way for the user to 8587 // actually re-launch them. 8588 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8589 && ps.getStopped(userId); 8590 } 8591 } 8592 return false; 8593 } 8594 8595 @Override 8596 protected boolean isPackageForFilter(String packageName, 8597 PackageParser.ServiceIntentInfo info) { 8598 return packageName.equals(info.service.owner.packageName); 8599 } 8600 8601 @Override 8602 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8603 int match, int userId) { 8604 if (!sUserManager.exists(userId)) return null; 8605 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8606 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8607 return null; 8608 } 8609 final PackageParser.Service service = info.service; 8610 if (mSafeMode && (service.info.applicationInfo.flags 8611 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8612 return null; 8613 } 8614 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8615 if (ps == null) { 8616 return null; 8617 } 8618 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8619 ps.readUserState(userId), userId); 8620 if (si == null) { 8621 return null; 8622 } 8623 final ResolveInfo res = new ResolveInfo(); 8624 res.serviceInfo = si; 8625 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8626 res.filter = filter; 8627 } 8628 res.priority = info.getPriority(); 8629 res.preferredOrder = service.owner.mPreferredOrder; 8630 res.match = match; 8631 res.isDefault = info.hasDefault; 8632 res.labelRes = info.labelRes; 8633 res.nonLocalizedLabel = info.nonLocalizedLabel; 8634 res.icon = info.icon; 8635 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8636 return res; 8637 } 8638 8639 @Override 8640 protected void sortResults(List<ResolveInfo> results) { 8641 Collections.sort(results, mResolvePrioritySorter); 8642 } 8643 8644 @Override 8645 protected void dumpFilter(PrintWriter out, String prefix, 8646 PackageParser.ServiceIntentInfo filter) { 8647 out.print(prefix); out.print( 8648 Integer.toHexString(System.identityHashCode(filter.service))); 8649 out.print(' '); 8650 filter.service.printComponentShortName(out); 8651 out.print(" filter "); 8652 out.println(Integer.toHexString(System.identityHashCode(filter))); 8653 } 8654 8655 @Override 8656 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8657 return filter.service; 8658 } 8659 8660 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8661 PackageParser.Service service = (PackageParser.Service)label; 8662 out.print(prefix); out.print( 8663 Integer.toHexString(System.identityHashCode(service))); 8664 out.print(' '); 8665 service.printComponentShortName(out); 8666 if (count > 1) { 8667 out.print(" ("); out.print(count); out.print(" filters)"); 8668 } 8669 out.println(); 8670 } 8671 8672// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8673// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8674// final List<ResolveInfo> retList = Lists.newArrayList(); 8675// while (i.hasNext()) { 8676// final ResolveInfo resolveInfo = (ResolveInfo) i; 8677// if (isEnabledLP(resolveInfo.serviceInfo)) { 8678// retList.add(resolveInfo); 8679// } 8680// } 8681// return retList; 8682// } 8683 8684 // Keys are String (activity class name), values are Activity. 8685 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8686 = new ArrayMap<ComponentName, PackageParser.Service>(); 8687 private int mFlags; 8688 }; 8689 8690 private final class ProviderIntentResolver 8691 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8692 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8693 boolean defaultOnly, int userId) { 8694 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8695 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8696 } 8697 8698 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8699 int userId) { 8700 if (!sUserManager.exists(userId)) 8701 return null; 8702 mFlags = flags; 8703 return super.queryIntent(intent, resolvedType, 8704 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8705 } 8706 8707 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8708 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8709 if (!sUserManager.exists(userId)) 8710 return null; 8711 if (packageProviders == null) { 8712 return null; 8713 } 8714 mFlags = flags; 8715 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8716 final int N = packageProviders.size(); 8717 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8718 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8719 8720 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8721 for (int i = 0; i < N; ++i) { 8722 intentFilters = packageProviders.get(i).intents; 8723 if (intentFilters != null && intentFilters.size() > 0) { 8724 PackageParser.ProviderIntentInfo[] array = 8725 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8726 intentFilters.toArray(array); 8727 listCut.add(array); 8728 } 8729 } 8730 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8731 } 8732 8733 public final void addProvider(PackageParser.Provider p) { 8734 if (mProviders.containsKey(p.getComponentName())) { 8735 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8736 return; 8737 } 8738 8739 mProviders.put(p.getComponentName(), p); 8740 if (DEBUG_SHOW_INFO) { 8741 Log.v(TAG, " " 8742 + (p.info.nonLocalizedLabel != null 8743 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8744 Log.v(TAG, " Class=" + p.info.name); 8745 } 8746 final int NI = p.intents.size(); 8747 int j; 8748 for (j = 0; j < NI; j++) { 8749 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8750 if (DEBUG_SHOW_INFO) { 8751 Log.v(TAG, " IntentFilter:"); 8752 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8753 } 8754 if (!intent.debugCheck()) { 8755 Log.w(TAG, "==> For Provider " + p.info.name); 8756 } 8757 addFilter(intent); 8758 } 8759 } 8760 8761 public final void removeProvider(PackageParser.Provider p) { 8762 mProviders.remove(p.getComponentName()); 8763 if (DEBUG_SHOW_INFO) { 8764 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8765 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8766 Log.v(TAG, " Class=" + p.info.name); 8767 } 8768 final int NI = p.intents.size(); 8769 int j; 8770 for (j = 0; j < NI; j++) { 8771 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8772 if (DEBUG_SHOW_INFO) { 8773 Log.v(TAG, " IntentFilter:"); 8774 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8775 } 8776 removeFilter(intent); 8777 } 8778 } 8779 8780 @Override 8781 protected boolean allowFilterResult( 8782 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8783 ProviderInfo filterPi = filter.provider.info; 8784 for (int i = dest.size() - 1; i >= 0; i--) { 8785 ProviderInfo destPi = dest.get(i).providerInfo; 8786 if (destPi.name == filterPi.name 8787 && destPi.packageName == filterPi.packageName) { 8788 return false; 8789 } 8790 } 8791 return true; 8792 } 8793 8794 @Override 8795 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8796 return new PackageParser.ProviderIntentInfo[size]; 8797 } 8798 8799 @Override 8800 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8801 if (!sUserManager.exists(userId)) 8802 return true; 8803 PackageParser.Package p = filter.provider.owner; 8804 if (p != null) { 8805 PackageSetting ps = (PackageSetting) p.mExtras; 8806 if (ps != null) { 8807 // System apps are never considered stopped for purposes of 8808 // filtering, because there may be no way for the user to 8809 // actually re-launch them. 8810 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8811 && ps.getStopped(userId); 8812 } 8813 } 8814 return false; 8815 } 8816 8817 @Override 8818 protected boolean isPackageForFilter(String packageName, 8819 PackageParser.ProviderIntentInfo info) { 8820 return packageName.equals(info.provider.owner.packageName); 8821 } 8822 8823 @Override 8824 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8825 int match, int userId) { 8826 if (!sUserManager.exists(userId)) 8827 return null; 8828 final PackageParser.ProviderIntentInfo info = filter; 8829 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8830 return null; 8831 } 8832 final PackageParser.Provider provider = info.provider; 8833 if (mSafeMode && (provider.info.applicationInfo.flags 8834 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8835 return null; 8836 } 8837 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8838 if (ps == null) { 8839 return null; 8840 } 8841 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8842 ps.readUserState(userId), userId); 8843 if (pi == null) { 8844 return null; 8845 } 8846 final ResolveInfo res = new ResolveInfo(); 8847 res.providerInfo = pi; 8848 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8849 res.filter = filter; 8850 } 8851 res.priority = info.getPriority(); 8852 res.preferredOrder = provider.owner.mPreferredOrder; 8853 res.match = match; 8854 res.isDefault = info.hasDefault; 8855 res.labelRes = info.labelRes; 8856 res.nonLocalizedLabel = info.nonLocalizedLabel; 8857 res.icon = info.icon; 8858 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8859 return res; 8860 } 8861 8862 @Override 8863 protected void sortResults(List<ResolveInfo> results) { 8864 Collections.sort(results, mResolvePrioritySorter); 8865 } 8866 8867 @Override 8868 protected void dumpFilter(PrintWriter out, String prefix, 8869 PackageParser.ProviderIntentInfo filter) { 8870 out.print(prefix); 8871 out.print( 8872 Integer.toHexString(System.identityHashCode(filter.provider))); 8873 out.print(' '); 8874 filter.provider.printComponentShortName(out); 8875 out.print(" filter "); 8876 out.println(Integer.toHexString(System.identityHashCode(filter))); 8877 } 8878 8879 @Override 8880 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8881 return filter.provider; 8882 } 8883 8884 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8885 PackageParser.Provider provider = (PackageParser.Provider)label; 8886 out.print(prefix); out.print( 8887 Integer.toHexString(System.identityHashCode(provider))); 8888 out.print(' '); 8889 provider.printComponentShortName(out); 8890 if (count > 1) { 8891 out.print(" ("); out.print(count); out.print(" filters)"); 8892 } 8893 out.println(); 8894 } 8895 8896 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8897 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8898 private int mFlags; 8899 }; 8900 8901 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8902 new Comparator<ResolveInfo>() { 8903 public int compare(ResolveInfo r1, ResolveInfo r2) { 8904 int v1 = r1.priority; 8905 int v2 = r2.priority; 8906 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8907 if (v1 != v2) { 8908 return (v1 > v2) ? -1 : 1; 8909 } 8910 v1 = r1.preferredOrder; 8911 v2 = r2.preferredOrder; 8912 if (v1 != v2) { 8913 return (v1 > v2) ? -1 : 1; 8914 } 8915 if (r1.isDefault != r2.isDefault) { 8916 return r1.isDefault ? -1 : 1; 8917 } 8918 v1 = r1.match; 8919 v2 = r2.match; 8920 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8921 if (v1 != v2) { 8922 return (v1 > v2) ? -1 : 1; 8923 } 8924 if (r1.system != r2.system) { 8925 return r1.system ? -1 : 1; 8926 } 8927 return 0; 8928 } 8929 }; 8930 8931 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8932 new Comparator<ProviderInfo>() { 8933 public int compare(ProviderInfo p1, ProviderInfo p2) { 8934 final int v1 = p1.initOrder; 8935 final int v2 = p2.initOrder; 8936 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8937 } 8938 }; 8939 8940 final void sendPackageBroadcast(final String action, final String pkg, 8941 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8942 final int[] userIds) { 8943 mHandler.post(new Runnable() { 8944 @Override 8945 public void run() { 8946 try { 8947 final IActivityManager am = ActivityManagerNative.getDefault(); 8948 if (am == null) return; 8949 final int[] resolvedUserIds; 8950 if (userIds == null) { 8951 resolvedUserIds = am.getRunningUserIds(); 8952 } else { 8953 resolvedUserIds = userIds; 8954 } 8955 for (int id : resolvedUserIds) { 8956 final Intent intent = new Intent(action, 8957 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8958 if (extras != null) { 8959 intent.putExtras(extras); 8960 } 8961 if (targetPkg != null) { 8962 intent.setPackage(targetPkg); 8963 } 8964 // Modify the UID when posting to other users 8965 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8966 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8967 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8968 intent.putExtra(Intent.EXTRA_UID, uid); 8969 } 8970 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8971 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8972 if (DEBUG_BROADCASTS) { 8973 RuntimeException here = new RuntimeException("here"); 8974 here.fillInStackTrace(); 8975 Slog.d(TAG, "Sending to user " + id + ": " 8976 + intent.toShortString(false, true, false, false) 8977 + " " + intent.getExtras(), here); 8978 } 8979 am.broadcastIntent(null, intent, null, finishedReceiver, 8980 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8981 null, finishedReceiver != null, false, id); 8982 } 8983 } catch (RemoteException ex) { 8984 } 8985 } 8986 }); 8987 } 8988 8989 /** 8990 * Check if the external storage media is available. This is true if there 8991 * is a mounted external storage medium or if the external storage is 8992 * emulated. 8993 */ 8994 private boolean isExternalMediaAvailable() { 8995 return mMediaMounted || Environment.isExternalStorageEmulated(); 8996 } 8997 8998 @Override 8999 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9000 // writer 9001 synchronized (mPackages) { 9002 if (!isExternalMediaAvailable()) { 9003 // If the external storage is no longer mounted at this point, 9004 // the caller may not have been able to delete all of this 9005 // packages files and can not delete any more. Bail. 9006 return null; 9007 } 9008 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9009 if (lastPackage != null) { 9010 pkgs.remove(lastPackage); 9011 } 9012 if (pkgs.size() > 0) { 9013 return pkgs.get(0); 9014 } 9015 } 9016 return null; 9017 } 9018 9019 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9020 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9021 userId, andCode ? 1 : 0, packageName); 9022 if (mSystemReady) { 9023 msg.sendToTarget(); 9024 } else { 9025 if (mPostSystemReadyMessages == null) { 9026 mPostSystemReadyMessages = new ArrayList<>(); 9027 } 9028 mPostSystemReadyMessages.add(msg); 9029 } 9030 } 9031 9032 void startCleaningPackages() { 9033 // reader 9034 synchronized (mPackages) { 9035 if (!isExternalMediaAvailable()) { 9036 return; 9037 } 9038 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9039 return; 9040 } 9041 } 9042 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9043 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9044 IActivityManager am = ActivityManagerNative.getDefault(); 9045 if (am != null) { 9046 try { 9047 am.startService(null, intent, null, UserHandle.USER_OWNER); 9048 } catch (RemoteException e) { 9049 } 9050 } 9051 } 9052 9053 @Override 9054 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9055 int installFlags, String installerPackageName, VerificationParams verificationParams, 9056 String packageAbiOverride) { 9057 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9058 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9059 } 9060 9061 @Override 9062 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9063 int installFlags, String installerPackageName, VerificationParams verificationParams, 9064 String packageAbiOverride, int userId) { 9065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9066 9067 final int callingUid = Binder.getCallingUid(); 9068 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9069 9070 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9071 try { 9072 if (observer != null) { 9073 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9074 } 9075 } catch (RemoteException re) { 9076 } 9077 return; 9078 } 9079 9080 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9081 installFlags |= PackageManager.INSTALL_FROM_ADB; 9082 9083 } else { 9084 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9085 // about installerPackageName. 9086 9087 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9088 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9089 } 9090 9091 UserHandle user; 9092 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9093 user = UserHandle.ALL; 9094 } else { 9095 user = new UserHandle(userId); 9096 } 9097 9098 // Only system components can circumvent runtime permissions when installing. 9099 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9100 && mContext.checkCallingOrSelfPermission(Manifest.permission 9101 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9102 throw new SecurityException("You need the " 9103 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9104 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9105 } 9106 9107 verificationParams.setInstallerUid(callingUid); 9108 9109 final File originFile = new File(originPath); 9110 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9111 9112 final Message msg = mHandler.obtainMessage(INIT_COPY); 9113 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9114 null, verificationParams, user, packageAbiOverride); 9115 mHandler.sendMessage(msg); 9116 } 9117 9118 void installStage(String packageName, File stagedDir, String stagedCid, 9119 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9120 String installerPackageName, int installerUid, UserHandle user) { 9121 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9122 params.referrerUri, installerUid, null); 9123 9124 final OriginInfo origin; 9125 if (stagedDir != null) { 9126 origin = OriginInfo.fromStagedFile(stagedDir); 9127 } else { 9128 origin = OriginInfo.fromStagedContainer(stagedCid); 9129 } 9130 9131 final Message msg = mHandler.obtainMessage(INIT_COPY); 9132 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9133 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9134 mHandler.sendMessage(msg); 9135 } 9136 9137 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9138 Bundle extras = new Bundle(1); 9139 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9140 9141 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9142 packageName, extras, null, null, new int[] {userId}); 9143 try { 9144 IActivityManager am = ActivityManagerNative.getDefault(); 9145 final boolean isSystem = 9146 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9147 if (isSystem && am.isUserRunning(userId, false)) { 9148 // The just-installed/enabled app is bundled on the system, so presumed 9149 // to be able to run automatically without needing an explicit launch. 9150 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9151 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9152 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9153 .setPackage(packageName); 9154 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9155 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9156 } 9157 } catch (RemoteException e) { 9158 // shouldn't happen 9159 Slog.w(TAG, "Unable to bootstrap installed package", e); 9160 } 9161 } 9162 9163 @Override 9164 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9165 int userId) { 9166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9167 PackageSetting pkgSetting; 9168 final int uid = Binder.getCallingUid(); 9169 enforceCrossUserPermission(uid, userId, true, true, 9170 "setApplicationHiddenSetting for user " + userId); 9171 9172 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9173 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9174 return false; 9175 } 9176 9177 long callingId = Binder.clearCallingIdentity(); 9178 try { 9179 boolean sendAdded = false; 9180 boolean sendRemoved = false; 9181 // writer 9182 synchronized (mPackages) { 9183 pkgSetting = mSettings.mPackages.get(packageName); 9184 if (pkgSetting == null) { 9185 return false; 9186 } 9187 if (pkgSetting.getHidden(userId) != hidden) { 9188 pkgSetting.setHidden(hidden, userId); 9189 mSettings.writePackageRestrictionsLPr(userId); 9190 if (hidden) { 9191 sendRemoved = true; 9192 } else { 9193 sendAdded = true; 9194 } 9195 } 9196 } 9197 if (sendAdded) { 9198 sendPackageAddedForUser(packageName, pkgSetting, userId); 9199 return true; 9200 } 9201 if (sendRemoved) { 9202 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9203 "hiding pkg"); 9204 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9205 } 9206 } finally { 9207 Binder.restoreCallingIdentity(callingId); 9208 } 9209 return false; 9210 } 9211 9212 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9213 int userId) { 9214 final PackageRemovedInfo info = new PackageRemovedInfo(); 9215 info.removedPackage = packageName; 9216 info.removedUsers = new int[] {userId}; 9217 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9218 info.sendBroadcast(false, false, false); 9219 } 9220 9221 /** 9222 * Returns true if application is not found or there was an error. Otherwise it returns 9223 * the hidden state of the package for the given user. 9224 */ 9225 @Override 9226 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9228 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9229 false, "getApplicationHidden for user " + userId); 9230 PackageSetting pkgSetting; 9231 long callingId = Binder.clearCallingIdentity(); 9232 try { 9233 // writer 9234 synchronized (mPackages) { 9235 pkgSetting = mSettings.mPackages.get(packageName); 9236 if (pkgSetting == null) { 9237 return true; 9238 } 9239 return pkgSetting.getHidden(userId); 9240 } 9241 } finally { 9242 Binder.restoreCallingIdentity(callingId); 9243 } 9244 } 9245 9246 /** 9247 * @hide 9248 */ 9249 @Override 9250 public int installExistingPackageAsUser(String packageName, int userId) { 9251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9252 null); 9253 PackageSetting pkgSetting; 9254 final int uid = Binder.getCallingUid(); 9255 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9256 + userId); 9257 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9258 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9259 } 9260 9261 long callingId = Binder.clearCallingIdentity(); 9262 try { 9263 boolean sendAdded = false; 9264 9265 // writer 9266 synchronized (mPackages) { 9267 pkgSetting = mSettings.mPackages.get(packageName); 9268 if (pkgSetting == null) { 9269 return PackageManager.INSTALL_FAILED_INVALID_URI; 9270 } 9271 if (!pkgSetting.getInstalled(userId)) { 9272 pkgSetting.setInstalled(true, userId); 9273 pkgSetting.setHidden(false, userId); 9274 mSettings.writePackageRestrictionsLPr(userId); 9275 sendAdded = true; 9276 } 9277 } 9278 9279 if (sendAdded) { 9280 sendPackageAddedForUser(packageName, pkgSetting, userId); 9281 } 9282 } finally { 9283 Binder.restoreCallingIdentity(callingId); 9284 } 9285 9286 return PackageManager.INSTALL_SUCCEEDED; 9287 } 9288 9289 boolean isUserRestricted(int userId, String restrictionKey) { 9290 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9291 if (restrictions.getBoolean(restrictionKey, false)) { 9292 Log.w(TAG, "User is restricted: " + restrictionKey); 9293 return true; 9294 } 9295 return false; 9296 } 9297 9298 @Override 9299 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9300 mContext.enforceCallingOrSelfPermission( 9301 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9302 "Only package verification agents can verify applications"); 9303 9304 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9305 final PackageVerificationResponse response = new PackageVerificationResponse( 9306 verificationCode, Binder.getCallingUid()); 9307 msg.arg1 = id; 9308 msg.obj = response; 9309 mHandler.sendMessage(msg); 9310 } 9311 9312 @Override 9313 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9314 long millisecondsToDelay) { 9315 mContext.enforceCallingOrSelfPermission( 9316 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9317 "Only package verification agents can extend verification timeouts"); 9318 9319 final PackageVerificationState state = mPendingVerification.get(id); 9320 final PackageVerificationResponse response = new PackageVerificationResponse( 9321 verificationCodeAtTimeout, Binder.getCallingUid()); 9322 9323 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9324 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9325 } 9326 if (millisecondsToDelay < 0) { 9327 millisecondsToDelay = 0; 9328 } 9329 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9330 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9331 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9332 } 9333 9334 if ((state != null) && !state.timeoutExtended()) { 9335 state.extendTimeout(); 9336 9337 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9338 msg.arg1 = id; 9339 msg.obj = response; 9340 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9341 } 9342 } 9343 9344 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9345 int verificationCode, UserHandle user) { 9346 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9347 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9348 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9349 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9350 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9351 9352 mContext.sendBroadcastAsUser(intent, user, 9353 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9354 } 9355 9356 private ComponentName matchComponentForVerifier(String packageName, 9357 List<ResolveInfo> receivers) { 9358 ActivityInfo targetReceiver = null; 9359 9360 final int NR = receivers.size(); 9361 for (int i = 0; i < NR; i++) { 9362 final ResolveInfo info = receivers.get(i); 9363 if (info.activityInfo == null) { 9364 continue; 9365 } 9366 9367 if (packageName.equals(info.activityInfo.packageName)) { 9368 targetReceiver = info.activityInfo; 9369 break; 9370 } 9371 } 9372 9373 if (targetReceiver == null) { 9374 return null; 9375 } 9376 9377 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9378 } 9379 9380 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9381 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9382 if (pkgInfo.verifiers.length == 0) { 9383 return null; 9384 } 9385 9386 final int N = pkgInfo.verifiers.length; 9387 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9388 for (int i = 0; i < N; i++) { 9389 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9390 9391 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9392 receivers); 9393 if (comp == null) { 9394 continue; 9395 } 9396 9397 final int verifierUid = getUidForVerifier(verifierInfo); 9398 if (verifierUid == -1) { 9399 continue; 9400 } 9401 9402 if (DEBUG_VERIFY) { 9403 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9404 + " with the correct signature"); 9405 } 9406 sufficientVerifiers.add(comp); 9407 verificationState.addSufficientVerifier(verifierUid); 9408 } 9409 9410 return sufficientVerifiers; 9411 } 9412 9413 private int getUidForVerifier(VerifierInfo verifierInfo) { 9414 synchronized (mPackages) { 9415 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9416 if (pkg == null) { 9417 return -1; 9418 } else if (pkg.mSignatures.length != 1) { 9419 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9420 + " has more than one signature; ignoring"); 9421 return -1; 9422 } 9423 9424 /* 9425 * If the public key of the package's signature does not match 9426 * our expected public key, then this is a different package and 9427 * we should skip. 9428 */ 9429 9430 final byte[] expectedPublicKey; 9431 try { 9432 final Signature verifierSig = pkg.mSignatures[0]; 9433 final PublicKey publicKey = verifierSig.getPublicKey(); 9434 expectedPublicKey = publicKey.getEncoded(); 9435 } catch (CertificateException e) { 9436 return -1; 9437 } 9438 9439 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9440 9441 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9442 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9443 + " does not have the expected public key; ignoring"); 9444 return -1; 9445 } 9446 9447 return pkg.applicationInfo.uid; 9448 } 9449 } 9450 9451 @Override 9452 public void finishPackageInstall(int token) { 9453 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9454 9455 if (DEBUG_INSTALL) { 9456 Slog.v(TAG, "BM finishing package install for " + token); 9457 } 9458 9459 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9460 mHandler.sendMessage(msg); 9461 } 9462 9463 /** 9464 * Get the verification agent timeout. 9465 * 9466 * @return verification timeout in milliseconds 9467 */ 9468 private long getVerificationTimeout() { 9469 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9470 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9471 DEFAULT_VERIFICATION_TIMEOUT); 9472 } 9473 9474 /** 9475 * Get the default verification agent response code. 9476 * 9477 * @return default verification response code 9478 */ 9479 private int getDefaultVerificationResponse() { 9480 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9481 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9482 DEFAULT_VERIFICATION_RESPONSE); 9483 } 9484 9485 /** 9486 * Check whether or not package verification has been enabled. 9487 * 9488 * @return true if verification should be performed 9489 */ 9490 private boolean isVerificationEnabled(int userId, int installFlags) { 9491 if (!DEFAULT_VERIFY_ENABLE) { 9492 return false; 9493 } 9494 9495 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9496 9497 // Check if installing from ADB 9498 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9499 // Do not run verification in a test harness environment 9500 if (ActivityManager.isRunningInTestHarness()) { 9501 return false; 9502 } 9503 if (ensureVerifyAppsEnabled) { 9504 return true; 9505 } 9506 // Check if the developer does not want package verification for ADB installs 9507 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9508 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9509 return false; 9510 } 9511 } 9512 9513 if (ensureVerifyAppsEnabled) { 9514 return true; 9515 } 9516 9517 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9518 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9519 } 9520 9521 @Override 9522 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9523 throws RemoteException { 9524 mContext.enforceCallingOrSelfPermission( 9525 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9526 "Only intentfilter verification agents can verify applications"); 9527 9528 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9529 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9530 Binder.getCallingUid(), verificationCode, failedDomains); 9531 msg.arg1 = id; 9532 msg.obj = response; 9533 mHandler.sendMessage(msg); 9534 } 9535 9536 @Override 9537 public int getIntentVerificationStatus(String packageName, int userId) { 9538 synchronized (mPackages) { 9539 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9540 } 9541 } 9542 9543 @Override 9544 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9545 boolean result = false; 9546 synchronized (mPackages) { 9547 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9548 } 9549 if (result) { 9550 scheduleWritePackageRestrictionsLocked(userId); 9551 } 9552 return result; 9553 } 9554 9555 @Override 9556 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9557 synchronized (mPackages) { 9558 return mSettings.getIntentFilterVerificationsLPr(packageName); 9559 } 9560 } 9561 9562 @Override 9563 public List<IntentFilter> getAllIntentFilters(String packageName) { 9564 if (TextUtils.isEmpty(packageName)) { 9565 return Collections.<IntentFilter>emptyList(); 9566 } 9567 synchronized (mPackages) { 9568 PackageParser.Package pkg = mPackages.get(packageName); 9569 if (pkg == null || pkg.activities == null) { 9570 return Collections.<IntentFilter>emptyList(); 9571 } 9572 final int count = pkg.activities.size(); 9573 ArrayList<IntentFilter> result = new ArrayList<>(); 9574 for (int n=0; n<count; n++) { 9575 PackageParser.Activity activity = pkg.activities.get(n); 9576 if (activity.intents != null || activity.intents.size() > 0) { 9577 result.addAll(activity.intents); 9578 } 9579 } 9580 return result; 9581 } 9582 } 9583 9584 @Override 9585 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9586 synchronized (mPackages) { 9587 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9588 if (packageName != null) { 9589 result |= updateIntentVerificationStatus(packageName, 9590 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9591 UserHandle.myUserId()); 9592 } 9593 return result; 9594 } 9595 } 9596 9597 @Override 9598 public String getDefaultBrowserPackageName(int userId) { 9599 synchronized (mPackages) { 9600 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9601 } 9602 } 9603 9604 /** 9605 * Get the "allow unknown sources" setting. 9606 * 9607 * @return the current "allow unknown sources" setting 9608 */ 9609 private int getUnknownSourcesSettings() { 9610 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9611 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9612 -1); 9613 } 9614 9615 @Override 9616 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9617 final int uid = Binder.getCallingUid(); 9618 // writer 9619 synchronized (mPackages) { 9620 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9621 if (targetPackageSetting == null) { 9622 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9623 } 9624 9625 PackageSetting installerPackageSetting; 9626 if (installerPackageName != null) { 9627 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9628 if (installerPackageSetting == null) { 9629 throw new IllegalArgumentException("Unknown installer package: " 9630 + installerPackageName); 9631 } 9632 } else { 9633 installerPackageSetting = null; 9634 } 9635 9636 Signature[] callerSignature; 9637 Object obj = mSettings.getUserIdLPr(uid); 9638 if (obj != null) { 9639 if (obj instanceof SharedUserSetting) { 9640 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9641 } else if (obj instanceof PackageSetting) { 9642 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9643 } else { 9644 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9645 } 9646 } else { 9647 throw new SecurityException("Unknown calling uid " + uid); 9648 } 9649 9650 // Verify: can't set installerPackageName to a package that is 9651 // not signed with the same cert as the caller. 9652 if (installerPackageSetting != null) { 9653 if (compareSignatures(callerSignature, 9654 installerPackageSetting.signatures.mSignatures) 9655 != PackageManager.SIGNATURE_MATCH) { 9656 throw new SecurityException( 9657 "Caller does not have same cert as new installer package " 9658 + installerPackageName); 9659 } 9660 } 9661 9662 // Verify: if target already has an installer package, it must 9663 // be signed with the same cert as the caller. 9664 if (targetPackageSetting.installerPackageName != null) { 9665 PackageSetting setting = mSettings.mPackages.get( 9666 targetPackageSetting.installerPackageName); 9667 // If the currently set package isn't valid, then it's always 9668 // okay to change it. 9669 if (setting != null) { 9670 if (compareSignatures(callerSignature, 9671 setting.signatures.mSignatures) 9672 != PackageManager.SIGNATURE_MATCH) { 9673 throw new SecurityException( 9674 "Caller does not have same cert as old installer package " 9675 + targetPackageSetting.installerPackageName); 9676 } 9677 } 9678 } 9679 9680 // Okay! 9681 targetPackageSetting.installerPackageName = installerPackageName; 9682 scheduleWriteSettingsLocked(); 9683 } 9684 } 9685 9686 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9687 // Queue up an async operation since the package installation may take a little while. 9688 mHandler.post(new Runnable() { 9689 public void run() { 9690 mHandler.removeCallbacks(this); 9691 // Result object to be returned 9692 PackageInstalledInfo res = new PackageInstalledInfo(); 9693 res.returnCode = currentStatus; 9694 res.uid = -1; 9695 res.pkg = null; 9696 res.removedInfo = new PackageRemovedInfo(); 9697 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9698 args.doPreInstall(res.returnCode); 9699 synchronized (mInstallLock) { 9700 installPackageLI(args, res); 9701 } 9702 args.doPostInstall(res.returnCode, res.uid); 9703 } 9704 9705 // A restore should be performed at this point if (a) the install 9706 // succeeded, (b) the operation is not an update, and (c) the new 9707 // package has not opted out of backup participation. 9708 final boolean update = res.removedInfo.removedPackage != null; 9709 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9710 boolean doRestore = !update 9711 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9712 9713 // Set up the post-install work request bookkeeping. This will be used 9714 // and cleaned up by the post-install event handling regardless of whether 9715 // there's a restore pass performed. Token values are >= 1. 9716 int token; 9717 if (mNextInstallToken < 0) mNextInstallToken = 1; 9718 token = mNextInstallToken++; 9719 9720 PostInstallData data = new PostInstallData(args, res); 9721 mRunningInstalls.put(token, data); 9722 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9723 9724 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9725 // Pass responsibility to the Backup Manager. It will perform a 9726 // restore if appropriate, then pass responsibility back to the 9727 // Package Manager to run the post-install observer callbacks 9728 // and broadcasts. 9729 IBackupManager bm = IBackupManager.Stub.asInterface( 9730 ServiceManager.getService(Context.BACKUP_SERVICE)); 9731 if (bm != null) { 9732 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9733 + " to BM for possible restore"); 9734 try { 9735 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9736 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9737 } else { 9738 doRestore = false; 9739 } 9740 } catch (RemoteException e) { 9741 // can't happen; the backup manager is local 9742 } catch (Exception e) { 9743 Slog.e(TAG, "Exception trying to enqueue restore", e); 9744 doRestore = false; 9745 } 9746 } else { 9747 Slog.e(TAG, "Backup Manager not found!"); 9748 doRestore = false; 9749 } 9750 } 9751 9752 if (!doRestore) { 9753 // No restore possible, or the Backup Manager was mysteriously not 9754 // available -- just fire the post-install work request directly. 9755 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9756 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9757 mHandler.sendMessage(msg); 9758 } 9759 } 9760 }); 9761 } 9762 9763 private abstract class HandlerParams { 9764 private static final int MAX_RETRIES = 4; 9765 9766 /** 9767 * Number of times startCopy() has been attempted and had a non-fatal 9768 * error. 9769 */ 9770 private int mRetries = 0; 9771 9772 /** User handle for the user requesting the information or installation. */ 9773 private final UserHandle mUser; 9774 9775 HandlerParams(UserHandle user) { 9776 mUser = user; 9777 } 9778 9779 UserHandle getUser() { 9780 return mUser; 9781 } 9782 9783 final boolean startCopy() { 9784 boolean res; 9785 try { 9786 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9787 9788 if (++mRetries > MAX_RETRIES) { 9789 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9790 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9791 handleServiceError(); 9792 return false; 9793 } else { 9794 handleStartCopy(); 9795 res = true; 9796 } 9797 } catch (RemoteException e) { 9798 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9799 mHandler.sendEmptyMessage(MCS_RECONNECT); 9800 res = false; 9801 } 9802 handleReturnCode(); 9803 return res; 9804 } 9805 9806 final void serviceError() { 9807 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9808 handleServiceError(); 9809 handleReturnCode(); 9810 } 9811 9812 abstract void handleStartCopy() throws RemoteException; 9813 abstract void handleServiceError(); 9814 abstract void handleReturnCode(); 9815 } 9816 9817 class MeasureParams extends HandlerParams { 9818 private final PackageStats mStats; 9819 private boolean mSuccess; 9820 9821 private final IPackageStatsObserver mObserver; 9822 9823 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9824 super(new UserHandle(stats.userHandle)); 9825 mObserver = observer; 9826 mStats = stats; 9827 } 9828 9829 @Override 9830 public String toString() { 9831 return "MeasureParams{" 9832 + Integer.toHexString(System.identityHashCode(this)) 9833 + " " + mStats.packageName + "}"; 9834 } 9835 9836 @Override 9837 void handleStartCopy() throws RemoteException { 9838 synchronized (mInstallLock) { 9839 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9840 } 9841 9842 if (mSuccess) { 9843 final boolean mounted; 9844 if (Environment.isExternalStorageEmulated()) { 9845 mounted = true; 9846 } else { 9847 final String status = Environment.getExternalStorageState(); 9848 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9849 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9850 } 9851 9852 if (mounted) { 9853 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9854 9855 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9856 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9857 9858 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9859 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9860 9861 // Always subtract cache size, since it's a subdirectory 9862 mStats.externalDataSize -= mStats.externalCacheSize; 9863 9864 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9865 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9866 9867 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9868 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9869 } 9870 } 9871 } 9872 9873 @Override 9874 void handleReturnCode() { 9875 if (mObserver != null) { 9876 try { 9877 mObserver.onGetStatsCompleted(mStats, mSuccess); 9878 } catch (RemoteException e) { 9879 Slog.i(TAG, "Observer no longer exists."); 9880 } 9881 } 9882 } 9883 9884 @Override 9885 void handleServiceError() { 9886 Slog.e(TAG, "Could not measure application " + mStats.packageName 9887 + " external storage"); 9888 } 9889 } 9890 9891 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9892 throws RemoteException { 9893 long result = 0; 9894 for (File path : paths) { 9895 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9896 } 9897 return result; 9898 } 9899 9900 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9901 for (File path : paths) { 9902 try { 9903 mcs.clearDirectory(path.getAbsolutePath()); 9904 } catch (RemoteException e) { 9905 } 9906 } 9907 } 9908 9909 static class OriginInfo { 9910 /** 9911 * Location where install is coming from, before it has been 9912 * copied/renamed into place. This could be a single monolithic APK 9913 * file, or a cluster directory. This location may be untrusted. 9914 */ 9915 final File file; 9916 final String cid; 9917 9918 /** 9919 * Flag indicating that {@link #file} or {@link #cid} has already been 9920 * staged, meaning downstream users don't need to defensively copy the 9921 * contents. 9922 */ 9923 final boolean staged; 9924 9925 /** 9926 * Flag indicating that {@link #file} or {@link #cid} is an already 9927 * installed app that is being moved. 9928 */ 9929 final boolean existing; 9930 9931 final String resolvedPath; 9932 final File resolvedFile; 9933 9934 static OriginInfo fromNothing() { 9935 return new OriginInfo(null, null, false, false); 9936 } 9937 9938 static OriginInfo fromUntrustedFile(File file) { 9939 return new OriginInfo(file, null, false, false); 9940 } 9941 9942 static OriginInfo fromExistingFile(File file) { 9943 return new OriginInfo(file, null, false, true); 9944 } 9945 9946 static OriginInfo fromStagedFile(File file) { 9947 return new OriginInfo(file, null, true, false); 9948 } 9949 9950 static OriginInfo fromStagedContainer(String cid) { 9951 return new OriginInfo(null, cid, true, false); 9952 } 9953 9954 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9955 this.file = file; 9956 this.cid = cid; 9957 this.staged = staged; 9958 this.existing = existing; 9959 9960 if (cid != null) { 9961 resolvedPath = PackageHelper.getSdDir(cid); 9962 resolvedFile = new File(resolvedPath); 9963 } else if (file != null) { 9964 resolvedPath = file.getAbsolutePath(); 9965 resolvedFile = file; 9966 } else { 9967 resolvedPath = null; 9968 resolvedFile = null; 9969 } 9970 } 9971 } 9972 9973 class MoveInfo { 9974 final int moveId; 9975 final String fromUuid; 9976 final String toUuid; 9977 final String packageName; 9978 final String dataAppName; 9979 final int appId; 9980 final String seinfo; 9981 9982 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9983 String dataAppName, int appId, String seinfo) { 9984 this.moveId = moveId; 9985 this.fromUuid = fromUuid; 9986 this.toUuid = toUuid; 9987 this.packageName = packageName; 9988 this.dataAppName = dataAppName; 9989 this.appId = appId; 9990 this.seinfo = seinfo; 9991 } 9992 } 9993 9994 class InstallParams extends HandlerParams { 9995 final OriginInfo origin; 9996 final MoveInfo move; 9997 final IPackageInstallObserver2 observer; 9998 int installFlags; 9999 final String installerPackageName; 10000 final String volumeUuid; 10001 final VerificationParams verificationParams; 10002 private InstallArgs mArgs; 10003 private int mRet; 10004 final String packageAbiOverride; 10005 10006 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10007 int installFlags, String installerPackageName, String volumeUuid, 10008 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10009 super(user); 10010 this.origin = origin; 10011 this.move = move; 10012 this.observer = observer; 10013 this.installFlags = installFlags; 10014 this.installerPackageName = installerPackageName; 10015 this.volumeUuid = volumeUuid; 10016 this.verificationParams = verificationParams; 10017 this.packageAbiOverride = packageAbiOverride; 10018 } 10019 10020 @Override 10021 public String toString() { 10022 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10023 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10024 } 10025 10026 public ManifestDigest getManifestDigest() { 10027 if (verificationParams == null) { 10028 return null; 10029 } 10030 return verificationParams.getManifestDigest(); 10031 } 10032 10033 private int installLocationPolicy(PackageInfoLite pkgLite) { 10034 String packageName = pkgLite.packageName; 10035 int installLocation = pkgLite.installLocation; 10036 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10037 // reader 10038 synchronized (mPackages) { 10039 PackageParser.Package pkg = mPackages.get(packageName); 10040 if (pkg != null) { 10041 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10042 // Check for downgrading. 10043 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10044 try { 10045 checkDowngrade(pkg, pkgLite); 10046 } catch (PackageManagerException e) { 10047 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10048 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10049 } 10050 } 10051 // Check for updated system application. 10052 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10053 if (onSd) { 10054 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10055 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10056 } 10057 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10058 } else { 10059 if (onSd) { 10060 // Install flag overrides everything. 10061 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10062 } 10063 // If current upgrade specifies particular preference 10064 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10065 // Application explicitly specified internal. 10066 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10067 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10068 // App explictly prefers external. Let policy decide 10069 } else { 10070 // Prefer previous location 10071 if (isExternal(pkg)) { 10072 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10073 } 10074 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10075 } 10076 } 10077 } else { 10078 // Invalid install. Return error code 10079 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10080 } 10081 } 10082 } 10083 // All the special cases have been taken care of. 10084 // Return result based on recommended install location. 10085 if (onSd) { 10086 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10087 } 10088 return pkgLite.recommendedInstallLocation; 10089 } 10090 10091 /* 10092 * Invoke remote method to get package information and install 10093 * location values. Override install location based on default 10094 * policy if needed and then create install arguments based 10095 * on the install location. 10096 */ 10097 public void handleStartCopy() throws RemoteException { 10098 int ret = PackageManager.INSTALL_SUCCEEDED; 10099 10100 // If we're already staged, we've firmly committed to an install location 10101 if (origin.staged) { 10102 if (origin.file != null) { 10103 installFlags |= PackageManager.INSTALL_INTERNAL; 10104 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10105 } else if (origin.cid != null) { 10106 installFlags |= PackageManager.INSTALL_EXTERNAL; 10107 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10108 } else { 10109 throw new IllegalStateException("Invalid stage location"); 10110 } 10111 } 10112 10113 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10114 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10115 10116 PackageInfoLite pkgLite = null; 10117 10118 if (onInt && onSd) { 10119 // Check if both bits are set. 10120 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10121 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10122 } else { 10123 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10124 packageAbiOverride); 10125 10126 /* 10127 * If we have too little free space, try to free cache 10128 * before giving up. 10129 */ 10130 if (!origin.staged && pkgLite.recommendedInstallLocation 10131 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10132 // TODO: focus freeing disk space on the target device 10133 final StorageManager storage = StorageManager.from(mContext); 10134 final long lowThreshold = storage.getStorageLowBytes( 10135 Environment.getDataDirectory()); 10136 10137 final long sizeBytes = mContainerService.calculateInstalledSize( 10138 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10139 10140 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10141 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10142 installFlags, packageAbiOverride); 10143 } 10144 10145 /* 10146 * The cache free must have deleted the file we 10147 * downloaded to install. 10148 * 10149 * TODO: fix the "freeCache" call to not delete 10150 * the file we care about. 10151 */ 10152 if (pkgLite.recommendedInstallLocation 10153 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10154 pkgLite.recommendedInstallLocation 10155 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10156 } 10157 } 10158 } 10159 10160 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10161 int loc = pkgLite.recommendedInstallLocation; 10162 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10163 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10164 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10165 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10166 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10167 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10168 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10169 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10170 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10171 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10172 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10173 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10174 } else { 10175 // Override with defaults if needed. 10176 loc = installLocationPolicy(pkgLite); 10177 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10178 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10179 } else if (!onSd && !onInt) { 10180 // Override install location with flags 10181 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10182 // Set the flag to install on external media. 10183 installFlags |= PackageManager.INSTALL_EXTERNAL; 10184 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10185 } else { 10186 // Make sure the flag for installing on external 10187 // media is unset 10188 installFlags |= PackageManager.INSTALL_INTERNAL; 10189 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10190 } 10191 } 10192 } 10193 } 10194 10195 final InstallArgs args = createInstallArgs(this); 10196 mArgs = args; 10197 10198 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10199 /* 10200 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10201 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10202 */ 10203 int userIdentifier = getUser().getIdentifier(); 10204 if (userIdentifier == UserHandle.USER_ALL 10205 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10206 userIdentifier = UserHandle.USER_OWNER; 10207 } 10208 10209 /* 10210 * Determine if we have any installed package verifiers. If we 10211 * do, then we'll defer to them to verify the packages. 10212 */ 10213 final int requiredUid = mRequiredVerifierPackage == null ? -1 10214 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10215 if (!origin.existing && requiredUid != -1 10216 && isVerificationEnabled(userIdentifier, installFlags)) { 10217 final Intent verification = new Intent( 10218 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10219 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10220 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10221 PACKAGE_MIME_TYPE); 10222 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10223 10224 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10225 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10226 0 /* TODO: Which userId? */); 10227 10228 if (DEBUG_VERIFY) { 10229 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10230 + verification.toString() + " with " + pkgLite.verifiers.length 10231 + " optional verifiers"); 10232 } 10233 10234 final int verificationId = mPendingVerificationToken++; 10235 10236 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10237 10238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10239 installerPackageName); 10240 10241 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10242 installFlags); 10243 10244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10245 pkgLite.packageName); 10246 10247 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10248 pkgLite.versionCode); 10249 10250 if (verificationParams != null) { 10251 if (verificationParams.getVerificationURI() != null) { 10252 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10253 verificationParams.getVerificationURI()); 10254 } 10255 if (verificationParams.getOriginatingURI() != null) { 10256 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10257 verificationParams.getOriginatingURI()); 10258 } 10259 if (verificationParams.getReferrer() != null) { 10260 verification.putExtra(Intent.EXTRA_REFERRER, 10261 verificationParams.getReferrer()); 10262 } 10263 if (verificationParams.getOriginatingUid() >= 0) { 10264 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10265 verificationParams.getOriginatingUid()); 10266 } 10267 if (verificationParams.getInstallerUid() >= 0) { 10268 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10269 verificationParams.getInstallerUid()); 10270 } 10271 } 10272 10273 final PackageVerificationState verificationState = new PackageVerificationState( 10274 requiredUid, args); 10275 10276 mPendingVerification.append(verificationId, verificationState); 10277 10278 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10279 receivers, verificationState); 10280 10281 /* 10282 * If any sufficient verifiers were listed in the package 10283 * manifest, attempt to ask them. 10284 */ 10285 if (sufficientVerifiers != null) { 10286 final int N = sufficientVerifiers.size(); 10287 if (N == 0) { 10288 Slog.i(TAG, "Additional verifiers required, but none installed."); 10289 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10290 } else { 10291 for (int i = 0; i < N; i++) { 10292 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10293 10294 final Intent sufficientIntent = new Intent(verification); 10295 sufficientIntent.setComponent(verifierComponent); 10296 10297 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10298 } 10299 } 10300 } 10301 10302 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10303 mRequiredVerifierPackage, receivers); 10304 if (ret == PackageManager.INSTALL_SUCCEEDED 10305 && mRequiredVerifierPackage != null) { 10306 /* 10307 * Send the intent to the required verification agent, 10308 * but only start the verification timeout after the 10309 * target BroadcastReceivers have run. 10310 */ 10311 verification.setComponent(requiredVerifierComponent); 10312 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10313 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10314 new BroadcastReceiver() { 10315 @Override 10316 public void onReceive(Context context, Intent intent) { 10317 final Message msg = mHandler 10318 .obtainMessage(CHECK_PENDING_VERIFICATION); 10319 msg.arg1 = verificationId; 10320 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10321 } 10322 }, null, 0, null, null); 10323 10324 /* 10325 * We don't want the copy to proceed until verification 10326 * succeeds, so null out this field. 10327 */ 10328 mArgs = null; 10329 } 10330 } else { 10331 /* 10332 * No package verification is enabled, so immediately start 10333 * the remote call to initiate copy using temporary file. 10334 */ 10335 ret = args.copyApk(mContainerService, true); 10336 } 10337 } 10338 10339 mRet = ret; 10340 } 10341 10342 @Override 10343 void handleReturnCode() { 10344 // If mArgs is null, then MCS couldn't be reached. When it 10345 // reconnects, it will try again to install. At that point, this 10346 // will succeed. 10347 if (mArgs != null) { 10348 processPendingInstall(mArgs, mRet); 10349 } 10350 } 10351 10352 @Override 10353 void handleServiceError() { 10354 mArgs = createInstallArgs(this); 10355 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10356 } 10357 10358 public boolean isForwardLocked() { 10359 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10360 } 10361 } 10362 10363 /** 10364 * Used during creation of InstallArgs 10365 * 10366 * @param installFlags package installation flags 10367 * @return true if should be installed on external storage 10368 */ 10369 private static boolean installOnExternalAsec(int installFlags) { 10370 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10371 return false; 10372 } 10373 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10374 return true; 10375 } 10376 return false; 10377 } 10378 10379 /** 10380 * Used during creation of InstallArgs 10381 * 10382 * @param installFlags package installation flags 10383 * @return true if should be installed as forward locked 10384 */ 10385 private static boolean installForwardLocked(int installFlags) { 10386 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10387 } 10388 10389 private InstallArgs createInstallArgs(InstallParams params) { 10390 if (params.move != null) { 10391 return new MoveInstallArgs(params); 10392 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10393 return new AsecInstallArgs(params); 10394 } else { 10395 return new FileInstallArgs(params); 10396 } 10397 } 10398 10399 /** 10400 * Create args that describe an existing installed package. Typically used 10401 * when cleaning up old installs, or used as a move source. 10402 */ 10403 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10404 String resourcePath, String[] instructionSets) { 10405 final boolean isInAsec; 10406 if (installOnExternalAsec(installFlags)) { 10407 /* Apps on SD card are always in ASEC containers. */ 10408 isInAsec = true; 10409 } else if (installForwardLocked(installFlags) 10410 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10411 /* 10412 * Forward-locked apps are only in ASEC containers if they're the 10413 * new style 10414 */ 10415 isInAsec = true; 10416 } else { 10417 isInAsec = false; 10418 } 10419 10420 if (isInAsec) { 10421 return new AsecInstallArgs(codePath, instructionSets, 10422 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10423 } else { 10424 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10425 } 10426 } 10427 10428 static abstract class InstallArgs { 10429 /** @see InstallParams#origin */ 10430 final OriginInfo origin; 10431 /** @see InstallParams#move */ 10432 final MoveInfo move; 10433 10434 final IPackageInstallObserver2 observer; 10435 // Always refers to PackageManager flags only 10436 final int installFlags; 10437 final String installerPackageName; 10438 final String volumeUuid; 10439 final ManifestDigest manifestDigest; 10440 final UserHandle user; 10441 final String abiOverride; 10442 10443 // The list of instruction sets supported by this app. This is currently 10444 // only used during the rmdex() phase to clean up resources. We can get rid of this 10445 // if we move dex files under the common app path. 10446 /* nullable */ String[] instructionSets; 10447 10448 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10449 int installFlags, String installerPackageName, String volumeUuid, 10450 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10451 String abiOverride) { 10452 this.origin = origin; 10453 this.move = move; 10454 this.installFlags = installFlags; 10455 this.observer = observer; 10456 this.installerPackageName = installerPackageName; 10457 this.volumeUuid = volumeUuid; 10458 this.manifestDigest = manifestDigest; 10459 this.user = user; 10460 this.instructionSets = instructionSets; 10461 this.abiOverride = abiOverride; 10462 } 10463 10464 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10465 abstract int doPreInstall(int status); 10466 10467 /** 10468 * Rename package into final resting place. All paths on the given 10469 * scanned package should be updated to reflect the rename. 10470 */ 10471 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10472 abstract int doPostInstall(int status, int uid); 10473 10474 /** @see PackageSettingBase#codePathString */ 10475 abstract String getCodePath(); 10476 /** @see PackageSettingBase#resourcePathString */ 10477 abstract String getResourcePath(); 10478 10479 // Need installer lock especially for dex file removal. 10480 abstract void cleanUpResourcesLI(); 10481 abstract boolean doPostDeleteLI(boolean delete); 10482 10483 /** 10484 * Called before the source arguments are copied. This is used mostly 10485 * for MoveParams when it needs to read the source file to put it in the 10486 * destination. 10487 */ 10488 int doPreCopy() { 10489 return PackageManager.INSTALL_SUCCEEDED; 10490 } 10491 10492 /** 10493 * Called after the source arguments are copied. This is used mostly for 10494 * MoveParams when it needs to read the source file to put it in the 10495 * destination. 10496 * 10497 * @return 10498 */ 10499 int doPostCopy(int uid) { 10500 return PackageManager.INSTALL_SUCCEEDED; 10501 } 10502 10503 protected boolean isFwdLocked() { 10504 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10505 } 10506 10507 protected boolean isExternalAsec() { 10508 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10509 } 10510 10511 UserHandle getUser() { 10512 return user; 10513 } 10514 } 10515 10516 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10517 if (!allCodePaths.isEmpty()) { 10518 if (instructionSets == null) { 10519 throw new IllegalStateException("instructionSet == null"); 10520 } 10521 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10522 for (String codePath : allCodePaths) { 10523 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10524 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10525 if (retCode < 0) { 10526 Slog.w(TAG, "Couldn't remove dex file for package: " 10527 + " at location " + codePath + ", retcode=" + retCode); 10528 // we don't consider this to be a failure of the core package deletion 10529 } 10530 } 10531 } 10532 } 10533 } 10534 10535 /** 10536 * Logic to handle installation of non-ASEC applications, including copying 10537 * and renaming logic. 10538 */ 10539 class FileInstallArgs extends InstallArgs { 10540 private File codeFile; 10541 private File resourceFile; 10542 10543 // Example topology: 10544 // /data/app/com.example/base.apk 10545 // /data/app/com.example/split_foo.apk 10546 // /data/app/com.example/lib/arm/libfoo.so 10547 // /data/app/com.example/lib/arm64/libfoo.so 10548 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10549 10550 /** New install */ 10551 FileInstallArgs(InstallParams params) { 10552 super(params.origin, params.move, params.observer, params.installFlags, 10553 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10554 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10555 if (isFwdLocked()) { 10556 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10557 } 10558 } 10559 10560 /** Existing install */ 10561 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10562 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10563 null); 10564 this.codeFile = (codePath != null) ? new File(codePath) : null; 10565 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10566 } 10567 10568 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10569 if (origin.staged) { 10570 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10571 codeFile = origin.file; 10572 resourceFile = origin.file; 10573 return PackageManager.INSTALL_SUCCEEDED; 10574 } 10575 10576 try { 10577 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10578 codeFile = tempDir; 10579 resourceFile = tempDir; 10580 } catch (IOException e) { 10581 Slog.w(TAG, "Failed to create copy file: " + e); 10582 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10583 } 10584 10585 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10586 @Override 10587 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10588 if (!FileUtils.isValidExtFilename(name)) { 10589 throw new IllegalArgumentException("Invalid filename: " + name); 10590 } 10591 try { 10592 final File file = new File(codeFile, name); 10593 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10594 O_RDWR | O_CREAT, 0644); 10595 Os.chmod(file.getAbsolutePath(), 0644); 10596 return new ParcelFileDescriptor(fd); 10597 } catch (ErrnoException e) { 10598 throw new RemoteException("Failed to open: " + e.getMessage()); 10599 } 10600 } 10601 }; 10602 10603 int ret = PackageManager.INSTALL_SUCCEEDED; 10604 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10605 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10606 Slog.e(TAG, "Failed to copy package"); 10607 return ret; 10608 } 10609 10610 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10611 NativeLibraryHelper.Handle handle = null; 10612 try { 10613 handle = NativeLibraryHelper.Handle.create(codeFile); 10614 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10615 abiOverride); 10616 } catch (IOException e) { 10617 Slog.e(TAG, "Copying native libraries failed", e); 10618 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10619 } finally { 10620 IoUtils.closeQuietly(handle); 10621 } 10622 10623 return ret; 10624 } 10625 10626 int doPreInstall(int status) { 10627 if (status != PackageManager.INSTALL_SUCCEEDED) { 10628 cleanUp(); 10629 } 10630 return status; 10631 } 10632 10633 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10634 if (status != PackageManager.INSTALL_SUCCEEDED) { 10635 cleanUp(); 10636 return false; 10637 } 10638 10639 final File targetDir = codeFile.getParentFile(); 10640 final File beforeCodeFile = codeFile; 10641 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10642 10643 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10644 try { 10645 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10646 } catch (ErrnoException e) { 10647 Slog.w(TAG, "Failed to rename", e); 10648 return false; 10649 } 10650 10651 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10652 Slog.w(TAG, "Failed to restorecon"); 10653 return false; 10654 } 10655 10656 // Reflect the rename internally 10657 codeFile = afterCodeFile; 10658 resourceFile = afterCodeFile; 10659 10660 // Reflect the rename in scanned details 10661 pkg.codePath = afterCodeFile.getAbsolutePath(); 10662 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10663 pkg.baseCodePath); 10664 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10665 pkg.splitCodePaths); 10666 10667 // Reflect the rename in app info 10668 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10669 pkg.applicationInfo.setCodePath(pkg.codePath); 10670 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10671 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10672 pkg.applicationInfo.setResourcePath(pkg.codePath); 10673 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10674 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10675 10676 return true; 10677 } 10678 10679 int doPostInstall(int status, int uid) { 10680 if (status != PackageManager.INSTALL_SUCCEEDED) { 10681 cleanUp(); 10682 } 10683 return status; 10684 } 10685 10686 @Override 10687 String getCodePath() { 10688 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10689 } 10690 10691 @Override 10692 String getResourcePath() { 10693 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10694 } 10695 10696 private boolean cleanUp() { 10697 if (codeFile == null || !codeFile.exists()) { 10698 return false; 10699 } 10700 10701 if (codeFile.isDirectory()) { 10702 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10703 } else { 10704 codeFile.delete(); 10705 } 10706 10707 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10708 resourceFile.delete(); 10709 } 10710 10711 return true; 10712 } 10713 10714 void cleanUpResourcesLI() { 10715 // Try enumerating all code paths before deleting 10716 List<String> allCodePaths = Collections.EMPTY_LIST; 10717 if (codeFile != null && codeFile.exists()) { 10718 try { 10719 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10720 allCodePaths = pkg.getAllCodePaths(); 10721 } catch (PackageParserException e) { 10722 // Ignored; we tried our best 10723 } 10724 } 10725 10726 cleanUp(); 10727 removeDexFiles(allCodePaths, instructionSets); 10728 } 10729 10730 boolean doPostDeleteLI(boolean delete) { 10731 // XXX err, shouldn't we respect the delete flag? 10732 cleanUpResourcesLI(); 10733 return true; 10734 } 10735 } 10736 10737 private boolean isAsecExternal(String cid) { 10738 final String asecPath = PackageHelper.getSdFilesystem(cid); 10739 return !asecPath.startsWith(mAsecInternalPath); 10740 } 10741 10742 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10743 PackageManagerException { 10744 if (copyRet < 0) { 10745 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10746 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10747 throw new PackageManagerException(copyRet, message); 10748 } 10749 } 10750 } 10751 10752 /** 10753 * Extract the MountService "container ID" from the full code path of an 10754 * .apk. 10755 */ 10756 static String cidFromCodePath(String fullCodePath) { 10757 int eidx = fullCodePath.lastIndexOf("/"); 10758 String subStr1 = fullCodePath.substring(0, eidx); 10759 int sidx = subStr1.lastIndexOf("/"); 10760 return subStr1.substring(sidx+1, eidx); 10761 } 10762 10763 /** 10764 * Logic to handle installation of ASEC applications, including copying and 10765 * renaming logic. 10766 */ 10767 class AsecInstallArgs extends InstallArgs { 10768 static final String RES_FILE_NAME = "pkg.apk"; 10769 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10770 10771 String cid; 10772 String packagePath; 10773 String resourcePath; 10774 10775 /** New install */ 10776 AsecInstallArgs(InstallParams params) { 10777 super(params.origin, params.move, params.observer, params.installFlags, 10778 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10779 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10780 } 10781 10782 /** Existing install */ 10783 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10784 boolean isExternal, boolean isForwardLocked) { 10785 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10786 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10787 instructionSets, null); 10788 // Hackily pretend we're still looking at a full code path 10789 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10790 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10791 } 10792 10793 // Extract cid from fullCodePath 10794 int eidx = fullCodePath.lastIndexOf("/"); 10795 String subStr1 = fullCodePath.substring(0, eidx); 10796 int sidx = subStr1.lastIndexOf("/"); 10797 cid = subStr1.substring(sidx+1, eidx); 10798 setMountPath(subStr1); 10799 } 10800 10801 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10802 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10803 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10804 instructionSets, null); 10805 this.cid = cid; 10806 setMountPath(PackageHelper.getSdDir(cid)); 10807 } 10808 10809 void createCopyFile() { 10810 cid = mInstallerService.allocateExternalStageCidLegacy(); 10811 } 10812 10813 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10814 if (origin.staged) { 10815 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10816 cid = origin.cid; 10817 setMountPath(PackageHelper.getSdDir(cid)); 10818 return PackageManager.INSTALL_SUCCEEDED; 10819 } 10820 10821 if (temp) { 10822 createCopyFile(); 10823 } else { 10824 /* 10825 * Pre-emptively destroy the container since it's destroyed if 10826 * copying fails due to it existing anyway. 10827 */ 10828 PackageHelper.destroySdDir(cid); 10829 } 10830 10831 final String newMountPath = imcs.copyPackageToContainer( 10832 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10833 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10834 10835 if (newMountPath != null) { 10836 setMountPath(newMountPath); 10837 return PackageManager.INSTALL_SUCCEEDED; 10838 } else { 10839 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10840 } 10841 } 10842 10843 @Override 10844 String getCodePath() { 10845 return packagePath; 10846 } 10847 10848 @Override 10849 String getResourcePath() { 10850 return resourcePath; 10851 } 10852 10853 int doPreInstall(int status) { 10854 if (status != PackageManager.INSTALL_SUCCEEDED) { 10855 // Destroy container 10856 PackageHelper.destroySdDir(cid); 10857 } else { 10858 boolean mounted = PackageHelper.isContainerMounted(cid); 10859 if (!mounted) { 10860 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10861 Process.SYSTEM_UID); 10862 if (newMountPath != null) { 10863 setMountPath(newMountPath); 10864 } else { 10865 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10866 } 10867 } 10868 } 10869 return status; 10870 } 10871 10872 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10873 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10874 String newMountPath = null; 10875 if (PackageHelper.isContainerMounted(cid)) { 10876 // Unmount the container 10877 if (!PackageHelper.unMountSdDir(cid)) { 10878 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10879 return false; 10880 } 10881 } 10882 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10883 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10884 " which might be stale. Will try to clean up."); 10885 // Clean up the stale container and proceed to recreate. 10886 if (!PackageHelper.destroySdDir(newCacheId)) { 10887 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10888 return false; 10889 } 10890 // Successfully cleaned up stale container. Try to rename again. 10891 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10892 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10893 + " inspite of cleaning it up."); 10894 return false; 10895 } 10896 } 10897 if (!PackageHelper.isContainerMounted(newCacheId)) { 10898 Slog.w(TAG, "Mounting container " + newCacheId); 10899 newMountPath = PackageHelper.mountSdDir(newCacheId, 10900 getEncryptKey(), Process.SYSTEM_UID); 10901 } else { 10902 newMountPath = PackageHelper.getSdDir(newCacheId); 10903 } 10904 if (newMountPath == null) { 10905 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10906 return false; 10907 } 10908 Log.i(TAG, "Succesfully renamed " + cid + 10909 " to " + newCacheId + 10910 " at new path: " + newMountPath); 10911 cid = newCacheId; 10912 10913 final File beforeCodeFile = new File(packagePath); 10914 setMountPath(newMountPath); 10915 final File afterCodeFile = new File(packagePath); 10916 10917 // Reflect the rename in scanned details 10918 pkg.codePath = afterCodeFile.getAbsolutePath(); 10919 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10920 pkg.baseCodePath); 10921 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10922 pkg.splitCodePaths); 10923 10924 // Reflect the rename in app info 10925 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10926 pkg.applicationInfo.setCodePath(pkg.codePath); 10927 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10928 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10929 pkg.applicationInfo.setResourcePath(pkg.codePath); 10930 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10931 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10932 10933 return true; 10934 } 10935 10936 private void setMountPath(String mountPath) { 10937 final File mountFile = new File(mountPath); 10938 10939 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10940 if (monolithicFile.exists()) { 10941 packagePath = monolithicFile.getAbsolutePath(); 10942 if (isFwdLocked()) { 10943 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10944 } else { 10945 resourcePath = packagePath; 10946 } 10947 } else { 10948 packagePath = mountFile.getAbsolutePath(); 10949 resourcePath = packagePath; 10950 } 10951 } 10952 10953 int doPostInstall(int status, int uid) { 10954 if (status != PackageManager.INSTALL_SUCCEEDED) { 10955 cleanUp(); 10956 } else { 10957 final int groupOwner; 10958 final String protectedFile; 10959 if (isFwdLocked()) { 10960 groupOwner = UserHandle.getSharedAppGid(uid); 10961 protectedFile = RES_FILE_NAME; 10962 } else { 10963 groupOwner = -1; 10964 protectedFile = null; 10965 } 10966 10967 if (uid < Process.FIRST_APPLICATION_UID 10968 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10969 Slog.e(TAG, "Failed to finalize " + cid); 10970 PackageHelper.destroySdDir(cid); 10971 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10972 } 10973 10974 boolean mounted = PackageHelper.isContainerMounted(cid); 10975 if (!mounted) { 10976 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10977 } 10978 } 10979 return status; 10980 } 10981 10982 private void cleanUp() { 10983 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10984 10985 // Destroy secure container 10986 PackageHelper.destroySdDir(cid); 10987 } 10988 10989 private List<String> getAllCodePaths() { 10990 final File codeFile = new File(getCodePath()); 10991 if (codeFile != null && codeFile.exists()) { 10992 try { 10993 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10994 return pkg.getAllCodePaths(); 10995 } catch (PackageParserException e) { 10996 // Ignored; we tried our best 10997 } 10998 } 10999 return Collections.EMPTY_LIST; 11000 } 11001 11002 void cleanUpResourcesLI() { 11003 // Enumerate all code paths before deleting 11004 cleanUpResourcesLI(getAllCodePaths()); 11005 } 11006 11007 private void cleanUpResourcesLI(List<String> allCodePaths) { 11008 cleanUp(); 11009 removeDexFiles(allCodePaths, instructionSets); 11010 } 11011 11012 String getPackageName() { 11013 return getAsecPackageName(cid); 11014 } 11015 11016 boolean doPostDeleteLI(boolean delete) { 11017 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11018 final List<String> allCodePaths = getAllCodePaths(); 11019 boolean mounted = PackageHelper.isContainerMounted(cid); 11020 if (mounted) { 11021 // Unmount first 11022 if (PackageHelper.unMountSdDir(cid)) { 11023 mounted = false; 11024 } 11025 } 11026 if (!mounted && delete) { 11027 cleanUpResourcesLI(allCodePaths); 11028 } 11029 return !mounted; 11030 } 11031 11032 @Override 11033 int doPreCopy() { 11034 if (isFwdLocked()) { 11035 if (!PackageHelper.fixSdPermissions(cid, 11036 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11037 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11038 } 11039 } 11040 11041 return PackageManager.INSTALL_SUCCEEDED; 11042 } 11043 11044 @Override 11045 int doPostCopy(int uid) { 11046 if (isFwdLocked()) { 11047 if (uid < Process.FIRST_APPLICATION_UID 11048 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11049 RES_FILE_NAME)) { 11050 Slog.e(TAG, "Failed to finalize " + cid); 11051 PackageHelper.destroySdDir(cid); 11052 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11053 } 11054 } 11055 11056 return PackageManager.INSTALL_SUCCEEDED; 11057 } 11058 } 11059 11060 /** 11061 * Logic to handle movement of existing installed applications. 11062 */ 11063 class MoveInstallArgs extends InstallArgs { 11064 private File codeFile; 11065 private File resourceFile; 11066 11067 /** New install */ 11068 MoveInstallArgs(InstallParams params) { 11069 super(params.origin, params.move, params.observer, params.installFlags, 11070 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11071 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11072 } 11073 11074 int copyApk(IMediaContainerService imcs, boolean temp) { 11075 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11076 + move.fromUuid + " to " + move.toUuid); 11077 synchronized (mInstaller) { 11078 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11079 move.dataAppName, move.appId, move.seinfo) != 0) { 11080 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11081 } 11082 } 11083 11084 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11085 resourceFile = codeFile; 11086 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11087 11088 return PackageManager.INSTALL_SUCCEEDED; 11089 } 11090 11091 int doPreInstall(int status) { 11092 if (status != PackageManager.INSTALL_SUCCEEDED) { 11093 cleanUp(); 11094 } 11095 return status; 11096 } 11097 11098 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11099 if (status != PackageManager.INSTALL_SUCCEEDED) { 11100 cleanUp(); 11101 return false; 11102 } 11103 11104 // Reflect the move in app info 11105 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11106 pkg.applicationInfo.setCodePath(pkg.codePath); 11107 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11108 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11109 pkg.applicationInfo.setResourcePath(pkg.codePath); 11110 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11111 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11112 11113 return true; 11114 } 11115 11116 int doPostInstall(int status, int uid) { 11117 if (status != PackageManager.INSTALL_SUCCEEDED) { 11118 cleanUp(); 11119 } 11120 return status; 11121 } 11122 11123 @Override 11124 String getCodePath() { 11125 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11126 } 11127 11128 @Override 11129 String getResourcePath() { 11130 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11131 } 11132 11133 private boolean cleanUp() { 11134 if (codeFile == null || !codeFile.exists()) { 11135 return false; 11136 } 11137 11138 if (codeFile.isDirectory()) { 11139 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11140 } else { 11141 codeFile.delete(); 11142 } 11143 11144 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11145 resourceFile.delete(); 11146 } 11147 11148 return true; 11149 } 11150 11151 void cleanUpResourcesLI() { 11152 cleanUp(); 11153 } 11154 11155 boolean doPostDeleteLI(boolean delete) { 11156 // XXX err, shouldn't we respect the delete flag? 11157 cleanUpResourcesLI(); 11158 return true; 11159 } 11160 } 11161 11162 static String getAsecPackageName(String packageCid) { 11163 int idx = packageCid.lastIndexOf("-"); 11164 if (idx == -1) { 11165 return packageCid; 11166 } 11167 return packageCid.substring(0, idx); 11168 } 11169 11170 // Utility method used to create code paths based on package name and available index. 11171 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11172 String idxStr = ""; 11173 int idx = 1; 11174 // Fall back to default value of idx=1 if prefix is not 11175 // part of oldCodePath 11176 if (oldCodePath != null) { 11177 String subStr = oldCodePath; 11178 // Drop the suffix right away 11179 if (suffix != null && subStr.endsWith(suffix)) { 11180 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11181 } 11182 // If oldCodePath already contains prefix find out the 11183 // ending index to either increment or decrement. 11184 int sidx = subStr.lastIndexOf(prefix); 11185 if (sidx != -1) { 11186 subStr = subStr.substring(sidx + prefix.length()); 11187 if (subStr != null) { 11188 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11189 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11190 } 11191 try { 11192 idx = Integer.parseInt(subStr); 11193 if (idx <= 1) { 11194 idx++; 11195 } else { 11196 idx--; 11197 } 11198 } catch(NumberFormatException e) { 11199 } 11200 } 11201 } 11202 } 11203 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11204 return prefix + idxStr; 11205 } 11206 11207 private File getNextCodePath(File targetDir, String packageName) { 11208 int suffix = 1; 11209 File result; 11210 do { 11211 result = new File(targetDir, packageName + "-" + suffix); 11212 suffix++; 11213 } while (result.exists()); 11214 return result; 11215 } 11216 11217 // Utility method that returns the relative package path with respect 11218 // to the installation directory. Like say for /data/data/com.test-1.apk 11219 // string com.test-1 is returned. 11220 static String deriveCodePathName(String codePath) { 11221 if (codePath == null) { 11222 return null; 11223 } 11224 final File codeFile = new File(codePath); 11225 final String name = codeFile.getName(); 11226 if (codeFile.isDirectory()) { 11227 return name; 11228 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11229 final int lastDot = name.lastIndexOf('.'); 11230 return name.substring(0, lastDot); 11231 } else { 11232 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11233 return null; 11234 } 11235 } 11236 11237 class PackageInstalledInfo { 11238 String name; 11239 int uid; 11240 // The set of users that originally had this package installed. 11241 int[] origUsers; 11242 // The set of users that now have this package installed. 11243 int[] newUsers; 11244 PackageParser.Package pkg; 11245 int returnCode; 11246 String returnMsg; 11247 PackageRemovedInfo removedInfo; 11248 11249 public void setError(int code, String msg) { 11250 returnCode = code; 11251 returnMsg = msg; 11252 Slog.w(TAG, msg); 11253 } 11254 11255 public void setError(String msg, PackageParserException e) { 11256 returnCode = e.error; 11257 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11258 Slog.w(TAG, msg, e); 11259 } 11260 11261 public void setError(String msg, PackageManagerException e) { 11262 returnCode = e.error; 11263 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11264 Slog.w(TAG, msg, e); 11265 } 11266 11267 // In some error cases we want to convey more info back to the observer 11268 String origPackage; 11269 String origPermission; 11270 } 11271 11272 /* 11273 * Install a non-existing package. 11274 */ 11275 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11276 UserHandle user, String installerPackageName, String volumeUuid, 11277 PackageInstalledInfo res) { 11278 // Remember this for later, in case we need to rollback this install 11279 String pkgName = pkg.packageName; 11280 11281 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11282 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11283 UserHandle.USER_OWNER).exists(); 11284 synchronized(mPackages) { 11285 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11286 // A package with the same name is already installed, though 11287 // it has been renamed to an older name. The package we 11288 // are trying to install should be installed as an update to 11289 // the existing one, but that has not been requested, so bail. 11290 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11291 + " without first uninstalling package running as " 11292 + mSettings.mRenamedPackages.get(pkgName)); 11293 return; 11294 } 11295 if (mPackages.containsKey(pkgName)) { 11296 // Don't allow installation over an existing package with the same name. 11297 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11298 + " without first uninstalling."); 11299 return; 11300 } 11301 } 11302 11303 try { 11304 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11305 System.currentTimeMillis(), user); 11306 11307 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11308 // delete the partially installed application. the data directory will have to be 11309 // restored if it was already existing 11310 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11311 // remove package from internal structures. Note that we want deletePackageX to 11312 // delete the package data and cache directories that it created in 11313 // scanPackageLocked, unless those directories existed before we even tried to 11314 // install. 11315 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11316 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11317 res.removedInfo, true); 11318 } 11319 11320 } catch (PackageManagerException e) { 11321 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11322 } 11323 } 11324 11325 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11326 // Can't rotate keys during boot or if sharedUser. 11327 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11328 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11329 return false; 11330 } 11331 // app is using upgradeKeySets; make sure all are valid 11332 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11333 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11334 for (int i = 0; i < upgradeKeySets.length; i++) { 11335 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11336 Slog.wtf(TAG, "Package " 11337 + (oldPs.name != null ? oldPs.name : "<null>") 11338 + " contains upgrade-key-set reference to unknown key-set: " 11339 + upgradeKeySets[i] 11340 + " reverting to signatures check."); 11341 return false; 11342 } 11343 } 11344 return true; 11345 } 11346 11347 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11348 // Upgrade keysets are being used. Determine if new package has a superset of the 11349 // required keys. 11350 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11351 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11352 for (int i = 0; i < upgradeKeySets.length; i++) { 11353 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11354 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11355 return true; 11356 } 11357 } 11358 return false; 11359 } 11360 11361 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11362 UserHandle user, String installerPackageName, String volumeUuid, 11363 PackageInstalledInfo res) { 11364 final PackageParser.Package oldPackage; 11365 final String pkgName = pkg.packageName; 11366 final int[] allUsers; 11367 final boolean[] perUserInstalled; 11368 final boolean weFroze; 11369 11370 // First find the old package info and check signatures 11371 synchronized(mPackages) { 11372 oldPackage = mPackages.get(pkgName); 11373 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11374 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11375 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11376 if(!checkUpgradeKeySetLP(ps, pkg)) { 11377 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11378 "New package not signed by keys specified by upgrade-keysets: " 11379 + pkgName); 11380 return; 11381 } 11382 } else { 11383 // default to original signature matching 11384 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11385 != PackageManager.SIGNATURE_MATCH) { 11386 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11387 "New package has a different signature: " + pkgName); 11388 return; 11389 } 11390 } 11391 11392 // In case of rollback, remember per-user/profile install state 11393 allUsers = sUserManager.getUserIds(); 11394 perUserInstalled = new boolean[allUsers.length]; 11395 for (int i = 0; i < allUsers.length; i++) { 11396 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11397 } 11398 11399 // Mark the app as frozen to prevent launching during the upgrade 11400 // process, and then kill all running instances 11401 if (!ps.frozen) { 11402 ps.frozen = true; 11403 weFroze = true; 11404 } else { 11405 weFroze = false; 11406 } 11407 } 11408 11409 // Now that we're guarded by frozen state, kill app during upgrade 11410 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11411 11412 try { 11413 boolean sysPkg = (isSystemApp(oldPackage)); 11414 if (sysPkg) { 11415 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11416 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11417 } else { 11418 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11419 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11420 } 11421 } finally { 11422 // Regardless of success or failure of upgrade steps above, always 11423 // unfreeze the package if we froze it 11424 if (weFroze) { 11425 unfreezePackage(pkgName); 11426 } 11427 } 11428 } 11429 11430 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11431 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11432 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11433 String volumeUuid, PackageInstalledInfo res) { 11434 String pkgName = deletedPackage.packageName; 11435 boolean deletedPkg = true; 11436 boolean updatedSettings = false; 11437 11438 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11439 + deletedPackage); 11440 long origUpdateTime; 11441 if (pkg.mExtras != null) { 11442 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11443 } else { 11444 origUpdateTime = 0; 11445 } 11446 11447 // First delete the existing package while retaining the data directory 11448 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11449 res.removedInfo, true)) { 11450 // If the existing package wasn't successfully deleted 11451 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11452 deletedPkg = false; 11453 } else { 11454 // Successfully deleted the old package; proceed with replace. 11455 11456 // If deleted package lived in a container, give users a chance to 11457 // relinquish resources before killing. 11458 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11459 if (DEBUG_INSTALL) { 11460 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11461 } 11462 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11463 final ArrayList<String> pkgList = new ArrayList<String>(1); 11464 pkgList.add(deletedPackage.applicationInfo.packageName); 11465 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11466 } 11467 11468 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11469 try { 11470 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11471 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11472 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11473 perUserInstalled, res, user); 11474 updatedSettings = true; 11475 } catch (PackageManagerException e) { 11476 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11477 } 11478 } 11479 11480 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11481 // remove package from internal structures. Note that we want deletePackageX to 11482 // delete the package data and cache directories that it created in 11483 // scanPackageLocked, unless those directories existed before we even tried to 11484 // install. 11485 if(updatedSettings) { 11486 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11487 deletePackageLI( 11488 pkgName, null, true, allUsers, perUserInstalled, 11489 PackageManager.DELETE_KEEP_DATA, 11490 res.removedInfo, true); 11491 } 11492 // Since we failed to install the new package we need to restore the old 11493 // package that we deleted. 11494 if (deletedPkg) { 11495 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11496 File restoreFile = new File(deletedPackage.codePath); 11497 // Parse old package 11498 boolean oldExternal = isExternal(deletedPackage); 11499 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11500 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11501 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11502 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11503 try { 11504 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11505 } catch (PackageManagerException e) { 11506 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11507 + e.getMessage()); 11508 return; 11509 } 11510 // Restore of old package succeeded. Update permissions. 11511 // writer 11512 synchronized (mPackages) { 11513 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11514 UPDATE_PERMISSIONS_ALL); 11515 // can downgrade to reader 11516 mSettings.writeLPr(); 11517 } 11518 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11519 } 11520 } 11521 } 11522 11523 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11524 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11525 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11526 String volumeUuid, PackageInstalledInfo res) { 11527 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11528 + ", old=" + deletedPackage); 11529 boolean disabledSystem = false; 11530 boolean updatedSettings = false; 11531 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11532 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11533 != 0) { 11534 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11535 } 11536 String packageName = deletedPackage.packageName; 11537 if (packageName == null) { 11538 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11539 "Attempt to delete null packageName."); 11540 return; 11541 } 11542 PackageParser.Package oldPkg; 11543 PackageSetting oldPkgSetting; 11544 // reader 11545 synchronized (mPackages) { 11546 oldPkg = mPackages.get(packageName); 11547 oldPkgSetting = mSettings.mPackages.get(packageName); 11548 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11549 (oldPkgSetting == null)) { 11550 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11551 "Couldn't find package:" + packageName + " information"); 11552 return; 11553 } 11554 } 11555 11556 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11557 res.removedInfo.removedPackage = packageName; 11558 // Remove existing system package 11559 removePackageLI(oldPkgSetting, true); 11560 // writer 11561 synchronized (mPackages) { 11562 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11563 if (!disabledSystem && deletedPackage != null) { 11564 // We didn't need to disable the .apk as a current system package, 11565 // which means we are replacing another update that is already 11566 // installed. We need to make sure to delete the older one's .apk. 11567 res.removedInfo.args = createInstallArgsForExisting(0, 11568 deletedPackage.applicationInfo.getCodePath(), 11569 deletedPackage.applicationInfo.getResourcePath(), 11570 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11571 } else { 11572 res.removedInfo.args = null; 11573 } 11574 } 11575 11576 // Successfully disabled the old package. Now proceed with re-installation 11577 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11578 11579 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11580 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11581 11582 PackageParser.Package newPackage = null; 11583 try { 11584 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11585 if (newPackage.mExtras != null) { 11586 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11587 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11588 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11589 11590 // is the update attempting to change shared user? that isn't going to work... 11591 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11592 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11593 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11594 + " to " + newPkgSetting.sharedUser); 11595 updatedSettings = true; 11596 } 11597 } 11598 11599 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11600 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11601 perUserInstalled, res, user); 11602 updatedSettings = true; 11603 } 11604 11605 } catch (PackageManagerException e) { 11606 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11607 } 11608 11609 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11610 // Re installation failed. Restore old information 11611 // Remove new pkg information 11612 if (newPackage != null) { 11613 removeInstalledPackageLI(newPackage, true); 11614 } 11615 // Add back the old system package 11616 try { 11617 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11618 } catch (PackageManagerException e) { 11619 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11620 } 11621 // Restore the old system information in Settings 11622 synchronized (mPackages) { 11623 if (disabledSystem) { 11624 mSettings.enableSystemPackageLPw(packageName); 11625 } 11626 if (updatedSettings) { 11627 mSettings.setInstallerPackageName(packageName, 11628 oldPkgSetting.installerPackageName); 11629 } 11630 mSettings.writeLPr(); 11631 } 11632 } 11633 } 11634 11635 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11636 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11637 UserHandle user) { 11638 String pkgName = newPackage.packageName; 11639 synchronized (mPackages) { 11640 //write settings. the installStatus will be incomplete at this stage. 11641 //note that the new package setting would have already been 11642 //added to mPackages. It hasn't been persisted yet. 11643 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11644 mSettings.writeLPr(); 11645 } 11646 11647 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11648 11649 synchronized (mPackages) { 11650 updatePermissionsLPw(newPackage.packageName, newPackage, 11651 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11652 ? UPDATE_PERMISSIONS_ALL : 0)); 11653 // For system-bundled packages, we assume that installing an upgraded version 11654 // of the package implies that the user actually wants to run that new code, 11655 // so we enable the package. 11656 PackageSetting ps = mSettings.mPackages.get(pkgName); 11657 if (ps != null) { 11658 if (isSystemApp(newPackage)) { 11659 // NB: implicit assumption that system package upgrades apply to all users 11660 if (DEBUG_INSTALL) { 11661 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11662 } 11663 if (res.origUsers != null) { 11664 for (int userHandle : res.origUsers) { 11665 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11666 userHandle, installerPackageName); 11667 } 11668 } 11669 // Also convey the prior install/uninstall state 11670 if (allUsers != null && perUserInstalled != null) { 11671 for (int i = 0; i < allUsers.length; i++) { 11672 if (DEBUG_INSTALL) { 11673 Slog.d(TAG, " user " + allUsers[i] 11674 + " => " + perUserInstalled[i]); 11675 } 11676 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11677 } 11678 // these install state changes will be persisted in the 11679 // upcoming call to mSettings.writeLPr(). 11680 } 11681 } 11682 // It's implied that when a user requests installation, they want the app to be 11683 // installed and enabled. 11684 int userId = user.getIdentifier(); 11685 if (userId != UserHandle.USER_ALL) { 11686 ps.setInstalled(true, userId); 11687 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11688 } 11689 } 11690 res.name = pkgName; 11691 res.uid = newPackage.applicationInfo.uid; 11692 res.pkg = newPackage; 11693 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11694 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11695 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11696 //to update install status 11697 mSettings.writeLPr(); 11698 } 11699 } 11700 11701 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11702 final int installFlags = args.installFlags; 11703 final String installerPackageName = args.installerPackageName; 11704 final String volumeUuid = args.volumeUuid; 11705 final File tmpPackageFile = new File(args.getCodePath()); 11706 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11707 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11708 || (args.volumeUuid != null)); 11709 boolean replace = false; 11710 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11711 // Result object to be returned 11712 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11713 11714 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11715 // Retrieve PackageSettings and parse package 11716 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11717 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11718 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11719 PackageParser pp = new PackageParser(); 11720 pp.setSeparateProcesses(mSeparateProcesses); 11721 pp.setDisplayMetrics(mMetrics); 11722 11723 final PackageParser.Package pkg; 11724 try { 11725 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11726 } catch (PackageParserException e) { 11727 res.setError("Failed parse during installPackageLI", e); 11728 return; 11729 } 11730 11731 // Mark that we have an install time CPU ABI override. 11732 pkg.cpuAbiOverride = args.abiOverride; 11733 11734 String pkgName = res.name = pkg.packageName; 11735 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11736 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11737 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11738 return; 11739 } 11740 } 11741 11742 try { 11743 pp.collectCertificates(pkg, parseFlags); 11744 pp.collectManifestDigest(pkg); 11745 } catch (PackageParserException e) { 11746 res.setError("Failed collect during installPackageLI", e); 11747 return; 11748 } 11749 11750 /* If the installer passed in a manifest digest, compare it now. */ 11751 if (args.manifestDigest != null) { 11752 if (DEBUG_INSTALL) { 11753 final String parsedManifest = pkg.manifestDigest == null ? "null" 11754 : pkg.manifestDigest.toString(); 11755 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11756 + parsedManifest); 11757 } 11758 11759 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11760 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11761 return; 11762 } 11763 } else if (DEBUG_INSTALL) { 11764 final String parsedManifest = pkg.manifestDigest == null 11765 ? "null" : pkg.manifestDigest.toString(); 11766 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11767 } 11768 11769 // Get rid of all references to package scan path via parser. 11770 pp = null; 11771 String oldCodePath = null; 11772 boolean systemApp = false; 11773 synchronized (mPackages) { 11774 // Check if installing already existing package 11775 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11776 String oldName = mSettings.mRenamedPackages.get(pkgName); 11777 if (pkg.mOriginalPackages != null 11778 && pkg.mOriginalPackages.contains(oldName) 11779 && mPackages.containsKey(oldName)) { 11780 // This package is derived from an original package, 11781 // and this device has been updating from that original 11782 // name. We must continue using the original name, so 11783 // rename the new package here. 11784 pkg.setPackageName(oldName); 11785 pkgName = pkg.packageName; 11786 replace = true; 11787 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11788 + oldName + " pkgName=" + pkgName); 11789 } else if (mPackages.containsKey(pkgName)) { 11790 // This package, under its official name, already exists 11791 // on the device; we should replace it. 11792 replace = true; 11793 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11794 } 11795 11796 // Prevent apps opting out from runtime permissions 11797 if (replace) { 11798 PackageParser.Package oldPackage = mPackages.get(pkgName); 11799 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11800 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11801 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11802 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11803 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11804 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11805 + " doesn't support runtime permissions but the old" 11806 + " target SDK " + oldTargetSdk + " does."); 11807 return; 11808 } 11809 } 11810 } 11811 11812 PackageSetting ps = mSettings.mPackages.get(pkgName); 11813 if (ps != null) { 11814 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11815 11816 // Quick sanity check that we're signed correctly if updating; 11817 // we'll check this again later when scanning, but we want to 11818 // bail early here before tripping over redefined permissions. 11819 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11820 if (!checkUpgradeKeySetLP(ps, pkg)) { 11821 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11822 + pkg.packageName + " upgrade keys do not match the " 11823 + "previously installed version"); 11824 return; 11825 } 11826 } else { 11827 try { 11828 verifySignaturesLP(ps, pkg); 11829 } catch (PackageManagerException e) { 11830 res.setError(e.error, e.getMessage()); 11831 return; 11832 } 11833 } 11834 11835 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11836 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11837 systemApp = (ps.pkg.applicationInfo.flags & 11838 ApplicationInfo.FLAG_SYSTEM) != 0; 11839 } 11840 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11841 } 11842 11843 // Check whether the newly-scanned package wants to define an already-defined perm 11844 int N = pkg.permissions.size(); 11845 for (int i = N-1; i >= 0; i--) { 11846 PackageParser.Permission perm = pkg.permissions.get(i); 11847 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11848 if (bp != null) { 11849 // If the defining package is signed with our cert, it's okay. This 11850 // also includes the "updating the same package" case, of course. 11851 // "updating same package" could also involve key-rotation. 11852 final boolean sigsOk; 11853 if (bp.sourcePackage.equals(pkg.packageName) 11854 && (bp.packageSetting instanceof PackageSetting) 11855 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11856 scanFlags))) { 11857 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11858 } else { 11859 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11860 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11861 } 11862 if (!sigsOk) { 11863 // If the owning package is the system itself, we log but allow 11864 // install to proceed; we fail the install on all other permission 11865 // redefinitions. 11866 if (!bp.sourcePackage.equals("android")) { 11867 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11868 + pkg.packageName + " attempting to redeclare permission " 11869 + perm.info.name + " already owned by " + bp.sourcePackage); 11870 res.origPermission = perm.info.name; 11871 res.origPackage = bp.sourcePackage; 11872 return; 11873 } else { 11874 Slog.w(TAG, "Package " + pkg.packageName 11875 + " attempting to redeclare system permission " 11876 + perm.info.name + "; ignoring new declaration"); 11877 pkg.permissions.remove(i); 11878 } 11879 } 11880 } 11881 } 11882 11883 } 11884 11885 if (systemApp && onExternal) { 11886 // Disable updates to system apps on sdcard 11887 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11888 "Cannot install updates to system apps on sdcard"); 11889 return; 11890 } 11891 11892 if (args.move != null) { 11893 // We did an in-place move, so dex is ready to roll 11894 scanFlags |= SCAN_NO_DEX; 11895 scanFlags |= SCAN_MOVE; 11896 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11897 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11898 scanFlags |= SCAN_NO_DEX; 11899 11900 try { 11901 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11902 true /* extract libs */); 11903 } catch (PackageManagerException pme) { 11904 Slog.e(TAG, "Error deriving application ABI", pme); 11905 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11906 return; 11907 } 11908 11909 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11910 int result = mPackageDexOptimizer 11911 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11912 false /* defer */, false /* inclDependencies */); 11913 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11914 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11915 return; 11916 } 11917 } 11918 11919 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11920 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11921 return; 11922 } 11923 11924 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 11925 11926 if (replace) { 11927 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11928 installerPackageName, volumeUuid, res); 11929 } else { 11930 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11931 args.user, installerPackageName, volumeUuid, res); 11932 } 11933 synchronized (mPackages) { 11934 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11935 if (ps != null) { 11936 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11937 } 11938 } 11939 } 11940 11941 private void startIntentFilterVerifications(int userId, boolean replacing, 11942 PackageParser.Package pkg) { 11943 if (mIntentFilterVerifierComponent == null) { 11944 Slog.w(TAG, "No IntentFilter verification will not be done as " 11945 + "there is no IntentFilterVerifier available!"); 11946 return; 11947 } 11948 11949 final int verifierUid = getPackageUid( 11950 mIntentFilterVerifierComponent.getPackageName(), 11951 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11952 11953 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11954 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11955 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 11956 mHandler.sendMessage(msg); 11957 } 11958 11959 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 11960 PackageParser.Package pkg) { 11961 int size = pkg.activities.size(); 11962 if (size == 0) { 11963 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11964 "No activity, so no need to verify any IntentFilter!"); 11965 return; 11966 } 11967 11968 final boolean hasDomainURLs = hasDomainURLs(pkg); 11969 if (!hasDomainURLs) { 11970 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11971 "No domain URLs, so no need to verify any IntentFilter!"); 11972 return; 11973 } 11974 11975 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11976 + " if any IntentFilter from the " + size 11977 + " Activities needs verification ..."); 11978 11979 int count = 0; 11980 final String packageName = pkg.packageName; 11981 11982 synchronized (mPackages) { 11983 // If this is a new install and we see that we've already run verification for this 11984 // package, we have nothing to do: it means the state was restored from backup. 11985 if (!replacing) { 11986 IntentFilterVerificationInfo ivi = 11987 mSettings.getIntentFilterVerificationLPr(packageName); 11988 if (ivi != null) { 11989 if (DEBUG_DOMAIN_VERIFICATION) { 11990 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 11991 + ivi.getStatusString()); 11992 } 11993 return; 11994 } 11995 } 11996 11997 // If any filters need to be verified, then all need to be. 11998 boolean needToVerify = false; 11999 for (PackageParser.Activity a : pkg.activities) { 12000 for (ActivityIntentInfo filter : a.intents) { 12001 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12002 if (DEBUG_DOMAIN_VERIFICATION) { 12003 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12004 } 12005 needToVerify = true; 12006 break; 12007 } 12008 } 12009 } 12010 12011 if (needToVerify) { 12012 final int verificationId = mIntentFilterVerificationToken++; 12013 for (PackageParser.Activity a : pkg.activities) { 12014 for (ActivityIntentInfo filter : a.intents) { 12015 boolean needsFilterVerification = filter.hasWebDataURI(); 12016 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 12017 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12018 "Verification needed for IntentFilter:" + filter.toString()); 12019 mIntentFilterVerifier.addOneIntentFilterVerification( 12020 verifierUid, userId, verificationId, filter, packageName); 12021 count++; 12022 } 12023 } 12024 } 12025 } 12026 } 12027 12028 if (count > 0) { 12029 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12030 + " IntentFilter verification" + (count > 1 ? "s" : "") 12031 + " for userId:" + userId); 12032 mIntentFilterVerifier.startVerifications(userId); 12033 } else { 12034 if (DEBUG_DOMAIN_VERIFICATION) { 12035 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12036 } 12037 } 12038 } 12039 12040 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12041 final ComponentName cn = filter.activity.getComponentName(); 12042 final String packageName = cn.getPackageName(); 12043 12044 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12045 packageName); 12046 if (ivi == null) { 12047 return true; 12048 } 12049 int status = ivi.getStatus(); 12050 switch (status) { 12051 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12052 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12053 return true; 12054 12055 default: 12056 // Nothing to do 12057 return false; 12058 } 12059 } 12060 12061 private static boolean isMultiArch(PackageSetting ps) { 12062 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12063 } 12064 12065 private static boolean isMultiArch(ApplicationInfo info) { 12066 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12067 } 12068 12069 private static boolean isExternal(PackageParser.Package pkg) { 12070 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12071 } 12072 12073 private static boolean isExternal(PackageSetting ps) { 12074 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12075 } 12076 12077 private static boolean isExternal(ApplicationInfo info) { 12078 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12079 } 12080 12081 private static boolean isSystemApp(PackageParser.Package pkg) { 12082 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12083 } 12084 12085 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12086 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12087 } 12088 12089 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12090 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12091 } 12092 12093 private static boolean isSystemApp(PackageSetting ps) { 12094 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12095 } 12096 12097 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12098 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12099 } 12100 12101 private int packageFlagsToInstallFlags(PackageSetting ps) { 12102 int installFlags = 0; 12103 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12104 // This existing package was an external ASEC install when we have 12105 // the external flag without a UUID 12106 installFlags |= PackageManager.INSTALL_EXTERNAL; 12107 } 12108 if (ps.isForwardLocked()) { 12109 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12110 } 12111 return installFlags; 12112 } 12113 12114 private void deleteTempPackageFiles() { 12115 final FilenameFilter filter = new FilenameFilter() { 12116 public boolean accept(File dir, String name) { 12117 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12118 } 12119 }; 12120 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12121 file.delete(); 12122 } 12123 } 12124 12125 @Override 12126 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12127 int flags) { 12128 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12129 flags); 12130 } 12131 12132 @Override 12133 public void deletePackage(final String packageName, 12134 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12135 mContext.enforceCallingOrSelfPermission( 12136 android.Manifest.permission.DELETE_PACKAGES, null); 12137 final int uid = Binder.getCallingUid(); 12138 if (UserHandle.getUserId(uid) != userId) { 12139 mContext.enforceCallingPermission( 12140 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12141 "deletePackage for user " + userId); 12142 } 12143 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12144 try { 12145 observer.onPackageDeleted(packageName, 12146 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12147 } catch (RemoteException re) { 12148 } 12149 return; 12150 } 12151 12152 boolean uninstallBlocked = false; 12153 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12154 int[] users = sUserManager.getUserIds(); 12155 for (int i = 0; i < users.length; ++i) { 12156 if (getBlockUninstallForUser(packageName, users[i])) { 12157 uninstallBlocked = true; 12158 break; 12159 } 12160 } 12161 } else { 12162 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12163 } 12164 if (uninstallBlocked) { 12165 try { 12166 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12167 null); 12168 } catch (RemoteException re) { 12169 } 12170 return; 12171 } 12172 12173 if (DEBUG_REMOVE) { 12174 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12175 } 12176 // Queue up an async operation since the package deletion may take a little while. 12177 mHandler.post(new Runnable() { 12178 public void run() { 12179 mHandler.removeCallbacks(this); 12180 final int returnCode = deletePackageX(packageName, userId, flags); 12181 if (observer != null) { 12182 try { 12183 observer.onPackageDeleted(packageName, returnCode, null); 12184 } catch (RemoteException e) { 12185 Log.i(TAG, "Observer no longer exists."); 12186 } //end catch 12187 } //end if 12188 } //end run 12189 }); 12190 } 12191 12192 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12193 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12194 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12195 try { 12196 if (dpm != null) { 12197 if (dpm.isDeviceOwner(packageName)) { 12198 return true; 12199 } 12200 int[] users; 12201 if (userId == UserHandle.USER_ALL) { 12202 users = sUserManager.getUserIds(); 12203 } else { 12204 users = new int[]{userId}; 12205 } 12206 for (int i = 0; i < users.length; ++i) { 12207 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12208 return true; 12209 } 12210 } 12211 } 12212 } catch (RemoteException e) { 12213 } 12214 return false; 12215 } 12216 12217 /** 12218 * This method is an internal method that could be get invoked either 12219 * to delete an installed package or to clean up a failed installation. 12220 * After deleting an installed package, a broadcast is sent to notify any 12221 * listeners that the package has been installed. For cleaning up a failed 12222 * installation, the broadcast is not necessary since the package's 12223 * installation wouldn't have sent the initial broadcast either 12224 * The key steps in deleting a package are 12225 * deleting the package information in internal structures like mPackages, 12226 * deleting the packages base directories through installd 12227 * updating mSettings to reflect current status 12228 * persisting settings for later use 12229 * sending a broadcast if necessary 12230 */ 12231 private int deletePackageX(String packageName, int userId, int flags) { 12232 final PackageRemovedInfo info = new PackageRemovedInfo(); 12233 final boolean res; 12234 12235 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12236 ? UserHandle.ALL : new UserHandle(userId); 12237 12238 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12239 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12240 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12241 } 12242 12243 boolean removedForAllUsers = false; 12244 boolean systemUpdate = false; 12245 12246 // for the uninstall-updates case and restricted profiles, remember the per- 12247 // userhandle installed state 12248 int[] allUsers; 12249 boolean[] perUserInstalled; 12250 synchronized (mPackages) { 12251 PackageSetting ps = mSettings.mPackages.get(packageName); 12252 allUsers = sUserManager.getUserIds(); 12253 perUserInstalled = new boolean[allUsers.length]; 12254 for (int i = 0; i < allUsers.length; i++) { 12255 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12256 } 12257 } 12258 12259 synchronized (mInstallLock) { 12260 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12261 res = deletePackageLI(packageName, removeForUser, 12262 true, allUsers, perUserInstalled, 12263 flags | REMOVE_CHATTY, info, true); 12264 systemUpdate = info.isRemovedPackageSystemUpdate; 12265 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12266 removedForAllUsers = true; 12267 } 12268 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12269 + " removedForAllUsers=" + removedForAllUsers); 12270 } 12271 12272 if (res) { 12273 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12274 12275 // If the removed package was a system update, the old system package 12276 // was re-enabled; we need to broadcast this information 12277 if (systemUpdate) { 12278 Bundle extras = new Bundle(1); 12279 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12280 ? info.removedAppId : info.uid); 12281 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12282 12283 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12284 extras, null, null, null); 12285 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12286 extras, null, null, null); 12287 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12288 null, packageName, null, null); 12289 } 12290 } 12291 // Force a gc here. 12292 Runtime.getRuntime().gc(); 12293 // Delete the resources here after sending the broadcast to let 12294 // other processes clean up before deleting resources. 12295 if (info.args != null) { 12296 synchronized (mInstallLock) { 12297 info.args.doPostDeleteLI(true); 12298 } 12299 } 12300 12301 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12302 } 12303 12304 class PackageRemovedInfo { 12305 String removedPackage; 12306 int uid = -1; 12307 int removedAppId = -1; 12308 int[] removedUsers = null; 12309 boolean isRemovedPackageSystemUpdate = false; 12310 // Clean up resources deleted packages. 12311 InstallArgs args = null; 12312 12313 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12314 Bundle extras = new Bundle(1); 12315 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12316 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12317 if (replacing) { 12318 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12319 } 12320 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12321 if (removedPackage != null) { 12322 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12323 extras, null, null, removedUsers); 12324 if (fullRemove && !replacing) { 12325 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12326 extras, null, null, removedUsers); 12327 } 12328 } 12329 if (removedAppId >= 0) { 12330 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12331 removedUsers); 12332 } 12333 } 12334 } 12335 12336 /* 12337 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12338 * flag is not set, the data directory is removed as well. 12339 * make sure this flag is set for partially installed apps. If not its meaningless to 12340 * delete a partially installed application. 12341 */ 12342 private void removePackageDataLI(PackageSetting ps, 12343 int[] allUserHandles, boolean[] perUserInstalled, 12344 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12345 String packageName = ps.name; 12346 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12347 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12348 // Retrieve object to delete permissions for shared user later on 12349 final PackageSetting deletedPs; 12350 // reader 12351 synchronized (mPackages) { 12352 deletedPs = mSettings.mPackages.get(packageName); 12353 if (outInfo != null) { 12354 outInfo.removedPackage = packageName; 12355 outInfo.removedUsers = deletedPs != null 12356 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12357 : null; 12358 } 12359 } 12360 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12361 removeDataDirsLI(ps.volumeUuid, packageName); 12362 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12363 } 12364 // writer 12365 synchronized (mPackages) { 12366 if (deletedPs != null) { 12367 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12368 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12369 clearDefaultBrowserIfNeeded(packageName); 12370 if (outInfo != null) { 12371 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12372 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12373 } 12374 updatePermissionsLPw(deletedPs.name, null, 0); 12375 if (deletedPs.sharedUser != null) { 12376 // Remove permissions associated with package. Since runtime 12377 // permissions are per user we have to kill the removed package 12378 // or packages running under the shared user of the removed 12379 // package if revoking the permissions requested only by the removed 12380 // package is successful and this causes a change in gids. 12381 for (int userId : UserManagerService.getInstance().getUserIds()) { 12382 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12383 userId); 12384 if (userIdToKill == UserHandle.USER_ALL 12385 || userIdToKill >= UserHandle.USER_OWNER) { 12386 // If gids changed for this user, kill all affected packages. 12387 mHandler.post(new Runnable() { 12388 @Override 12389 public void run() { 12390 // This has to happen with no lock held. 12391 killSettingPackagesForUser(deletedPs, userIdToKill, 12392 KILL_APP_REASON_GIDS_CHANGED); 12393 } 12394 }); 12395 break; 12396 } 12397 } 12398 } 12399 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12400 } 12401 // make sure to preserve per-user disabled state if this removal was just 12402 // a downgrade of a system app to the factory package 12403 if (allUserHandles != null && perUserInstalled != null) { 12404 if (DEBUG_REMOVE) { 12405 Slog.d(TAG, "Propagating install state across downgrade"); 12406 } 12407 for (int i = 0; i < allUserHandles.length; i++) { 12408 if (DEBUG_REMOVE) { 12409 Slog.d(TAG, " user " + allUserHandles[i] 12410 + " => " + perUserInstalled[i]); 12411 } 12412 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12413 } 12414 } 12415 } 12416 // can downgrade to reader 12417 if (writeSettings) { 12418 // Save settings now 12419 mSettings.writeLPr(); 12420 } 12421 } 12422 if (outInfo != null) { 12423 // A user ID was deleted here. Go through all users and remove it 12424 // from KeyStore. 12425 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12426 } 12427 } 12428 12429 static boolean locationIsPrivileged(File path) { 12430 try { 12431 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12432 .getCanonicalPath(); 12433 return path.getCanonicalPath().startsWith(privilegedAppDir); 12434 } catch (IOException e) { 12435 Slog.e(TAG, "Unable to access code path " + path); 12436 } 12437 return false; 12438 } 12439 12440 /* 12441 * Tries to delete system package. 12442 */ 12443 private boolean deleteSystemPackageLI(PackageSetting newPs, 12444 int[] allUserHandles, boolean[] perUserInstalled, 12445 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12446 final boolean applyUserRestrictions 12447 = (allUserHandles != null) && (perUserInstalled != null); 12448 PackageSetting disabledPs = null; 12449 // Confirm if the system package has been updated 12450 // An updated system app can be deleted. This will also have to restore 12451 // the system pkg from system partition 12452 // reader 12453 synchronized (mPackages) { 12454 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12455 } 12456 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12457 + " disabledPs=" + disabledPs); 12458 if (disabledPs == null) { 12459 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12460 return false; 12461 } else if (DEBUG_REMOVE) { 12462 Slog.d(TAG, "Deleting system pkg from data partition"); 12463 } 12464 if (DEBUG_REMOVE) { 12465 if (applyUserRestrictions) { 12466 Slog.d(TAG, "Remembering install states:"); 12467 for (int i = 0; i < allUserHandles.length; i++) { 12468 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12469 } 12470 } 12471 } 12472 // Delete the updated package 12473 outInfo.isRemovedPackageSystemUpdate = true; 12474 if (disabledPs.versionCode < newPs.versionCode) { 12475 // Delete data for downgrades 12476 flags &= ~PackageManager.DELETE_KEEP_DATA; 12477 } else { 12478 // Preserve data by setting flag 12479 flags |= PackageManager.DELETE_KEEP_DATA; 12480 } 12481 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12482 allUserHandles, perUserInstalled, outInfo, writeSettings); 12483 if (!ret) { 12484 return false; 12485 } 12486 // writer 12487 synchronized (mPackages) { 12488 // Reinstate the old system package 12489 mSettings.enableSystemPackageLPw(newPs.name); 12490 // Remove any native libraries from the upgraded package. 12491 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12492 } 12493 // Install the system package 12494 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12495 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12496 if (locationIsPrivileged(disabledPs.codePath)) { 12497 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12498 } 12499 12500 final PackageParser.Package newPkg; 12501 try { 12502 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12503 } catch (PackageManagerException e) { 12504 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12505 return false; 12506 } 12507 12508 // writer 12509 synchronized (mPackages) { 12510 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12511 updatePermissionsLPw(newPkg.packageName, newPkg, 12512 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12513 if (applyUserRestrictions) { 12514 if (DEBUG_REMOVE) { 12515 Slog.d(TAG, "Propagating install state across reinstall"); 12516 } 12517 for (int i = 0; i < allUserHandles.length; i++) { 12518 if (DEBUG_REMOVE) { 12519 Slog.d(TAG, " user " + allUserHandles[i] 12520 + " => " + perUserInstalled[i]); 12521 } 12522 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12523 } 12524 // Regardless of writeSettings we need to ensure that this restriction 12525 // state propagation is persisted 12526 mSettings.writeAllUsersPackageRestrictionsLPr(); 12527 } 12528 // can downgrade to reader here 12529 if (writeSettings) { 12530 mSettings.writeLPr(); 12531 } 12532 } 12533 return true; 12534 } 12535 12536 private boolean deleteInstalledPackageLI(PackageSetting ps, 12537 boolean deleteCodeAndResources, int flags, 12538 int[] allUserHandles, boolean[] perUserInstalled, 12539 PackageRemovedInfo outInfo, boolean writeSettings) { 12540 if (outInfo != null) { 12541 outInfo.uid = ps.appId; 12542 } 12543 12544 // Delete package data from internal structures and also remove data if flag is set 12545 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12546 12547 // Delete application code and resources 12548 if (deleteCodeAndResources && (outInfo != null)) { 12549 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12550 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12551 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12552 } 12553 return true; 12554 } 12555 12556 @Override 12557 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12558 int userId) { 12559 mContext.enforceCallingOrSelfPermission( 12560 android.Manifest.permission.DELETE_PACKAGES, null); 12561 synchronized (mPackages) { 12562 PackageSetting ps = mSettings.mPackages.get(packageName); 12563 if (ps == null) { 12564 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12565 return false; 12566 } 12567 if (!ps.getInstalled(userId)) { 12568 // Can't block uninstall for an app that is not installed or enabled. 12569 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12570 return false; 12571 } 12572 ps.setBlockUninstall(blockUninstall, userId); 12573 mSettings.writePackageRestrictionsLPr(userId); 12574 } 12575 return true; 12576 } 12577 12578 @Override 12579 public boolean getBlockUninstallForUser(String packageName, int userId) { 12580 synchronized (mPackages) { 12581 PackageSetting ps = mSettings.mPackages.get(packageName); 12582 if (ps == null) { 12583 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12584 return false; 12585 } 12586 return ps.getBlockUninstall(userId); 12587 } 12588 } 12589 12590 /* 12591 * This method handles package deletion in general 12592 */ 12593 private boolean deletePackageLI(String packageName, UserHandle user, 12594 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12595 int flags, PackageRemovedInfo outInfo, 12596 boolean writeSettings) { 12597 if (packageName == null) { 12598 Slog.w(TAG, "Attempt to delete null packageName."); 12599 return false; 12600 } 12601 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12602 PackageSetting ps; 12603 boolean dataOnly = false; 12604 int removeUser = -1; 12605 int appId = -1; 12606 synchronized (mPackages) { 12607 ps = mSettings.mPackages.get(packageName); 12608 if (ps == null) { 12609 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12610 return false; 12611 } 12612 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12613 && user.getIdentifier() != UserHandle.USER_ALL) { 12614 // The caller is asking that the package only be deleted for a single 12615 // user. To do this, we just mark its uninstalled state and delete 12616 // its data. If this is a system app, we only allow this to happen if 12617 // they have set the special DELETE_SYSTEM_APP which requests different 12618 // semantics than normal for uninstalling system apps. 12619 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12620 ps.setUserState(user.getIdentifier(), 12621 COMPONENT_ENABLED_STATE_DEFAULT, 12622 false, //installed 12623 true, //stopped 12624 true, //notLaunched 12625 false, //hidden 12626 null, null, null, 12627 false, // blockUninstall 12628 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12629 if (!isSystemApp(ps)) { 12630 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12631 // Other user still have this package installed, so all 12632 // we need to do is clear this user's data and save that 12633 // it is uninstalled. 12634 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12635 removeUser = user.getIdentifier(); 12636 appId = ps.appId; 12637 scheduleWritePackageRestrictionsLocked(removeUser); 12638 } else { 12639 // We need to set it back to 'installed' so the uninstall 12640 // broadcasts will be sent correctly. 12641 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12642 ps.setInstalled(true, user.getIdentifier()); 12643 } 12644 } else { 12645 // This is a system app, so we assume that the 12646 // other users still have this package installed, so all 12647 // we need to do is clear this user's data and save that 12648 // it is uninstalled. 12649 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12650 removeUser = user.getIdentifier(); 12651 appId = ps.appId; 12652 scheduleWritePackageRestrictionsLocked(removeUser); 12653 } 12654 } 12655 } 12656 12657 if (removeUser >= 0) { 12658 // From above, we determined that we are deleting this only 12659 // for a single user. Continue the work here. 12660 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12661 if (outInfo != null) { 12662 outInfo.removedPackage = packageName; 12663 outInfo.removedAppId = appId; 12664 outInfo.removedUsers = new int[] {removeUser}; 12665 } 12666 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12667 removeKeystoreDataIfNeeded(removeUser, appId); 12668 schedulePackageCleaning(packageName, removeUser, false); 12669 synchronized (mPackages) { 12670 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12671 scheduleWritePackageRestrictionsLocked(removeUser); 12672 } 12673 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12674 removeUser); 12675 } 12676 return true; 12677 } 12678 12679 if (dataOnly) { 12680 // Delete application data first 12681 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12682 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12683 return true; 12684 } 12685 12686 boolean ret = false; 12687 if (isSystemApp(ps)) { 12688 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12689 // When an updated system application is deleted we delete the existing resources as well and 12690 // fall back to existing code in system partition 12691 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12692 flags, outInfo, writeSettings); 12693 } else { 12694 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12695 // Kill application pre-emptively especially for apps on sd. 12696 killApplication(packageName, ps.appId, "uninstall pkg"); 12697 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12698 allUserHandles, perUserInstalled, 12699 outInfo, writeSettings); 12700 } 12701 12702 return ret; 12703 } 12704 12705 private final class ClearStorageConnection implements ServiceConnection { 12706 IMediaContainerService mContainerService; 12707 12708 @Override 12709 public void onServiceConnected(ComponentName name, IBinder service) { 12710 synchronized (this) { 12711 mContainerService = IMediaContainerService.Stub.asInterface(service); 12712 notifyAll(); 12713 } 12714 } 12715 12716 @Override 12717 public void onServiceDisconnected(ComponentName name) { 12718 } 12719 } 12720 12721 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12722 final boolean mounted; 12723 if (Environment.isExternalStorageEmulated()) { 12724 mounted = true; 12725 } else { 12726 final String status = Environment.getExternalStorageState(); 12727 12728 mounted = status.equals(Environment.MEDIA_MOUNTED) 12729 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12730 } 12731 12732 if (!mounted) { 12733 return; 12734 } 12735 12736 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12737 int[] users; 12738 if (userId == UserHandle.USER_ALL) { 12739 users = sUserManager.getUserIds(); 12740 } else { 12741 users = new int[] { userId }; 12742 } 12743 final ClearStorageConnection conn = new ClearStorageConnection(); 12744 if (mContext.bindServiceAsUser( 12745 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12746 try { 12747 for (int curUser : users) { 12748 long timeout = SystemClock.uptimeMillis() + 5000; 12749 synchronized (conn) { 12750 long now = SystemClock.uptimeMillis(); 12751 while (conn.mContainerService == null && now < timeout) { 12752 try { 12753 conn.wait(timeout - now); 12754 } catch (InterruptedException e) { 12755 } 12756 } 12757 } 12758 if (conn.mContainerService == null) { 12759 return; 12760 } 12761 12762 final UserEnvironment userEnv = new UserEnvironment(curUser); 12763 clearDirectory(conn.mContainerService, 12764 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12765 if (allData) { 12766 clearDirectory(conn.mContainerService, 12767 userEnv.buildExternalStorageAppDataDirs(packageName)); 12768 clearDirectory(conn.mContainerService, 12769 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12770 } 12771 } 12772 } finally { 12773 mContext.unbindService(conn); 12774 } 12775 } 12776 } 12777 12778 @Override 12779 public void clearApplicationUserData(final String packageName, 12780 final IPackageDataObserver observer, final int userId) { 12781 mContext.enforceCallingOrSelfPermission( 12782 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12783 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12784 // Queue up an async operation since the package deletion may take a little while. 12785 mHandler.post(new Runnable() { 12786 public void run() { 12787 mHandler.removeCallbacks(this); 12788 final boolean succeeded; 12789 synchronized (mInstallLock) { 12790 succeeded = clearApplicationUserDataLI(packageName, userId); 12791 } 12792 clearExternalStorageDataSync(packageName, userId, true); 12793 if (succeeded) { 12794 // invoke DeviceStorageMonitor's update method to clear any notifications 12795 DeviceStorageMonitorInternal 12796 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12797 if (dsm != null) { 12798 dsm.checkMemory(); 12799 } 12800 } 12801 if(observer != null) { 12802 try { 12803 observer.onRemoveCompleted(packageName, succeeded); 12804 } catch (RemoteException e) { 12805 Log.i(TAG, "Observer no longer exists."); 12806 } 12807 } //end if observer 12808 } //end run 12809 }); 12810 } 12811 12812 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12813 if (packageName == null) { 12814 Slog.w(TAG, "Attempt to delete null packageName."); 12815 return false; 12816 } 12817 12818 // Try finding details about the requested package 12819 PackageParser.Package pkg; 12820 synchronized (mPackages) { 12821 pkg = mPackages.get(packageName); 12822 if (pkg == null) { 12823 final PackageSetting ps = mSettings.mPackages.get(packageName); 12824 if (ps != null) { 12825 pkg = ps.pkg; 12826 } 12827 } 12828 12829 if (pkg == null) { 12830 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12831 return false; 12832 } 12833 12834 PackageSetting ps = (PackageSetting) pkg.mExtras; 12835 PermissionsState permissionsState = ps.getPermissionsState(); 12836 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12837 } 12838 12839 // Always delete data directories for package, even if we found no other 12840 // record of app. This helps users recover from UID mismatches without 12841 // resorting to a full data wipe. 12842 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12843 if (retCode < 0) { 12844 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12845 return false; 12846 } 12847 12848 final int appId = pkg.applicationInfo.uid; 12849 removeKeystoreDataIfNeeded(userId, appId); 12850 12851 // Create a native library symlink only if we have native libraries 12852 // and if the native libraries are 32 bit libraries. We do not provide 12853 // this symlink for 64 bit libraries. 12854 if (pkg.applicationInfo.primaryCpuAbi != null && 12855 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12856 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12857 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12858 nativeLibPath, userId) < 0) { 12859 Slog.w(TAG, "Failed linking native library dir"); 12860 return false; 12861 } 12862 } 12863 12864 return true; 12865 } 12866 12867 12868 /** 12869 * Revokes granted runtime permissions and clears resettable flags 12870 * which are flags that can be set by a user interaction. 12871 * 12872 * @param permissionsState The permission state to reset. 12873 * @param userId The device user for which to do a reset. 12874 */ 12875 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12876 PermissionsState permissionsState, int userId) { 12877 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12878 | PackageManager.FLAG_PERMISSION_USER_FIXED 12879 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12880 12881 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12882 } 12883 12884 /** 12885 * Revokes granted runtime permissions and clears all flags. 12886 * 12887 * @param permissionsState The permission state to reset. 12888 * @param userId The device user for which to do a reset. 12889 */ 12890 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12891 PermissionsState permissionsState, int userId) { 12892 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12893 PackageManager.MASK_PERMISSION_FLAGS); 12894 } 12895 12896 /** 12897 * Revokes granted runtime permissions and clears certain flags. 12898 * 12899 * @param permissionsState The permission state to reset. 12900 * @param userId The device user for which to do a reset. 12901 * @param flags The flags that is going to be reset. 12902 */ 12903 private void revokeRuntimePermissionsAndClearFlagsLocked( 12904 PermissionsState permissionsState, int userId, int flags) { 12905 boolean needsWrite = false; 12906 12907 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12908 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12909 if (bp != null) { 12910 permissionsState.revokeRuntimePermission(bp, userId); 12911 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12912 needsWrite = true; 12913 } 12914 } 12915 12916 // Ensure default permissions are never cleared. 12917 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12918 12919 if (needsWrite) { 12920 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12921 } 12922 } 12923 12924 /** 12925 * Remove entries from the keystore daemon. Will only remove it if the 12926 * {@code appId} is valid. 12927 */ 12928 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12929 if (appId < 0) { 12930 return; 12931 } 12932 12933 final KeyStore keyStore = KeyStore.getInstance(); 12934 if (keyStore != null) { 12935 if (userId == UserHandle.USER_ALL) { 12936 for (final int individual : sUserManager.getUserIds()) { 12937 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12938 } 12939 } else { 12940 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12941 } 12942 } else { 12943 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12944 } 12945 } 12946 12947 @Override 12948 public void deleteApplicationCacheFiles(final String packageName, 12949 final IPackageDataObserver observer) { 12950 mContext.enforceCallingOrSelfPermission( 12951 android.Manifest.permission.DELETE_CACHE_FILES, null); 12952 // Queue up an async operation since the package deletion may take a little while. 12953 final int userId = UserHandle.getCallingUserId(); 12954 mHandler.post(new Runnable() { 12955 public void run() { 12956 mHandler.removeCallbacks(this); 12957 final boolean succeded; 12958 synchronized (mInstallLock) { 12959 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12960 } 12961 clearExternalStorageDataSync(packageName, userId, false); 12962 if (observer != null) { 12963 try { 12964 observer.onRemoveCompleted(packageName, succeded); 12965 } catch (RemoteException e) { 12966 Log.i(TAG, "Observer no longer exists."); 12967 } 12968 } //end if observer 12969 } //end run 12970 }); 12971 } 12972 12973 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12974 if (packageName == null) { 12975 Slog.w(TAG, "Attempt to delete null packageName."); 12976 return false; 12977 } 12978 PackageParser.Package p; 12979 synchronized (mPackages) { 12980 p = mPackages.get(packageName); 12981 } 12982 if (p == null) { 12983 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12984 return false; 12985 } 12986 final ApplicationInfo applicationInfo = p.applicationInfo; 12987 if (applicationInfo == null) { 12988 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12989 return false; 12990 } 12991 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12992 if (retCode < 0) { 12993 Slog.w(TAG, "Couldn't remove cache files for package: " 12994 + packageName + " u" + userId); 12995 return false; 12996 } 12997 return true; 12998 } 12999 13000 @Override 13001 public void getPackageSizeInfo(final String packageName, int userHandle, 13002 final IPackageStatsObserver observer) { 13003 mContext.enforceCallingOrSelfPermission( 13004 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13005 if (packageName == null) { 13006 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13007 } 13008 13009 PackageStats stats = new PackageStats(packageName, userHandle); 13010 13011 /* 13012 * Queue up an async operation since the package measurement may take a 13013 * little while. 13014 */ 13015 Message msg = mHandler.obtainMessage(INIT_COPY); 13016 msg.obj = new MeasureParams(stats, observer); 13017 mHandler.sendMessage(msg); 13018 } 13019 13020 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13021 PackageStats pStats) { 13022 if (packageName == null) { 13023 Slog.w(TAG, "Attempt to get size of null packageName."); 13024 return false; 13025 } 13026 PackageParser.Package p; 13027 boolean dataOnly = false; 13028 String libDirRoot = null; 13029 String asecPath = null; 13030 PackageSetting ps = null; 13031 synchronized (mPackages) { 13032 p = mPackages.get(packageName); 13033 ps = mSettings.mPackages.get(packageName); 13034 if(p == null) { 13035 dataOnly = true; 13036 if((ps == null) || (ps.pkg == null)) { 13037 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13038 return false; 13039 } 13040 p = ps.pkg; 13041 } 13042 if (ps != null) { 13043 libDirRoot = ps.legacyNativeLibraryPathString; 13044 } 13045 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13046 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13047 if (secureContainerId != null) { 13048 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13049 } 13050 } 13051 } 13052 String publicSrcDir = null; 13053 if(!dataOnly) { 13054 final ApplicationInfo applicationInfo = p.applicationInfo; 13055 if (applicationInfo == null) { 13056 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13057 return false; 13058 } 13059 if (p.isForwardLocked()) { 13060 publicSrcDir = applicationInfo.getBaseResourcePath(); 13061 } 13062 } 13063 // TODO: extend to measure size of split APKs 13064 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13065 // not just the first level. 13066 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13067 // just the primary. 13068 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13069 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13070 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13071 if (res < 0) { 13072 return false; 13073 } 13074 13075 // Fix-up for forward-locked applications in ASEC containers. 13076 if (!isExternal(p)) { 13077 pStats.codeSize += pStats.externalCodeSize; 13078 pStats.externalCodeSize = 0L; 13079 } 13080 13081 return true; 13082 } 13083 13084 13085 @Override 13086 public void addPackageToPreferred(String packageName) { 13087 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13088 } 13089 13090 @Override 13091 public void removePackageFromPreferred(String packageName) { 13092 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13093 } 13094 13095 @Override 13096 public List<PackageInfo> getPreferredPackages(int flags) { 13097 return new ArrayList<PackageInfo>(); 13098 } 13099 13100 private int getUidTargetSdkVersionLockedLPr(int uid) { 13101 Object obj = mSettings.getUserIdLPr(uid); 13102 if (obj instanceof SharedUserSetting) { 13103 final SharedUserSetting sus = (SharedUserSetting) obj; 13104 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13105 final Iterator<PackageSetting> it = sus.packages.iterator(); 13106 while (it.hasNext()) { 13107 final PackageSetting ps = it.next(); 13108 if (ps.pkg != null) { 13109 int v = ps.pkg.applicationInfo.targetSdkVersion; 13110 if (v < vers) vers = v; 13111 } 13112 } 13113 return vers; 13114 } else if (obj instanceof PackageSetting) { 13115 final PackageSetting ps = (PackageSetting) obj; 13116 if (ps.pkg != null) { 13117 return ps.pkg.applicationInfo.targetSdkVersion; 13118 } 13119 } 13120 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13121 } 13122 13123 @Override 13124 public void addPreferredActivity(IntentFilter filter, int match, 13125 ComponentName[] set, ComponentName activity, int userId) { 13126 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13127 "Adding preferred"); 13128 } 13129 13130 private void addPreferredActivityInternal(IntentFilter filter, int match, 13131 ComponentName[] set, ComponentName activity, boolean always, int userId, 13132 String opname) { 13133 // writer 13134 int callingUid = Binder.getCallingUid(); 13135 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13136 if (filter.countActions() == 0) { 13137 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13138 return; 13139 } 13140 synchronized (mPackages) { 13141 if (mContext.checkCallingOrSelfPermission( 13142 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13143 != PackageManager.PERMISSION_GRANTED) { 13144 if (getUidTargetSdkVersionLockedLPr(callingUid) 13145 < Build.VERSION_CODES.FROYO) { 13146 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13147 + callingUid); 13148 return; 13149 } 13150 mContext.enforceCallingOrSelfPermission( 13151 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13152 } 13153 13154 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13155 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13156 + userId + ":"); 13157 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13158 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13159 scheduleWritePackageRestrictionsLocked(userId); 13160 } 13161 } 13162 13163 @Override 13164 public void replacePreferredActivity(IntentFilter filter, int match, 13165 ComponentName[] set, ComponentName activity, int userId) { 13166 if (filter.countActions() != 1) { 13167 throw new IllegalArgumentException( 13168 "replacePreferredActivity expects filter to have only 1 action."); 13169 } 13170 if (filter.countDataAuthorities() != 0 13171 || filter.countDataPaths() != 0 13172 || filter.countDataSchemes() > 1 13173 || filter.countDataTypes() != 0) { 13174 throw new IllegalArgumentException( 13175 "replacePreferredActivity expects filter to have no data authorities, " + 13176 "paths, or types; and at most one scheme."); 13177 } 13178 13179 final int callingUid = Binder.getCallingUid(); 13180 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13181 synchronized (mPackages) { 13182 if (mContext.checkCallingOrSelfPermission( 13183 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13184 != PackageManager.PERMISSION_GRANTED) { 13185 if (getUidTargetSdkVersionLockedLPr(callingUid) 13186 < Build.VERSION_CODES.FROYO) { 13187 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13188 + Binder.getCallingUid()); 13189 return; 13190 } 13191 mContext.enforceCallingOrSelfPermission( 13192 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13193 } 13194 13195 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13196 if (pir != null) { 13197 // Get all of the existing entries that exactly match this filter. 13198 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13199 if (existing != null && existing.size() == 1) { 13200 PreferredActivity cur = existing.get(0); 13201 if (DEBUG_PREFERRED) { 13202 Slog.i(TAG, "Checking replace of preferred:"); 13203 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13204 if (!cur.mPref.mAlways) { 13205 Slog.i(TAG, " -- CUR; not mAlways!"); 13206 } else { 13207 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13208 Slog.i(TAG, " -- CUR: mSet=" 13209 + Arrays.toString(cur.mPref.mSetComponents)); 13210 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13211 Slog.i(TAG, " -- NEW: mMatch=" 13212 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13213 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13214 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13215 } 13216 } 13217 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13218 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13219 && cur.mPref.sameSet(set)) { 13220 // Setting the preferred activity to what it happens to be already 13221 if (DEBUG_PREFERRED) { 13222 Slog.i(TAG, "Replacing with same preferred activity " 13223 + cur.mPref.mShortComponent + " for user " 13224 + userId + ":"); 13225 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13226 } 13227 return; 13228 } 13229 } 13230 13231 if (existing != null) { 13232 if (DEBUG_PREFERRED) { 13233 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13234 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13235 } 13236 for (int i = 0; i < existing.size(); i++) { 13237 PreferredActivity pa = existing.get(i); 13238 if (DEBUG_PREFERRED) { 13239 Slog.i(TAG, "Removing existing preferred activity " 13240 + pa.mPref.mComponent + ":"); 13241 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13242 } 13243 pir.removeFilter(pa); 13244 } 13245 } 13246 } 13247 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13248 "Replacing preferred"); 13249 } 13250 } 13251 13252 @Override 13253 public void clearPackagePreferredActivities(String packageName) { 13254 final int uid = Binder.getCallingUid(); 13255 // writer 13256 synchronized (mPackages) { 13257 PackageParser.Package pkg = mPackages.get(packageName); 13258 if (pkg == null || pkg.applicationInfo.uid != uid) { 13259 if (mContext.checkCallingOrSelfPermission( 13260 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13261 != PackageManager.PERMISSION_GRANTED) { 13262 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13263 < Build.VERSION_CODES.FROYO) { 13264 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13265 + Binder.getCallingUid()); 13266 return; 13267 } 13268 mContext.enforceCallingOrSelfPermission( 13269 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13270 } 13271 } 13272 13273 int user = UserHandle.getCallingUserId(); 13274 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13275 scheduleWritePackageRestrictionsLocked(user); 13276 } 13277 } 13278 } 13279 13280 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13281 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13282 ArrayList<PreferredActivity> removed = null; 13283 boolean changed = false; 13284 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13285 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13286 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13287 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13288 continue; 13289 } 13290 Iterator<PreferredActivity> it = pir.filterIterator(); 13291 while (it.hasNext()) { 13292 PreferredActivity pa = it.next(); 13293 // Mark entry for removal only if it matches the package name 13294 // and the entry is of type "always". 13295 if (packageName == null || 13296 (pa.mPref.mComponent.getPackageName().equals(packageName) 13297 && pa.mPref.mAlways)) { 13298 if (removed == null) { 13299 removed = new ArrayList<PreferredActivity>(); 13300 } 13301 removed.add(pa); 13302 } 13303 } 13304 if (removed != null) { 13305 for (int j=0; j<removed.size(); j++) { 13306 PreferredActivity pa = removed.get(j); 13307 pir.removeFilter(pa); 13308 } 13309 changed = true; 13310 } 13311 } 13312 return changed; 13313 } 13314 13315 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13316 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13317 if (userId == UserHandle.USER_ALL) { 13318 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13319 sUserManager.getUserIds())) { 13320 for (int oneUserId : sUserManager.getUserIds()) { 13321 scheduleWritePackageRestrictionsLocked(oneUserId); 13322 } 13323 } 13324 } else { 13325 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13326 scheduleWritePackageRestrictionsLocked(userId); 13327 } 13328 } 13329 } 13330 13331 13332 void clearDefaultBrowserIfNeeded(String packageName) { 13333 for (int oneUserId : sUserManager.getUserIds()) { 13334 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13335 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13336 if (packageName.equals(defaultBrowserPackageName)) { 13337 setDefaultBrowserPackageName(null, oneUserId); 13338 } 13339 } 13340 } 13341 13342 @Override 13343 public void resetPreferredActivities(int userId) { 13344 /* TODO: Actually use userId. Why is it being passed in? */ 13345 mContext.enforceCallingOrSelfPermission( 13346 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13347 // writer 13348 synchronized (mPackages) { 13349 int user = UserHandle.getCallingUserId(); 13350 clearPackagePreferredActivitiesLPw(null, user); 13351 mSettings.readDefaultPreferredAppsLPw(this, user); 13352 scheduleWritePackageRestrictionsLocked(user); 13353 } 13354 } 13355 13356 @Override 13357 public int getPreferredActivities(List<IntentFilter> outFilters, 13358 List<ComponentName> outActivities, String packageName) { 13359 13360 int num = 0; 13361 final int userId = UserHandle.getCallingUserId(); 13362 // reader 13363 synchronized (mPackages) { 13364 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13365 if (pir != null) { 13366 final Iterator<PreferredActivity> it = pir.filterIterator(); 13367 while (it.hasNext()) { 13368 final PreferredActivity pa = it.next(); 13369 if (packageName == null 13370 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13371 && pa.mPref.mAlways)) { 13372 if (outFilters != null) { 13373 outFilters.add(new IntentFilter(pa)); 13374 } 13375 if (outActivities != null) { 13376 outActivities.add(pa.mPref.mComponent); 13377 } 13378 } 13379 } 13380 } 13381 } 13382 13383 return num; 13384 } 13385 13386 @Override 13387 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13388 int userId) { 13389 int callingUid = Binder.getCallingUid(); 13390 if (callingUid != Process.SYSTEM_UID) { 13391 throw new SecurityException( 13392 "addPersistentPreferredActivity can only be run by the system"); 13393 } 13394 if (filter.countActions() == 0) { 13395 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13396 return; 13397 } 13398 synchronized (mPackages) { 13399 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13400 " :"); 13401 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13402 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13403 new PersistentPreferredActivity(filter, activity)); 13404 scheduleWritePackageRestrictionsLocked(userId); 13405 } 13406 } 13407 13408 @Override 13409 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13410 int callingUid = Binder.getCallingUid(); 13411 if (callingUid != Process.SYSTEM_UID) { 13412 throw new SecurityException( 13413 "clearPackagePersistentPreferredActivities can only be run by the system"); 13414 } 13415 ArrayList<PersistentPreferredActivity> removed = null; 13416 boolean changed = false; 13417 synchronized (mPackages) { 13418 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13419 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13420 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13421 .valueAt(i); 13422 if (userId != thisUserId) { 13423 continue; 13424 } 13425 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13426 while (it.hasNext()) { 13427 PersistentPreferredActivity ppa = it.next(); 13428 // Mark entry for removal only if it matches the package name. 13429 if (ppa.mComponent.getPackageName().equals(packageName)) { 13430 if (removed == null) { 13431 removed = new ArrayList<PersistentPreferredActivity>(); 13432 } 13433 removed.add(ppa); 13434 } 13435 } 13436 if (removed != null) { 13437 for (int j=0; j<removed.size(); j++) { 13438 PersistentPreferredActivity ppa = removed.get(j); 13439 ppir.removeFilter(ppa); 13440 } 13441 changed = true; 13442 } 13443 } 13444 13445 if (changed) { 13446 scheduleWritePackageRestrictionsLocked(userId); 13447 } 13448 } 13449 } 13450 13451 /** 13452 * Common machinery for picking apart a restored XML blob and passing 13453 * it to a caller-supplied functor to be applied to the running system. 13454 */ 13455 private void restoreFromXml(XmlPullParser parser, int userId, 13456 String expectedStartTag, BlobXmlRestorer functor) 13457 throws IOException, XmlPullParserException { 13458 int type; 13459 while ((type = parser.next()) != XmlPullParser.START_TAG 13460 && type != XmlPullParser.END_DOCUMENT) { 13461 } 13462 if (type != XmlPullParser.START_TAG) { 13463 // oops didn't find a start tag?! 13464 if (DEBUG_BACKUP) { 13465 Slog.e(TAG, "Didn't find start tag during restore"); 13466 } 13467 return; 13468 } 13469 13470 // this is supposed to be TAG_PREFERRED_BACKUP 13471 if (!expectedStartTag.equals(parser.getName())) { 13472 if (DEBUG_BACKUP) { 13473 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13474 } 13475 return; 13476 } 13477 13478 // skip interfering stuff, then we're aligned with the backing implementation 13479 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13480 functor.apply(parser, userId); 13481 } 13482 13483 private interface BlobXmlRestorer { 13484 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13485 } 13486 13487 /** 13488 * Non-Binder method, support for the backup/restore mechanism: write the 13489 * full set of preferred activities in its canonical XML format. Returns the 13490 * XML output as a byte array, or null if there is none. 13491 */ 13492 @Override 13493 public byte[] getPreferredActivityBackup(int userId) { 13494 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13495 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13496 } 13497 13498 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13499 try { 13500 final XmlSerializer serializer = new FastXmlSerializer(); 13501 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13502 serializer.startDocument(null, true); 13503 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13504 13505 synchronized (mPackages) { 13506 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13507 } 13508 13509 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13510 serializer.endDocument(); 13511 serializer.flush(); 13512 } catch (Exception e) { 13513 if (DEBUG_BACKUP) { 13514 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13515 } 13516 return null; 13517 } 13518 13519 return dataStream.toByteArray(); 13520 } 13521 13522 @Override 13523 public void restorePreferredActivities(byte[] backup, int userId) { 13524 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13525 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13526 } 13527 13528 try { 13529 final XmlPullParser parser = Xml.newPullParser(); 13530 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13531 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13532 new BlobXmlRestorer() { 13533 @Override 13534 public void apply(XmlPullParser parser, int userId) 13535 throws XmlPullParserException, IOException { 13536 synchronized (mPackages) { 13537 mSettings.readPreferredActivitiesLPw(parser, userId); 13538 } 13539 } 13540 } ); 13541 } catch (Exception e) { 13542 if (DEBUG_BACKUP) { 13543 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13544 } 13545 } 13546 } 13547 13548 /** 13549 * Non-Binder method, support for the backup/restore mechanism: write the 13550 * default browser (etc) settings in its canonical XML format. Returns the default 13551 * browser XML representation as a byte array, or null if there is none. 13552 */ 13553 @Override 13554 public byte[] getDefaultAppsBackup(int userId) { 13555 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13556 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13557 } 13558 13559 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13560 try { 13561 final XmlSerializer serializer = new FastXmlSerializer(); 13562 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13563 serializer.startDocument(null, true); 13564 serializer.startTag(null, TAG_DEFAULT_APPS); 13565 13566 synchronized (mPackages) { 13567 mSettings.writeDefaultAppsLPr(serializer, userId); 13568 } 13569 13570 serializer.endTag(null, TAG_DEFAULT_APPS); 13571 serializer.endDocument(); 13572 serializer.flush(); 13573 } catch (Exception e) { 13574 if (DEBUG_BACKUP) { 13575 Slog.e(TAG, "Unable to write default apps for backup", e); 13576 } 13577 return null; 13578 } 13579 13580 return dataStream.toByteArray(); 13581 } 13582 13583 @Override 13584 public void restoreDefaultApps(byte[] backup, int userId) { 13585 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13586 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13587 } 13588 13589 try { 13590 final XmlPullParser parser = Xml.newPullParser(); 13591 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13592 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13593 new BlobXmlRestorer() { 13594 @Override 13595 public void apply(XmlPullParser parser, int userId) 13596 throws XmlPullParserException, IOException { 13597 synchronized (mPackages) { 13598 mSettings.readDefaultAppsLPw(parser, userId); 13599 } 13600 } 13601 } ); 13602 } catch (Exception e) { 13603 if (DEBUG_BACKUP) { 13604 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13605 } 13606 } 13607 } 13608 13609 @Override 13610 public byte[] getIntentFilterVerificationBackup(int userId) { 13611 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13612 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13613 } 13614 13615 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13616 try { 13617 final XmlSerializer serializer = new FastXmlSerializer(); 13618 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13619 serializer.startDocument(null, true); 13620 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13621 13622 synchronized (mPackages) { 13623 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13624 } 13625 13626 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13627 serializer.endDocument(); 13628 serializer.flush(); 13629 } catch (Exception e) { 13630 if (DEBUG_BACKUP) { 13631 Slog.e(TAG, "Unable to write default apps for backup", e); 13632 } 13633 return null; 13634 } 13635 13636 return dataStream.toByteArray(); 13637 } 13638 13639 @Override 13640 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13641 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13642 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13643 } 13644 13645 try { 13646 final XmlPullParser parser = Xml.newPullParser(); 13647 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13648 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13649 new BlobXmlRestorer() { 13650 @Override 13651 public void apply(XmlPullParser parser, int userId) 13652 throws XmlPullParserException, IOException { 13653 synchronized (mPackages) { 13654 mSettings.readAllDomainVerificationsLPr(parser, userId); 13655 mSettings.writeLPr(); 13656 } 13657 } 13658 } ); 13659 } catch (Exception e) { 13660 if (DEBUG_BACKUP) { 13661 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13662 } 13663 } 13664 } 13665 13666 @Override 13667 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13668 int sourceUserId, int targetUserId, int flags) { 13669 mContext.enforceCallingOrSelfPermission( 13670 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13671 int callingUid = Binder.getCallingUid(); 13672 enforceOwnerRights(ownerPackage, callingUid); 13673 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13674 if (intentFilter.countActions() == 0) { 13675 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13676 return; 13677 } 13678 synchronized (mPackages) { 13679 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13680 ownerPackage, targetUserId, flags); 13681 CrossProfileIntentResolver resolver = 13682 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13683 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13684 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13685 if (existing != null) { 13686 int size = existing.size(); 13687 for (int i = 0; i < size; i++) { 13688 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13689 return; 13690 } 13691 } 13692 } 13693 resolver.addFilter(newFilter); 13694 scheduleWritePackageRestrictionsLocked(sourceUserId); 13695 } 13696 } 13697 13698 @Override 13699 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13700 mContext.enforceCallingOrSelfPermission( 13701 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13702 int callingUid = Binder.getCallingUid(); 13703 enforceOwnerRights(ownerPackage, callingUid); 13704 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13705 synchronized (mPackages) { 13706 CrossProfileIntentResolver resolver = 13707 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13708 ArraySet<CrossProfileIntentFilter> set = 13709 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13710 for (CrossProfileIntentFilter filter : set) { 13711 if (filter.getOwnerPackage().equals(ownerPackage)) { 13712 resolver.removeFilter(filter); 13713 } 13714 } 13715 scheduleWritePackageRestrictionsLocked(sourceUserId); 13716 } 13717 } 13718 13719 // Enforcing that callingUid is owning pkg on userId 13720 private void enforceOwnerRights(String pkg, int callingUid) { 13721 // The system owns everything. 13722 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13723 return; 13724 } 13725 int callingUserId = UserHandle.getUserId(callingUid); 13726 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13727 if (pi == null) { 13728 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13729 + callingUserId); 13730 } 13731 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13732 throw new SecurityException("Calling uid " + callingUid 13733 + " does not own package " + pkg); 13734 } 13735 } 13736 13737 @Override 13738 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13739 Intent intent = new Intent(Intent.ACTION_MAIN); 13740 intent.addCategory(Intent.CATEGORY_HOME); 13741 13742 final int callingUserId = UserHandle.getCallingUserId(); 13743 List<ResolveInfo> list = queryIntentActivities(intent, null, 13744 PackageManager.GET_META_DATA, callingUserId); 13745 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13746 true, false, false, callingUserId); 13747 13748 allHomeCandidates.clear(); 13749 if (list != null) { 13750 for (ResolveInfo ri : list) { 13751 allHomeCandidates.add(ri); 13752 } 13753 } 13754 return (preferred == null || preferred.activityInfo == null) 13755 ? null 13756 : new ComponentName(preferred.activityInfo.packageName, 13757 preferred.activityInfo.name); 13758 } 13759 13760 @Override 13761 public void setApplicationEnabledSetting(String appPackageName, 13762 int newState, int flags, int userId, String callingPackage) { 13763 if (!sUserManager.exists(userId)) return; 13764 if (callingPackage == null) { 13765 callingPackage = Integer.toString(Binder.getCallingUid()); 13766 } 13767 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13768 } 13769 13770 @Override 13771 public void setComponentEnabledSetting(ComponentName componentName, 13772 int newState, int flags, int userId) { 13773 if (!sUserManager.exists(userId)) return; 13774 setEnabledSetting(componentName.getPackageName(), 13775 componentName.getClassName(), newState, flags, userId, null); 13776 } 13777 13778 private void setEnabledSetting(final String packageName, String className, int newState, 13779 final int flags, int userId, String callingPackage) { 13780 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13781 || newState == COMPONENT_ENABLED_STATE_ENABLED 13782 || newState == COMPONENT_ENABLED_STATE_DISABLED 13783 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13784 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13785 throw new IllegalArgumentException("Invalid new component state: " 13786 + newState); 13787 } 13788 PackageSetting pkgSetting; 13789 final int uid = Binder.getCallingUid(); 13790 final int permission = mContext.checkCallingOrSelfPermission( 13791 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13792 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13793 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13794 boolean sendNow = false; 13795 boolean isApp = (className == null); 13796 String componentName = isApp ? packageName : className; 13797 int packageUid = -1; 13798 ArrayList<String> components; 13799 13800 // writer 13801 synchronized (mPackages) { 13802 pkgSetting = mSettings.mPackages.get(packageName); 13803 if (pkgSetting == null) { 13804 if (className == null) { 13805 throw new IllegalArgumentException( 13806 "Unknown package: " + packageName); 13807 } 13808 throw new IllegalArgumentException( 13809 "Unknown component: " + packageName 13810 + "/" + className); 13811 } 13812 // Allow root and verify that userId is not being specified by a different user 13813 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13814 throw new SecurityException( 13815 "Permission Denial: attempt to change component state from pid=" 13816 + Binder.getCallingPid() 13817 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13818 } 13819 if (className == null) { 13820 // We're dealing with an application/package level state change 13821 if (pkgSetting.getEnabled(userId) == newState) { 13822 // Nothing to do 13823 return; 13824 } 13825 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13826 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13827 // Don't care about who enables an app. 13828 callingPackage = null; 13829 } 13830 pkgSetting.setEnabled(newState, userId, callingPackage); 13831 // pkgSetting.pkg.mSetEnabled = newState; 13832 } else { 13833 // We're dealing with a component level state change 13834 // First, verify that this is a valid class name. 13835 PackageParser.Package pkg = pkgSetting.pkg; 13836 if (pkg == null || !pkg.hasComponentClassName(className)) { 13837 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13838 throw new IllegalArgumentException("Component class " + className 13839 + " does not exist in " + packageName); 13840 } else { 13841 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13842 + className + " does not exist in " + packageName); 13843 } 13844 } 13845 switch (newState) { 13846 case COMPONENT_ENABLED_STATE_ENABLED: 13847 if (!pkgSetting.enableComponentLPw(className, userId)) { 13848 return; 13849 } 13850 break; 13851 case COMPONENT_ENABLED_STATE_DISABLED: 13852 if (!pkgSetting.disableComponentLPw(className, userId)) { 13853 return; 13854 } 13855 break; 13856 case COMPONENT_ENABLED_STATE_DEFAULT: 13857 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13858 return; 13859 } 13860 break; 13861 default: 13862 Slog.e(TAG, "Invalid new component state: " + newState); 13863 return; 13864 } 13865 } 13866 scheduleWritePackageRestrictionsLocked(userId); 13867 components = mPendingBroadcasts.get(userId, packageName); 13868 final boolean newPackage = components == null; 13869 if (newPackage) { 13870 components = new ArrayList<String>(); 13871 } 13872 if (!components.contains(componentName)) { 13873 components.add(componentName); 13874 } 13875 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13876 sendNow = true; 13877 // Purge entry from pending broadcast list if another one exists already 13878 // since we are sending one right away. 13879 mPendingBroadcasts.remove(userId, packageName); 13880 } else { 13881 if (newPackage) { 13882 mPendingBroadcasts.put(userId, packageName, components); 13883 } 13884 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13885 // Schedule a message 13886 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13887 } 13888 } 13889 } 13890 13891 long callingId = Binder.clearCallingIdentity(); 13892 try { 13893 if (sendNow) { 13894 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13895 sendPackageChangedBroadcast(packageName, 13896 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13897 } 13898 } finally { 13899 Binder.restoreCallingIdentity(callingId); 13900 } 13901 } 13902 13903 private void sendPackageChangedBroadcast(String packageName, 13904 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13905 if (DEBUG_INSTALL) 13906 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13907 + componentNames); 13908 Bundle extras = new Bundle(4); 13909 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13910 String nameList[] = new String[componentNames.size()]; 13911 componentNames.toArray(nameList); 13912 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13913 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13914 extras.putInt(Intent.EXTRA_UID, packageUid); 13915 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13916 new int[] {UserHandle.getUserId(packageUid)}); 13917 } 13918 13919 @Override 13920 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13921 if (!sUserManager.exists(userId)) return; 13922 final int uid = Binder.getCallingUid(); 13923 final int permission = mContext.checkCallingOrSelfPermission( 13924 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13925 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13926 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13927 // writer 13928 synchronized (mPackages) { 13929 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13930 allowedByPermission, uid, userId)) { 13931 scheduleWritePackageRestrictionsLocked(userId); 13932 } 13933 } 13934 } 13935 13936 @Override 13937 public String getInstallerPackageName(String packageName) { 13938 // reader 13939 synchronized (mPackages) { 13940 return mSettings.getInstallerPackageNameLPr(packageName); 13941 } 13942 } 13943 13944 @Override 13945 public int getApplicationEnabledSetting(String packageName, int userId) { 13946 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13947 int uid = Binder.getCallingUid(); 13948 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13949 // reader 13950 synchronized (mPackages) { 13951 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13952 } 13953 } 13954 13955 @Override 13956 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13957 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13958 int uid = Binder.getCallingUid(); 13959 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13960 // reader 13961 synchronized (mPackages) { 13962 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13963 } 13964 } 13965 13966 @Override 13967 public void enterSafeMode() { 13968 enforceSystemOrRoot("Only the system can request entering safe mode"); 13969 13970 if (!mSystemReady) { 13971 mSafeMode = true; 13972 } 13973 } 13974 13975 @Override 13976 public void systemReady() { 13977 mSystemReady = true; 13978 13979 // Read the compatibilty setting when the system is ready. 13980 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13981 mContext.getContentResolver(), 13982 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13983 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13984 if (DEBUG_SETTINGS) { 13985 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13986 } 13987 13988 synchronized (mPackages) { 13989 // Verify that all of the preferred activity components actually 13990 // exist. It is possible for applications to be updated and at 13991 // that point remove a previously declared activity component that 13992 // had been set as a preferred activity. We try to clean this up 13993 // the next time we encounter that preferred activity, but it is 13994 // possible for the user flow to never be able to return to that 13995 // situation so here we do a sanity check to make sure we haven't 13996 // left any junk around. 13997 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13998 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13999 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14000 removed.clear(); 14001 for (PreferredActivity pa : pir.filterSet()) { 14002 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14003 removed.add(pa); 14004 } 14005 } 14006 if (removed.size() > 0) { 14007 for (int r=0; r<removed.size(); r++) { 14008 PreferredActivity pa = removed.get(r); 14009 Slog.w(TAG, "Removing dangling preferred activity: " 14010 + pa.mPref.mComponent); 14011 pir.removeFilter(pa); 14012 } 14013 mSettings.writePackageRestrictionsLPr( 14014 mSettings.mPreferredActivities.keyAt(i)); 14015 } 14016 } 14017 } 14018 sUserManager.systemReady(); 14019 14020 // If we upgraded grant all default permissions before kicking off. 14021 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 14022 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14023 for (int userId : UserManagerService.getInstance().getUserIds()) { 14024 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14025 } 14026 } 14027 14028 // Kick off any messages waiting for system ready 14029 if (mPostSystemReadyMessages != null) { 14030 for (Message msg : mPostSystemReadyMessages) { 14031 msg.sendToTarget(); 14032 } 14033 mPostSystemReadyMessages = null; 14034 } 14035 14036 // Watch for external volumes that come and go over time 14037 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14038 storage.registerListener(mStorageListener); 14039 14040 mInstallerService.systemReady(); 14041 mPackageDexOptimizer.systemReady(); 14042 } 14043 14044 @Override 14045 public boolean isSafeMode() { 14046 return mSafeMode; 14047 } 14048 14049 @Override 14050 public boolean hasSystemUidErrors() { 14051 return mHasSystemUidErrors; 14052 } 14053 14054 static String arrayToString(int[] array) { 14055 StringBuffer buf = new StringBuffer(128); 14056 buf.append('['); 14057 if (array != null) { 14058 for (int i=0; i<array.length; i++) { 14059 if (i > 0) buf.append(", "); 14060 buf.append(array[i]); 14061 } 14062 } 14063 buf.append(']'); 14064 return buf.toString(); 14065 } 14066 14067 static class DumpState { 14068 public static final int DUMP_LIBS = 1 << 0; 14069 public static final int DUMP_FEATURES = 1 << 1; 14070 public static final int DUMP_RESOLVERS = 1 << 2; 14071 public static final int DUMP_PERMISSIONS = 1 << 3; 14072 public static final int DUMP_PACKAGES = 1 << 4; 14073 public static final int DUMP_SHARED_USERS = 1 << 5; 14074 public static final int DUMP_MESSAGES = 1 << 6; 14075 public static final int DUMP_PROVIDERS = 1 << 7; 14076 public static final int DUMP_VERIFIERS = 1 << 8; 14077 public static final int DUMP_PREFERRED = 1 << 9; 14078 public static final int DUMP_PREFERRED_XML = 1 << 10; 14079 public static final int DUMP_KEYSETS = 1 << 11; 14080 public static final int DUMP_VERSION = 1 << 12; 14081 public static final int DUMP_INSTALLS = 1 << 13; 14082 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14083 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14084 14085 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14086 14087 private int mTypes; 14088 14089 private int mOptions; 14090 14091 private boolean mTitlePrinted; 14092 14093 private SharedUserSetting mSharedUser; 14094 14095 public boolean isDumping(int type) { 14096 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14097 return true; 14098 } 14099 14100 return (mTypes & type) != 0; 14101 } 14102 14103 public void setDump(int type) { 14104 mTypes |= type; 14105 } 14106 14107 public boolean isOptionEnabled(int option) { 14108 return (mOptions & option) != 0; 14109 } 14110 14111 public void setOptionEnabled(int option) { 14112 mOptions |= option; 14113 } 14114 14115 public boolean onTitlePrinted() { 14116 final boolean printed = mTitlePrinted; 14117 mTitlePrinted = true; 14118 return printed; 14119 } 14120 14121 public boolean getTitlePrinted() { 14122 return mTitlePrinted; 14123 } 14124 14125 public void setTitlePrinted(boolean enabled) { 14126 mTitlePrinted = enabled; 14127 } 14128 14129 public SharedUserSetting getSharedUser() { 14130 return mSharedUser; 14131 } 14132 14133 public void setSharedUser(SharedUserSetting user) { 14134 mSharedUser = user; 14135 } 14136 } 14137 14138 @Override 14139 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14140 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14141 != PackageManager.PERMISSION_GRANTED) { 14142 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14143 + Binder.getCallingPid() 14144 + ", uid=" + Binder.getCallingUid() 14145 + " without permission " 14146 + android.Manifest.permission.DUMP); 14147 return; 14148 } 14149 14150 DumpState dumpState = new DumpState(); 14151 boolean fullPreferred = false; 14152 boolean checkin = false; 14153 14154 String packageName = null; 14155 14156 int opti = 0; 14157 while (opti < args.length) { 14158 String opt = args[opti]; 14159 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14160 break; 14161 } 14162 opti++; 14163 14164 if ("-a".equals(opt)) { 14165 // Right now we only know how to print all. 14166 } else if ("-h".equals(opt)) { 14167 pw.println("Package manager dump options:"); 14168 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14169 pw.println(" --checkin: dump for a checkin"); 14170 pw.println(" -f: print details of intent filters"); 14171 pw.println(" -h: print this help"); 14172 pw.println(" cmd may be one of:"); 14173 pw.println(" l[ibraries]: list known shared libraries"); 14174 pw.println(" f[ibraries]: list device features"); 14175 pw.println(" k[eysets]: print known keysets"); 14176 pw.println(" r[esolvers]: dump intent resolvers"); 14177 pw.println(" perm[issions]: dump permissions"); 14178 pw.println(" pref[erred]: print preferred package settings"); 14179 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14180 pw.println(" prov[iders]: dump content providers"); 14181 pw.println(" p[ackages]: dump installed packages"); 14182 pw.println(" s[hared-users]: dump shared user IDs"); 14183 pw.println(" m[essages]: print collected runtime messages"); 14184 pw.println(" v[erifiers]: print package verifier info"); 14185 pw.println(" version: print database version info"); 14186 pw.println(" write: write current settings now"); 14187 pw.println(" <package.name>: info about given package"); 14188 pw.println(" installs: details about install sessions"); 14189 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14190 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14191 return; 14192 } else if ("--checkin".equals(opt)) { 14193 checkin = true; 14194 } else if ("-f".equals(opt)) { 14195 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14196 } else { 14197 pw.println("Unknown argument: " + opt + "; use -h for help"); 14198 } 14199 } 14200 14201 // Is the caller requesting to dump a particular piece of data? 14202 if (opti < args.length) { 14203 String cmd = args[opti]; 14204 opti++; 14205 // Is this a package name? 14206 if ("android".equals(cmd) || cmd.contains(".")) { 14207 packageName = cmd; 14208 // When dumping a single package, we always dump all of its 14209 // filter information since the amount of data will be reasonable. 14210 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14211 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14212 dumpState.setDump(DumpState.DUMP_LIBS); 14213 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14214 dumpState.setDump(DumpState.DUMP_FEATURES); 14215 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14216 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14217 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14218 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14219 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14220 dumpState.setDump(DumpState.DUMP_PREFERRED); 14221 } else if ("preferred-xml".equals(cmd)) { 14222 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14223 if (opti < args.length && "--full".equals(args[opti])) { 14224 fullPreferred = true; 14225 opti++; 14226 } 14227 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14228 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14229 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14230 dumpState.setDump(DumpState.DUMP_PACKAGES); 14231 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14232 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14233 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14234 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14235 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14236 dumpState.setDump(DumpState.DUMP_MESSAGES); 14237 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14238 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14239 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14240 || "intent-filter-verifiers".equals(cmd)) { 14241 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14242 } else if ("version".equals(cmd)) { 14243 dumpState.setDump(DumpState.DUMP_VERSION); 14244 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14245 dumpState.setDump(DumpState.DUMP_KEYSETS); 14246 } else if ("installs".equals(cmd)) { 14247 dumpState.setDump(DumpState.DUMP_INSTALLS); 14248 } else if ("write".equals(cmd)) { 14249 synchronized (mPackages) { 14250 mSettings.writeLPr(); 14251 pw.println("Settings written."); 14252 return; 14253 } 14254 } 14255 } 14256 14257 if (checkin) { 14258 pw.println("vers,1"); 14259 } 14260 14261 // reader 14262 synchronized (mPackages) { 14263 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14264 if (!checkin) { 14265 if (dumpState.onTitlePrinted()) 14266 pw.println(); 14267 pw.println("Database versions:"); 14268 pw.print(" SDK Version:"); 14269 pw.print(" internal="); 14270 pw.print(mSettings.mInternalSdkPlatform); 14271 pw.print(" external="); 14272 pw.println(mSettings.mExternalSdkPlatform); 14273 pw.print(" DB Version:"); 14274 pw.print(" internal="); 14275 pw.print(mSettings.mInternalDatabaseVersion); 14276 pw.print(" external="); 14277 pw.println(mSettings.mExternalDatabaseVersion); 14278 } 14279 } 14280 14281 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14282 if (!checkin) { 14283 if (dumpState.onTitlePrinted()) 14284 pw.println(); 14285 pw.println("Verifiers:"); 14286 pw.print(" Required: "); 14287 pw.print(mRequiredVerifierPackage); 14288 pw.print(" (uid="); 14289 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14290 pw.println(")"); 14291 } else if (mRequiredVerifierPackage != null) { 14292 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14293 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14294 } 14295 } 14296 14297 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14298 packageName == null) { 14299 if (mIntentFilterVerifierComponent != null) { 14300 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14301 if (!checkin) { 14302 if (dumpState.onTitlePrinted()) 14303 pw.println(); 14304 pw.println("Intent Filter Verifier:"); 14305 pw.print(" Using: "); 14306 pw.print(verifierPackageName); 14307 pw.print(" (uid="); 14308 pw.print(getPackageUid(verifierPackageName, 0)); 14309 pw.println(")"); 14310 } else if (verifierPackageName != null) { 14311 pw.print("ifv,"); pw.print(verifierPackageName); 14312 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14313 } 14314 } else { 14315 pw.println(); 14316 pw.println("No Intent Filter Verifier available!"); 14317 } 14318 } 14319 14320 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14321 boolean printedHeader = false; 14322 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14323 while (it.hasNext()) { 14324 String name = it.next(); 14325 SharedLibraryEntry ent = mSharedLibraries.get(name); 14326 if (!checkin) { 14327 if (!printedHeader) { 14328 if (dumpState.onTitlePrinted()) 14329 pw.println(); 14330 pw.println("Libraries:"); 14331 printedHeader = true; 14332 } 14333 pw.print(" "); 14334 } else { 14335 pw.print("lib,"); 14336 } 14337 pw.print(name); 14338 if (!checkin) { 14339 pw.print(" -> "); 14340 } 14341 if (ent.path != null) { 14342 if (!checkin) { 14343 pw.print("(jar) "); 14344 pw.print(ent.path); 14345 } else { 14346 pw.print(",jar,"); 14347 pw.print(ent.path); 14348 } 14349 } else { 14350 if (!checkin) { 14351 pw.print("(apk) "); 14352 pw.print(ent.apk); 14353 } else { 14354 pw.print(",apk,"); 14355 pw.print(ent.apk); 14356 } 14357 } 14358 pw.println(); 14359 } 14360 } 14361 14362 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14363 if (dumpState.onTitlePrinted()) 14364 pw.println(); 14365 if (!checkin) { 14366 pw.println("Features:"); 14367 } 14368 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14369 while (it.hasNext()) { 14370 String name = it.next(); 14371 if (!checkin) { 14372 pw.print(" "); 14373 } else { 14374 pw.print("feat,"); 14375 } 14376 pw.println(name); 14377 } 14378 } 14379 14380 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14381 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14382 : "Activity Resolver Table:", " ", packageName, 14383 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14384 dumpState.setTitlePrinted(true); 14385 } 14386 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14387 : "Receiver Resolver Table:", " ", packageName, 14388 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14389 dumpState.setTitlePrinted(true); 14390 } 14391 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14392 : "Service Resolver Table:", " ", packageName, 14393 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14394 dumpState.setTitlePrinted(true); 14395 } 14396 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14397 : "Provider Resolver Table:", " ", packageName, 14398 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14399 dumpState.setTitlePrinted(true); 14400 } 14401 } 14402 14403 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14404 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14405 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14406 int user = mSettings.mPreferredActivities.keyAt(i); 14407 if (pir.dump(pw, 14408 dumpState.getTitlePrinted() 14409 ? "\nPreferred Activities User " + user + ":" 14410 : "Preferred Activities User " + user + ":", " ", 14411 packageName, true, false)) { 14412 dumpState.setTitlePrinted(true); 14413 } 14414 } 14415 } 14416 14417 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14418 pw.flush(); 14419 FileOutputStream fout = new FileOutputStream(fd); 14420 BufferedOutputStream str = new BufferedOutputStream(fout); 14421 XmlSerializer serializer = new FastXmlSerializer(); 14422 try { 14423 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14424 serializer.startDocument(null, true); 14425 serializer.setFeature( 14426 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14427 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14428 serializer.endDocument(); 14429 serializer.flush(); 14430 } catch (IllegalArgumentException e) { 14431 pw.println("Failed writing: " + e); 14432 } catch (IllegalStateException e) { 14433 pw.println("Failed writing: " + e); 14434 } catch (IOException e) { 14435 pw.println("Failed writing: " + e); 14436 } 14437 } 14438 14439 if (!checkin 14440 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14441 && packageName == null) { 14442 pw.println(); 14443 int count = mSettings.mPackages.size(); 14444 if (count == 0) { 14445 pw.println("No domain preferred apps!"); 14446 pw.println(); 14447 } else { 14448 final String prefix = " "; 14449 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14450 if (allPackageSettings.size() == 0) { 14451 pw.println("No domain preferred apps!"); 14452 pw.println(); 14453 } else { 14454 pw.println("Domain preferred apps status:"); 14455 pw.println(); 14456 count = 0; 14457 for (PackageSetting ps : allPackageSettings) { 14458 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14459 if (ivi == null || ivi.getPackageName() == null) continue; 14460 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14461 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14462 pw.println(prefix + "Status: " + ivi.getStatusString()); 14463 pw.println(); 14464 count++; 14465 } 14466 if (count == 0) { 14467 pw.println(prefix + "No domain preferred app status!"); 14468 pw.println(); 14469 } 14470 for (int userId : sUserManager.getUserIds()) { 14471 pw.println("Domain preferred apps for User " + userId + ":"); 14472 pw.println(); 14473 count = 0; 14474 for (PackageSetting ps : allPackageSettings) { 14475 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14476 if (ivi == null || ivi.getPackageName() == null) { 14477 continue; 14478 } 14479 final int status = ps.getDomainVerificationStatusForUser(userId); 14480 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14481 continue; 14482 } 14483 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14484 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14485 String statusStr = IntentFilterVerificationInfo. 14486 getStatusStringFromValue(status); 14487 pw.println(prefix + "Status: " + statusStr); 14488 pw.println(); 14489 count++; 14490 } 14491 if (count == 0) { 14492 pw.println(prefix + "No domain preferred apps!"); 14493 pw.println(); 14494 } 14495 } 14496 } 14497 } 14498 } 14499 14500 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14501 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14502 if (packageName == null) { 14503 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14504 if (iperm == 0) { 14505 if (dumpState.onTitlePrinted()) 14506 pw.println(); 14507 pw.println("AppOp Permissions:"); 14508 } 14509 pw.print(" AppOp Permission "); 14510 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14511 pw.println(":"); 14512 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14513 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14514 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14515 } 14516 } 14517 } 14518 } 14519 14520 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14521 boolean printedSomething = false; 14522 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14523 if (packageName != null && !packageName.equals(p.info.packageName)) { 14524 continue; 14525 } 14526 if (!printedSomething) { 14527 if (dumpState.onTitlePrinted()) 14528 pw.println(); 14529 pw.println("Registered ContentProviders:"); 14530 printedSomething = true; 14531 } 14532 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14533 pw.print(" "); pw.println(p.toString()); 14534 } 14535 printedSomething = false; 14536 for (Map.Entry<String, PackageParser.Provider> entry : 14537 mProvidersByAuthority.entrySet()) { 14538 PackageParser.Provider p = entry.getValue(); 14539 if (packageName != null && !packageName.equals(p.info.packageName)) { 14540 continue; 14541 } 14542 if (!printedSomething) { 14543 if (dumpState.onTitlePrinted()) 14544 pw.println(); 14545 pw.println("ContentProvider Authorities:"); 14546 printedSomething = true; 14547 } 14548 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14549 pw.print(" "); pw.println(p.toString()); 14550 if (p.info != null && p.info.applicationInfo != null) { 14551 final String appInfo = p.info.applicationInfo.toString(); 14552 pw.print(" applicationInfo="); pw.println(appInfo); 14553 } 14554 } 14555 } 14556 14557 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14558 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14559 } 14560 14561 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14562 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14563 } 14564 14565 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14566 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14567 } 14568 14569 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14570 // XXX should handle packageName != null by dumping only install data that 14571 // the given package is involved with. 14572 if (dumpState.onTitlePrinted()) pw.println(); 14573 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14574 } 14575 14576 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14577 if (dumpState.onTitlePrinted()) pw.println(); 14578 mSettings.dumpReadMessagesLPr(pw, dumpState); 14579 14580 pw.println(); 14581 pw.println("Package warning messages:"); 14582 BufferedReader in = null; 14583 String line = null; 14584 try { 14585 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14586 while ((line = in.readLine()) != null) { 14587 if (line.contains("ignored: updated version")) continue; 14588 pw.println(line); 14589 } 14590 } catch (IOException ignored) { 14591 } finally { 14592 IoUtils.closeQuietly(in); 14593 } 14594 } 14595 14596 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14597 BufferedReader in = null; 14598 String line = null; 14599 try { 14600 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14601 while ((line = in.readLine()) != null) { 14602 if (line.contains("ignored: updated version")) continue; 14603 pw.print("msg,"); 14604 pw.println(line); 14605 } 14606 } catch (IOException ignored) { 14607 } finally { 14608 IoUtils.closeQuietly(in); 14609 } 14610 } 14611 } 14612 } 14613 14614 // ------- apps on sdcard specific code ------- 14615 static final boolean DEBUG_SD_INSTALL = false; 14616 14617 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14618 14619 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14620 14621 private boolean mMediaMounted = false; 14622 14623 static String getEncryptKey() { 14624 try { 14625 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14626 SD_ENCRYPTION_KEYSTORE_NAME); 14627 if (sdEncKey == null) { 14628 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14629 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14630 if (sdEncKey == null) { 14631 Slog.e(TAG, "Failed to create encryption keys"); 14632 return null; 14633 } 14634 } 14635 return sdEncKey; 14636 } catch (NoSuchAlgorithmException nsae) { 14637 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14638 return null; 14639 } catch (IOException ioe) { 14640 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14641 return null; 14642 } 14643 } 14644 14645 /* 14646 * Update media status on PackageManager. 14647 */ 14648 @Override 14649 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14650 int callingUid = Binder.getCallingUid(); 14651 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14652 throw new SecurityException("Media status can only be updated by the system"); 14653 } 14654 // reader; this apparently protects mMediaMounted, but should probably 14655 // be a different lock in that case. 14656 synchronized (mPackages) { 14657 Log.i(TAG, "Updating external media status from " 14658 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14659 + (mediaStatus ? "mounted" : "unmounted")); 14660 if (DEBUG_SD_INSTALL) 14661 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14662 + ", mMediaMounted=" + mMediaMounted); 14663 if (mediaStatus == mMediaMounted) { 14664 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14665 : 0, -1); 14666 mHandler.sendMessage(msg); 14667 return; 14668 } 14669 mMediaMounted = mediaStatus; 14670 } 14671 // Queue up an async operation since the package installation may take a 14672 // little while. 14673 mHandler.post(new Runnable() { 14674 public void run() { 14675 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14676 } 14677 }); 14678 } 14679 14680 /** 14681 * Called by MountService when the initial ASECs to scan are available. 14682 * Should block until all the ASEC containers are finished being scanned. 14683 */ 14684 public void scanAvailableAsecs() { 14685 updateExternalMediaStatusInner(true, false, false); 14686 if (mShouldRestoreconData) { 14687 SELinuxMMAC.setRestoreconDone(); 14688 mShouldRestoreconData = false; 14689 } 14690 } 14691 14692 /* 14693 * Collect information of applications on external media, map them against 14694 * existing containers and update information based on current mount status. 14695 * Please note that we always have to report status if reportStatus has been 14696 * set to true especially when unloading packages. 14697 */ 14698 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14699 boolean externalStorage) { 14700 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14701 int[] uidArr = EmptyArray.INT; 14702 14703 final String[] list = PackageHelper.getSecureContainerList(); 14704 if (ArrayUtils.isEmpty(list)) { 14705 Log.i(TAG, "No secure containers found"); 14706 } else { 14707 // Process list of secure containers and categorize them 14708 // as active or stale based on their package internal state. 14709 14710 // reader 14711 synchronized (mPackages) { 14712 for (String cid : list) { 14713 // Leave stages untouched for now; installer service owns them 14714 if (PackageInstallerService.isStageName(cid)) continue; 14715 14716 if (DEBUG_SD_INSTALL) 14717 Log.i(TAG, "Processing container " + cid); 14718 String pkgName = getAsecPackageName(cid); 14719 if (pkgName == null) { 14720 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14721 continue; 14722 } 14723 if (DEBUG_SD_INSTALL) 14724 Log.i(TAG, "Looking for pkg : " + pkgName); 14725 14726 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14727 if (ps == null) { 14728 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14729 continue; 14730 } 14731 14732 /* 14733 * Skip packages that are not external if we're unmounting 14734 * external storage. 14735 */ 14736 if (externalStorage && !isMounted && !isExternal(ps)) { 14737 continue; 14738 } 14739 14740 final AsecInstallArgs args = new AsecInstallArgs(cid, 14741 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14742 // The package status is changed only if the code path 14743 // matches between settings and the container id. 14744 if (ps.codePathString != null 14745 && ps.codePathString.startsWith(args.getCodePath())) { 14746 if (DEBUG_SD_INSTALL) { 14747 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14748 + " at code path: " + ps.codePathString); 14749 } 14750 14751 // We do have a valid package installed on sdcard 14752 processCids.put(args, ps.codePathString); 14753 final int uid = ps.appId; 14754 if (uid != -1) { 14755 uidArr = ArrayUtils.appendInt(uidArr, uid); 14756 } 14757 } else { 14758 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14759 + ps.codePathString); 14760 } 14761 } 14762 } 14763 14764 Arrays.sort(uidArr); 14765 } 14766 14767 // Process packages with valid entries. 14768 if (isMounted) { 14769 if (DEBUG_SD_INSTALL) 14770 Log.i(TAG, "Loading packages"); 14771 loadMediaPackages(processCids, uidArr); 14772 startCleaningPackages(); 14773 mInstallerService.onSecureContainersAvailable(); 14774 } else { 14775 if (DEBUG_SD_INSTALL) 14776 Log.i(TAG, "Unloading packages"); 14777 unloadMediaPackages(processCids, uidArr, reportStatus); 14778 } 14779 } 14780 14781 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14782 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14783 final int size = infos.size(); 14784 final String[] packageNames = new String[size]; 14785 final int[] packageUids = new int[size]; 14786 for (int i = 0; i < size; i++) { 14787 final ApplicationInfo info = infos.get(i); 14788 packageNames[i] = info.packageName; 14789 packageUids[i] = info.uid; 14790 } 14791 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14792 finishedReceiver); 14793 } 14794 14795 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14796 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14797 sendResourcesChangedBroadcast(mediaStatus, replacing, 14798 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14799 } 14800 14801 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14802 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14803 int size = pkgList.length; 14804 if (size > 0) { 14805 // Send broadcasts here 14806 Bundle extras = new Bundle(); 14807 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14808 if (uidArr != null) { 14809 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14810 } 14811 if (replacing) { 14812 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14813 } 14814 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14815 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14816 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14817 } 14818 } 14819 14820 /* 14821 * Look at potentially valid container ids from processCids If package 14822 * information doesn't match the one on record or package scanning fails, 14823 * the cid is added to list of removeCids. We currently don't delete stale 14824 * containers. 14825 */ 14826 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14827 ArrayList<String> pkgList = new ArrayList<String>(); 14828 Set<AsecInstallArgs> keys = processCids.keySet(); 14829 14830 for (AsecInstallArgs args : keys) { 14831 String codePath = processCids.get(args); 14832 if (DEBUG_SD_INSTALL) 14833 Log.i(TAG, "Loading container : " + args.cid); 14834 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14835 try { 14836 // Make sure there are no container errors first. 14837 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14838 Slog.e(TAG, "Failed to mount cid : " + args.cid 14839 + " when installing from sdcard"); 14840 continue; 14841 } 14842 // Check code path here. 14843 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14844 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14845 + " does not match one in settings " + codePath); 14846 continue; 14847 } 14848 // Parse package 14849 int parseFlags = mDefParseFlags; 14850 if (args.isExternalAsec()) { 14851 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14852 } 14853 if (args.isFwdLocked()) { 14854 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14855 } 14856 14857 synchronized (mInstallLock) { 14858 PackageParser.Package pkg = null; 14859 try { 14860 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14861 } catch (PackageManagerException e) { 14862 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14863 } 14864 // Scan the package 14865 if (pkg != null) { 14866 /* 14867 * TODO why is the lock being held? doPostInstall is 14868 * called in other places without the lock. This needs 14869 * to be straightened out. 14870 */ 14871 // writer 14872 synchronized (mPackages) { 14873 retCode = PackageManager.INSTALL_SUCCEEDED; 14874 pkgList.add(pkg.packageName); 14875 // Post process args 14876 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14877 pkg.applicationInfo.uid); 14878 } 14879 } else { 14880 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14881 } 14882 } 14883 14884 } finally { 14885 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14886 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14887 } 14888 } 14889 } 14890 // writer 14891 synchronized (mPackages) { 14892 // If the platform SDK has changed since the last time we booted, 14893 // we need to re-grant app permission to catch any new ones that 14894 // appear. This is really a hack, and means that apps can in some 14895 // cases get permissions that the user didn't initially explicitly 14896 // allow... it would be nice to have some better way to handle 14897 // this situation. 14898 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14899 if (regrantPermissions) 14900 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14901 + mSdkVersion + "; regranting permissions for external storage"); 14902 mSettings.mExternalSdkPlatform = mSdkVersion; 14903 14904 // Make sure group IDs have been assigned, and any permission 14905 // changes in other apps are accounted for 14906 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14907 | (regrantPermissions 14908 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14909 : 0)); 14910 14911 mSettings.updateExternalDatabaseVersion(); 14912 14913 // can downgrade to reader 14914 // Persist settings 14915 mSettings.writeLPr(); 14916 } 14917 // Send a broadcast to let everyone know we are done processing 14918 if (pkgList.size() > 0) { 14919 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14920 } 14921 } 14922 14923 /* 14924 * Utility method to unload a list of specified containers 14925 */ 14926 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14927 // Just unmount all valid containers. 14928 for (AsecInstallArgs arg : cidArgs) { 14929 synchronized (mInstallLock) { 14930 arg.doPostDeleteLI(false); 14931 } 14932 } 14933 } 14934 14935 /* 14936 * Unload packages mounted on external media. This involves deleting package 14937 * data from internal structures, sending broadcasts about diabled packages, 14938 * gc'ing to free up references, unmounting all secure containers 14939 * corresponding to packages on external media, and posting a 14940 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14941 * that we always have to post this message if status has been requested no 14942 * matter what. 14943 */ 14944 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14945 final boolean reportStatus) { 14946 if (DEBUG_SD_INSTALL) 14947 Log.i(TAG, "unloading media packages"); 14948 ArrayList<String> pkgList = new ArrayList<String>(); 14949 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14950 final Set<AsecInstallArgs> keys = processCids.keySet(); 14951 for (AsecInstallArgs args : keys) { 14952 String pkgName = args.getPackageName(); 14953 if (DEBUG_SD_INSTALL) 14954 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14955 // Delete package internally 14956 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14957 synchronized (mInstallLock) { 14958 boolean res = deletePackageLI(pkgName, null, false, null, null, 14959 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14960 if (res) { 14961 pkgList.add(pkgName); 14962 } else { 14963 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14964 failedList.add(args); 14965 } 14966 } 14967 } 14968 14969 // reader 14970 synchronized (mPackages) { 14971 // We didn't update the settings after removing each package; 14972 // write them now for all packages. 14973 mSettings.writeLPr(); 14974 } 14975 14976 // We have to absolutely send UPDATED_MEDIA_STATUS only 14977 // after confirming that all the receivers processed the ordered 14978 // broadcast when packages get disabled, force a gc to clean things up. 14979 // and unload all the containers. 14980 if (pkgList.size() > 0) { 14981 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14982 new IIntentReceiver.Stub() { 14983 public void performReceive(Intent intent, int resultCode, String data, 14984 Bundle extras, boolean ordered, boolean sticky, 14985 int sendingUser) throws RemoteException { 14986 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14987 reportStatus ? 1 : 0, 1, keys); 14988 mHandler.sendMessage(msg); 14989 } 14990 }); 14991 } else { 14992 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14993 keys); 14994 mHandler.sendMessage(msg); 14995 } 14996 } 14997 14998 private void loadPrivatePackages(VolumeInfo vol) { 14999 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15000 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15001 synchronized (mInstallLock) { 15002 synchronized (mPackages) { 15003 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15004 for (PackageSetting ps : packages) { 15005 final PackageParser.Package pkg; 15006 try { 15007 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 15008 loaded.add(pkg.applicationInfo); 15009 } catch (PackageManagerException e) { 15010 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15011 } 15012 } 15013 15014 // TODO: regrant any permissions that changed based since original install 15015 15016 mSettings.writeLPr(); 15017 } 15018 } 15019 15020 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15021 sendResourcesChangedBroadcast(true, false, loaded, null); 15022 } 15023 15024 private void unloadPrivatePackages(VolumeInfo vol) { 15025 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15026 synchronized (mInstallLock) { 15027 synchronized (mPackages) { 15028 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15029 for (PackageSetting ps : packages) { 15030 if (ps.pkg == null) continue; 15031 15032 final ApplicationInfo info = ps.pkg.applicationInfo; 15033 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15034 if (deletePackageLI(ps.name, null, false, null, null, 15035 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15036 unloaded.add(info); 15037 } else { 15038 Slog.w(TAG, "Failed to unload " + ps.codePath); 15039 } 15040 } 15041 15042 mSettings.writeLPr(); 15043 } 15044 } 15045 15046 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15047 sendResourcesChangedBroadcast(false, false, unloaded, null); 15048 } 15049 15050 private void unfreezePackage(String packageName) { 15051 synchronized (mPackages) { 15052 final PackageSetting ps = mSettings.mPackages.get(packageName); 15053 if (ps != null) { 15054 ps.frozen = false; 15055 } 15056 } 15057 } 15058 15059 @Override 15060 public int movePackage(final String packageName, final String volumeUuid) { 15061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15062 15063 final int moveId = mNextMoveId.getAndIncrement(); 15064 try { 15065 movePackageInternal(packageName, volumeUuid, moveId); 15066 } catch (PackageManagerException e) { 15067 Slog.w(TAG, "Failed to move " + packageName, e); 15068 mMoveCallbacks.notifyStatusChanged(moveId, 15069 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15070 } 15071 return moveId; 15072 } 15073 15074 private void movePackageInternal(final String packageName, final String volumeUuid, 15075 final int moveId) throws PackageManagerException { 15076 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15077 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15078 final PackageManager pm = mContext.getPackageManager(); 15079 15080 final boolean currentAsec; 15081 final String currentVolumeUuid; 15082 final File codeFile; 15083 final String installerPackageName; 15084 final String packageAbiOverride; 15085 final int appId; 15086 final String seinfo; 15087 final String label; 15088 15089 // reader 15090 synchronized (mPackages) { 15091 final PackageParser.Package pkg = mPackages.get(packageName); 15092 final PackageSetting ps = mSettings.mPackages.get(packageName); 15093 if (pkg == null || ps == null) { 15094 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15095 } 15096 15097 if (pkg.applicationInfo.isSystemApp()) { 15098 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15099 "Cannot move system application"); 15100 } 15101 15102 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15103 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15104 "Package already moved to " + volumeUuid); 15105 } 15106 15107 final File probe = new File(pkg.codePath); 15108 final File probeOat = new File(probe, "oat"); 15109 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15110 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15111 "Move only supported for modern cluster style installs"); 15112 } 15113 15114 if (ps.frozen) { 15115 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15116 "Failed to move already frozen package"); 15117 } 15118 ps.frozen = true; 15119 15120 currentAsec = pkg.applicationInfo.isForwardLocked() 15121 || pkg.applicationInfo.isExternalAsec(); 15122 currentVolumeUuid = ps.volumeUuid; 15123 codeFile = new File(pkg.codePath); 15124 installerPackageName = ps.installerPackageName; 15125 packageAbiOverride = ps.cpuAbiOverrideString; 15126 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15127 seinfo = pkg.applicationInfo.seinfo; 15128 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15129 } 15130 15131 // Now that we're guarded by frozen state, kill app during move 15132 killApplication(packageName, appId, "move pkg"); 15133 15134 final Bundle extras = new Bundle(); 15135 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15136 extras.putString(Intent.EXTRA_TITLE, label); 15137 mMoveCallbacks.notifyCreated(moveId, extras); 15138 15139 int installFlags; 15140 final boolean moveCompleteApp; 15141 final File measurePath; 15142 15143 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15144 installFlags = INSTALL_INTERNAL; 15145 moveCompleteApp = !currentAsec; 15146 measurePath = Environment.getDataAppDirectory(volumeUuid); 15147 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15148 installFlags = INSTALL_EXTERNAL; 15149 moveCompleteApp = false; 15150 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15151 } else { 15152 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15153 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15154 || !volume.isMountedWritable()) { 15155 unfreezePackage(packageName); 15156 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15157 "Move location not mounted private volume"); 15158 } 15159 15160 Preconditions.checkState(!currentAsec); 15161 15162 installFlags = INSTALL_INTERNAL; 15163 moveCompleteApp = true; 15164 measurePath = Environment.getDataAppDirectory(volumeUuid); 15165 } 15166 15167 final PackageStats stats = new PackageStats(null, -1); 15168 synchronized (mInstaller) { 15169 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15170 unfreezePackage(packageName); 15171 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15172 "Failed to measure package size"); 15173 } 15174 } 15175 15176 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15177 + stats.dataSize); 15178 15179 final long startFreeBytes = measurePath.getFreeSpace(); 15180 final long sizeBytes; 15181 if (moveCompleteApp) { 15182 sizeBytes = stats.codeSize + stats.dataSize; 15183 } else { 15184 sizeBytes = stats.codeSize; 15185 } 15186 15187 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15188 unfreezePackage(packageName); 15189 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15190 "Not enough free space to move"); 15191 } 15192 15193 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15194 15195 final CountDownLatch installedLatch = new CountDownLatch(1); 15196 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15197 @Override 15198 public void onUserActionRequired(Intent intent) throws RemoteException { 15199 throw new IllegalStateException(); 15200 } 15201 15202 @Override 15203 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15204 Bundle extras) throws RemoteException { 15205 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15206 + PackageManager.installStatusToString(returnCode, msg)); 15207 15208 installedLatch.countDown(); 15209 15210 // Regardless of success or failure of the move operation, 15211 // always unfreeze the package 15212 unfreezePackage(packageName); 15213 15214 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15215 switch (status) { 15216 case PackageInstaller.STATUS_SUCCESS: 15217 mMoveCallbacks.notifyStatusChanged(moveId, 15218 PackageManager.MOVE_SUCCEEDED); 15219 break; 15220 case PackageInstaller.STATUS_FAILURE_STORAGE: 15221 mMoveCallbacks.notifyStatusChanged(moveId, 15222 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15223 break; 15224 default: 15225 mMoveCallbacks.notifyStatusChanged(moveId, 15226 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15227 break; 15228 } 15229 } 15230 }; 15231 15232 final MoveInfo move; 15233 if (moveCompleteApp) { 15234 // Kick off a thread to report progress estimates 15235 new Thread() { 15236 @Override 15237 public void run() { 15238 while (true) { 15239 try { 15240 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15241 break; 15242 } 15243 } catch (InterruptedException ignored) { 15244 } 15245 15246 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15247 final int progress = 10 + (int) MathUtils.constrain( 15248 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15249 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15250 } 15251 } 15252 }.start(); 15253 15254 final String dataAppName = codeFile.getName(); 15255 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15256 dataAppName, appId, seinfo); 15257 } else { 15258 move = null; 15259 } 15260 15261 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15262 15263 final Message msg = mHandler.obtainMessage(INIT_COPY); 15264 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15265 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15266 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15267 mHandler.sendMessage(msg); 15268 } 15269 15270 @Override 15271 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15273 15274 final int realMoveId = mNextMoveId.getAndIncrement(); 15275 final Bundle extras = new Bundle(); 15276 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15277 mMoveCallbacks.notifyCreated(realMoveId, extras); 15278 15279 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15280 @Override 15281 public void onCreated(int moveId, Bundle extras) { 15282 // Ignored 15283 } 15284 15285 @Override 15286 public void onStatusChanged(int moveId, int status, long estMillis) { 15287 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15288 } 15289 }; 15290 15291 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15292 storage.setPrimaryStorageUuid(volumeUuid, callback); 15293 return realMoveId; 15294 } 15295 15296 @Override 15297 public int getMoveStatus(int moveId) { 15298 mContext.enforceCallingOrSelfPermission( 15299 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15300 return mMoveCallbacks.mLastStatus.get(moveId); 15301 } 15302 15303 @Override 15304 public void registerMoveCallback(IPackageMoveObserver callback) { 15305 mContext.enforceCallingOrSelfPermission( 15306 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15307 mMoveCallbacks.register(callback); 15308 } 15309 15310 @Override 15311 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15312 mContext.enforceCallingOrSelfPermission( 15313 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15314 mMoveCallbacks.unregister(callback); 15315 } 15316 15317 @Override 15318 public boolean setInstallLocation(int loc) { 15319 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15320 null); 15321 if (getInstallLocation() == loc) { 15322 return true; 15323 } 15324 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15325 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15326 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15327 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15328 return true; 15329 } 15330 return false; 15331 } 15332 15333 @Override 15334 public int getInstallLocation() { 15335 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15336 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15337 PackageHelper.APP_INSTALL_AUTO); 15338 } 15339 15340 /** Called by UserManagerService */ 15341 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15342 mDirtyUsers.remove(userHandle); 15343 mSettings.removeUserLPw(userHandle); 15344 mPendingBroadcasts.remove(userHandle); 15345 if (mInstaller != null) { 15346 // Technically, we shouldn't be doing this with the package lock 15347 // held. However, this is very rare, and there is already so much 15348 // other disk I/O going on, that we'll let it slide for now. 15349 final StorageManager storage = StorageManager.from(mContext); 15350 final List<VolumeInfo> vols = storage.getVolumes(); 15351 for (VolumeInfo vol : vols) { 15352 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15353 final String volumeUuid = vol.getFsUuid(); 15354 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15355 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15356 } 15357 } 15358 } 15359 mUserNeedsBadging.delete(userHandle); 15360 removeUnusedPackagesLILPw(userManager, userHandle); 15361 } 15362 15363 /** 15364 * We're removing userHandle and would like to remove any downloaded packages 15365 * that are no longer in use by any other user. 15366 * @param userHandle the user being removed 15367 */ 15368 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15369 final boolean DEBUG_CLEAN_APKS = false; 15370 int [] users = userManager.getUserIdsLPr(); 15371 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15372 while (psit.hasNext()) { 15373 PackageSetting ps = psit.next(); 15374 if (ps.pkg == null) { 15375 continue; 15376 } 15377 final String packageName = ps.pkg.packageName; 15378 // Skip over if system app 15379 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15380 continue; 15381 } 15382 if (DEBUG_CLEAN_APKS) { 15383 Slog.i(TAG, "Checking package " + packageName); 15384 } 15385 boolean keep = false; 15386 for (int i = 0; i < users.length; i++) { 15387 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15388 keep = true; 15389 if (DEBUG_CLEAN_APKS) { 15390 Slog.i(TAG, " Keeping package " + packageName + " for user " 15391 + users[i]); 15392 } 15393 break; 15394 } 15395 } 15396 if (!keep) { 15397 if (DEBUG_CLEAN_APKS) { 15398 Slog.i(TAG, " Removing package " + packageName); 15399 } 15400 mHandler.post(new Runnable() { 15401 public void run() { 15402 deletePackageX(packageName, userHandle, 0); 15403 } //end run 15404 }); 15405 } 15406 } 15407 } 15408 15409 /** Called by UserManagerService */ 15410 void createNewUserLILPw(int userHandle, File path) { 15411 if (mInstaller != null) { 15412 mInstaller.createUserConfig(userHandle); 15413 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15414 } 15415 } 15416 15417 void newUserCreatedLILPw(final int userHandle) { 15418 // We cannot grant the default permissions with a lock held as 15419 // we query providers from other components for default handlers 15420 // such as enabled IMEs, etc. 15421 mHandler.post(new Runnable() { 15422 @Override 15423 public void run() { 15424 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15425 } 15426 }); 15427 } 15428 15429 @Override 15430 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15431 mContext.enforceCallingOrSelfPermission( 15432 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15433 "Only package verification agents can read the verifier device identity"); 15434 15435 synchronized (mPackages) { 15436 return mSettings.getVerifierDeviceIdentityLPw(); 15437 } 15438 } 15439 15440 @Override 15441 public void setPermissionEnforced(String permission, boolean enforced) { 15442 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15443 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15444 synchronized (mPackages) { 15445 if (mSettings.mReadExternalStorageEnforced == null 15446 || mSettings.mReadExternalStorageEnforced != enforced) { 15447 mSettings.mReadExternalStorageEnforced = enforced; 15448 mSettings.writeLPr(); 15449 } 15450 } 15451 // kill any non-foreground processes so we restart them and 15452 // grant/revoke the GID. 15453 final IActivityManager am = ActivityManagerNative.getDefault(); 15454 if (am != null) { 15455 final long token = Binder.clearCallingIdentity(); 15456 try { 15457 am.killProcessesBelowForeground("setPermissionEnforcement"); 15458 } catch (RemoteException e) { 15459 } finally { 15460 Binder.restoreCallingIdentity(token); 15461 } 15462 } 15463 } else { 15464 throw new IllegalArgumentException("No selective enforcement for " + permission); 15465 } 15466 } 15467 15468 @Override 15469 @Deprecated 15470 public boolean isPermissionEnforced(String permission) { 15471 return true; 15472 } 15473 15474 @Override 15475 public boolean isStorageLow() { 15476 final long token = Binder.clearCallingIdentity(); 15477 try { 15478 final DeviceStorageMonitorInternal 15479 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15480 if (dsm != null) { 15481 return dsm.isMemoryLow(); 15482 } else { 15483 return false; 15484 } 15485 } finally { 15486 Binder.restoreCallingIdentity(token); 15487 } 15488 } 15489 15490 @Override 15491 public IPackageInstaller getPackageInstaller() { 15492 return mInstallerService; 15493 } 15494 15495 private boolean userNeedsBadging(int userId) { 15496 int index = mUserNeedsBadging.indexOfKey(userId); 15497 if (index < 0) { 15498 final UserInfo userInfo; 15499 final long token = Binder.clearCallingIdentity(); 15500 try { 15501 userInfo = sUserManager.getUserInfo(userId); 15502 } finally { 15503 Binder.restoreCallingIdentity(token); 15504 } 15505 final boolean b; 15506 if (userInfo != null && userInfo.isManagedProfile()) { 15507 b = true; 15508 } else { 15509 b = false; 15510 } 15511 mUserNeedsBadging.put(userId, b); 15512 return b; 15513 } 15514 return mUserNeedsBadging.valueAt(index); 15515 } 15516 15517 @Override 15518 public KeySet getKeySetByAlias(String packageName, String alias) { 15519 if (packageName == null || alias == null) { 15520 return null; 15521 } 15522 synchronized(mPackages) { 15523 final PackageParser.Package pkg = mPackages.get(packageName); 15524 if (pkg == null) { 15525 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15526 throw new IllegalArgumentException("Unknown package: " + packageName); 15527 } 15528 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15529 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15530 } 15531 } 15532 15533 @Override 15534 public KeySet getSigningKeySet(String packageName) { 15535 if (packageName == null) { 15536 return null; 15537 } 15538 synchronized(mPackages) { 15539 final PackageParser.Package pkg = mPackages.get(packageName); 15540 if (pkg == null) { 15541 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15542 throw new IllegalArgumentException("Unknown package: " + packageName); 15543 } 15544 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15545 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15546 throw new SecurityException("May not access signing KeySet of other apps."); 15547 } 15548 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15549 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15550 } 15551 } 15552 15553 @Override 15554 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15555 if (packageName == null || ks == null) { 15556 return false; 15557 } 15558 synchronized(mPackages) { 15559 final PackageParser.Package pkg = mPackages.get(packageName); 15560 if (pkg == null) { 15561 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15562 throw new IllegalArgumentException("Unknown package: " + packageName); 15563 } 15564 IBinder ksh = ks.getToken(); 15565 if (ksh instanceof KeySetHandle) { 15566 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15567 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15568 } 15569 return false; 15570 } 15571 } 15572 15573 @Override 15574 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15575 if (packageName == null || ks == null) { 15576 return false; 15577 } 15578 synchronized(mPackages) { 15579 final PackageParser.Package pkg = mPackages.get(packageName); 15580 if (pkg == null) { 15581 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15582 throw new IllegalArgumentException("Unknown package: " + packageName); 15583 } 15584 IBinder ksh = ks.getToken(); 15585 if (ksh instanceof KeySetHandle) { 15586 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15587 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15588 } 15589 return false; 15590 } 15591 } 15592 15593 public void getUsageStatsIfNoPackageUsageInfo() { 15594 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15595 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15596 if (usm == null) { 15597 throw new IllegalStateException("UsageStatsManager must be initialized"); 15598 } 15599 long now = System.currentTimeMillis(); 15600 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15601 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15602 String packageName = entry.getKey(); 15603 PackageParser.Package pkg = mPackages.get(packageName); 15604 if (pkg == null) { 15605 continue; 15606 } 15607 UsageStats usage = entry.getValue(); 15608 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15609 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15610 } 15611 } 15612 } 15613 15614 /** 15615 * Check and throw if the given before/after packages would be considered a 15616 * downgrade. 15617 */ 15618 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15619 throws PackageManagerException { 15620 if (after.versionCode < before.mVersionCode) { 15621 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15622 "Update version code " + after.versionCode + " is older than current " 15623 + before.mVersionCode); 15624 } else if (after.versionCode == before.mVersionCode) { 15625 if (after.baseRevisionCode < before.baseRevisionCode) { 15626 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15627 "Update base revision code " + after.baseRevisionCode 15628 + " is older than current " + before.baseRevisionCode); 15629 } 15630 15631 if (!ArrayUtils.isEmpty(after.splitNames)) { 15632 for (int i = 0; i < after.splitNames.length; i++) { 15633 final String splitName = after.splitNames[i]; 15634 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15635 if (j != -1) { 15636 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15637 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15638 "Update split " + splitName + " revision code " 15639 + after.splitRevisionCodes[i] + " is older than current " 15640 + before.splitRevisionCodes[j]); 15641 } 15642 } 15643 } 15644 } 15645 } 15646 } 15647 15648 private static class MoveCallbacks extends Handler { 15649 private static final int MSG_CREATED = 1; 15650 private static final int MSG_STATUS_CHANGED = 2; 15651 15652 private final RemoteCallbackList<IPackageMoveObserver> 15653 mCallbacks = new RemoteCallbackList<>(); 15654 15655 private final SparseIntArray mLastStatus = new SparseIntArray(); 15656 15657 public MoveCallbacks(Looper looper) { 15658 super(looper); 15659 } 15660 15661 public void register(IPackageMoveObserver callback) { 15662 mCallbacks.register(callback); 15663 } 15664 15665 public void unregister(IPackageMoveObserver callback) { 15666 mCallbacks.unregister(callback); 15667 } 15668 15669 @Override 15670 public void handleMessage(Message msg) { 15671 final SomeArgs args = (SomeArgs) msg.obj; 15672 final int n = mCallbacks.beginBroadcast(); 15673 for (int i = 0; i < n; i++) { 15674 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15675 try { 15676 invokeCallback(callback, msg.what, args); 15677 } catch (RemoteException ignored) { 15678 } 15679 } 15680 mCallbacks.finishBroadcast(); 15681 args.recycle(); 15682 } 15683 15684 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15685 throws RemoteException { 15686 switch (what) { 15687 case MSG_CREATED: { 15688 callback.onCreated(args.argi1, (Bundle) args.arg2); 15689 break; 15690 } 15691 case MSG_STATUS_CHANGED: { 15692 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15693 break; 15694 } 15695 } 15696 } 15697 15698 private void notifyCreated(int moveId, Bundle extras) { 15699 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15700 15701 final SomeArgs args = SomeArgs.obtain(); 15702 args.argi1 = moveId; 15703 args.arg2 = extras; 15704 obtainMessage(MSG_CREATED, args).sendToTarget(); 15705 } 15706 15707 private void notifyStatusChanged(int moveId, int status) { 15708 notifyStatusChanged(moveId, status, -1); 15709 } 15710 15711 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15712 Slog.v(TAG, "Move " + moveId + " status " + status); 15713 15714 final SomeArgs args = SomeArgs.obtain(); 15715 args.argi1 = moveId; 15716 args.argi2 = status; 15717 args.arg3 = estMillis; 15718 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15719 15720 synchronized (mLastStatus) { 15721 mLastStatus.put(moveId, status); 15722 } 15723 } 15724 } 15725 15726 private final class OnPermissionChangeListeners extends Handler { 15727 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15728 15729 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15730 new RemoteCallbackList<>(); 15731 15732 public OnPermissionChangeListeners(Looper looper) { 15733 super(looper); 15734 } 15735 15736 @Override 15737 public void handleMessage(Message msg) { 15738 switch (msg.what) { 15739 case MSG_ON_PERMISSIONS_CHANGED: { 15740 final int uid = msg.arg1; 15741 handleOnPermissionsChanged(uid); 15742 } break; 15743 } 15744 } 15745 15746 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15747 mPermissionListeners.register(listener); 15748 15749 } 15750 15751 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15752 mPermissionListeners.unregister(listener); 15753 } 15754 15755 public void onPermissionsChanged(int uid) { 15756 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15757 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15758 } 15759 } 15760 15761 private void handleOnPermissionsChanged(int uid) { 15762 final int count = mPermissionListeners.beginBroadcast(); 15763 try { 15764 for (int i = 0; i < count; i++) { 15765 IOnPermissionsChangeListener callback = mPermissionListeners 15766 .getBroadcastItem(i); 15767 try { 15768 callback.onPermissionsChanged(uid); 15769 } catch (RemoteException e) { 15770 Log.e(TAG, "Permission listener is dead", e); 15771 } 15772 } 15773 } finally { 15774 mPermissionListeners.finishBroadcast(); 15775 } 15776 } 15777 } 15778 15779 private class PackageManagerInternalImpl extends PackageManagerInternal { 15780 @Override 15781 public void setLocationPackagesProvider(PackagesProvider provider) { 15782 synchronized (mPackages) { 15783 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15784 } 15785 } 15786 15787 @Override 15788 public void setImePackagesProvider(PackagesProvider provider) { 15789 synchronized (mPackages) { 15790 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15791 } 15792 } 15793 15794 @Override 15795 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15796 synchronized (mPackages) { 15797 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15798 } 15799 } 15800 } 15801 15802 @Override 15803 public void grantDefaultPermissions(final int userId) { 15804 enforceSystemOrPhoneCaller("grantDefaultPermissions"); 15805 long token = Binder.clearCallingIdentity(); 15806 try { 15807 // We cannot grant the default permissions with a lock held as 15808 // we query providers from other components for default handlers 15809 // such as enabled IMEs, etc. 15810 mHandler.post(new Runnable() { 15811 @Override 15812 public void run() { 15813 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15814 } 15815 }); 15816 } finally { 15817 Binder.restoreCallingIdentity(token); 15818 } 15819 } 15820 15821 @Override 15822 public void setCarrierAppPackagesProvider(final IPackagesProvider provider) { 15823 enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider"); 15824 long token = Binder.clearCallingIdentity(); 15825 try { 15826 PackageManagerInternal.PackagesProvider wrapper = 15827 new PackageManagerInternal.PackagesProvider() { 15828 @Override 15829 public String[] getPackages(int userId) { 15830 try { 15831 return provider.getPackages(userId); 15832 } catch (RemoteException e) { 15833 return null; 15834 } 15835 } 15836 }; 15837 synchronized (mPackages) { 15838 mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper); 15839 } 15840 } finally { 15841 Binder.restoreCallingIdentity(token); 15842 } 15843 } 15844 15845 private static void enforceSystemOrPhoneCaller(String tag) { 15846 int callingUid = Binder.getCallingUid(); 15847 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 15848 throw new SecurityException( 15849 "Cannot call " + tag + " from UID " + callingUid); 15850 } 15851 } 15852} 15853