PackageManagerService.java revision 279a9a3131635fe84d33231711f40daaa798ae26
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.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.InstrumentationInfo; 106import android.content.pm.IntentFilterVerificationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageManagerInternal; 116import android.content.pm.PackageParser; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Debug; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteCallbackList; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.os.storage.IMountService; 159import android.os.storage.StorageEventListener; 160import android.os.storage.StorageManager; 161import android.os.storage.VolumeInfo; 162import android.os.storage.VolumeRecord; 163import android.security.KeyStore; 164import android.security.SystemKeyStore; 165import android.system.ErrnoException; 166import android.system.Os; 167import android.system.StructStat; 168import android.text.TextUtils; 169import android.text.format.DateUtils; 170import android.util.ArrayMap; 171import android.util.ArraySet; 172import android.util.AtomicFile; 173import android.util.DisplayMetrics; 174import android.util.EventLog; 175import android.util.ExceptionUtils; 176import android.util.Log; 177import android.util.LogPrinter; 178import android.util.MathUtils; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.util.SparseIntArray; 184import android.util.Xml; 185import android.view.Display; 186 187import dalvik.system.DexFile; 188import dalvik.system.VMRuntime; 189 190import libcore.io.IoUtils; 191import libcore.util.EmptyArray; 192 193import com.android.internal.R; 194import com.android.internal.app.IMediaContainerService; 195import com.android.internal.app.ResolverActivity; 196import com.android.internal.content.NativeLibraryHelper; 197import com.android.internal.content.PackageHelper; 198import com.android.internal.os.IParcelFileDescriptorFactory; 199import com.android.internal.os.SomeArgs; 200import com.android.internal.os.Zygote; 201import com.android.internal.util.ArrayUtils; 202import com.android.internal.util.FastPrintWriter; 203import com.android.internal.util.FastXmlSerializer; 204import com.android.internal.util.IndentingPrintWriter; 205import com.android.internal.util.Preconditions; 206import com.android.server.EventLogTags; 207import com.android.server.FgThread; 208import com.android.server.IntentResolver; 209import com.android.server.LocalServices; 210import com.android.server.ServiceThread; 211import com.android.server.SystemConfig; 212import com.android.server.Watchdog; 213import com.android.server.pm.PermissionsState.PermissionState; 214import com.android.server.pm.Settings.DatabaseVersion; 215import com.android.server.storage.DeviceStorageMonitorInternal; 216 217import org.xmlpull.v1.XmlPullParser; 218import org.xmlpull.v1.XmlPullParserException; 219import org.xmlpull.v1.XmlSerializer; 220 221import java.io.BufferedInputStream; 222import java.io.BufferedOutputStream; 223import java.io.BufferedReader; 224import java.io.ByteArrayInputStream; 225import java.io.ByteArrayOutputStream; 226import java.io.File; 227import java.io.FileDescriptor; 228import java.io.FileNotFoundException; 229import java.io.FileOutputStream; 230import java.io.FileReader; 231import java.io.FilenameFilter; 232import java.io.IOException; 233import java.io.InputStream; 234import java.io.PrintWriter; 235import java.nio.charset.StandardCharsets; 236import java.security.NoSuchAlgorithmException; 237import java.security.PublicKey; 238import java.security.cert.CertificateEncodingException; 239import java.security.cert.CertificateException; 240import java.text.SimpleDateFormat; 241import java.util.ArrayList; 242import java.util.Arrays; 243import java.util.Collection; 244import java.util.Collections; 245import java.util.Comparator; 246import java.util.Date; 247import java.util.Iterator; 248import java.util.List; 249import java.util.Map; 250import java.util.Objects; 251import java.util.Set; 252import java.util.concurrent.CountDownLatch; 253import java.util.concurrent.TimeUnit; 254import java.util.concurrent.atomic.AtomicBoolean; 255import java.util.concurrent.atomic.AtomicInteger; 256import java.util.concurrent.atomic.AtomicLong; 257 258/** 259 * Keep track of all those .apks everywhere. 260 * 261 * This is very central to the platform's security; please run the unit 262 * tests whenever making modifications here: 263 * 264runtest -c android.content.pm.PackageManagerTests frameworks-core 265 * 266 * {@hide} 267 */ 268public class PackageManagerService extends IPackageManager.Stub { 269 static final String TAG = "PackageManager"; 270 static final boolean DEBUG_SETTINGS = false; 271 static final boolean DEBUG_PREFERRED = false; 272 static final boolean DEBUG_UPGRADE = false; 273 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 274 private static final boolean DEBUG_BACKUP = true; 275 private static final boolean DEBUG_INSTALL = false; 276 private static final boolean DEBUG_REMOVE = false; 277 private static final boolean DEBUG_BROADCASTS = false; 278 private static final boolean DEBUG_SHOW_INFO = false; 279 private static final boolean DEBUG_PACKAGE_INFO = false; 280 private static final boolean DEBUG_INTENT_MATCHING = false; 281 private static final boolean DEBUG_PACKAGE_SCANNING = false; 282 private static final boolean DEBUG_VERIFY = false; 283 private static final boolean DEBUG_DEXOPT = false; 284 private static final boolean DEBUG_ABI_SELECTION = false; 285 286 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 287 288 private static final int RADIO_UID = Process.PHONE_UID; 289 private static final int LOG_UID = Process.LOG_UID; 290 private static final int NFC_UID = Process.NFC_UID; 291 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 292 private static final int SHELL_UID = Process.SHELL_UID; 293 294 // Cap the size of permission trees that 3rd party apps can define 295 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 296 297 // Suffix used during package installation when copying/moving 298 // package apks to install directory. 299 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 300 301 static final int SCAN_NO_DEX = 1<<1; 302 static final int SCAN_FORCE_DEX = 1<<2; 303 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 304 static final int SCAN_NEW_INSTALL = 1<<4; 305 static final int SCAN_NO_PATHS = 1<<5; 306 static final int SCAN_UPDATE_TIME = 1<<6; 307 static final int SCAN_DEFER_DEX = 1<<7; 308 static final int SCAN_BOOTING = 1<<8; 309 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 310 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 311 static final int SCAN_REQUIRE_KNOWN = 1<<12; 312 static final int SCAN_MOVE = 1<<13; 313 static final int SCAN_INITIAL = 1<<14; 314 315 static final int REMOVE_CHATTY = 1<<16; 316 317 private static final int[] EMPTY_INT_ARRAY = new int[0]; 318 319 /** 320 * Timeout (in milliseconds) after which the watchdog should declare that 321 * our handler thread is wedged. The usual default for such things is one 322 * minute but we sometimes do very lengthy I/O operations on this thread, 323 * such as installing multi-gigabyte applications, so ours needs to be longer. 324 */ 325 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 326 327 /** 328 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 329 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 330 * settings entry if available, otherwise we use the hardcoded default. If it's been 331 * more than this long since the last fstrim, we force one during the boot sequence. 332 * 333 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 334 * one gets run at the next available charging+idle time. This final mandatory 335 * no-fstrim check kicks in only of the other scheduling criteria is never met. 336 */ 337 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 338 339 /** 340 * Whether verification is enabled by default. 341 */ 342 private static final boolean DEFAULT_VERIFY_ENABLE = true; 343 344 /** 345 * The default maximum time to wait for the verification agent to return in 346 * milliseconds. 347 */ 348 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 349 350 /** 351 * The default response for package verification timeout. 352 * 353 * This can be either PackageManager.VERIFICATION_ALLOW or 354 * PackageManager.VERIFICATION_REJECT. 355 */ 356 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 357 358 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 359 360 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 361 DEFAULT_CONTAINER_PACKAGE, 362 "com.android.defcontainer.DefaultContainerService"); 363 364 private static final String KILL_APP_REASON_GIDS_CHANGED = 365 "permission grant or revoke changed gids"; 366 367 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 368 "permissions revoked"; 369 370 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 371 372 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 373 374 /** Permission grant: not grant the permission. */ 375 private static final int GRANT_DENIED = 1; 376 377 /** Permission grant: grant the permission as an install permission. */ 378 private static final int GRANT_INSTALL = 2; 379 380 /** Permission grant: grant the permission as an install permission for a legacy app. */ 381 private static final int GRANT_INSTALL_LEGACY = 3; 382 383 /** Permission grant: grant the permission as a runtime one. */ 384 private static final int GRANT_RUNTIME = 4; 385 386 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 387 private static final int GRANT_UPGRADE = 5; 388 389 final ServiceThread mHandlerThread; 390 391 final PackageHandler mHandler; 392 393 /** 394 * Messages for {@link #mHandler} that need to wait for system ready before 395 * being dispatched. 396 */ 397 private ArrayList<Message> mPostSystemReadyMessages; 398 399 final int mSdkVersion = Build.VERSION.SDK_INT; 400 401 final Context mContext; 402 final boolean mFactoryTest; 403 final boolean mOnlyCore; 404 final boolean mLazyDexOpt; 405 final long mDexOptLRUThresholdInMills; 406 final DisplayMetrics mMetrics; 407 final int mDefParseFlags; 408 final String[] mSeparateProcesses; 409 final boolean mIsUpgrade; 410 411 // This is where all application persistent data goes. 412 final File mAppDataDir; 413 414 // This is where all application persistent data goes for secondary users. 415 final File mUserAppDataDir; 416 417 /** The location for ASEC container files on internal storage. */ 418 final String mAsecInternalPath; 419 420 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 421 // LOCK HELD. Can be called with mInstallLock held. 422 final Installer mInstaller; 423 424 /** Directory where installed third-party apps stored */ 425 final File mAppInstallDir; 426 427 /** 428 * Directory to which applications installed internally have their 429 * 32 bit native libraries copied. 430 */ 431 private File mAppLib32InstallDir; 432 433 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 434 // apps. 435 final File mDrmAppPrivateInstallDir; 436 437 // ---------------------------------------------------------------- 438 439 // Lock for state used when installing and doing other long running 440 // operations. Methods that must be called with this lock held have 441 // the suffix "LI". 442 final Object mInstallLock = new Object(); 443 444 // ---------------------------------------------------------------- 445 446 // Keys are String (package name), values are Package. This also serves 447 // as the lock for the global state. Methods that must be called with 448 // this lock held have the prefix "LP". 449 final ArrayMap<String, PackageParser.Package> mPackages = 450 new ArrayMap<String, PackageParser.Package>(); 451 452 // Tracks available target package names -> overlay package paths. 453 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 454 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 455 456 final Settings mSettings; 457 boolean mRestoredSettings; 458 459 // System configuration read by SystemConfig. 460 final int[] mGlobalGids; 461 final SparseArray<ArraySet<String>> mSystemPermissions; 462 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 463 464 // If mac_permissions.xml was found for seinfo labeling. 465 boolean mFoundPolicyFile; 466 467 // If a recursive restorecon of /data/data/<pkg> is needed. 468 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 469 470 public static final class SharedLibraryEntry { 471 public final String path; 472 public final String apk; 473 474 SharedLibraryEntry(String _path, String _apk) { 475 path = _path; 476 apk = _apk; 477 } 478 } 479 480 // Currently known shared libraries. 481 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 482 new ArrayMap<String, SharedLibraryEntry>(); 483 484 // All available activities, for your resolving pleasure. 485 final ActivityIntentResolver mActivities = 486 new ActivityIntentResolver(); 487 488 // All available receivers, for your resolving pleasure. 489 final ActivityIntentResolver mReceivers = 490 new ActivityIntentResolver(); 491 492 // All available services, for your resolving pleasure. 493 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 494 495 // All available providers, for your resolving pleasure. 496 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 497 498 // Mapping from provider base names (first directory in content URI codePath) 499 // to the provider information. 500 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 501 new ArrayMap<String, PackageParser.Provider>(); 502 503 // Mapping from instrumentation class names to info about them. 504 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 505 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 506 507 // Mapping from permission names to info about them. 508 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 509 new ArrayMap<String, PackageParser.PermissionGroup>(); 510 511 // Packages whose data we have transfered into another package, thus 512 // should no longer exist. 513 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 514 515 // Broadcast actions that are only available to the system. 516 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 517 518 /** List of packages waiting for verification. */ 519 final SparseArray<PackageVerificationState> mPendingVerification 520 = new SparseArray<PackageVerificationState>(); 521 522 /** Set of packages associated with each app op permission. */ 523 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 524 525 final PackageInstallerService mInstallerService; 526 527 private final PackageDexOptimizer mPackageDexOptimizer; 528 529 private AtomicInteger mNextMoveId = new AtomicInteger(); 530 private final MoveCallbacks mMoveCallbacks; 531 532 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 533 534 // Cache of users who need badging. 535 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 536 537 /** Token for keys in mPendingVerification. */ 538 private int mPendingVerificationToken = 0; 539 540 volatile boolean mSystemReady; 541 volatile boolean mSafeMode; 542 volatile boolean mHasSystemUidErrors; 543 544 ApplicationInfo mAndroidApplication; 545 final ActivityInfo mResolveActivity = new ActivityInfo(); 546 final ResolveInfo mResolveInfo = new ResolveInfo(); 547 ComponentName mResolveComponentName; 548 PackageParser.Package mPlatformPackage; 549 ComponentName mCustomResolverComponentName; 550 551 boolean mResolverReplaced = false; 552 553 private final ComponentName mIntentFilterVerifierComponent; 554 private int mIntentFilterVerificationToken = 0; 555 556 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 557 = new SparseArray<IntentFilterVerificationState>(); 558 559 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 560 new DefaultPermissionGrantPolicy(this); 561 562 private static class IFVerificationParams { 563 PackageParser.Package pkg; 564 boolean replacing; 565 int userId; 566 int verifierUid; 567 568 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 569 int _userId, int _verifierUid) { 570 pkg = _pkg; 571 replacing = _replacing; 572 userId = _userId; 573 replacing = _replacing; 574 verifierUid = _verifierUid; 575 } 576 } 577 578 private interface IntentFilterVerifier<T extends IntentFilter> { 579 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 580 T filter, String packageName); 581 void startVerifications(int userId); 582 void receiveVerificationResponse(int verificationId); 583 } 584 585 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 586 private Context mContext; 587 private ComponentName mIntentFilterVerifierComponent; 588 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 589 590 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 591 mContext = context; 592 mIntentFilterVerifierComponent = verifierComponent; 593 } 594 595 private String getDefaultScheme() { 596 return IntentFilter.SCHEME_HTTPS; 597 } 598 599 @Override 600 public void startVerifications(int userId) { 601 // Launch verifications requests 602 int count = mCurrentIntentFilterVerifications.size(); 603 for (int n=0; n<count; n++) { 604 int verificationId = mCurrentIntentFilterVerifications.get(n); 605 final IntentFilterVerificationState ivs = 606 mIntentFilterVerificationStates.get(verificationId); 607 608 String packageName = ivs.getPackageName(); 609 610 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 611 final int filterCount = filters.size(); 612 ArraySet<String> domainsSet = new ArraySet<>(); 613 for (int m=0; m<filterCount; m++) { 614 PackageParser.ActivityIntentInfo filter = filters.get(m); 615 domainsSet.addAll(filter.getHostsList()); 616 } 617 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 618 synchronized (mPackages) { 619 if (mSettings.createIntentFilterVerificationIfNeededLPw( 620 packageName, domainsList) != null) { 621 scheduleWriteSettingsLocked(); 622 } 623 } 624 sendVerificationRequest(userId, verificationId, ivs); 625 } 626 mCurrentIntentFilterVerifications.clear(); 627 } 628 629 private void sendVerificationRequest(int userId, int verificationId, 630 IntentFilterVerificationState ivs) { 631 632 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 633 verificationIntent.putExtra( 634 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 635 verificationId); 636 verificationIntent.putExtra( 637 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 638 getDefaultScheme()); 639 verificationIntent.putExtra( 640 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 641 ivs.getHostsString()); 642 verificationIntent.putExtra( 643 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 644 ivs.getPackageName()); 645 verificationIntent.setComponent(mIntentFilterVerifierComponent); 646 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 647 648 UserHandle user = new UserHandle(userId); 649 mContext.sendBroadcastAsUser(verificationIntent, user); 650 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 651 "Sending IntentFilter verification broadcast"); 652 } 653 654 public void receiveVerificationResponse(int verificationId) { 655 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 656 657 final boolean verified = ivs.isVerified(); 658 659 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 660 final int count = filters.size(); 661 if (DEBUG_DOMAIN_VERIFICATION) { 662 Slog.i(TAG, "Received verification response " + verificationId 663 + " for " + count + " filters, verified=" + verified); 664 } 665 for (int n=0; n<count; n++) { 666 PackageParser.ActivityIntentInfo filter = filters.get(n); 667 filter.setVerified(verified); 668 669 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 670 + " verified with result:" + verified + " and hosts:" 671 + ivs.getHostsString()); 672 } 673 674 mIntentFilterVerificationStates.remove(verificationId); 675 676 final String packageName = ivs.getPackageName(); 677 IntentFilterVerificationInfo ivi = null; 678 679 synchronized (mPackages) { 680 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 681 } 682 if (ivi == null) { 683 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 684 + verificationId + " packageName:" + packageName); 685 return; 686 } 687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 688 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 689 690 synchronized (mPackages) { 691 if (verified) { 692 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 693 } else { 694 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 695 } 696 scheduleWriteSettingsLocked(); 697 698 final int userId = ivs.getUserId(); 699 if (userId != UserHandle.USER_ALL) { 700 final int userStatus = 701 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 702 703 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 704 boolean needUpdate = false; 705 706 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 707 // already been set by the User thru the Disambiguation dialog 708 switch (userStatus) { 709 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 710 if (verified) { 711 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 712 } else { 713 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 714 } 715 needUpdate = true; 716 break; 717 718 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 719 if (verified) { 720 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 721 needUpdate = true; 722 } 723 break; 724 725 default: 726 // Nothing to do 727 } 728 729 if (needUpdate) { 730 mSettings.updateIntentFilterVerificationStatusLPw( 731 packageName, updatedStatus, userId); 732 scheduleWritePackageRestrictionsLocked(userId); 733 } 734 } 735 } 736 } 737 738 @Override 739 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 740 ActivityIntentInfo filter, String packageName) { 741 if (!hasValidDomains(filter)) { 742 return false; 743 } 744 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 745 if (ivs == null) { 746 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 747 packageName); 748 } 749 if (DEBUG_DOMAIN_VERIFICATION) { 750 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 751 } 752 ivs.addFilter(filter); 753 return true; 754 } 755 756 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 757 int userId, int verificationId, String packageName) { 758 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 759 verifierUid, userId, packageName); 760 ivs.setPendingState(); 761 synchronized (mPackages) { 762 mIntentFilterVerificationStates.append(verificationId, ivs); 763 mCurrentIntentFilterVerifications.add(verificationId); 764 } 765 return ivs; 766 } 767 } 768 769 private static boolean hasValidDomains(ActivityIntentInfo filter) { 770 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 771 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 772 if (!hasHTTPorHTTPS) { 773 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 774 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 775 return false; 776 } 777 return true; 778 } 779 780 private IntentFilterVerifier mIntentFilterVerifier; 781 782 // Set of pending broadcasts for aggregating enable/disable of components. 783 static class PendingPackageBroadcasts { 784 // for each user id, a map of <package name -> components within that package> 785 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 786 787 public PendingPackageBroadcasts() { 788 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 789 } 790 791 public ArrayList<String> get(int userId, String packageName) { 792 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 793 return packages.get(packageName); 794 } 795 796 public void put(int userId, String packageName, ArrayList<String> components) { 797 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 798 packages.put(packageName, components); 799 } 800 801 public void remove(int userId, String packageName) { 802 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 803 if (packages != null) { 804 packages.remove(packageName); 805 } 806 } 807 808 public void remove(int userId) { 809 mUidMap.remove(userId); 810 } 811 812 public int userIdCount() { 813 return mUidMap.size(); 814 } 815 816 public int userIdAt(int n) { 817 return mUidMap.keyAt(n); 818 } 819 820 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 821 return mUidMap.get(userId); 822 } 823 824 public int size() { 825 // total number of pending broadcast entries across all userIds 826 int num = 0; 827 for (int i = 0; i< mUidMap.size(); i++) { 828 num += mUidMap.valueAt(i).size(); 829 } 830 return num; 831 } 832 833 public void clear() { 834 mUidMap.clear(); 835 } 836 837 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 838 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 839 if (map == null) { 840 map = new ArrayMap<String, ArrayList<String>>(); 841 mUidMap.put(userId, map); 842 } 843 return map; 844 } 845 } 846 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 847 848 // Service Connection to remote media container service to copy 849 // package uri's from external media onto secure containers 850 // or internal storage. 851 private IMediaContainerService mContainerService = null; 852 853 static final int SEND_PENDING_BROADCAST = 1; 854 static final int MCS_BOUND = 3; 855 static final int END_COPY = 4; 856 static final int INIT_COPY = 5; 857 static final int MCS_UNBIND = 6; 858 static final int START_CLEANING_PACKAGE = 7; 859 static final int FIND_INSTALL_LOC = 8; 860 static final int POST_INSTALL = 9; 861 static final int MCS_RECONNECT = 10; 862 static final int MCS_GIVE_UP = 11; 863 static final int UPDATED_MEDIA_STATUS = 12; 864 static final int WRITE_SETTINGS = 13; 865 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 866 static final int PACKAGE_VERIFIED = 15; 867 static final int CHECK_PENDING_VERIFICATION = 16; 868 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 869 static final int INTENT_FILTER_VERIFIED = 18; 870 871 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 872 873 // Delay time in millisecs 874 static final int BROADCAST_DELAY = 10 * 1000; 875 876 static UserManagerService sUserManager; 877 878 // Stores a list of users whose package restrictions file needs to be updated 879 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 880 881 final private DefaultContainerConnection mDefContainerConn = 882 new DefaultContainerConnection(); 883 class DefaultContainerConnection implements ServiceConnection { 884 public void onServiceConnected(ComponentName name, IBinder service) { 885 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 886 IMediaContainerService imcs = 887 IMediaContainerService.Stub.asInterface(service); 888 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 889 } 890 891 public void onServiceDisconnected(ComponentName name) { 892 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 893 } 894 } 895 896 // Recordkeeping of restore-after-install operations that are currently in flight 897 // between the Package Manager and the Backup Manager 898 class PostInstallData { 899 public InstallArgs args; 900 public PackageInstalledInfo res; 901 902 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 903 args = _a; 904 res = _r; 905 } 906 } 907 908 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 909 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 910 911 // XML tags for backup/restore of various bits of state 912 private static final String TAG_PREFERRED_BACKUP = "pa"; 913 private static final String TAG_DEFAULT_APPS = "da"; 914 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 915 916 private final String mRequiredVerifierPackage; 917 918 private final PackageUsage mPackageUsage = new PackageUsage(); 919 920 private class PackageUsage { 921 private static final int WRITE_INTERVAL 922 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 923 924 private final Object mFileLock = new Object(); 925 private final AtomicLong mLastWritten = new AtomicLong(0); 926 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 927 928 private boolean mIsHistoricalPackageUsageAvailable = true; 929 930 boolean isHistoricalPackageUsageAvailable() { 931 return mIsHistoricalPackageUsageAvailable; 932 } 933 934 void write(boolean force) { 935 if (force) { 936 writeInternal(); 937 return; 938 } 939 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 940 && !DEBUG_DEXOPT) { 941 return; 942 } 943 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 944 new Thread("PackageUsage_DiskWriter") { 945 @Override 946 public void run() { 947 try { 948 writeInternal(); 949 } finally { 950 mBackgroundWriteRunning.set(false); 951 } 952 } 953 }.start(); 954 } 955 } 956 957 private void writeInternal() { 958 synchronized (mPackages) { 959 synchronized (mFileLock) { 960 AtomicFile file = getFile(); 961 FileOutputStream f = null; 962 try { 963 f = file.startWrite(); 964 BufferedOutputStream out = new BufferedOutputStream(f); 965 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 966 StringBuilder sb = new StringBuilder(); 967 for (PackageParser.Package pkg : mPackages.values()) { 968 if (pkg.mLastPackageUsageTimeInMills == 0) { 969 continue; 970 } 971 sb.setLength(0); 972 sb.append(pkg.packageName); 973 sb.append(' '); 974 sb.append((long)pkg.mLastPackageUsageTimeInMills); 975 sb.append('\n'); 976 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 977 } 978 out.flush(); 979 file.finishWrite(f); 980 } catch (IOException e) { 981 if (f != null) { 982 file.failWrite(f); 983 } 984 Log.e(TAG, "Failed to write package usage times", e); 985 } 986 } 987 } 988 mLastWritten.set(SystemClock.elapsedRealtime()); 989 } 990 991 void readLP() { 992 synchronized (mFileLock) { 993 AtomicFile file = getFile(); 994 BufferedInputStream in = null; 995 try { 996 in = new BufferedInputStream(file.openRead()); 997 StringBuffer sb = new StringBuffer(); 998 while (true) { 999 String packageName = readToken(in, sb, ' '); 1000 if (packageName == null) { 1001 break; 1002 } 1003 String timeInMillisString = readToken(in, sb, '\n'); 1004 if (timeInMillisString == null) { 1005 throw new IOException("Failed to find last usage time for package " 1006 + packageName); 1007 } 1008 PackageParser.Package pkg = mPackages.get(packageName); 1009 if (pkg == null) { 1010 continue; 1011 } 1012 long timeInMillis; 1013 try { 1014 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1015 } catch (NumberFormatException e) { 1016 throw new IOException("Failed to parse " + timeInMillisString 1017 + " as a long.", e); 1018 } 1019 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1020 } 1021 } catch (FileNotFoundException expected) { 1022 mIsHistoricalPackageUsageAvailable = false; 1023 } catch (IOException e) { 1024 Log.w(TAG, "Failed to read package usage times", e); 1025 } finally { 1026 IoUtils.closeQuietly(in); 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1033 throws IOException { 1034 sb.setLength(0); 1035 while (true) { 1036 int ch = in.read(); 1037 if (ch == -1) { 1038 if (sb.length() == 0) { 1039 return null; 1040 } 1041 throw new IOException("Unexpected EOF"); 1042 } 1043 if (ch == endOfToken) { 1044 return sb.toString(); 1045 } 1046 sb.append((char)ch); 1047 } 1048 } 1049 1050 private AtomicFile getFile() { 1051 File dataDir = Environment.getDataDirectory(); 1052 File systemDir = new File(dataDir, "system"); 1053 File fname = new File(systemDir, "package-usage.list"); 1054 return new AtomicFile(fname); 1055 } 1056 } 1057 1058 class PackageHandler extends Handler { 1059 private boolean mBound = false; 1060 final ArrayList<HandlerParams> mPendingInstalls = 1061 new ArrayList<HandlerParams>(); 1062 1063 private boolean connectToService() { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1065 " DefaultContainerService"); 1066 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1068 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1069 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1070 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1071 mBound = true; 1072 return true; 1073 } 1074 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1075 return false; 1076 } 1077 1078 private void disconnectService() { 1079 mContainerService = null; 1080 mBound = false; 1081 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1082 mContext.unbindService(mDefContainerConn); 1083 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1084 } 1085 1086 PackageHandler(Looper looper) { 1087 super(looper); 1088 } 1089 1090 public void handleMessage(Message msg) { 1091 try { 1092 doHandleMessage(msg); 1093 } finally { 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1095 } 1096 } 1097 1098 void doHandleMessage(Message msg) { 1099 switch (msg.what) { 1100 case INIT_COPY: { 1101 HandlerParams params = (HandlerParams) msg.obj; 1102 int idx = mPendingInstalls.size(); 1103 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1104 // If a bind was already initiated we dont really 1105 // need to do anything. The pending install 1106 // will be processed later on. 1107 if (!mBound) { 1108 // If this is the only one pending we might 1109 // have to bind to the service again. 1110 if (!connectToService()) { 1111 Slog.e(TAG, "Failed to bind to media container service"); 1112 params.serviceError(); 1113 return; 1114 } else { 1115 // Once we bind to the service, the first 1116 // pending request will be processed. 1117 mPendingInstalls.add(idx, params); 1118 } 1119 } else { 1120 mPendingInstalls.add(idx, params); 1121 // Already bound to the service. Just make 1122 // sure we trigger off processing the first request. 1123 if (idx == 0) { 1124 mHandler.sendEmptyMessage(MCS_BOUND); 1125 } 1126 } 1127 break; 1128 } 1129 case MCS_BOUND: { 1130 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1131 if (msg.obj != null) { 1132 mContainerService = (IMediaContainerService) msg.obj; 1133 } 1134 if (mContainerService == null) { 1135 if (!mBound) { 1136 // Something seriously wrong since we are not bound and we are not 1137 // waiting for connection. Bail out. 1138 Slog.e(TAG, "Cannot bind to media container service"); 1139 for (HandlerParams params : mPendingInstalls) { 1140 // Indicate service bind error 1141 params.serviceError(); 1142 } 1143 mPendingInstalls.clear(); 1144 } else { 1145 Slog.w(TAG, "Waiting to connect to media container service"); 1146 } 1147 } else if (mPendingInstalls.size() > 0) { 1148 HandlerParams params = mPendingInstalls.get(0); 1149 if (params != null) { 1150 if (params.startCopy()) { 1151 // We are done... look for more work or to 1152 // go idle. 1153 if (DEBUG_SD_INSTALL) Log.i(TAG, 1154 "Checking for more work or unbind..."); 1155 // Delete pending install 1156 if (mPendingInstalls.size() > 0) { 1157 mPendingInstalls.remove(0); 1158 } 1159 if (mPendingInstalls.size() == 0) { 1160 if (mBound) { 1161 if (DEBUG_SD_INSTALL) Log.i(TAG, 1162 "Posting delayed MCS_UNBIND"); 1163 removeMessages(MCS_UNBIND); 1164 Message ubmsg = obtainMessage(MCS_UNBIND); 1165 // Unbind after a little delay, to avoid 1166 // continual thrashing. 1167 sendMessageDelayed(ubmsg, 10000); 1168 } 1169 } else { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 if (DEBUG_SD_INSTALL) Log.i(TAG, 1174 "Posting MCS_BOUND for next work"); 1175 mHandler.sendEmptyMessage(MCS_BOUND); 1176 } 1177 } 1178 } 1179 } else { 1180 // Should never happen ideally. 1181 Slog.w(TAG, "Empty queue"); 1182 } 1183 break; 1184 } 1185 case MCS_RECONNECT: { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1187 if (mPendingInstalls.size() > 0) { 1188 if (mBound) { 1189 disconnectService(); 1190 } 1191 if (!connectToService()) { 1192 Slog.e(TAG, "Failed to bind to media container service"); 1193 for (HandlerParams params : mPendingInstalls) { 1194 // Indicate service bind error 1195 params.serviceError(); 1196 } 1197 mPendingInstalls.clear(); 1198 } 1199 } 1200 break; 1201 } 1202 case MCS_UNBIND: { 1203 // If there is no actual work left, then time to unbind. 1204 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1205 1206 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1207 if (mBound) { 1208 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1209 1210 disconnectService(); 1211 } 1212 } else if (mPendingInstalls.size() > 0) { 1213 // There are more pending requests in queue. 1214 // Just post MCS_BOUND message to trigger processing 1215 // of next pending install. 1216 mHandler.sendEmptyMessage(MCS_BOUND); 1217 } 1218 1219 break; 1220 } 1221 case MCS_GIVE_UP: { 1222 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1223 mPendingInstalls.remove(0); 1224 break; 1225 } 1226 case SEND_PENDING_BROADCAST: { 1227 String packages[]; 1228 ArrayList<String> components[]; 1229 int size = 0; 1230 int uids[]; 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1232 synchronized (mPackages) { 1233 if (mPendingBroadcasts == null) { 1234 return; 1235 } 1236 size = mPendingBroadcasts.size(); 1237 if (size <= 0) { 1238 // Nothing to be done. Just return 1239 return; 1240 } 1241 packages = new String[size]; 1242 components = new ArrayList[size]; 1243 uids = new int[size]; 1244 int i = 0; // filling out the above arrays 1245 1246 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1247 int packageUserId = mPendingBroadcasts.userIdAt(n); 1248 Iterator<Map.Entry<String, ArrayList<String>>> it 1249 = mPendingBroadcasts.packagesForUserId(packageUserId) 1250 .entrySet().iterator(); 1251 while (it.hasNext() && i < size) { 1252 Map.Entry<String, ArrayList<String>> ent = it.next(); 1253 packages[i] = ent.getKey(); 1254 components[i] = ent.getValue(); 1255 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1256 uids[i] = (ps != null) 1257 ? UserHandle.getUid(packageUserId, ps.appId) 1258 : -1; 1259 i++; 1260 } 1261 } 1262 size = i; 1263 mPendingBroadcasts.clear(); 1264 } 1265 // Send broadcasts 1266 for (int i = 0; i < size; i++) { 1267 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1268 } 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 break; 1271 } 1272 case START_CLEANING_PACKAGE: { 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1274 final String packageName = (String)msg.obj; 1275 final int userId = msg.arg1; 1276 final boolean andCode = msg.arg2 != 0; 1277 synchronized (mPackages) { 1278 if (userId == UserHandle.USER_ALL) { 1279 int[] users = sUserManager.getUserIds(); 1280 for (int user : users) { 1281 mSettings.addPackageToCleanLPw( 1282 new PackageCleanItem(user, packageName, andCode)); 1283 } 1284 } else { 1285 mSettings.addPackageToCleanLPw( 1286 new PackageCleanItem(userId, packageName, andCode)); 1287 } 1288 } 1289 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1290 startCleaningPackages(); 1291 } break; 1292 case POST_INSTALL: { 1293 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1294 PostInstallData data = mRunningInstalls.get(msg.arg1); 1295 mRunningInstalls.delete(msg.arg1); 1296 boolean deleteOld = false; 1297 1298 if (data != null) { 1299 InstallArgs args = data.args; 1300 PackageInstalledInfo res = data.res; 1301 1302 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1303 res.removedInfo.sendBroadcast(false, true, false); 1304 Bundle extras = new Bundle(1); 1305 extras.putInt(Intent.EXTRA_UID, res.uid); 1306 1307 // Now that we successfully installed the package, grant runtime 1308 // permissions if requested before broadcasting the install. 1309 if ((args.installFlags 1310 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1311 grantRequestedRuntimePermissions(res.pkg, 1312 args.user.getIdentifier()); 1313 } 1314 1315 // Determine the set of users who are adding this 1316 // package for the first time vs. those who are seeing 1317 // an update. 1318 int[] firstUsers; 1319 int[] updateUsers = new int[0]; 1320 if (res.origUsers == null || res.origUsers.length == 0) { 1321 firstUsers = res.newUsers; 1322 } else { 1323 firstUsers = new int[0]; 1324 for (int i=0; i<res.newUsers.length; i++) { 1325 int user = res.newUsers[i]; 1326 boolean isNew = true; 1327 for (int j=0; j<res.origUsers.length; j++) { 1328 if (res.origUsers[j] == user) { 1329 isNew = false; 1330 break; 1331 } 1332 } 1333 if (isNew) { 1334 int[] newFirst = new int[firstUsers.length+1]; 1335 System.arraycopy(firstUsers, 0, newFirst, 0, 1336 firstUsers.length); 1337 newFirst[firstUsers.length] = user; 1338 firstUsers = newFirst; 1339 } else { 1340 int[] newUpdate = new int[updateUsers.length+1]; 1341 System.arraycopy(updateUsers, 0, newUpdate, 0, 1342 updateUsers.length); 1343 newUpdate[updateUsers.length] = user; 1344 updateUsers = newUpdate; 1345 } 1346 } 1347 } 1348 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1349 res.pkg.applicationInfo.packageName, 1350 extras, null, null, firstUsers); 1351 final boolean update = res.removedInfo.removedPackage != null; 1352 if (update) { 1353 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1354 } 1355 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1356 res.pkg.applicationInfo.packageName, 1357 extras, null, null, updateUsers); 1358 if (update) { 1359 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1360 res.pkg.applicationInfo.packageName, 1361 extras, null, null, updateUsers); 1362 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1363 null, null, 1364 res.pkg.applicationInfo.packageName, null, updateUsers); 1365 1366 // treat asec-hosted packages like removable media on upgrade 1367 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1368 if (DEBUG_INSTALL) { 1369 Slog.i(TAG, "upgrading pkg " + res.pkg 1370 + " is ASEC-hosted -> AVAILABLE"); 1371 } 1372 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1373 ArrayList<String> pkgList = new ArrayList<String>(1); 1374 pkgList.add(res.pkg.applicationInfo.packageName); 1375 sendResourcesChangedBroadcast(true, true, 1376 pkgList,uidArray, null); 1377 } 1378 } 1379 if (res.removedInfo.args != null) { 1380 // Remove the replaced package's older resources safely now 1381 deleteOld = true; 1382 } 1383 1384 // Log current value of "unknown sources" setting 1385 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1386 getUnknownSourcesSettings()); 1387 } 1388 // Force a gc to clear up things 1389 Runtime.getRuntime().gc(); 1390 // We delete after a gc for applications on sdcard. 1391 if (deleteOld) { 1392 synchronized (mInstallLock) { 1393 res.removedInfo.args.doPostDeleteLI(true); 1394 } 1395 } 1396 if (args.observer != null) { 1397 try { 1398 Bundle extras = extrasForInstallResult(res); 1399 args.observer.onPackageInstalled(res.name, res.returnCode, 1400 res.returnMsg, extras); 1401 } catch (RemoteException e) { 1402 Slog.i(TAG, "Observer no longer exists."); 1403 } 1404 } 1405 } else { 1406 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1407 } 1408 } break; 1409 case UPDATED_MEDIA_STATUS: { 1410 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1411 boolean reportStatus = msg.arg1 == 1; 1412 boolean doGc = msg.arg2 == 1; 1413 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1414 if (doGc) { 1415 // Force a gc to clear up stale containers. 1416 Runtime.getRuntime().gc(); 1417 } 1418 if (msg.obj != null) { 1419 @SuppressWarnings("unchecked") 1420 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1421 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1422 // Unload containers 1423 unloadAllContainers(args); 1424 } 1425 if (reportStatus) { 1426 try { 1427 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1428 PackageHelper.getMountService().finishMediaUpdate(); 1429 } catch (RemoteException e) { 1430 Log.e(TAG, "MountService not running?"); 1431 } 1432 } 1433 } break; 1434 case WRITE_SETTINGS: { 1435 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1436 synchronized (mPackages) { 1437 removeMessages(WRITE_SETTINGS); 1438 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1439 mSettings.writeLPr(); 1440 mDirtyUsers.clear(); 1441 } 1442 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1443 } break; 1444 case WRITE_PACKAGE_RESTRICTIONS: { 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1448 for (int userId : mDirtyUsers) { 1449 mSettings.writePackageRestrictionsLPr(userId); 1450 } 1451 mDirtyUsers.clear(); 1452 } 1453 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1454 } break; 1455 case CHECK_PENDING_VERIFICATION: { 1456 final int verificationId = msg.arg1; 1457 final PackageVerificationState state = mPendingVerification.get(verificationId); 1458 1459 if ((state != null) && !state.timeoutExtended()) { 1460 final InstallArgs args = state.getInstallArgs(); 1461 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1462 1463 Slog.i(TAG, "Verification timed out for " + originUri); 1464 mPendingVerification.remove(verificationId); 1465 1466 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1467 1468 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1469 Slog.i(TAG, "Continuing with installation of " + originUri); 1470 state.setVerifierResponse(Binder.getCallingUid(), 1471 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1472 broadcastPackageVerified(verificationId, originUri, 1473 PackageManager.VERIFICATION_ALLOW, 1474 state.getInstallArgs().getUser()); 1475 try { 1476 ret = args.copyApk(mContainerService, true); 1477 } catch (RemoteException e) { 1478 Slog.e(TAG, "Could not contact the ContainerService"); 1479 } 1480 } else { 1481 broadcastPackageVerified(verificationId, originUri, 1482 PackageManager.VERIFICATION_REJECT, 1483 state.getInstallArgs().getUser()); 1484 } 1485 1486 processPendingInstall(args, ret); 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 break; 1490 } 1491 case PACKAGE_VERIFIED: { 1492 final int verificationId = msg.arg1; 1493 1494 final PackageVerificationState state = mPendingVerification.get(verificationId); 1495 if (state == null) { 1496 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1497 break; 1498 } 1499 1500 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1501 1502 state.setVerifierResponse(response.callerUid, response.code); 1503 1504 if (state.isVerificationComplete()) { 1505 mPendingVerification.remove(verificationId); 1506 1507 final InstallArgs args = state.getInstallArgs(); 1508 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1509 1510 int ret; 1511 if (state.isInstallAllowed()) { 1512 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1513 broadcastPackageVerified(verificationId, originUri, 1514 response.code, state.getInstallArgs().getUser()); 1515 try { 1516 ret = args.copyApk(mContainerService, true); 1517 } catch (RemoteException e) { 1518 Slog.e(TAG, "Could not contact the ContainerService"); 1519 } 1520 } else { 1521 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1522 } 1523 1524 processPendingInstall(args, ret); 1525 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 1529 break; 1530 } 1531 case START_INTENT_FILTER_VERIFICATIONS: { 1532 IFVerificationParams params = (IFVerificationParams) msg.obj; 1533 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1534 params.replacing, params.pkg); 1535 break; 1536 } 1537 case INTENT_FILTER_VERIFIED: { 1538 final int verificationId = msg.arg1; 1539 1540 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1541 verificationId); 1542 if (state == null) { 1543 Slog.w(TAG, "Invalid IntentFilter verification token " 1544 + verificationId + " received"); 1545 break; 1546 } 1547 1548 final int userId = state.getUserId(); 1549 1550 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1551 "Processing IntentFilter verification with token:" 1552 + verificationId + " and userId:" + userId); 1553 1554 final IntentFilterVerificationResponse response = 1555 (IntentFilterVerificationResponse) msg.obj; 1556 1557 state.setVerifierResponse(response.callerUid, response.code); 1558 1559 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1560 "IntentFilter verification with token:" + verificationId 1561 + " and userId:" + userId 1562 + " is settings verifier response with response code:" 1563 + response.code); 1564 1565 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1566 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1567 + response.getFailedDomainsString()); 1568 } 1569 1570 if (state.isVerificationComplete()) { 1571 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1572 } else { 1573 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1574 "IntentFilter verification with token:" + verificationId 1575 + " was not said to be complete"); 1576 } 1577 1578 break; 1579 } 1580 } 1581 } 1582 } 1583 1584 private StorageEventListener mStorageListener = new StorageEventListener() { 1585 @Override 1586 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1587 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1588 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1589 // TODO: ensure that private directories exist for all active users 1590 // TODO: remove user data whose serial number doesn't match 1591 loadPrivatePackages(vol); 1592 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1593 unloadPrivatePackages(vol); 1594 } 1595 } 1596 1597 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1598 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1599 updateExternalMediaStatus(true, false); 1600 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1601 updateExternalMediaStatus(false, false); 1602 } 1603 } 1604 } 1605 1606 @Override 1607 public void onVolumeForgotten(String fsUuid) { 1608 // TODO: remove all packages hosted on this uuid 1609 } 1610 }; 1611 1612 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1613 if (userId >= UserHandle.USER_OWNER) { 1614 grantRequestedRuntimePermissionsForUser(pkg, userId); 1615 } else if (userId == UserHandle.USER_ALL) { 1616 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1617 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1618 } 1619 } 1620 1621 // We could have touched GID membership, so flush out packages.list 1622 synchronized (mPackages) { 1623 mSettings.writePackageListLPr(); 1624 } 1625 } 1626 1627 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1628 SettingBase sb = (SettingBase) pkg.mExtras; 1629 if (sb == null) { 1630 return; 1631 } 1632 1633 PermissionsState permissionsState = sb.getPermissionsState(); 1634 1635 for (String permission : pkg.requestedPermissions) { 1636 BasePermission bp = mSettings.mPermissions.get(permission); 1637 if (bp != null && bp.isRuntime()) { 1638 permissionsState.grantRuntimePermission(bp, userId); 1639 } 1640 } 1641 } 1642 1643 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1644 Bundle extras = null; 1645 switch (res.returnCode) { 1646 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1647 extras = new Bundle(); 1648 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1649 res.origPermission); 1650 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1651 res.origPackage); 1652 break; 1653 } 1654 case PackageManager.INSTALL_SUCCEEDED: { 1655 extras = new Bundle(); 1656 extras.putBoolean(Intent.EXTRA_REPLACING, 1657 res.removedInfo != null && res.removedInfo.removedPackage != null); 1658 break; 1659 } 1660 } 1661 return extras; 1662 } 1663 1664 void scheduleWriteSettingsLocked() { 1665 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1666 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1667 } 1668 } 1669 1670 void scheduleWritePackageRestrictionsLocked(int userId) { 1671 if (!sUserManager.exists(userId)) return; 1672 mDirtyUsers.add(userId); 1673 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1674 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1675 } 1676 } 1677 1678 public static PackageManagerService main(Context context, Installer installer, 1679 boolean factoryTest, boolean onlyCore) { 1680 PackageManagerService m = new PackageManagerService(context, installer, 1681 factoryTest, onlyCore); 1682 ServiceManager.addService("package", m); 1683 return m; 1684 } 1685 1686 static String[] splitString(String str, char sep) { 1687 int count = 1; 1688 int i = 0; 1689 while ((i=str.indexOf(sep, i)) >= 0) { 1690 count++; 1691 i++; 1692 } 1693 1694 String[] res = new String[count]; 1695 i=0; 1696 count = 0; 1697 int lastI=0; 1698 while ((i=str.indexOf(sep, i)) >= 0) { 1699 res[count] = str.substring(lastI, i); 1700 count++; 1701 i++; 1702 lastI = i; 1703 } 1704 res[count] = str.substring(lastI, str.length()); 1705 return res; 1706 } 1707 1708 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1709 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1710 Context.DISPLAY_SERVICE); 1711 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1712 } 1713 1714 public PackageManagerService(Context context, Installer installer, 1715 boolean factoryTest, boolean onlyCore) { 1716 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1717 SystemClock.uptimeMillis()); 1718 1719 if (mSdkVersion <= 0) { 1720 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1721 } 1722 1723 mContext = context; 1724 mFactoryTest = factoryTest; 1725 mOnlyCore = onlyCore; 1726 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1727 mMetrics = new DisplayMetrics(); 1728 mSettings = new Settings(mPackages); 1729 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1730 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1731 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1732 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1733 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1734 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1735 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1736 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1737 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1738 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1739 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1740 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1741 1742 // TODO: add a property to control this? 1743 long dexOptLRUThresholdInMinutes; 1744 if (mLazyDexOpt) { 1745 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1746 } else { 1747 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1748 } 1749 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1750 1751 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1752 if (separateProcesses != null && separateProcesses.length() > 0) { 1753 if ("*".equals(separateProcesses)) { 1754 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1755 mSeparateProcesses = null; 1756 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1757 } else { 1758 mDefParseFlags = 0; 1759 mSeparateProcesses = separateProcesses.split(","); 1760 Slog.w(TAG, "Running with debug.separate_processes: " 1761 + separateProcesses); 1762 } 1763 } else { 1764 mDefParseFlags = 0; 1765 mSeparateProcesses = null; 1766 } 1767 1768 mInstaller = installer; 1769 mPackageDexOptimizer = new PackageDexOptimizer(this); 1770 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1771 1772 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1773 FgThread.get().getLooper()); 1774 1775 getDefaultDisplayMetrics(context, mMetrics); 1776 1777 SystemConfig systemConfig = SystemConfig.getInstance(); 1778 mGlobalGids = systemConfig.getGlobalGids(); 1779 mSystemPermissions = systemConfig.getSystemPermissions(); 1780 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1781 1782 synchronized (mInstallLock) { 1783 // writer 1784 synchronized (mPackages) { 1785 mHandlerThread = new ServiceThread(TAG, 1786 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1787 mHandlerThread.start(); 1788 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1789 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1790 1791 File dataDir = Environment.getDataDirectory(); 1792 mAppDataDir = new File(dataDir, "data"); 1793 mAppInstallDir = new File(dataDir, "app"); 1794 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1795 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1796 mUserAppDataDir = new File(dataDir, "user"); 1797 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1798 1799 sUserManager = new UserManagerService(context, this, 1800 mInstallLock, mPackages); 1801 1802 // Propagate permission configuration in to package manager. 1803 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1804 = systemConfig.getPermissions(); 1805 for (int i=0; i<permConfig.size(); i++) { 1806 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1807 BasePermission bp = mSettings.mPermissions.get(perm.name); 1808 if (bp == null) { 1809 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1810 mSettings.mPermissions.put(perm.name, bp); 1811 } 1812 if (perm.gids != null) { 1813 bp.setGids(perm.gids, perm.perUser); 1814 } 1815 } 1816 1817 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1818 for (int i=0; i<libConfig.size(); i++) { 1819 mSharedLibraries.put(libConfig.keyAt(i), 1820 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1821 } 1822 1823 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1824 1825 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1826 mSdkVersion, mOnlyCore); 1827 1828 String customResolverActivity = Resources.getSystem().getString( 1829 R.string.config_customResolverActivity); 1830 if (TextUtils.isEmpty(customResolverActivity)) { 1831 customResolverActivity = null; 1832 } else { 1833 mCustomResolverComponentName = ComponentName.unflattenFromString( 1834 customResolverActivity); 1835 } 1836 1837 long startTime = SystemClock.uptimeMillis(); 1838 1839 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1840 startTime); 1841 1842 // Set flag to monitor and not change apk file paths when 1843 // scanning install directories. 1844 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1845 1846 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1847 1848 /** 1849 * Add everything in the in the boot class path to the 1850 * list of process files because dexopt will have been run 1851 * if necessary during zygote startup. 1852 */ 1853 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1854 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1855 1856 if (bootClassPath != null) { 1857 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1858 for (String element : bootClassPathElements) { 1859 alreadyDexOpted.add(element); 1860 } 1861 } else { 1862 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1863 } 1864 1865 if (systemServerClassPath != null) { 1866 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1867 for (String element : systemServerClassPathElements) { 1868 alreadyDexOpted.add(element); 1869 } 1870 } else { 1871 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1872 } 1873 1874 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1875 final String[] dexCodeInstructionSets = 1876 getDexCodeInstructionSets( 1877 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1878 1879 /** 1880 * Ensure all external libraries have had dexopt run on them. 1881 */ 1882 if (mSharedLibraries.size() > 0) { 1883 // NOTE: For now, we're compiling these system "shared libraries" 1884 // (and framework jars) into all available architectures. It's possible 1885 // to compile them only when we come across an app that uses them (there's 1886 // already logic for that in scanPackageLI) but that adds some complexity. 1887 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1888 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1889 final String lib = libEntry.path; 1890 if (lib == null) { 1891 continue; 1892 } 1893 1894 try { 1895 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1896 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1897 alreadyDexOpted.add(lib); 1898 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1899 } 1900 } catch (FileNotFoundException e) { 1901 Slog.w(TAG, "Library not found: " + lib); 1902 } catch (IOException e) { 1903 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1904 + e.getMessage()); 1905 } 1906 } 1907 } 1908 } 1909 1910 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1911 1912 // Gross hack for now: we know this file doesn't contain any 1913 // code, so don't dexopt it to avoid the resulting log spew. 1914 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1915 1916 // Gross hack for now: we know this file is only part of 1917 // the boot class path for art, so don't dexopt it to 1918 // avoid the resulting log spew. 1919 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1920 1921 /** 1922 * There are a number of commands implemented in Java, which 1923 * we currently need to do the dexopt on so that they can be 1924 * run from a non-root shell. 1925 */ 1926 String[] frameworkFiles = frameworkDir.list(); 1927 if (frameworkFiles != null) { 1928 // TODO: We could compile these only for the most preferred ABI. We should 1929 // first double check that the dex files for these commands are not referenced 1930 // by other system apps. 1931 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1932 for (int i=0; i<frameworkFiles.length; i++) { 1933 File libPath = new File(frameworkDir, frameworkFiles[i]); 1934 String path = libPath.getPath(); 1935 // Skip the file if we already did it. 1936 if (alreadyDexOpted.contains(path)) { 1937 continue; 1938 } 1939 // Skip the file if it is not a type we want to dexopt. 1940 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1941 continue; 1942 } 1943 try { 1944 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1945 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1946 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1947 } 1948 } catch (FileNotFoundException e) { 1949 Slog.w(TAG, "Jar not found: " + path); 1950 } catch (IOException e) { 1951 Slog.w(TAG, "Exception reading jar: " + path, e); 1952 } 1953 } 1954 } 1955 } 1956 1957 // Collect vendor overlay packages. 1958 // (Do this before scanning any apps.) 1959 // For security and version matching reason, only consider 1960 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1961 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1962 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1963 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1964 1965 // Find base frameworks (resource packages without code). 1966 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1967 | PackageParser.PARSE_IS_SYSTEM_DIR 1968 | PackageParser.PARSE_IS_PRIVILEGED, 1969 scanFlags | SCAN_NO_DEX, 0); 1970 1971 // Collected privileged system packages. 1972 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1973 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1974 | PackageParser.PARSE_IS_SYSTEM_DIR 1975 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1976 1977 // Collect ordinary system packages. 1978 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1979 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1980 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1981 1982 // Collect all vendor packages. 1983 File vendorAppDir = new File("/vendor/app"); 1984 try { 1985 vendorAppDir = vendorAppDir.getCanonicalFile(); 1986 } catch (IOException e) { 1987 // failed to look up canonical path, continue with original one 1988 } 1989 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1990 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1991 1992 // Collect all OEM packages. 1993 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1994 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1995 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1996 1997 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1998 mInstaller.moveFiles(); 1999 2000 // Prune any system packages that no longer exist. 2001 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2002 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2003 if (!mOnlyCore) { 2004 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2005 while (psit.hasNext()) { 2006 PackageSetting ps = psit.next(); 2007 2008 /* 2009 * If this is not a system app, it can't be a 2010 * disable system app. 2011 */ 2012 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2013 continue; 2014 } 2015 2016 /* 2017 * If the package is scanned, it's not erased. 2018 */ 2019 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2020 if (scannedPkg != null) { 2021 /* 2022 * If the system app is both scanned and in the 2023 * disabled packages list, then it must have been 2024 * added via OTA. Remove it from the currently 2025 * scanned package so the previously user-installed 2026 * application can be scanned. 2027 */ 2028 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2029 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2030 + ps.name + "; removing system app. Last known codePath=" 2031 + ps.codePathString + ", installStatus=" + ps.installStatus 2032 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2033 + scannedPkg.mVersionCode); 2034 removePackageLI(ps, true); 2035 expectingBetter.put(ps.name, ps.codePath); 2036 } 2037 2038 continue; 2039 } 2040 2041 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2042 psit.remove(); 2043 logCriticalInfo(Log.WARN, "System package " + ps.name 2044 + " no longer exists; wiping its data"); 2045 removeDataDirsLI(null, ps.name); 2046 } else { 2047 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2048 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2049 possiblyDeletedUpdatedSystemApps.add(ps.name); 2050 } 2051 } 2052 } 2053 } 2054 2055 //look for any incomplete package installations 2056 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2057 //clean up list 2058 for(int i = 0; i < deletePkgsList.size(); i++) { 2059 //clean up here 2060 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2061 } 2062 //delete tmp files 2063 deleteTempPackageFiles(); 2064 2065 // Remove any shared userIDs that have no associated packages 2066 mSettings.pruneSharedUsersLPw(); 2067 2068 if (!mOnlyCore) { 2069 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2070 SystemClock.uptimeMillis()); 2071 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2072 2073 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2074 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2075 2076 /** 2077 * Remove disable package settings for any updated system 2078 * apps that were removed via an OTA. If they're not a 2079 * previously-updated app, remove them completely. 2080 * Otherwise, just revoke their system-level permissions. 2081 */ 2082 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2083 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2084 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2085 2086 String msg; 2087 if (deletedPkg == null) { 2088 msg = "Updated system package " + deletedAppName 2089 + " no longer exists; wiping its data"; 2090 removeDataDirsLI(null, deletedAppName); 2091 } else { 2092 msg = "Updated system app + " + deletedAppName 2093 + " no longer present; removing system privileges for " 2094 + deletedAppName; 2095 2096 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2097 2098 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2099 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2100 } 2101 logCriticalInfo(Log.WARN, msg); 2102 } 2103 2104 /** 2105 * Make sure all system apps that we expected to appear on 2106 * the userdata partition actually showed up. If they never 2107 * appeared, crawl back and revive the system version. 2108 */ 2109 for (int i = 0; i < expectingBetter.size(); i++) { 2110 final String packageName = expectingBetter.keyAt(i); 2111 if (!mPackages.containsKey(packageName)) { 2112 final File scanFile = expectingBetter.valueAt(i); 2113 2114 logCriticalInfo(Log.WARN, "Expected better " + packageName 2115 + " but never showed up; reverting to system"); 2116 2117 final int reparseFlags; 2118 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2119 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2120 | PackageParser.PARSE_IS_SYSTEM_DIR 2121 | PackageParser.PARSE_IS_PRIVILEGED; 2122 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2123 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2124 | PackageParser.PARSE_IS_SYSTEM_DIR; 2125 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2126 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR; 2128 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2129 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2130 | PackageParser.PARSE_IS_SYSTEM_DIR; 2131 } else { 2132 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2133 continue; 2134 } 2135 2136 mSettings.enableSystemPackageLPw(packageName); 2137 2138 try { 2139 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2140 } catch (PackageManagerException e) { 2141 Slog.e(TAG, "Failed to parse original system package: " 2142 + e.getMessage()); 2143 } 2144 } 2145 } 2146 } 2147 2148 // Now that we know all of the shared libraries, update all clients to have 2149 // the correct library paths. 2150 updateAllSharedLibrariesLPw(); 2151 2152 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2153 // NOTE: We ignore potential failures here during a system scan (like 2154 // the rest of the commands above) because there's precious little we 2155 // can do about it. A settings error is reported, though. 2156 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2157 false /* force dexopt */, false /* defer dexopt */); 2158 } 2159 2160 // Now that we know all the packages we are keeping, 2161 // read and update their last usage times. 2162 mPackageUsage.readLP(); 2163 2164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2165 SystemClock.uptimeMillis()); 2166 Slog.i(TAG, "Time to scan packages: " 2167 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2168 + " seconds"); 2169 2170 // If the platform SDK has changed since the last time we booted, 2171 // we need to re-grant app permission to catch any new ones that 2172 // appear. This is really a hack, and means that apps can in some 2173 // cases get permissions that the user didn't initially explicitly 2174 // allow... it would be nice to have some better way to handle 2175 // this situation. 2176 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2177 != mSdkVersion; 2178 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2179 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2180 + "; regranting permissions for internal storage"); 2181 mSettings.mInternalSdkPlatform = mSdkVersion; 2182 2183 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2184 | (regrantPermissions 2185 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2186 : 0)); 2187 2188 // If this is the first boot, and it is a normal boot, then 2189 // we need to initialize the default preferred apps. 2190 if (!mRestoredSettings && !onlyCore) { 2191 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2192 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2193 } 2194 2195 // If this is first boot after an OTA, and a normal boot, then 2196 // we need to clear code cache directories. 2197 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2198 if (mIsUpgrade && !onlyCore) { 2199 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2200 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2201 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2202 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2203 } 2204 mSettings.mFingerprint = Build.FINGERPRINT; 2205 } 2206 2207 primeDomainVerificationsLPw(); 2208 checkDefaultBrowser(); 2209 2210 // All the changes are done during package scanning. 2211 mSettings.updateInternalDatabaseVersion(); 2212 2213 // can downgrade to reader 2214 mSettings.writeLPr(); 2215 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2217 SystemClock.uptimeMillis()); 2218 2219 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2220 2221 mInstallerService = new PackageInstallerService(context, this); 2222 2223 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2224 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2225 mIntentFilterVerifierComponent); 2226 2227 } // synchronized (mPackages) 2228 } // synchronized (mInstallLock) 2229 2230 // Now after opening every single application zip, make sure they 2231 // are all flushed. Not really needed, but keeps things nice and 2232 // tidy. 2233 Runtime.getRuntime().gc(); 2234 2235 // Expose private service for system components to use. 2236 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2237 } 2238 2239 @Override 2240 public boolean isFirstBoot() { 2241 return !mRestoredSettings; 2242 } 2243 2244 @Override 2245 public boolean isOnlyCoreApps() { 2246 return mOnlyCore; 2247 } 2248 2249 @Override 2250 public boolean isUpgrade() { 2251 return mIsUpgrade; 2252 } 2253 2254 private String getRequiredVerifierLPr() { 2255 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2256 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2257 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2258 2259 String requiredVerifier = null; 2260 2261 final int N = receivers.size(); 2262 for (int i = 0; i < N; i++) { 2263 final ResolveInfo info = receivers.get(i); 2264 2265 if (info.activityInfo == null) { 2266 continue; 2267 } 2268 2269 final String packageName = info.activityInfo.packageName; 2270 2271 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2272 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2273 continue; 2274 } 2275 2276 if (requiredVerifier != null) { 2277 throw new RuntimeException("There can be only one required verifier"); 2278 } 2279 2280 requiredVerifier = packageName; 2281 } 2282 2283 return requiredVerifier; 2284 } 2285 2286 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2287 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2288 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2289 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2290 2291 ComponentName verifierComponentName = null; 2292 2293 int priority = -1000; 2294 final int N = receivers.size(); 2295 for (int i = 0; i < N; i++) { 2296 final ResolveInfo info = receivers.get(i); 2297 2298 if (info.activityInfo == null) { 2299 continue; 2300 } 2301 2302 final String packageName = info.activityInfo.packageName; 2303 2304 final PackageSetting ps = mSettings.mPackages.get(packageName); 2305 if (ps == null) { 2306 continue; 2307 } 2308 2309 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2310 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2311 continue; 2312 } 2313 2314 // Select the IntentFilterVerifier with the highest priority 2315 if (priority < info.priority) { 2316 priority = info.priority; 2317 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2318 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2319 + verifierComponentName + " with priority: " + info.priority); 2320 } 2321 } 2322 2323 return verifierComponentName; 2324 } 2325 2326 private void primeDomainVerificationsLPw() { 2327 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2328 boolean updated = false; 2329 ArraySet<String> allHostsSet = new ArraySet<>(); 2330 for (PackageParser.Package pkg : mPackages.values()) { 2331 final String packageName = pkg.packageName; 2332 if (!hasDomainURLs(pkg)) { 2333 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2334 "package with no domain URLs: " + packageName); 2335 continue; 2336 } 2337 if (!pkg.isSystemApp()) { 2338 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2339 "No priming domain verifications for a non system package : " + 2340 packageName); 2341 continue; 2342 } 2343 for (PackageParser.Activity a : pkg.activities) { 2344 for (ActivityIntentInfo filter : a.intents) { 2345 if (hasValidDomains(filter)) { 2346 allHostsSet.addAll(filter.getHostsList()); 2347 } 2348 } 2349 } 2350 if (allHostsSet.size() == 0) { 2351 allHostsSet.add("*"); 2352 } 2353 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2354 IntentFilterVerificationInfo ivi = 2355 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2356 if (ivi != null) { 2357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2358 "Priming domain verifications for package: " + packageName + 2359 " with hosts:" + ivi.getDomainsString()); 2360 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2361 updated = true; 2362 } 2363 else { 2364 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2365 "No priming domain verifications for package: " + packageName); 2366 } 2367 allHostsSet.clear(); 2368 } 2369 if (updated) { 2370 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2371 "Will need to write primed domain verifications"); 2372 } 2373 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2374 } 2375 2376 private void applyFactoryDefaultBrowserLPw(int userId) { 2377 // The default browser app's package name is stored in a string resource, 2378 // with a product-specific overlay used for vendor customization. 2379 String browserPkg = mContext.getResources().getString( 2380 com.android.internal.R.string.default_browser); 2381 if (browserPkg != null) { 2382 // non-empty string => required to be a known package 2383 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2384 if (ps == null) { 2385 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2386 browserPkg = null; 2387 } else { 2388 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2389 } 2390 } 2391 2392 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2393 // default. If there's more than one, just leave everything alone. 2394 if (browserPkg == null) { 2395 calculateDefaultBrowserLPw(userId); 2396 } 2397 } 2398 2399 private void calculateDefaultBrowserLPw(int userId) { 2400 List<String> allBrowsers = resolveAllBrowserApps(userId); 2401 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2402 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2403 } 2404 2405 private List<String> resolveAllBrowserApps(int userId) { 2406 // Match all generic http: browser apps 2407 Intent intent = new Intent(); 2408 intent.setAction(Intent.ACTION_VIEW); 2409 intent.addCategory(Intent.CATEGORY_BROWSABLE); 2410 intent.setData(Uri.parse("http:")); 2411 2412 // Resolve that intent and check that the handleAllWebDataURI boolean is set 2413 List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId); 2414 2415 final int count = list.size(); 2416 List<String> result = new ArrayList<String>(count); 2417 for (int i=0; i<count; i++) { 2418 ResolveInfo info = list.get(i); 2419 if (info.activityInfo == null 2420 || !info.handleAllWebDataURI 2421 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2422 || result.contains(info.activityInfo.packageName)) { 2423 continue; 2424 } 2425 result.add(info.activityInfo.packageName); 2426 } 2427 2428 return result; 2429 } 2430 2431 private void checkDefaultBrowser() { 2432 final int myUserId = UserHandle.myUserId(); 2433 final String packageName = getDefaultBrowserPackageName(myUserId); 2434 if (packageName != null) { 2435 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2436 if (info == null) { 2437 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2438 synchronized (mPackages) { 2439 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2440 } 2441 } 2442 } 2443 } 2444 2445 @Override 2446 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2447 throws RemoteException { 2448 try { 2449 return super.onTransact(code, data, reply, flags); 2450 } catch (RuntimeException e) { 2451 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2452 Slog.wtf(TAG, "Package Manager Crash", e); 2453 } 2454 throw e; 2455 } 2456 } 2457 2458 void cleanupInstallFailedPackage(PackageSetting ps) { 2459 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2460 2461 removeDataDirsLI(ps.volumeUuid, ps.name); 2462 if (ps.codePath != null) { 2463 if (ps.codePath.isDirectory()) { 2464 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2465 } else { 2466 ps.codePath.delete(); 2467 } 2468 } 2469 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2470 if (ps.resourcePath.isDirectory()) { 2471 FileUtils.deleteContents(ps.resourcePath); 2472 } 2473 ps.resourcePath.delete(); 2474 } 2475 mSettings.removePackageLPw(ps.name); 2476 } 2477 2478 static int[] appendInts(int[] cur, int[] add) { 2479 if (add == null) return cur; 2480 if (cur == null) return add; 2481 final int N = add.length; 2482 for (int i=0; i<N; i++) { 2483 cur = appendInt(cur, add[i]); 2484 } 2485 return cur; 2486 } 2487 2488 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2489 if (!sUserManager.exists(userId)) return null; 2490 final PackageSetting ps = (PackageSetting) p.mExtras; 2491 if (ps == null) { 2492 return null; 2493 } 2494 2495 final PermissionsState permissionsState = ps.getPermissionsState(); 2496 2497 final int[] gids = permissionsState.computeGids(userId); 2498 final Set<String> permissions = permissionsState.getPermissions(userId); 2499 final PackageUserState state = ps.readUserState(userId); 2500 2501 return PackageParser.generatePackageInfo(p, gids, flags, 2502 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2503 } 2504 2505 @Override 2506 public boolean isPackageFrozen(String packageName) { 2507 synchronized (mPackages) { 2508 final PackageSetting ps = mSettings.mPackages.get(packageName); 2509 if (ps != null) { 2510 return ps.frozen; 2511 } 2512 } 2513 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2514 return true; 2515 } 2516 2517 @Override 2518 public boolean isPackageAvailable(String packageName, int userId) { 2519 if (!sUserManager.exists(userId)) return false; 2520 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2521 synchronized (mPackages) { 2522 PackageParser.Package p = mPackages.get(packageName); 2523 if (p != null) { 2524 final PackageSetting ps = (PackageSetting) p.mExtras; 2525 if (ps != null) { 2526 final PackageUserState state = ps.readUserState(userId); 2527 if (state != null) { 2528 return PackageParser.isAvailable(state); 2529 } 2530 } 2531 } 2532 } 2533 return false; 2534 } 2535 2536 @Override 2537 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2538 if (!sUserManager.exists(userId)) return null; 2539 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2540 // reader 2541 synchronized (mPackages) { 2542 PackageParser.Package p = mPackages.get(packageName); 2543 if (DEBUG_PACKAGE_INFO) 2544 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2545 if (p != null) { 2546 return generatePackageInfo(p, flags, userId); 2547 } 2548 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2549 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2550 } 2551 } 2552 return null; 2553 } 2554 2555 @Override 2556 public String[] currentToCanonicalPackageNames(String[] names) { 2557 String[] out = new String[names.length]; 2558 // reader 2559 synchronized (mPackages) { 2560 for (int i=names.length-1; i>=0; i--) { 2561 PackageSetting ps = mSettings.mPackages.get(names[i]); 2562 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2563 } 2564 } 2565 return out; 2566 } 2567 2568 @Override 2569 public String[] canonicalToCurrentPackageNames(String[] names) { 2570 String[] out = new String[names.length]; 2571 // reader 2572 synchronized (mPackages) { 2573 for (int i=names.length-1; i>=0; i--) { 2574 String cur = mSettings.mRenamedPackages.get(names[i]); 2575 out[i] = cur != null ? cur : names[i]; 2576 } 2577 } 2578 return out; 2579 } 2580 2581 @Override 2582 public int getPackageUid(String packageName, int userId) { 2583 if (!sUserManager.exists(userId)) return -1; 2584 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2585 2586 // reader 2587 synchronized (mPackages) { 2588 PackageParser.Package p = mPackages.get(packageName); 2589 if(p != null) { 2590 return UserHandle.getUid(userId, p.applicationInfo.uid); 2591 } 2592 PackageSetting ps = mSettings.mPackages.get(packageName); 2593 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2594 return -1; 2595 } 2596 p = ps.pkg; 2597 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2598 } 2599 } 2600 2601 @Override 2602 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2603 if (!sUserManager.exists(userId)) { 2604 return null; 2605 } 2606 2607 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2608 "getPackageGids"); 2609 2610 // reader 2611 synchronized (mPackages) { 2612 PackageParser.Package p = mPackages.get(packageName); 2613 if (DEBUG_PACKAGE_INFO) { 2614 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2615 } 2616 if (p != null) { 2617 PackageSetting ps = (PackageSetting) p.mExtras; 2618 return ps.getPermissionsState().computeGids(userId); 2619 } 2620 } 2621 2622 return null; 2623 } 2624 2625 @Override 2626 public int getMountExternalMode(int uid) { 2627 if (Process.isIsolated(uid)) { 2628 return Zygote.MOUNT_EXTERNAL_NONE; 2629 } else { 2630 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2631 return Zygote.MOUNT_EXTERNAL_WRITE; 2632 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2633 return Zygote.MOUNT_EXTERNAL_READ; 2634 } else { 2635 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2636 } 2637 } 2638 } 2639 2640 static PermissionInfo generatePermissionInfo( 2641 BasePermission bp, int flags) { 2642 if (bp.perm != null) { 2643 return PackageParser.generatePermissionInfo(bp.perm, flags); 2644 } 2645 PermissionInfo pi = new PermissionInfo(); 2646 pi.name = bp.name; 2647 pi.packageName = bp.sourcePackage; 2648 pi.nonLocalizedLabel = bp.name; 2649 pi.protectionLevel = bp.protectionLevel; 2650 return pi; 2651 } 2652 2653 @Override 2654 public PermissionInfo getPermissionInfo(String name, int flags) { 2655 // reader 2656 synchronized (mPackages) { 2657 final BasePermission p = mSettings.mPermissions.get(name); 2658 if (p != null) { 2659 return generatePermissionInfo(p, flags); 2660 } 2661 return null; 2662 } 2663 } 2664 2665 @Override 2666 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2667 // reader 2668 synchronized (mPackages) { 2669 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2670 for (BasePermission p : mSettings.mPermissions.values()) { 2671 if (group == null) { 2672 if (p.perm == null || p.perm.info.group == null) { 2673 out.add(generatePermissionInfo(p, flags)); 2674 } 2675 } else { 2676 if (p.perm != null && group.equals(p.perm.info.group)) { 2677 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2678 } 2679 } 2680 } 2681 2682 if (out.size() > 0) { 2683 return out; 2684 } 2685 return mPermissionGroups.containsKey(group) ? out : null; 2686 } 2687 } 2688 2689 @Override 2690 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2691 // reader 2692 synchronized (mPackages) { 2693 return PackageParser.generatePermissionGroupInfo( 2694 mPermissionGroups.get(name), flags); 2695 } 2696 } 2697 2698 @Override 2699 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2700 // reader 2701 synchronized (mPackages) { 2702 final int N = mPermissionGroups.size(); 2703 ArrayList<PermissionGroupInfo> out 2704 = new ArrayList<PermissionGroupInfo>(N); 2705 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2706 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2707 } 2708 return out; 2709 } 2710 } 2711 2712 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2713 int userId) { 2714 if (!sUserManager.exists(userId)) return null; 2715 PackageSetting ps = mSettings.mPackages.get(packageName); 2716 if (ps != null) { 2717 if (ps.pkg == null) { 2718 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2719 flags, userId); 2720 if (pInfo != null) { 2721 return pInfo.applicationInfo; 2722 } 2723 return null; 2724 } 2725 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2726 ps.readUserState(userId), userId); 2727 } 2728 return null; 2729 } 2730 2731 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2732 int userId) { 2733 if (!sUserManager.exists(userId)) return null; 2734 PackageSetting ps = mSettings.mPackages.get(packageName); 2735 if (ps != null) { 2736 PackageParser.Package pkg = ps.pkg; 2737 if (pkg == null) { 2738 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2739 return null; 2740 } 2741 // Only data remains, so we aren't worried about code paths 2742 pkg = new PackageParser.Package(packageName); 2743 pkg.applicationInfo.packageName = packageName; 2744 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2745 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2746 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2747 packageName, userId).getAbsolutePath(); 2748 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2749 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2750 } 2751 return generatePackageInfo(pkg, flags, userId); 2752 } 2753 return null; 2754 } 2755 2756 @Override 2757 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2758 if (!sUserManager.exists(userId)) return null; 2759 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2760 // writer 2761 synchronized (mPackages) { 2762 PackageParser.Package p = mPackages.get(packageName); 2763 if (DEBUG_PACKAGE_INFO) Log.v( 2764 TAG, "getApplicationInfo " + packageName 2765 + ": " + p); 2766 if (p != null) { 2767 PackageSetting ps = mSettings.mPackages.get(packageName); 2768 if (ps == null) return null; 2769 // Note: isEnabledLP() does not apply here - always return info 2770 return PackageParser.generateApplicationInfo( 2771 p, flags, ps.readUserState(userId), userId); 2772 } 2773 if ("android".equals(packageName)||"system".equals(packageName)) { 2774 return mAndroidApplication; 2775 } 2776 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2777 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2778 } 2779 } 2780 return null; 2781 } 2782 2783 @Override 2784 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2785 final IPackageDataObserver observer) { 2786 mContext.enforceCallingOrSelfPermission( 2787 android.Manifest.permission.CLEAR_APP_CACHE, null); 2788 // Queue up an async operation since clearing cache may take a little while. 2789 mHandler.post(new Runnable() { 2790 public void run() { 2791 mHandler.removeCallbacks(this); 2792 int retCode = -1; 2793 synchronized (mInstallLock) { 2794 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2795 if (retCode < 0) { 2796 Slog.w(TAG, "Couldn't clear application caches"); 2797 } 2798 } 2799 if (observer != null) { 2800 try { 2801 observer.onRemoveCompleted(null, (retCode >= 0)); 2802 } catch (RemoteException e) { 2803 Slog.w(TAG, "RemoveException when invoking call back"); 2804 } 2805 } 2806 } 2807 }); 2808 } 2809 2810 @Override 2811 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2812 final IntentSender pi) { 2813 mContext.enforceCallingOrSelfPermission( 2814 android.Manifest.permission.CLEAR_APP_CACHE, null); 2815 // Queue up an async operation since clearing cache may take a little while. 2816 mHandler.post(new Runnable() { 2817 public void run() { 2818 mHandler.removeCallbacks(this); 2819 int retCode = -1; 2820 synchronized (mInstallLock) { 2821 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2822 if (retCode < 0) { 2823 Slog.w(TAG, "Couldn't clear application caches"); 2824 } 2825 } 2826 if(pi != null) { 2827 try { 2828 // Callback via pending intent 2829 int code = (retCode >= 0) ? 1 : 0; 2830 pi.sendIntent(null, code, null, 2831 null, null); 2832 } catch (SendIntentException e1) { 2833 Slog.i(TAG, "Failed to send pending intent"); 2834 } 2835 } 2836 } 2837 }); 2838 } 2839 2840 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2841 synchronized (mInstallLock) { 2842 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2843 throw new IOException("Failed to free enough space"); 2844 } 2845 } 2846 } 2847 2848 @Override 2849 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2850 if (!sUserManager.exists(userId)) return null; 2851 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2852 synchronized (mPackages) { 2853 PackageParser.Activity a = mActivities.mActivities.get(component); 2854 2855 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2856 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2857 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2858 if (ps == null) return null; 2859 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2860 userId); 2861 } 2862 if (mResolveComponentName.equals(component)) { 2863 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2864 new PackageUserState(), userId); 2865 } 2866 } 2867 return null; 2868 } 2869 2870 @Override 2871 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2872 String resolvedType) { 2873 synchronized (mPackages) { 2874 PackageParser.Activity a = mActivities.mActivities.get(component); 2875 if (a == null) { 2876 return false; 2877 } 2878 for (int i=0; i<a.intents.size(); i++) { 2879 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2880 intent.getData(), intent.getCategories(), TAG) >= 0) { 2881 return true; 2882 } 2883 } 2884 return false; 2885 } 2886 } 2887 2888 @Override 2889 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2892 synchronized (mPackages) { 2893 PackageParser.Activity a = mReceivers.mActivities.get(component); 2894 if (DEBUG_PACKAGE_INFO) Log.v( 2895 TAG, "getReceiverInfo " + component + ": " + a); 2896 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2897 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2898 if (ps == null) return null; 2899 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2900 userId); 2901 } 2902 } 2903 return null; 2904 } 2905 2906 @Override 2907 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2908 if (!sUserManager.exists(userId)) return null; 2909 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2910 synchronized (mPackages) { 2911 PackageParser.Service s = mServices.mServices.get(component); 2912 if (DEBUG_PACKAGE_INFO) Log.v( 2913 TAG, "getServiceInfo " + component + ": " + s); 2914 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2915 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2916 if (ps == null) return null; 2917 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2918 userId); 2919 } 2920 } 2921 return null; 2922 } 2923 2924 @Override 2925 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2926 if (!sUserManager.exists(userId)) return null; 2927 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2928 synchronized (mPackages) { 2929 PackageParser.Provider p = mProviders.mProviders.get(component); 2930 if (DEBUG_PACKAGE_INFO) Log.v( 2931 TAG, "getProviderInfo " + component + ": " + p); 2932 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2933 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2934 if (ps == null) return null; 2935 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2936 userId); 2937 } 2938 } 2939 return null; 2940 } 2941 2942 @Override 2943 public String[] getSystemSharedLibraryNames() { 2944 Set<String> libSet; 2945 synchronized (mPackages) { 2946 libSet = mSharedLibraries.keySet(); 2947 int size = libSet.size(); 2948 if (size > 0) { 2949 String[] libs = new String[size]; 2950 libSet.toArray(libs); 2951 return libs; 2952 } 2953 } 2954 return null; 2955 } 2956 2957 /** 2958 * @hide 2959 */ 2960 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2961 synchronized (mPackages) { 2962 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2963 if (lib != null && lib.apk != null) { 2964 return mPackages.get(lib.apk); 2965 } 2966 } 2967 return null; 2968 } 2969 2970 @Override 2971 public FeatureInfo[] getSystemAvailableFeatures() { 2972 Collection<FeatureInfo> featSet; 2973 synchronized (mPackages) { 2974 featSet = mAvailableFeatures.values(); 2975 int size = featSet.size(); 2976 if (size > 0) { 2977 FeatureInfo[] features = new FeatureInfo[size+1]; 2978 featSet.toArray(features); 2979 FeatureInfo fi = new FeatureInfo(); 2980 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2981 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2982 features[size] = fi; 2983 return features; 2984 } 2985 } 2986 return null; 2987 } 2988 2989 @Override 2990 public boolean hasSystemFeature(String name) { 2991 synchronized (mPackages) { 2992 return mAvailableFeatures.containsKey(name); 2993 } 2994 } 2995 2996 private void checkValidCaller(int uid, int userId) { 2997 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2998 return; 2999 3000 throw new SecurityException("Caller uid=" + uid 3001 + " is not privileged to communicate with user=" + userId); 3002 } 3003 3004 @Override 3005 public int checkPermission(String permName, String pkgName, int userId) { 3006 if (!sUserManager.exists(userId)) { 3007 return PackageManager.PERMISSION_DENIED; 3008 } 3009 3010 synchronized (mPackages) { 3011 final PackageParser.Package p = mPackages.get(pkgName); 3012 if (p != null && p.mExtras != null) { 3013 final PackageSetting ps = (PackageSetting) p.mExtras; 3014 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3015 return PackageManager.PERMISSION_GRANTED; 3016 } 3017 } 3018 } 3019 3020 return PackageManager.PERMISSION_DENIED; 3021 } 3022 3023 @Override 3024 public int checkUidPermission(String permName, int uid) { 3025 final int userId = UserHandle.getUserId(uid); 3026 3027 if (!sUserManager.exists(userId)) { 3028 return PackageManager.PERMISSION_DENIED; 3029 } 3030 3031 synchronized (mPackages) { 3032 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3033 if (obj != null) { 3034 final SettingBase ps = (SettingBase) obj; 3035 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3036 return PackageManager.PERMISSION_GRANTED; 3037 } 3038 } else { 3039 ArraySet<String> perms = mSystemPermissions.get(uid); 3040 if (perms != null && perms.contains(permName)) { 3041 return PackageManager.PERMISSION_GRANTED; 3042 } 3043 } 3044 } 3045 3046 return PackageManager.PERMISSION_DENIED; 3047 } 3048 3049 /** 3050 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3051 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3052 * @param checkShell TODO(yamasani): 3053 * @param message the message to log on security exception 3054 */ 3055 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3056 boolean checkShell, String message) { 3057 if (userId < 0) { 3058 throw new IllegalArgumentException("Invalid userId " + userId); 3059 } 3060 if (checkShell) { 3061 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3062 } 3063 if (userId == UserHandle.getUserId(callingUid)) return; 3064 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3065 if (requireFullPermission) { 3066 mContext.enforceCallingOrSelfPermission( 3067 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3068 } else { 3069 try { 3070 mContext.enforceCallingOrSelfPermission( 3071 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3072 } catch (SecurityException se) { 3073 mContext.enforceCallingOrSelfPermission( 3074 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3075 } 3076 } 3077 } 3078 } 3079 3080 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3081 if (callingUid == Process.SHELL_UID) { 3082 if (userHandle >= 0 3083 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3084 throw new SecurityException("Shell does not have permission to access user " 3085 + userHandle); 3086 } else if (userHandle < 0) { 3087 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3088 + Debug.getCallers(3)); 3089 } 3090 } 3091 } 3092 3093 private BasePermission findPermissionTreeLP(String permName) { 3094 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3095 if (permName.startsWith(bp.name) && 3096 permName.length() > bp.name.length() && 3097 permName.charAt(bp.name.length()) == '.') { 3098 return bp; 3099 } 3100 } 3101 return null; 3102 } 3103 3104 private BasePermission checkPermissionTreeLP(String permName) { 3105 if (permName != null) { 3106 BasePermission bp = findPermissionTreeLP(permName); 3107 if (bp != null) { 3108 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3109 return bp; 3110 } 3111 throw new SecurityException("Calling uid " 3112 + Binder.getCallingUid() 3113 + " is not allowed to add to permission tree " 3114 + bp.name + " owned by uid " + bp.uid); 3115 } 3116 } 3117 throw new SecurityException("No permission tree found for " + permName); 3118 } 3119 3120 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3121 if (s1 == null) { 3122 return s2 == null; 3123 } 3124 if (s2 == null) { 3125 return false; 3126 } 3127 if (s1.getClass() != s2.getClass()) { 3128 return false; 3129 } 3130 return s1.equals(s2); 3131 } 3132 3133 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3134 if (pi1.icon != pi2.icon) return false; 3135 if (pi1.logo != pi2.logo) return false; 3136 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3137 if (!compareStrings(pi1.name, pi2.name)) return false; 3138 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3139 // We'll take care of setting this one. 3140 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3141 // These are not currently stored in settings. 3142 //if (!compareStrings(pi1.group, pi2.group)) return false; 3143 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3144 //if (pi1.labelRes != pi2.labelRes) return false; 3145 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3146 return true; 3147 } 3148 3149 int permissionInfoFootprint(PermissionInfo info) { 3150 int size = info.name.length(); 3151 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3152 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3153 return size; 3154 } 3155 3156 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3157 int size = 0; 3158 for (BasePermission perm : mSettings.mPermissions.values()) { 3159 if (perm.uid == tree.uid) { 3160 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3161 } 3162 } 3163 return size; 3164 } 3165 3166 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3167 // We calculate the max size of permissions defined by this uid and throw 3168 // if that plus the size of 'info' would exceed our stated maximum. 3169 if (tree.uid != Process.SYSTEM_UID) { 3170 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3171 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3172 throw new SecurityException("Permission tree size cap exceeded"); 3173 } 3174 } 3175 } 3176 3177 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3178 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3179 throw new SecurityException("Label must be specified in permission"); 3180 } 3181 BasePermission tree = checkPermissionTreeLP(info.name); 3182 BasePermission bp = mSettings.mPermissions.get(info.name); 3183 boolean added = bp == null; 3184 boolean changed = true; 3185 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3186 if (added) { 3187 enforcePermissionCapLocked(info, tree); 3188 bp = new BasePermission(info.name, tree.sourcePackage, 3189 BasePermission.TYPE_DYNAMIC); 3190 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3191 throw new SecurityException( 3192 "Not allowed to modify non-dynamic permission " 3193 + info.name); 3194 } else { 3195 if (bp.protectionLevel == fixedLevel 3196 && bp.perm.owner.equals(tree.perm.owner) 3197 && bp.uid == tree.uid 3198 && comparePermissionInfos(bp.perm.info, info)) { 3199 changed = false; 3200 } 3201 } 3202 bp.protectionLevel = fixedLevel; 3203 info = new PermissionInfo(info); 3204 info.protectionLevel = fixedLevel; 3205 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3206 bp.perm.info.packageName = tree.perm.info.packageName; 3207 bp.uid = tree.uid; 3208 if (added) { 3209 mSettings.mPermissions.put(info.name, bp); 3210 } 3211 if (changed) { 3212 if (!async) { 3213 mSettings.writeLPr(); 3214 } else { 3215 scheduleWriteSettingsLocked(); 3216 } 3217 } 3218 return added; 3219 } 3220 3221 @Override 3222 public boolean addPermission(PermissionInfo info) { 3223 synchronized (mPackages) { 3224 return addPermissionLocked(info, false); 3225 } 3226 } 3227 3228 @Override 3229 public boolean addPermissionAsync(PermissionInfo info) { 3230 synchronized (mPackages) { 3231 return addPermissionLocked(info, true); 3232 } 3233 } 3234 3235 @Override 3236 public void removePermission(String name) { 3237 synchronized (mPackages) { 3238 checkPermissionTreeLP(name); 3239 BasePermission bp = mSettings.mPermissions.get(name); 3240 if (bp != null) { 3241 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3242 throw new SecurityException( 3243 "Not allowed to modify non-dynamic permission " 3244 + name); 3245 } 3246 mSettings.mPermissions.remove(name); 3247 mSettings.writeLPr(); 3248 } 3249 } 3250 } 3251 3252 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3253 BasePermission bp) { 3254 int index = pkg.requestedPermissions.indexOf(bp.name); 3255 if (index == -1) { 3256 throw new SecurityException("Package " + pkg.packageName 3257 + " has not requested permission " + bp.name); 3258 } 3259 if (!bp.isRuntime()) { 3260 throw new SecurityException("Permission " + bp.name 3261 + " is not a changeable permission type"); 3262 } 3263 } 3264 3265 @Override 3266 public void grantRuntimePermission(String packageName, String name, final int userId) { 3267 if (!sUserManager.exists(userId)) { 3268 Log.e(TAG, "No such user:" + userId); 3269 return; 3270 } 3271 3272 mContext.enforceCallingOrSelfPermission( 3273 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3274 "grantRuntimePermission"); 3275 3276 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3277 "grantRuntimePermission"); 3278 3279 final int uid; 3280 final SettingBase sb; 3281 3282 synchronized (mPackages) { 3283 final PackageParser.Package pkg = mPackages.get(packageName); 3284 if (pkg == null) { 3285 throw new IllegalArgumentException("Unknown package: " + packageName); 3286 } 3287 3288 final BasePermission bp = mSettings.mPermissions.get(name); 3289 if (bp == null) { 3290 throw new IllegalArgumentException("Unknown permission: " + name); 3291 } 3292 3293 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3294 3295 uid = pkg.applicationInfo.uid; 3296 sb = (SettingBase) pkg.mExtras; 3297 if (sb == null) { 3298 throw new IllegalArgumentException("Unknown package: " + packageName); 3299 } 3300 3301 final PermissionsState permissionsState = sb.getPermissionsState(); 3302 3303 final int flags = permissionsState.getPermissionFlags(name, userId); 3304 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3305 throw new SecurityException("Cannot grant system fixed permission: " 3306 + name + " for package: " + packageName); 3307 } 3308 3309 final int result = permissionsState.grantRuntimePermission(bp, userId); 3310 switch (result) { 3311 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3312 return; 3313 } 3314 3315 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3316 mHandler.post(new Runnable() { 3317 @Override 3318 public void run() { 3319 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3320 } 3321 }); 3322 } break; 3323 } 3324 3325 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3326 3327 // Not critical if that is lost - app has to request again. 3328 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3329 } 3330 3331 if (READ_EXTERNAL_STORAGE.equals(name) 3332 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3333 final long token = Binder.clearCallingIdentity(); 3334 try { 3335 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3336 storage.remountUid(uid); 3337 } finally { 3338 Binder.restoreCallingIdentity(token); 3339 } 3340 } 3341 } 3342 3343 @Override 3344 public void revokeRuntimePermission(String packageName, String name, int userId) { 3345 if (!sUserManager.exists(userId)) { 3346 Log.e(TAG, "No such user:" + userId); 3347 return; 3348 } 3349 3350 mContext.enforceCallingOrSelfPermission( 3351 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3352 "revokeRuntimePermission"); 3353 3354 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3355 "revokeRuntimePermission"); 3356 3357 final SettingBase sb; 3358 3359 synchronized (mPackages) { 3360 final PackageParser.Package pkg = mPackages.get(packageName); 3361 if (pkg == null) { 3362 throw new IllegalArgumentException("Unknown package: " + packageName); 3363 } 3364 3365 final BasePermission bp = mSettings.mPermissions.get(name); 3366 if (bp == null) { 3367 throw new IllegalArgumentException("Unknown permission: " + name); 3368 } 3369 3370 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3371 3372 sb = (SettingBase) pkg.mExtras; 3373 if (sb == null) { 3374 throw new IllegalArgumentException("Unknown package: " + packageName); 3375 } 3376 3377 final PermissionsState permissionsState = sb.getPermissionsState(); 3378 3379 final int flags = permissionsState.getPermissionFlags(name, userId); 3380 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3381 throw new SecurityException("Cannot revoke system fixed permission: " 3382 + name + " for package: " + packageName); 3383 } 3384 3385 if (permissionsState.revokeRuntimePermission(bp, userId) == 3386 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3387 return; 3388 } 3389 3390 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3391 3392 // Critical, after this call app should never have the permission. 3393 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3394 } 3395 3396 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3397 } 3398 3399 @Override 3400 public void resetRuntimePermissions() { 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3403 "revokeRuntimePermission"); 3404 3405 int callingUid = Binder.getCallingUid(); 3406 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3407 mContext.enforceCallingOrSelfPermission( 3408 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3409 "resetRuntimePermissions"); 3410 } 3411 3412 final int[] userIds; 3413 3414 synchronized (mPackages) { 3415 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3416 final int userCount = UserManagerService.getInstance().getUserIds().length; 3417 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3418 } 3419 3420 for (int userId : userIds) { 3421 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3422 } 3423 } 3424 3425 @Override 3426 public int getPermissionFlags(String name, String packageName, int userId) { 3427 if (!sUserManager.exists(userId)) { 3428 return 0; 3429 } 3430 3431 mContext.enforceCallingOrSelfPermission( 3432 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3433 "getPermissionFlags"); 3434 3435 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3436 "getPermissionFlags"); 3437 3438 synchronized (mPackages) { 3439 final PackageParser.Package pkg = mPackages.get(packageName); 3440 if (pkg == null) { 3441 throw new IllegalArgumentException("Unknown package: " + packageName); 3442 } 3443 3444 final BasePermission bp = mSettings.mPermissions.get(name); 3445 if (bp == null) { 3446 throw new IllegalArgumentException("Unknown permission: " + name); 3447 } 3448 3449 SettingBase sb = (SettingBase) pkg.mExtras; 3450 if (sb == null) { 3451 throw new IllegalArgumentException("Unknown package: " + packageName); 3452 } 3453 3454 PermissionsState permissionsState = sb.getPermissionsState(); 3455 return permissionsState.getPermissionFlags(name, userId); 3456 } 3457 } 3458 3459 @Override 3460 public void updatePermissionFlags(String name, String packageName, int flagMask, 3461 int flagValues, int userId) { 3462 if (!sUserManager.exists(userId)) { 3463 return; 3464 } 3465 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3468 "updatePermissionFlags"); 3469 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3471 "updatePermissionFlags"); 3472 3473 // Only the system can change system fixed flags. 3474 if (getCallingUid() != Process.SYSTEM_UID) { 3475 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3476 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3477 } 3478 3479 synchronized (mPackages) { 3480 final PackageParser.Package pkg = mPackages.get(packageName); 3481 if (pkg == null) { 3482 throw new IllegalArgumentException("Unknown package: " + packageName); 3483 } 3484 3485 final BasePermission bp = mSettings.mPermissions.get(name); 3486 if (bp == null) { 3487 throw new IllegalArgumentException("Unknown permission: " + name); 3488 } 3489 3490 SettingBase sb = (SettingBase) pkg.mExtras; 3491 if (sb == null) { 3492 throw new IllegalArgumentException("Unknown package: " + packageName); 3493 } 3494 3495 PermissionsState permissionsState = sb.getPermissionsState(); 3496 3497 // Only the package manager can change flags for system component permissions. 3498 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3499 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3500 return; 3501 } 3502 3503 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3504 3505 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3506 // Install and runtime permissions are stored in different places, 3507 // so figure out what permission changed and persist the change. 3508 if (permissionsState.getInstallPermissionState(name) != null) { 3509 scheduleWriteSettingsLocked(); 3510 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3511 || hadState) { 3512 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3513 } 3514 } 3515 } 3516 } 3517 3518 /** 3519 * Update the permission flags for all packages and runtime permissions of a user in order 3520 * to allow device or profile owner to remove POLICY_FIXED. 3521 */ 3522 @Override 3523 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3524 if (!sUserManager.exists(userId)) { 3525 return; 3526 } 3527 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3530 "updatePermissionFlagsForAllApps"); 3531 3532 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3533 "updatePermissionFlagsForAllApps"); 3534 3535 // Only the system can change system fixed flags. 3536 if (getCallingUid() != Process.SYSTEM_UID) { 3537 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3538 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3539 } 3540 3541 synchronized (mPackages) { 3542 boolean changed = false; 3543 final int packageCount = mPackages.size(); 3544 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3545 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3546 SettingBase sb = (SettingBase) pkg.mExtras; 3547 if (sb == null) { 3548 continue; 3549 } 3550 PermissionsState permissionsState = sb.getPermissionsState(); 3551 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3552 userId, flagMask, flagValues); 3553 } 3554 if (changed) { 3555 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3556 } 3557 } 3558 } 3559 3560 @Override 3561 public boolean shouldShowRequestPermissionRationale(String permissionName, 3562 String packageName, int userId) { 3563 if (UserHandle.getCallingUserId() != userId) { 3564 mContext.enforceCallingPermission( 3565 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3566 "canShowRequestPermissionRationale for user " + userId); 3567 } 3568 3569 final int uid = getPackageUid(packageName, userId); 3570 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3571 return false; 3572 } 3573 3574 if (checkPermission(permissionName, packageName, userId) 3575 == PackageManager.PERMISSION_GRANTED) { 3576 return false; 3577 } 3578 3579 final int flags; 3580 3581 final long identity = Binder.clearCallingIdentity(); 3582 try { 3583 flags = getPermissionFlags(permissionName, 3584 packageName, userId); 3585 } finally { 3586 Binder.restoreCallingIdentity(identity); 3587 } 3588 3589 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3590 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3591 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3592 3593 if ((flags & fixedFlags) != 0) { 3594 return false; 3595 } 3596 3597 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3598 } 3599 3600 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3601 BasePermission bp = mSettings.mPermissions.get(permission); 3602 if (bp == null) { 3603 throw new SecurityException("Missing " + permission + " permission"); 3604 } 3605 3606 SettingBase sb = (SettingBase) pkg.mExtras; 3607 PermissionsState permissionsState = sb.getPermissionsState(); 3608 3609 if (permissionsState.grantInstallPermission(bp) != 3610 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3611 scheduleWriteSettingsLocked(); 3612 } 3613 } 3614 3615 @Override 3616 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3617 mContext.enforceCallingOrSelfPermission( 3618 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3619 "addOnPermissionsChangeListener"); 3620 3621 synchronized (mPackages) { 3622 mOnPermissionChangeListeners.addListenerLocked(listener); 3623 } 3624 } 3625 3626 @Override 3627 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3628 synchronized (mPackages) { 3629 mOnPermissionChangeListeners.removeListenerLocked(listener); 3630 } 3631 } 3632 3633 @Override 3634 public boolean isProtectedBroadcast(String actionName) { 3635 synchronized (mPackages) { 3636 return mProtectedBroadcasts.contains(actionName); 3637 } 3638 } 3639 3640 @Override 3641 public int checkSignatures(String pkg1, String pkg2) { 3642 synchronized (mPackages) { 3643 final PackageParser.Package p1 = mPackages.get(pkg1); 3644 final PackageParser.Package p2 = mPackages.get(pkg2); 3645 if (p1 == null || p1.mExtras == null 3646 || p2 == null || p2.mExtras == null) { 3647 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3648 } 3649 return compareSignatures(p1.mSignatures, p2.mSignatures); 3650 } 3651 } 3652 3653 @Override 3654 public int checkUidSignatures(int uid1, int uid2) { 3655 // Map to base uids. 3656 uid1 = UserHandle.getAppId(uid1); 3657 uid2 = UserHandle.getAppId(uid2); 3658 // reader 3659 synchronized (mPackages) { 3660 Signature[] s1; 3661 Signature[] s2; 3662 Object obj = mSettings.getUserIdLPr(uid1); 3663 if (obj != null) { 3664 if (obj instanceof SharedUserSetting) { 3665 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3666 } else if (obj instanceof PackageSetting) { 3667 s1 = ((PackageSetting)obj).signatures.mSignatures; 3668 } else { 3669 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3670 } 3671 } else { 3672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3673 } 3674 obj = mSettings.getUserIdLPr(uid2); 3675 if (obj != null) { 3676 if (obj instanceof SharedUserSetting) { 3677 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3678 } else if (obj instanceof PackageSetting) { 3679 s2 = ((PackageSetting)obj).signatures.mSignatures; 3680 } else { 3681 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3682 } 3683 } else { 3684 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3685 } 3686 return compareSignatures(s1, s2); 3687 } 3688 } 3689 3690 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3691 final long identity = Binder.clearCallingIdentity(); 3692 try { 3693 if (sb instanceof SharedUserSetting) { 3694 SharedUserSetting sus = (SharedUserSetting) sb; 3695 final int packageCount = sus.packages.size(); 3696 for (int i = 0; i < packageCount; i++) { 3697 PackageSetting susPs = sus.packages.valueAt(i); 3698 if (userId == UserHandle.USER_ALL) { 3699 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3700 } else { 3701 final int uid = UserHandle.getUid(userId, susPs.appId); 3702 killUid(uid, reason); 3703 } 3704 } 3705 } else if (sb instanceof PackageSetting) { 3706 PackageSetting ps = (PackageSetting) sb; 3707 if (userId == UserHandle.USER_ALL) { 3708 killApplication(ps.pkg.packageName, ps.appId, reason); 3709 } else { 3710 final int uid = UserHandle.getUid(userId, ps.appId); 3711 killUid(uid, reason); 3712 } 3713 } 3714 } finally { 3715 Binder.restoreCallingIdentity(identity); 3716 } 3717 } 3718 3719 private static void killUid(int uid, String reason) { 3720 IActivityManager am = ActivityManagerNative.getDefault(); 3721 if (am != null) { 3722 try { 3723 am.killUid(uid, reason); 3724 } catch (RemoteException e) { 3725 /* ignore - same process */ 3726 } 3727 } 3728 } 3729 3730 /** 3731 * Compares two sets of signatures. Returns: 3732 * <br /> 3733 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3734 * <br /> 3735 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3736 * <br /> 3737 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3738 * <br /> 3739 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3740 * <br /> 3741 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3742 */ 3743 static int compareSignatures(Signature[] s1, Signature[] s2) { 3744 if (s1 == null) { 3745 return s2 == null 3746 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3747 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3748 } 3749 3750 if (s2 == null) { 3751 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3752 } 3753 3754 if (s1.length != s2.length) { 3755 return PackageManager.SIGNATURE_NO_MATCH; 3756 } 3757 3758 // Since both signature sets are of size 1, we can compare without HashSets. 3759 if (s1.length == 1) { 3760 return s1[0].equals(s2[0]) ? 3761 PackageManager.SIGNATURE_MATCH : 3762 PackageManager.SIGNATURE_NO_MATCH; 3763 } 3764 3765 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3766 for (Signature sig : s1) { 3767 set1.add(sig); 3768 } 3769 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3770 for (Signature sig : s2) { 3771 set2.add(sig); 3772 } 3773 // Make sure s2 contains all signatures in s1. 3774 if (set1.equals(set2)) { 3775 return PackageManager.SIGNATURE_MATCH; 3776 } 3777 return PackageManager.SIGNATURE_NO_MATCH; 3778 } 3779 3780 /** 3781 * If the database version for this type of package (internal storage or 3782 * external storage) is less than the version where package signatures 3783 * were updated, return true. 3784 */ 3785 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3786 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3787 DatabaseVersion.SIGNATURE_END_ENTITY)) 3788 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3789 DatabaseVersion.SIGNATURE_END_ENTITY)); 3790 } 3791 3792 /** 3793 * Used for backward compatibility to make sure any packages with 3794 * certificate chains get upgraded to the new style. {@code existingSigs} 3795 * will be in the old format (since they were stored on disk from before the 3796 * system upgrade) and {@code scannedSigs} will be in the newer format. 3797 */ 3798 private int compareSignaturesCompat(PackageSignatures existingSigs, 3799 PackageParser.Package scannedPkg) { 3800 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3801 return PackageManager.SIGNATURE_NO_MATCH; 3802 } 3803 3804 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3805 for (Signature sig : existingSigs.mSignatures) { 3806 existingSet.add(sig); 3807 } 3808 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3809 for (Signature sig : scannedPkg.mSignatures) { 3810 try { 3811 Signature[] chainSignatures = sig.getChainSignatures(); 3812 for (Signature chainSig : chainSignatures) { 3813 scannedCompatSet.add(chainSig); 3814 } 3815 } catch (CertificateEncodingException e) { 3816 scannedCompatSet.add(sig); 3817 } 3818 } 3819 /* 3820 * Make sure the expanded scanned set contains all signatures in the 3821 * existing one. 3822 */ 3823 if (scannedCompatSet.equals(existingSet)) { 3824 // Migrate the old signatures to the new scheme. 3825 existingSigs.assignSignatures(scannedPkg.mSignatures); 3826 // The new KeySets will be re-added later in the scanning process. 3827 synchronized (mPackages) { 3828 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3829 } 3830 return PackageManager.SIGNATURE_MATCH; 3831 } 3832 return PackageManager.SIGNATURE_NO_MATCH; 3833 } 3834 3835 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3836 if (isExternal(scannedPkg)) { 3837 return mSettings.isExternalDatabaseVersionOlderThan( 3838 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3839 } else { 3840 return mSettings.isInternalDatabaseVersionOlderThan( 3841 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3842 } 3843 } 3844 3845 private int compareSignaturesRecover(PackageSignatures existingSigs, 3846 PackageParser.Package scannedPkg) { 3847 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3848 return PackageManager.SIGNATURE_NO_MATCH; 3849 } 3850 3851 String msg = null; 3852 try { 3853 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3854 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3855 + scannedPkg.packageName); 3856 return PackageManager.SIGNATURE_MATCH; 3857 } 3858 } catch (CertificateException e) { 3859 msg = e.getMessage(); 3860 } 3861 3862 logCriticalInfo(Log.INFO, 3863 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3864 return PackageManager.SIGNATURE_NO_MATCH; 3865 } 3866 3867 @Override 3868 public String[] getPackagesForUid(int uid) { 3869 uid = UserHandle.getAppId(uid); 3870 // reader 3871 synchronized (mPackages) { 3872 Object obj = mSettings.getUserIdLPr(uid); 3873 if (obj instanceof SharedUserSetting) { 3874 final SharedUserSetting sus = (SharedUserSetting) obj; 3875 final int N = sus.packages.size(); 3876 final String[] res = new String[N]; 3877 final Iterator<PackageSetting> it = sus.packages.iterator(); 3878 int i = 0; 3879 while (it.hasNext()) { 3880 res[i++] = it.next().name; 3881 } 3882 return res; 3883 } else if (obj instanceof PackageSetting) { 3884 final PackageSetting ps = (PackageSetting) obj; 3885 return new String[] { ps.name }; 3886 } 3887 } 3888 return null; 3889 } 3890 3891 @Override 3892 public String getNameForUid(int uid) { 3893 // reader 3894 synchronized (mPackages) { 3895 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3896 if (obj instanceof SharedUserSetting) { 3897 final SharedUserSetting sus = (SharedUserSetting) obj; 3898 return sus.name + ":" + sus.userId; 3899 } else if (obj instanceof PackageSetting) { 3900 final PackageSetting ps = (PackageSetting) obj; 3901 return ps.name; 3902 } 3903 } 3904 return null; 3905 } 3906 3907 @Override 3908 public int getUidForSharedUser(String sharedUserName) { 3909 if(sharedUserName == null) { 3910 return -1; 3911 } 3912 // reader 3913 synchronized (mPackages) { 3914 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3915 if (suid == null) { 3916 return -1; 3917 } 3918 return suid.userId; 3919 } 3920 } 3921 3922 @Override 3923 public int getFlagsForUid(int uid) { 3924 synchronized (mPackages) { 3925 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3926 if (obj instanceof SharedUserSetting) { 3927 final SharedUserSetting sus = (SharedUserSetting) obj; 3928 return sus.pkgFlags; 3929 } else if (obj instanceof PackageSetting) { 3930 final PackageSetting ps = (PackageSetting) obj; 3931 return ps.pkgFlags; 3932 } 3933 } 3934 return 0; 3935 } 3936 3937 @Override 3938 public int getPrivateFlagsForUid(int uid) { 3939 synchronized (mPackages) { 3940 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3941 if (obj instanceof SharedUserSetting) { 3942 final SharedUserSetting sus = (SharedUserSetting) obj; 3943 return sus.pkgPrivateFlags; 3944 } else if (obj instanceof PackageSetting) { 3945 final PackageSetting ps = (PackageSetting) obj; 3946 return ps.pkgPrivateFlags; 3947 } 3948 } 3949 return 0; 3950 } 3951 3952 @Override 3953 public boolean isUidPrivileged(int uid) { 3954 uid = UserHandle.getAppId(uid); 3955 // reader 3956 synchronized (mPackages) { 3957 Object obj = mSettings.getUserIdLPr(uid); 3958 if (obj instanceof SharedUserSetting) { 3959 final SharedUserSetting sus = (SharedUserSetting) obj; 3960 final Iterator<PackageSetting> it = sus.packages.iterator(); 3961 while (it.hasNext()) { 3962 if (it.next().isPrivileged()) { 3963 return true; 3964 } 3965 } 3966 } else if (obj instanceof PackageSetting) { 3967 final PackageSetting ps = (PackageSetting) obj; 3968 return ps.isPrivileged(); 3969 } 3970 } 3971 return false; 3972 } 3973 3974 @Override 3975 public String[] getAppOpPermissionPackages(String permissionName) { 3976 synchronized (mPackages) { 3977 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3978 if (pkgs == null) { 3979 return null; 3980 } 3981 return pkgs.toArray(new String[pkgs.size()]); 3982 } 3983 } 3984 3985 @Override 3986 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3987 int flags, int userId) { 3988 if (!sUserManager.exists(userId)) return null; 3989 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3990 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3991 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3992 } 3993 3994 @Override 3995 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3996 IntentFilter filter, int match, ComponentName activity) { 3997 final int userId = UserHandle.getCallingUserId(); 3998 if (DEBUG_PREFERRED) { 3999 Log.v(TAG, "setLastChosenActivity intent=" + intent 4000 + " resolvedType=" + resolvedType 4001 + " flags=" + flags 4002 + " filter=" + filter 4003 + " match=" + match 4004 + " activity=" + activity); 4005 filter.dump(new PrintStreamPrinter(System.out), " "); 4006 } 4007 intent.setComponent(null); 4008 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4009 // Find any earlier preferred or last chosen entries and nuke them 4010 findPreferredActivity(intent, resolvedType, 4011 flags, query, 0, false, true, false, userId); 4012 // Add the new activity as the last chosen for this filter 4013 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4014 "Setting last chosen"); 4015 } 4016 4017 @Override 4018 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4019 final int userId = UserHandle.getCallingUserId(); 4020 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4021 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4022 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4023 false, false, false, userId); 4024 } 4025 4026 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4027 int flags, List<ResolveInfo> query, int userId) { 4028 if (query != null) { 4029 final int N = query.size(); 4030 if (N == 1) { 4031 return query.get(0); 4032 } else if (N > 1) { 4033 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4034 // If there is more than one activity with the same priority, 4035 // then let the user decide between them. 4036 ResolveInfo r0 = query.get(0); 4037 ResolveInfo r1 = query.get(1); 4038 if (DEBUG_INTENT_MATCHING || debug) { 4039 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4040 + r1.activityInfo.name + "=" + r1.priority); 4041 } 4042 // If the first activity has a higher priority, or a different 4043 // default, then it is always desireable to pick it. 4044 if (r0.priority != r1.priority 4045 || r0.preferredOrder != r1.preferredOrder 4046 || r0.isDefault != r1.isDefault) { 4047 return query.get(0); 4048 } 4049 // If we have saved a preference for a preferred activity for 4050 // this Intent, use that. 4051 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4052 flags, query, r0.priority, true, false, debug, userId); 4053 if (ri != null) { 4054 return ri; 4055 } 4056 if (userId != 0) { 4057 ri = new ResolveInfo(mResolveInfo); 4058 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4059 ri.activityInfo.applicationInfo = new ApplicationInfo( 4060 ri.activityInfo.applicationInfo); 4061 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4062 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4063 return ri; 4064 } 4065 return mResolveInfo; 4066 } 4067 } 4068 return null; 4069 } 4070 4071 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4072 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4073 final int N = query.size(); 4074 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4075 .get(userId); 4076 // Get the list of persistent preferred activities that handle the intent 4077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4078 List<PersistentPreferredActivity> pprefs = ppir != null 4079 ? ppir.queryIntent(intent, resolvedType, 4080 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4081 : null; 4082 if (pprefs != null && pprefs.size() > 0) { 4083 final int M = pprefs.size(); 4084 for (int i=0; i<M; i++) { 4085 final PersistentPreferredActivity ppa = pprefs.get(i); 4086 if (DEBUG_PREFERRED || debug) { 4087 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4088 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4089 + "\n component=" + ppa.mComponent); 4090 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4091 } 4092 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4093 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4094 if (DEBUG_PREFERRED || debug) { 4095 Slog.v(TAG, "Found persistent preferred activity:"); 4096 if (ai != null) { 4097 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4098 } else { 4099 Slog.v(TAG, " null"); 4100 } 4101 } 4102 if (ai == null) { 4103 // This previously registered persistent preferred activity 4104 // component is no longer known. Ignore it and do NOT remove it. 4105 continue; 4106 } 4107 for (int j=0; j<N; j++) { 4108 final ResolveInfo ri = query.get(j); 4109 if (!ri.activityInfo.applicationInfo.packageName 4110 .equals(ai.applicationInfo.packageName)) { 4111 continue; 4112 } 4113 if (!ri.activityInfo.name.equals(ai.name)) { 4114 continue; 4115 } 4116 // Found a persistent preference that can handle the intent. 4117 if (DEBUG_PREFERRED || debug) { 4118 Slog.v(TAG, "Returning persistent preferred activity: " + 4119 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4120 } 4121 return ri; 4122 } 4123 } 4124 } 4125 return null; 4126 } 4127 4128 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4129 List<ResolveInfo> query, int priority, boolean always, 4130 boolean removeMatches, boolean debug, int userId) { 4131 if (!sUserManager.exists(userId)) return null; 4132 // writer 4133 synchronized (mPackages) { 4134 if (intent.getSelector() != null) { 4135 intent = intent.getSelector(); 4136 } 4137 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4138 4139 // Try to find a matching persistent preferred activity. 4140 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4141 debug, userId); 4142 4143 // If a persistent preferred activity matched, use it. 4144 if (pri != null) { 4145 return pri; 4146 } 4147 4148 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4149 // Get the list of preferred activities that handle the intent 4150 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4151 List<PreferredActivity> prefs = pir != null 4152 ? pir.queryIntent(intent, resolvedType, 4153 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4154 : null; 4155 if (prefs != null && prefs.size() > 0) { 4156 boolean changed = false; 4157 try { 4158 // First figure out how good the original match set is. 4159 // We will only allow preferred activities that came 4160 // from the same match quality. 4161 int match = 0; 4162 4163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4164 4165 final int N = query.size(); 4166 for (int j=0; j<N; j++) { 4167 final ResolveInfo ri = query.get(j); 4168 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4169 + ": 0x" + Integer.toHexString(match)); 4170 if (ri.match > match) { 4171 match = ri.match; 4172 } 4173 } 4174 4175 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4176 + Integer.toHexString(match)); 4177 4178 match &= IntentFilter.MATCH_CATEGORY_MASK; 4179 final int M = prefs.size(); 4180 for (int i=0; i<M; i++) { 4181 final PreferredActivity pa = prefs.get(i); 4182 if (DEBUG_PREFERRED || debug) { 4183 Slog.v(TAG, "Checking PreferredActivity ds=" 4184 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4185 + "\n component=" + pa.mPref.mComponent); 4186 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4187 } 4188 if (pa.mPref.mMatch != match) { 4189 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4190 + Integer.toHexString(pa.mPref.mMatch)); 4191 continue; 4192 } 4193 // If it's not an "always" type preferred activity and that's what we're 4194 // looking for, skip it. 4195 if (always && !pa.mPref.mAlways) { 4196 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4197 continue; 4198 } 4199 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4200 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4201 if (DEBUG_PREFERRED || debug) { 4202 Slog.v(TAG, "Found preferred activity:"); 4203 if (ai != null) { 4204 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4205 } else { 4206 Slog.v(TAG, " null"); 4207 } 4208 } 4209 if (ai == null) { 4210 // This previously registered preferred activity 4211 // component is no longer known. Most likely an update 4212 // to the app was installed and in the new version this 4213 // component no longer exists. Clean it up by removing 4214 // it from the preferred activities list, and skip it. 4215 Slog.w(TAG, "Removing dangling preferred activity: " 4216 + pa.mPref.mComponent); 4217 pir.removeFilter(pa); 4218 changed = true; 4219 continue; 4220 } 4221 for (int j=0; j<N; j++) { 4222 final ResolveInfo ri = query.get(j); 4223 if (!ri.activityInfo.applicationInfo.packageName 4224 .equals(ai.applicationInfo.packageName)) { 4225 continue; 4226 } 4227 if (!ri.activityInfo.name.equals(ai.name)) { 4228 continue; 4229 } 4230 4231 if (removeMatches) { 4232 pir.removeFilter(pa); 4233 changed = true; 4234 if (DEBUG_PREFERRED) { 4235 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4236 } 4237 break; 4238 } 4239 4240 // Okay we found a previously set preferred or last chosen app. 4241 // If the result set is different from when this 4242 // was created, we need to clear it and re-ask the 4243 // user their preference, if we're looking for an "always" type entry. 4244 if (always && !pa.mPref.sameSet(query)) { 4245 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4246 + intent + " type " + resolvedType); 4247 if (DEBUG_PREFERRED) { 4248 Slog.v(TAG, "Removing preferred activity since set changed " 4249 + pa.mPref.mComponent); 4250 } 4251 pir.removeFilter(pa); 4252 // Re-add the filter as a "last chosen" entry (!always) 4253 PreferredActivity lastChosen = new PreferredActivity( 4254 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4255 pir.addFilter(lastChosen); 4256 changed = true; 4257 return null; 4258 } 4259 4260 // Yay! Either the set matched or we're looking for the last chosen 4261 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4262 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4263 return ri; 4264 } 4265 } 4266 } finally { 4267 if (changed) { 4268 if (DEBUG_PREFERRED) { 4269 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4270 } 4271 scheduleWritePackageRestrictionsLocked(userId); 4272 } 4273 } 4274 } 4275 } 4276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4277 return null; 4278 } 4279 4280 /* 4281 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4282 */ 4283 @Override 4284 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4285 int targetUserId) { 4286 mContext.enforceCallingOrSelfPermission( 4287 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4288 List<CrossProfileIntentFilter> matches = 4289 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4290 if (matches != null) { 4291 int size = matches.size(); 4292 for (int i = 0; i < size; i++) { 4293 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4294 } 4295 } 4296 if (hasWebURI(intent)) { 4297 // cross-profile app linking works only towards the parent. 4298 final UserInfo parent = getProfileParent(sourceUserId); 4299 synchronized(mPackages) { 4300 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4301 parent.id) != null; 4302 } 4303 } 4304 return false; 4305 } 4306 4307 private UserInfo getProfileParent(int userId) { 4308 final long identity = Binder.clearCallingIdentity(); 4309 try { 4310 return sUserManager.getProfileParent(userId); 4311 } finally { 4312 Binder.restoreCallingIdentity(identity); 4313 } 4314 } 4315 4316 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4317 String resolvedType, int userId) { 4318 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4319 if (resolver != null) { 4320 return resolver.queryIntent(intent, resolvedType, false, userId); 4321 } 4322 return null; 4323 } 4324 4325 @Override 4326 public List<ResolveInfo> queryIntentActivities(Intent intent, 4327 String resolvedType, int flags, int userId) { 4328 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4329 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4330 ComponentName comp = intent.getComponent(); 4331 if (comp == null) { 4332 if (intent.getSelector() != null) { 4333 intent = intent.getSelector(); 4334 comp = intent.getComponent(); 4335 } 4336 } 4337 4338 if (comp != null) { 4339 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4340 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4341 if (ai != null) { 4342 final ResolveInfo ri = new ResolveInfo(); 4343 ri.activityInfo = ai; 4344 list.add(ri); 4345 } 4346 return list; 4347 } 4348 4349 // reader 4350 synchronized (mPackages) { 4351 final String pkgName = intent.getPackage(); 4352 if (pkgName == null) { 4353 List<CrossProfileIntentFilter> matchingFilters = 4354 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4355 // Check for results that need to skip the current profile. 4356 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4357 resolvedType, flags, userId); 4358 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4359 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4360 result.add(xpResolveInfo); 4361 return filterIfNotPrimaryUser(result, userId); 4362 } 4363 4364 // Check for results in the current profile. 4365 List<ResolveInfo> result = mActivities.queryIntent( 4366 intent, resolvedType, flags, userId); 4367 4368 // Check for cross profile results. 4369 xpResolveInfo = queryCrossProfileIntents( 4370 matchingFilters, intent, resolvedType, flags, userId); 4371 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4372 result.add(xpResolveInfo); 4373 Collections.sort(result, mResolvePrioritySorter); 4374 } 4375 result = filterIfNotPrimaryUser(result, userId); 4376 if (hasWebURI(intent)) { 4377 CrossProfileDomainInfo xpDomainInfo = null; 4378 final UserInfo parent = getProfileParent(userId); 4379 if (parent != null) { 4380 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4381 flags, userId, parent.id); 4382 } 4383 if (xpDomainInfo != null) { 4384 if (xpResolveInfo != null) { 4385 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4386 // in the result. 4387 result.remove(xpResolveInfo); 4388 } 4389 if (result.size() == 0) { 4390 result.add(xpDomainInfo.resolveInfo); 4391 return result; 4392 } 4393 } else if (result.size() <= 1) { 4394 return result; 4395 } 4396 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4397 xpDomainInfo); 4398 Collections.sort(result, mResolvePrioritySorter); 4399 } 4400 return result; 4401 } 4402 final PackageParser.Package pkg = mPackages.get(pkgName); 4403 if (pkg != null) { 4404 return filterIfNotPrimaryUser( 4405 mActivities.queryIntentForPackage( 4406 intent, resolvedType, flags, pkg.activities, userId), 4407 userId); 4408 } 4409 return new ArrayList<ResolveInfo>(); 4410 } 4411 } 4412 4413 private static class CrossProfileDomainInfo { 4414 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4415 ResolveInfo resolveInfo; 4416 /* Best domain verification status of the activities found in the other profile */ 4417 int bestDomainVerificationStatus; 4418 } 4419 4420 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4421 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4422 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4423 sourceUserId)) { 4424 return null; 4425 } 4426 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4427 resolvedType, flags, parentUserId); 4428 4429 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4430 return null; 4431 } 4432 CrossProfileDomainInfo result = null; 4433 int size = resultTargetUser.size(); 4434 for (int i = 0; i < size; i++) { 4435 ResolveInfo riTargetUser = resultTargetUser.get(i); 4436 // Intent filter verification is only for filters that specify a host. So don't return 4437 // those that handle all web uris. 4438 if (riTargetUser.handleAllWebDataURI) { 4439 continue; 4440 } 4441 String packageName = riTargetUser.activityInfo.packageName; 4442 PackageSetting ps = mSettings.mPackages.get(packageName); 4443 if (ps == null) { 4444 continue; 4445 } 4446 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4447 if (result == null) { 4448 result = new CrossProfileDomainInfo(); 4449 result.resolveInfo = 4450 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4451 result.bestDomainVerificationStatus = status; 4452 } else { 4453 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4454 result.bestDomainVerificationStatus); 4455 } 4456 } 4457 return result; 4458 } 4459 4460 /** 4461 * Verification statuses are ordered from the worse to the best, except for 4462 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4463 */ 4464 private int bestDomainVerificationStatus(int status1, int status2) { 4465 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4466 return status2; 4467 } 4468 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4469 return status1; 4470 } 4471 return (int) MathUtils.max(status1, status2); 4472 } 4473 4474 private boolean isUserEnabled(int userId) { 4475 long callingId = Binder.clearCallingIdentity(); 4476 try { 4477 UserInfo userInfo = sUserManager.getUserInfo(userId); 4478 return userInfo != null && userInfo.isEnabled(); 4479 } finally { 4480 Binder.restoreCallingIdentity(callingId); 4481 } 4482 } 4483 4484 /** 4485 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4486 * 4487 * @return filtered list 4488 */ 4489 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4490 if (userId == UserHandle.USER_OWNER) { 4491 return resolveInfos; 4492 } 4493 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4494 ResolveInfo info = resolveInfos.get(i); 4495 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4496 resolveInfos.remove(i); 4497 } 4498 } 4499 return resolveInfos; 4500 } 4501 4502 private static boolean hasWebURI(Intent intent) { 4503 if (intent.getData() == null) { 4504 return false; 4505 } 4506 final String scheme = intent.getScheme(); 4507 if (TextUtils.isEmpty(scheme)) { 4508 return false; 4509 } 4510 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4511 } 4512 4513 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4514 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4515 if (DEBUG_PREFERRED) { 4516 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4517 candidates.size()); 4518 } 4519 4520 final int userId = UserHandle.getCallingUserId(); 4521 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4522 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4523 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4524 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4525 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4526 4527 synchronized (mPackages) { 4528 final int count = candidates.size(); 4529 // First, try to use the domain preferred app. Partition the candidates into four lists: 4530 // one for the final results, one for the "do not use ever", one for "undefined status" 4531 // and finally one for "Browser App type". 4532 for (int n=0; n<count; n++) { 4533 ResolveInfo info = candidates.get(n); 4534 String packageName = info.activityInfo.packageName; 4535 PackageSetting ps = mSettings.mPackages.get(packageName); 4536 if (ps != null) { 4537 // Add to the special match all list (Browser use case) 4538 if (info.handleAllWebDataURI) { 4539 matchAllList.add(info); 4540 continue; 4541 } 4542 // Try to get the status from User settings first 4543 int status = getDomainVerificationStatusLPr(ps, userId); 4544 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4545 alwaysList.add(info); 4546 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4547 neverList.add(info); 4548 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4549 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4550 undefinedList.add(info); 4551 } 4552 } 4553 } 4554 // First try to add the "always" resolution for the current user if there is any 4555 if (alwaysList.size() > 0) { 4556 result.addAll(alwaysList); 4557 // if there is an "always" for the parent user, add it. 4558 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4559 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4560 result.add(xpDomainInfo.resolveInfo); 4561 } else { 4562 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4563 result.addAll(undefinedList); 4564 if (xpDomainInfo != null && ( 4565 xpDomainInfo.bestDomainVerificationStatus 4566 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4567 || xpDomainInfo.bestDomainVerificationStatus 4568 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4569 result.add(xpDomainInfo.resolveInfo); 4570 } 4571 // Also add Browsers (all of them or only the default one) 4572 if ((flags & MATCH_ALL) != 0) { 4573 result.addAll(matchAllList); 4574 } else { 4575 // Try to add the Default Browser if we can 4576 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4577 UserHandle.myUserId()); 4578 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4579 boolean defaultBrowserFound = false; 4580 final int browserCount = matchAllList.size(); 4581 for (int n=0; n<browserCount; n++) { 4582 ResolveInfo browser = matchAllList.get(n); 4583 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4584 result.add(browser); 4585 defaultBrowserFound = true; 4586 break; 4587 } 4588 } 4589 if (!defaultBrowserFound) { 4590 result.addAll(matchAllList); 4591 } 4592 } else { 4593 result.addAll(matchAllList); 4594 } 4595 } 4596 4597 // If there is nothing selected, add all candidates and remove the ones that the User 4598 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4599 if (result.size() == 0) { 4600 result.addAll(candidates); 4601 result.removeAll(neverList); 4602 } 4603 } 4604 } 4605 if (DEBUG_PREFERRED) { 4606 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4607 result.size()); 4608 } 4609 return result; 4610 } 4611 4612 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4613 int status = ps.getDomainVerificationStatusForUser(userId); 4614 // if none available, get the master status 4615 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4616 if (ps.getIntentFilterVerificationInfo() != null) { 4617 status = ps.getIntentFilterVerificationInfo().getStatus(); 4618 } 4619 } 4620 return status; 4621 } 4622 4623 private ResolveInfo querySkipCurrentProfileIntents( 4624 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4625 int flags, int sourceUserId) { 4626 if (matchingFilters != null) { 4627 int size = matchingFilters.size(); 4628 for (int i = 0; i < size; i ++) { 4629 CrossProfileIntentFilter filter = matchingFilters.get(i); 4630 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4631 // Checking if there are activities in the target user that can handle the 4632 // intent. 4633 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4634 flags, sourceUserId); 4635 if (resolveInfo != null) { 4636 return resolveInfo; 4637 } 4638 } 4639 } 4640 } 4641 return null; 4642 } 4643 4644 // Return matching ResolveInfo if any for skip current profile intent filters. 4645 private ResolveInfo queryCrossProfileIntents( 4646 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4647 int flags, int sourceUserId) { 4648 if (matchingFilters != null) { 4649 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4650 // match the same intent. For performance reasons, it is better not to 4651 // run queryIntent twice for the same userId 4652 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4653 int size = matchingFilters.size(); 4654 for (int i = 0; i < size; i++) { 4655 CrossProfileIntentFilter filter = matchingFilters.get(i); 4656 int targetUserId = filter.getTargetUserId(); 4657 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4658 && !alreadyTriedUserIds.get(targetUserId)) { 4659 // Checking if there are activities in the target user that can handle the 4660 // intent. 4661 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4662 flags, sourceUserId); 4663 if (resolveInfo != null) return resolveInfo; 4664 alreadyTriedUserIds.put(targetUserId, true); 4665 } 4666 } 4667 } 4668 return null; 4669 } 4670 4671 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4672 String resolvedType, int flags, int sourceUserId) { 4673 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4674 resolvedType, flags, filter.getTargetUserId()); 4675 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4676 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4677 } 4678 return null; 4679 } 4680 4681 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4682 int sourceUserId, int targetUserId) { 4683 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4684 String className; 4685 if (targetUserId == UserHandle.USER_OWNER) { 4686 className = FORWARD_INTENT_TO_USER_OWNER; 4687 } else { 4688 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4689 } 4690 ComponentName forwardingActivityComponentName = new ComponentName( 4691 mAndroidApplication.packageName, className); 4692 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4693 sourceUserId); 4694 if (targetUserId == UserHandle.USER_OWNER) { 4695 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4696 forwardingResolveInfo.noResourceId = true; 4697 } 4698 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4699 forwardingResolveInfo.priority = 0; 4700 forwardingResolveInfo.preferredOrder = 0; 4701 forwardingResolveInfo.match = 0; 4702 forwardingResolveInfo.isDefault = true; 4703 forwardingResolveInfo.filter = filter; 4704 forwardingResolveInfo.targetUserId = targetUserId; 4705 return forwardingResolveInfo; 4706 } 4707 4708 @Override 4709 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4710 Intent[] specifics, String[] specificTypes, Intent intent, 4711 String resolvedType, int flags, int userId) { 4712 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4713 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4714 false, "query intent activity options"); 4715 final String resultsAction = intent.getAction(); 4716 4717 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4718 | PackageManager.GET_RESOLVED_FILTER, userId); 4719 4720 if (DEBUG_INTENT_MATCHING) { 4721 Log.v(TAG, "Query " + intent + ": " + results); 4722 } 4723 4724 int specificsPos = 0; 4725 int N; 4726 4727 // todo: note that the algorithm used here is O(N^2). This 4728 // isn't a problem in our current environment, but if we start running 4729 // into situations where we have more than 5 or 10 matches then this 4730 // should probably be changed to something smarter... 4731 4732 // First we go through and resolve each of the specific items 4733 // that were supplied, taking care of removing any corresponding 4734 // duplicate items in the generic resolve list. 4735 if (specifics != null) { 4736 for (int i=0; i<specifics.length; i++) { 4737 final Intent sintent = specifics[i]; 4738 if (sintent == null) { 4739 continue; 4740 } 4741 4742 if (DEBUG_INTENT_MATCHING) { 4743 Log.v(TAG, "Specific #" + i + ": " + sintent); 4744 } 4745 4746 String action = sintent.getAction(); 4747 if (resultsAction != null && resultsAction.equals(action)) { 4748 // If this action was explicitly requested, then don't 4749 // remove things that have it. 4750 action = null; 4751 } 4752 4753 ResolveInfo ri = null; 4754 ActivityInfo ai = null; 4755 4756 ComponentName comp = sintent.getComponent(); 4757 if (comp == null) { 4758 ri = resolveIntent( 4759 sintent, 4760 specificTypes != null ? specificTypes[i] : null, 4761 flags, userId); 4762 if (ri == null) { 4763 continue; 4764 } 4765 if (ri == mResolveInfo) { 4766 // ACK! Must do something better with this. 4767 } 4768 ai = ri.activityInfo; 4769 comp = new ComponentName(ai.applicationInfo.packageName, 4770 ai.name); 4771 } else { 4772 ai = getActivityInfo(comp, flags, userId); 4773 if (ai == null) { 4774 continue; 4775 } 4776 } 4777 4778 // Look for any generic query activities that are duplicates 4779 // of this specific one, and remove them from the results. 4780 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4781 N = results.size(); 4782 int j; 4783 for (j=specificsPos; j<N; j++) { 4784 ResolveInfo sri = results.get(j); 4785 if ((sri.activityInfo.name.equals(comp.getClassName()) 4786 && sri.activityInfo.applicationInfo.packageName.equals( 4787 comp.getPackageName())) 4788 || (action != null && sri.filter.matchAction(action))) { 4789 results.remove(j); 4790 if (DEBUG_INTENT_MATCHING) Log.v( 4791 TAG, "Removing duplicate item from " + j 4792 + " due to specific " + specificsPos); 4793 if (ri == null) { 4794 ri = sri; 4795 } 4796 j--; 4797 N--; 4798 } 4799 } 4800 4801 // Add this specific item to its proper place. 4802 if (ri == null) { 4803 ri = new ResolveInfo(); 4804 ri.activityInfo = ai; 4805 } 4806 results.add(specificsPos, ri); 4807 ri.specificIndex = i; 4808 specificsPos++; 4809 } 4810 } 4811 4812 // Now we go through the remaining generic results and remove any 4813 // duplicate actions that are found here. 4814 N = results.size(); 4815 for (int i=specificsPos; i<N-1; i++) { 4816 final ResolveInfo rii = results.get(i); 4817 if (rii.filter == null) { 4818 continue; 4819 } 4820 4821 // Iterate over all of the actions of this result's intent 4822 // filter... typically this should be just one. 4823 final Iterator<String> it = rii.filter.actionsIterator(); 4824 if (it == null) { 4825 continue; 4826 } 4827 while (it.hasNext()) { 4828 final String action = it.next(); 4829 if (resultsAction != null && resultsAction.equals(action)) { 4830 // If this action was explicitly requested, then don't 4831 // remove things that have it. 4832 continue; 4833 } 4834 for (int j=i+1; j<N; j++) { 4835 final ResolveInfo rij = results.get(j); 4836 if (rij.filter != null && rij.filter.hasAction(action)) { 4837 results.remove(j); 4838 if (DEBUG_INTENT_MATCHING) Log.v( 4839 TAG, "Removing duplicate item from " + j 4840 + " due to action " + action + " at " + i); 4841 j--; 4842 N--; 4843 } 4844 } 4845 } 4846 4847 // If the caller didn't request filter information, drop it now 4848 // so we don't have to marshall/unmarshall it. 4849 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4850 rii.filter = null; 4851 } 4852 } 4853 4854 // Filter out the caller activity if so requested. 4855 if (caller != null) { 4856 N = results.size(); 4857 for (int i=0; i<N; i++) { 4858 ActivityInfo ainfo = results.get(i).activityInfo; 4859 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4860 && caller.getClassName().equals(ainfo.name)) { 4861 results.remove(i); 4862 break; 4863 } 4864 } 4865 } 4866 4867 // If the caller didn't request filter information, 4868 // drop them now so we don't have to 4869 // marshall/unmarshall it. 4870 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4871 N = results.size(); 4872 for (int i=0; i<N; i++) { 4873 results.get(i).filter = null; 4874 } 4875 } 4876 4877 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4878 return results; 4879 } 4880 4881 @Override 4882 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4883 int userId) { 4884 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4885 ComponentName comp = intent.getComponent(); 4886 if (comp == null) { 4887 if (intent.getSelector() != null) { 4888 intent = intent.getSelector(); 4889 comp = intent.getComponent(); 4890 } 4891 } 4892 if (comp != null) { 4893 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4894 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4895 if (ai != null) { 4896 ResolveInfo ri = new ResolveInfo(); 4897 ri.activityInfo = ai; 4898 list.add(ri); 4899 } 4900 return list; 4901 } 4902 4903 // reader 4904 synchronized (mPackages) { 4905 String pkgName = intent.getPackage(); 4906 if (pkgName == null) { 4907 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4908 } 4909 final PackageParser.Package pkg = mPackages.get(pkgName); 4910 if (pkg != null) { 4911 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4912 userId); 4913 } 4914 return null; 4915 } 4916 } 4917 4918 @Override 4919 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4920 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4921 if (!sUserManager.exists(userId)) return null; 4922 if (query != null) { 4923 if (query.size() >= 1) { 4924 // If there is more than one service with the same priority, 4925 // just arbitrarily pick the first one. 4926 return query.get(0); 4927 } 4928 } 4929 return null; 4930 } 4931 4932 @Override 4933 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4934 int userId) { 4935 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4936 ComponentName comp = intent.getComponent(); 4937 if (comp == null) { 4938 if (intent.getSelector() != null) { 4939 intent = intent.getSelector(); 4940 comp = intent.getComponent(); 4941 } 4942 } 4943 if (comp != null) { 4944 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4945 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4946 if (si != null) { 4947 final ResolveInfo ri = new ResolveInfo(); 4948 ri.serviceInfo = si; 4949 list.add(ri); 4950 } 4951 return list; 4952 } 4953 4954 // reader 4955 synchronized (mPackages) { 4956 String pkgName = intent.getPackage(); 4957 if (pkgName == null) { 4958 return mServices.queryIntent(intent, resolvedType, flags, userId); 4959 } 4960 final PackageParser.Package pkg = mPackages.get(pkgName); 4961 if (pkg != null) { 4962 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4963 userId); 4964 } 4965 return null; 4966 } 4967 } 4968 4969 @Override 4970 public List<ResolveInfo> queryIntentContentProviders( 4971 Intent intent, String resolvedType, int flags, int userId) { 4972 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4973 ComponentName comp = intent.getComponent(); 4974 if (comp == null) { 4975 if (intent.getSelector() != null) { 4976 intent = intent.getSelector(); 4977 comp = intent.getComponent(); 4978 } 4979 } 4980 if (comp != null) { 4981 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4982 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4983 if (pi != null) { 4984 final ResolveInfo ri = new ResolveInfo(); 4985 ri.providerInfo = pi; 4986 list.add(ri); 4987 } 4988 return list; 4989 } 4990 4991 // reader 4992 synchronized (mPackages) { 4993 String pkgName = intent.getPackage(); 4994 if (pkgName == null) { 4995 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4996 } 4997 final PackageParser.Package pkg = mPackages.get(pkgName); 4998 if (pkg != null) { 4999 return mProviders.queryIntentForPackage( 5000 intent, resolvedType, flags, pkg.providers, userId); 5001 } 5002 return null; 5003 } 5004 } 5005 5006 @Override 5007 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5008 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5009 5010 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5011 5012 // writer 5013 synchronized (mPackages) { 5014 ArrayList<PackageInfo> list; 5015 if (listUninstalled) { 5016 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5017 for (PackageSetting ps : mSettings.mPackages.values()) { 5018 PackageInfo pi; 5019 if (ps.pkg != null) { 5020 pi = generatePackageInfo(ps.pkg, flags, userId); 5021 } else { 5022 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5023 } 5024 if (pi != null) { 5025 list.add(pi); 5026 } 5027 } 5028 } else { 5029 list = new ArrayList<PackageInfo>(mPackages.size()); 5030 for (PackageParser.Package p : mPackages.values()) { 5031 PackageInfo pi = generatePackageInfo(p, flags, userId); 5032 if (pi != null) { 5033 list.add(pi); 5034 } 5035 } 5036 } 5037 5038 return new ParceledListSlice<PackageInfo>(list); 5039 } 5040 } 5041 5042 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5043 String[] permissions, boolean[] tmp, int flags, int userId) { 5044 int numMatch = 0; 5045 final PermissionsState permissionsState = ps.getPermissionsState(); 5046 for (int i=0; i<permissions.length; i++) { 5047 final String permission = permissions[i]; 5048 if (permissionsState.hasPermission(permission, userId)) { 5049 tmp[i] = true; 5050 numMatch++; 5051 } else { 5052 tmp[i] = false; 5053 } 5054 } 5055 if (numMatch == 0) { 5056 return; 5057 } 5058 PackageInfo pi; 5059 if (ps.pkg != null) { 5060 pi = generatePackageInfo(ps.pkg, flags, userId); 5061 } else { 5062 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5063 } 5064 // The above might return null in cases of uninstalled apps or install-state 5065 // skew across users/profiles. 5066 if (pi != null) { 5067 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5068 if (numMatch == permissions.length) { 5069 pi.requestedPermissions = permissions; 5070 } else { 5071 pi.requestedPermissions = new String[numMatch]; 5072 numMatch = 0; 5073 for (int i=0; i<permissions.length; i++) { 5074 if (tmp[i]) { 5075 pi.requestedPermissions[numMatch] = permissions[i]; 5076 numMatch++; 5077 } 5078 } 5079 } 5080 } 5081 list.add(pi); 5082 } 5083 } 5084 5085 @Override 5086 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5087 String[] permissions, int flags, int userId) { 5088 if (!sUserManager.exists(userId)) return null; 5089 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5090 5091 // writer 5092 synchronized (mPackages) { 5093 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5094 boolean[] tmpBools = new boolean[permissions.length]; 5095 if (listUninstalled) { 5096 for (PackageSetting ps : mSettings.mPackages.values()) { 5097 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5098 } 5099 } else { 5100 for (PackageParser.Package pkg : mPackages.values()) { 5101 PackageSetting ps = (PackageSetting)pkg.mExtras; 5102 if (ps != null) { 5103 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5104 userId); 5105 } 5106 } 5107 } 5108 5109 return new ParceledListSlice<PackageInfo>(list); 5110 } 5111 } 5112 5113 @Override 5114 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5115 if (!sUserManager.exists(userId)) return null; 5116 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5117 5118 // writer 5119 synchronized (mPackages) { 5120 ArrayList<ApplicationInfo> list; 5121 if (listUninstalled) { 5122 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5123 for (PackageSetting ps : mSettings.mPackages.values()) { 5124 ApplicationInfo ai; 5125 if (ps.pkg != null) { 5126 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5127 ps.readUserState(userId), userId); 5128 } else { 5129 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5130 } 5131 if (ai != null) { 5132 list.add(ai); 5133 } 5134 } 5135 } else { 5136 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5137 for (PackageParser.Package p : mPackages.values()) { 5138 if (p.mExtras != null) { 5139 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5140 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5141 if (ai != null) { 5142 list.add(ai); 5143 } 5144 } 5145 } 5146 } 5147 5148 return new ParceledListSlice<ApplicationInfo>(list); 5149 } 5150 } 5151 5152 public List<ApplicationInfo> getPersistentApplications(int flags) { 5153 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5154 5155 // reader 5156 synchronized (mPackages) { 5157 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5158 final int userId = UserHandle.getCallingUserId(); 5159 while (i.hasNext()) { 5160 final PackageParser.Package p = i.next(); 5161 if (p.applicationInfo != null 5162 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5163 && (!mSafeMode || isSystemApp(p))) { 5164 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5165 if (ps != null) { 5166 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5167 ps.readUserState(userId), userId); 5168 if (ai != null) { 5169 finalList.add(ai); 5170 } 5171 } 5172 } 5173 } 5174 } 5175 5176 return finalList; 5177 } 5178 5179 @Override 5180 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5181 if (!sUserManager.exists(userId)) return null; 5182 // reader 5183 synchronized (mPackages) { 5184 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5185 PackageSetting ps = provider != null 5186 ? mSettings.mPackages.get(provider.owner.packageName) 5187 : null; 5188 return ps != null 5189 && mSettings.isEnabledLPr(provider.info, flags, userId) 5190 && (!mSafeMode || (provider.info.applicationInfo.flags 5191 &ApplicationInfo.FLAG_SYSTEM) != 0) 5192 ? PackageParser.generateProviderInfo(provider, flags, 5193 ps.readUserState(userId), userId) 5194 : null; 5195 } 5196 } 5197 5198 /** 5199 * @deprecated 5200 */ 5201 @Deprecated 5202 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5203 // reader 5204 synchronized (mPackages) { 5205 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5206 .entrySet().iterator(); 5207 final int userId = UserHandle.getCallingUserId(); 5208 while (i.hasNext()) { 5209 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5210 PackageParser.Provider p = entry.getValue(); 5211 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5212 5213 if (ps != null && p.syncable 5214 && (!mSafeMode || (p.info.applicationInfo.flags 5215 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5216 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5217 ps.readUserState(userId), userId); 5218 if (info != null) { 5219 outNames.add(entry.getKey()); 5220 outInfo.add(info); 5221 } 5222 } 5223 } 5224 } 5225 } 5226 5227 @Override 5228 public List<ProviderInfo> queryContentProviders(String processName, 5229 int uid, int flags) { 5230 ArrayList<ProviderInfo> finalList = null; 5231 // reader 5232 synchronized (mPackages) { 5233 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5234 final int userId = processName != null ? 5235 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5236 while (i.hasNext()) { 5237 final PackageParser.Provider p = i.next(); 5238 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5239 if (ps != null && p.info.authority != null 5240 && (processName == null 5241 || (p.info.processName.equals(processName) 5242 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5243 && mSettings.isEnabledLPr(p.info, flags, userId) 5244 && (!mSafeMode 5245 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5246 if (finalList == null) { 5247 finalList = new ArrayList<ProviderInfo>(3); 5248 } 5249 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5250 ps.readUserState(userId), userId); 5251 if (info != null) { 5252 finalList.add(info); 5253 } 5254 } 5255 } 5256 } 5257 5258 if (finalList != null) { 5259 Collections.sort(finalList, mProviderInitOrderSorter); 5260 } 5261 5262 return finalList; 5263 } 5264 5265 @Override 5266 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5267 int flags) { 5268 // reader 5269 synchronized (mPackages) { 5270 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5271 return PackageParser.generateInstrumentationInfo(i, flags); 5272 } 5273 } 5274 5275 @Override 5276 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5277 int flags) { 5278 ArrayList<InstrumentationInfo> finalList = 5279 new ArrayList<InstrumentationInfo>(); 5280 5281 // reader 5282 synchronized (mPackages) { 5283 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5284 while (i.hasNext()) { 5285 final PackageParser.Instrumentation p = i.next(); 5286 if (targetPackage == null 5287 || targetPackage.equals(p.info.targetPackage)) { 5288 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5289 flags); 5290 if (ii != null) { 5291 finalList.add(ii); 5292 } 5293 } 5294 } 5295 } 5296 5297 return finalList; 5298 } 5299 5300 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5301 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5302 if (overlays == null) { 5303 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5304 return; 5305 } 5306 for (PackageParser.Package opkg : overlays.values()) { 5307 // Not much to do if idmap fails: we already logged the error 5308 // and we certainly don't want to abort installation of pkg simply 5309 // because an overlay didn't fit properly. For these reasons, 5310 // ignore the return value of createIdmapForPackagePairLI. 5311 createIdmapForPackagePairLI(pkg, opkg); 5312 } 5313 } 5314 5315 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5316 PackageParser.Package opkg) { 5317 if (!opkg.mTrustedOverlay) { 5318 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5319 opkg.baseCodePath + ": overlay not trusted"); 5320 return false; 5321 } 5322 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5323 if (overlaySet == null) { 5324 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5325 opkg.baseCodePath + " but target package has no known overlays"); 5326 return false; 5327 } 5328 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5329 // TODO: generate idmap for split APKs 5330 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5331 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5332 + opkg.baseCodePath); 5333 return false; 5334 } 5335 PackageParser.Package[] overlayArray = 5336 overlaySet.values().toArray(new PackageParser.Package[0]); 5337 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5338 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5339 return p1.mOverlayPriority - p2.mOverlayPriority; 5340 } 5341 }; 5342 Arrays.sort(overlayArray, cmp); 5343 5344 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5345 int i = 0; 5346 for (PackageParser.Package p : overlayArray) { 5347 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5348 } 5349 return true; 5350 } 5351 5352 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5353 final File[] files = dir.listFiles(); 5354 if (ArrayUtils.isEmpty(files)) { 5355 Log.d(TAG, "No files in app dir " + dir); 5356 return; 5357 } 5358 5359 if (DEBUG_PACKAGE_SCANNING) { 5360 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5361 + " flags=0x" + Integer.toHexString(parseFlags)); 5362 } 5363 5364 for (File file : files) { 5365 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5366 && !PackageInstallerService.isStageName(file.getName()); 5367 if (!isPackage) { 5368 // Ignore entries which are not packages 5369 continue; 5370 } 5371 try { 5372 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5373 scanFlags, currentTime, null); 5374 } catch (PackageManagerException e) { 5375 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5376 5377 // Delete invalid userdata apps 5378 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5379 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5380 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5381 if (file.isDirectory()) { 5382 mInstaller.rmPackageDir(file.getAbsolutePath()); 5383 } else { 5384 file.delete(); 5385 } 5386 } 5387 } 5388 } 5389 } 5390 5391 private static File getSettingsProblemFile() { 5392 File dataDir = Environment.getDataDirectory(); 5393 File systemDir = new File(dataDir, "system"); 5394 File fname = new File(systemDir, "uiderrors.txt"); 5395 return fname; 5396 } 5397 5398 static void reportSettingsProblem(int priority, String msg) { 5399 logCriticalInfo(priority, msg); 5400 } 5401 5402 static void logCriticalInfo(int priority, String msg) { 5403 Slog.println(priority, TAG, msg); 5404 EventLogTags.writePmCriticalInfo(msg); 5405 try { 5406 File fname = getSettingsProblemFile(); 5407 FileOutputStream out = new FileOutputStream(fname, true); 5408 PrintWriter pw = new FastPrintWriter(out); 5409 SimpleDateFormat formatter = new SimpleDateFormat(); 5410 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5411 pw.println(dateString + ": " + msg); 5412 pw.close(); 5413 FileUtils.setPermissions( 5414 fname.toString(), 5415 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5416 -1, -1); 5417 } catch (java.io.IOException e) { 5418 } 5419 } 5420 5421 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5422 PackageParser.Package pkg, File srcFile, int parseFlags) 5423 throws PackageManagerException { 5424 if (ps != null 5425 && ps.codePath.equals(srcFile) 5426 && ps.timeStamp == srcFile.lastModified() 5427 && !isCompatSignatureUpdateNeeded(pkg) 5428 && !isRecoverSignatureUpdateNeeded(pkg)) { 5429 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5430 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5431 ArraySet<PublicKey> signingKs; 5432 synchronized (mPackages) { 5433 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5434 } 5435 if (ps.signatures.mSignatures != null 5436 && ps.signatures.mSignatures.length != 0 5437 && signingKs != null) { 5438 // Optimization: reuse the existing cached certificates 5439 // if the package appears to be unchanged. 5440 pkg.mSignatures = ps.signatures.mSignatures; 5441 pkg.mSigningKeys = signingKs; 5442 return; 5443 } 5444 5445 Slog.w(TAG, "PackageSetting for " + ps.name 5446 + " is missing signatures. Collecting certs again to recover them."); 5447 } else { 5448 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5449 } 5450 5451 try { 5452 pp.collectCertificates(pkg, parseFlags); 5453 pp.collectManifestDigest(pkg); 5454 } catch (PackageParserException e) { 5455 throw PackageManagerException.from(e); 5456 } 5457 } 5458 5459 /* 5460 * Scan a package and return the newly parsed package. 5461 * Returns null in case of errors and the error code is stored in mLastScanError 5462 */ 5463 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5464 long currentTime, UserHandle user) throws PackageManagerException { 5465 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5466 parseFlags |= mDefParseFlags; 5467 PackageParser pp = new PackageParser(); 5468 pp.setSeparateProcesses(mSeparateProcesses); 5469 pp.setOnlyCoreApps(mOnlyCore); 5470 pp.setDisplayMetrics(mMetrics); 5471 5472 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5473 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5474 } 5475 5476 final PackageParser.Package pkg; 5477 try { 5478 pkg = pp.parsePackage(scanFile, parseFlags); 5479 } catch (PackageParserException e) { 5480 throw PackageManagerException.from(e); 5481 } 5482 5483 PackageSetting ps = null; 5484 PackageSetting updatedPkg; 5485 // reader 5486 synchronized (mPackages) { 5487 // Look to see if we already know about this package. 5488 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5489 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5490 // This package has been renamed to its original name. Let's 5491 // use that. 5492 ps = mSettings.peekPackageLPr(oldName); 5493 } 5494 // If there was no original package, see one for the real package name. 5495 if (ps == null) { 5496 ps = mSettings.peekPackageLPr(pkg.packageName); 5497 } 5498 // Check to see if this package could be hiding/updating a system 5499 // package. Must look for it either under the original or real 5500 // package name depending on our state. 5501 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5502 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5503 } 5504 boolean updatedPkgBetter = false; 5505 // First check if this is a system package that may involve an update 5506 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5507 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5508 // it needs to drop FLAG_PRIVILEGED. 5509 if (locationIsPrivileged(scanFile)) { 5510 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5511 } else { 5512 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5513 } 5514 5515 if (ps != null && !ps.codePath.equals(scanFile)) { 5516 // The path has changed from what was last scanned... check the 5517 // version of the new path against what we have stored to determine 5518 // what to do. 5519 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5520 if (pkg.mVersionCode <= ps.versionCode) { 5521 // The system package has been updated and the code path does not match 5522 // Ignore entry. Skip it. 5523 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5524 + " ignored: updated version " + ps.versionCode 5525 + " better than this " + pkg.mVersionCode); 5526 if (!updatedPkg.codePath.equals(scanFile)) { 5527 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5528 + ps.name + " changing from " + updatedPkg.codePathString 5529 + " to " + scanFile); 5530 updatedPkg.codePath = scanFile; 5531 updatedPkg.codePathString = scanFile.toString(); 5532 updatedPkg.resourcePath = scanFile; 5533 updatedPkg.resourcePathString = scanFile.toString(); 5534 } 5535 updatedPkg.pkg = pkg; 5536 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5537 } else { 5538 // The current app on the system partition is better than 5539 // what we have updated to on the data partition; switch 5540 // back to the system partition version. 5541 // At this point, its safely assumed that package installation for 5542 // apps in system partition will go through. If not there won't be a working 5543 // version of the app 5544 // writer 5545 synchronized (mPackages) { 5546 // Just remove the loaded entries from package lists. 5547 mPackages.remove(ps.name); 5548 } 5549 5550 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5551 + " reverting from " + ps.codePathString 5552 + ": new version " + pkg.mVersionCode 5553 + " better than installed " + ps.versionCode); 5554 5555 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5556 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5557 synchronized (mInstallLock) { 5558 args.cleanUpResourcesLI(); 5559 } 5560 synchronized (mPackages) { 5561 mSettings.enableSystemPackageLPw(ps.name); 5562 } 5563 updatedPkgBetter = true; 5564 } 5565 } 5566 } 5567 5568 if (updatedPkg != null) { 5569 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5570 // initially 5571 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5572 5573 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5574 // flag set initially 5575 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5576 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5577 } 5578 } 5579 5580 // Verify certificates against what was last scanned 5581 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5582 5583 /* 5584 * A new system app appeared, but we already had a non-system one of the 5585 * same name installed earlier. 5586 */ 5587 boolean shouldHideSystemApp = false; 5588 if (updatedPkg == null && ps != null 5589 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5590 /* 5591 * Check to make sure the signatures match first. If they don't, 5592 * wipe the installed application and its data. 5593 */ 5594 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5595 != PackageManager.SIGNATURE_MATCH) { 5596 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5597 + " signatures don't match existing userdata copy; removing"); 5598 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5599 ps = null; 5600 } else { 5601 /* 5602 * If the newly-added system app is an older version than the 5603 * already installed version, hide it. It will be scanned later 5604 * and re-added like an update. 5605 */ 5606 if (pkg.mVersionCode <= ps.versionCode) { 5607 shouldHideSystemApp = true; 5608 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5609 + " but new version " + pkg.mVersionCode + " better than installed " 5610 + ps.versionCode + "; hiding system"); 5611 } else { 5612 /* 5613 * The newly found system app is a newer version that the 5614 * one previously installed. Simply remove the 5615 * already-installed application and replace it with our own 5616 * while keeping the application data. 5617 */ 5618 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5619 + " reverting from " + ps.codePathString + ": new version " 5620 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5621 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5622 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5623 synchronized (mInstallLock) { 5624 args.cleanUpResourcesLI(); 5625 } 5626 } 5627 } 5628 } 5629 5630 // The apk is forward locked (not public) if its code and resources 5631 // are kept in different files. (except for app in either system or 5632 // vendor path). 5633 // TODO grab this value from PackageSettings 5634 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5635 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5636 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5637 } 5638 } 5639 5640 // TODO: extend to support forward-locked splits 5641 String resourcePath = null; 5642 String baseResourcePath = null; 5643 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5644 if (ps != null && ps.resourcePathString != null) { 5645 resourcePath = ps.resourcePathString; 5646 baseResourcePath = ps.resourcePathString; 5647 } else { 5648 // Should not happen at all. Just log an error. 5649 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5650 } 5651 } else { 5652 resourcePath = pkg.codePath; 5653 baseResourcePath = pkg.baseCodePath; 5654 } 5655 5656 // Set application objects path explicitly. 5657 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5658 pkg.applicationInfo.setCodePath(pkg.codePath); 5659 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5660 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5661 pkg.applicationInfo.setResourcePath(resourcePath); 5662 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5663 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5664 5665 // Note that we invoke the following method only if we are about to unpack an application 5666 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5667 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5668 5669 /* 5670 * If the system app should be overridden by a previously installed 5671 * data, hide the system app now and let the /data/app scan pick it up 5672 * again. 5673 */ 5674 if (shouldHideSystemApp) { 5675 synchronized (mPackages) { 5676 /* 5677 * We have to grant systems permissions before we hide, because 5678 * grantPermissions will assume the package update is trying to 5679 * expand its permissions. 5680 */ 5681 grantPermissionsLPw(pkg, true, pkg.packageName); 5682 mSettings.disableSystemPackageLPw(pkg.packageName); 5683 } 5684 } 5685 5686 return scannedPkg; 5687 } 5688 5689 private static String fixProcessName(String defProcessName, 5690 String processName, int uid) { 5691 if (processName == null) { 5692 return defProcessName; 5693 } 5694 return processName; 5695 } 5696 5697 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5698 throws PackageManagerException { 5699 if (pkgSetting.signatures.mSignatures != null) { 5700 // Already existing package. Make sure signatures match 5701 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5702 == PackageManager.SIGNATURE_MATCH; 5703 if (!match) { 5704 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5705 == PackageManager.SIGNATURE_MATCH; 5706 } 5707 if (!match) { 5708 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5709 == PackageManager.SIGNATURE_MATCH; 5710 } 5711 if (!match) { 5712 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5713 + pkg.packageName + " signatures do not match the " 5714 + "previously installed version; ignoring!"); 5715 } 5716 } 5717 5718 // Check for shared user signatures 5719 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5720 // Already existing package. Make sure signatures match 5721 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5722 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5723 if (!match) { 5724 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5725 == PackageManager.SIGNATURE_MATCH; 5726 } 5727 if (!match) { 5728 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5729 == PackageManager.SIGNATURE_MATCH; 5730 } 5731 if (!match) { 5732 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5733 "Package " + pkg.packageName 5734 + " has no signatures that match those in shared user " 5735 + pkgSetting.sharedUser.name + "; ignoring!"); 5736 } 5737 } 5738 } 5739 5740 /** 5741 * Enforces that only the system UID or root's UID can call a method exposed 5742 * via Binder. 5743 * 5744 * @param message used as message if SecurityException is thrown 5745 * @throws SecurityException if the caller is not system or root 5746 */ 5747 private static final void enforceSystemOrRoot(String message) { 5748 final int uid = Binder.getCallingUid(); 5749 if (uid != Process.SYSTEM_UID && uid != 0) { 5750 throw new SecurityException(message); 5751 } 5752 } 5753 5754 @Override 5755 public void performBootDexOpt() { 5756 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5757 5758 // Before everything else, see whether we need to fstrim. 5759 try { 5760 IMountService ms = PackageHelper.getMountService(); 5761 if (ms != null) { 5762 final boolean isUpgrade = isUpgrade(); 5763 boolean doTrim = isUpgrade; 5764 if (doTrim) { 5765 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5766 } else { 5767 final long interval = android.provider.Settings.Global.getLong( 5768 mContext.getContentResolver(), 5769 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5770 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5771 if (interval > 0) { 5772 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5773 if (timeSinceLast > interval) { 5774 doTrim = true; 5775 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5776 + "; running immediately"); 5777 } 5778 } 5779 } 5780 if (doTrim) { 5781 if (!isFirstBoot()) { 5782 try { 5783 ActivityManagerNative.getDefault().showBootMessage( 5784 mContext.getResources().getString( 5785 R.string.android_upgrading_fstrim), true); 5786 } catch (RemoteException e) { 5787 } 5788 } 5789 ms.runMaintenance(); 5790 } 5791 } else { 5792 Slog.e(TAG, "Mount service unavailable!"); 5793 } 5794 } catch (RemoteException e) { 5795 // Can't happen; MountService is local 5796 } 5797 5798 final ArraySet<PackageParser.Package> pkgs; 5799 synchronized (mPackages) { 5800 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5801 } 5802 5803 if (pkgs != null) { 5804 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5805 // in case the device runs out of space. 5806 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5807 // Give priority to core apps. 5808 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5809 PackageParser.Package pkg = it.next(); 5810 if (pkg.coreApp) { 5811 if (DEBUG_DEXOPT) { 5812 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5813 } 5814 sortedPkgs.add(pkg); 5815 it.remove(); 5816 } 5817 } 5818 // Give priority to system apps that listen for pre boot complete. 5819 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5820 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5821 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5822 PackageParser.Package pkg = it.next(); 5823 if (pkgNames.contains(pkg.packageName)) { 5824 if (DEBUG_DEXOPT) { 5825 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5826 } 5827 sortedPkgs.add(pkg); 5828 it.remove(); 5829 } 5830 } 5831 // Give priority to system apps. 5832 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5833 PackageParser.Package pkg = it.next(); 5834 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5835 if (DEBUG_DEXOPT) { 5836 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5837 } 5838 sortedPkgs.add(pkg); 5839 it.remove(); 5840 } 5841 } 5842 // Give priority to updated system apps. 5843 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5844 PackageParser.Package pkg = it.next(); 5845 if (pkg.isUpdatedSystemApp()) { 5846 if (DEBUG_DEXOPT) { 5847 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5848 } 5849 sortedPkgs.add(pkg); 5850 it.remove(); 5851 } 5852 } 5853 // Give priority to apps that listen for boot complete. 5854 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5855 pkgNames = getPackageNamesForIntent(intent); 5856 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5857 PackageParser.Package pkg = it.next(); 5858 if (pkgNames.contains(pkg.packageName)) { 5859 if (DEBUG_DEXOPT) { 5860 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5861 } 5862 sortedPkgs.add(pkg); 5863 it.remove(); 5864 } 5865 } 5866 // Filter out packages that aren't recently used. 5867 filterRecentlyUsedApps(pkgs); 5868 // Add all remaining apps. 5869 for (PackageParser.Package pkg : pkgs) { 5870 if (DEBUG_DEXOPT) { 5871 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5872 } 5873 sortedPkgs.add(pkg); 5874 } 5875 5876 // If we want to be lazy, filter everything that wasn't recently used. 5877 if (mLazyDexOpt) { 5878 filterRecentlyUsedApps(sortedPkgs); 5879 } 5880 5881 int i = 0; 5882 int total = sortedPkgs.size(); 5883 File dataDir = Environment.getDataDirectory(); 5884 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5885 if (lowThreshold == 0) { 5886 throw new IllegalStateException("Invalid low memory threshold"); 5887 } 5888 for (PackageParser.Package pkg : sortedPkgs) { 5889 long usableSpace = dataDir.getUsableSpace(); 5890 if (usableSpace < lowThreshold) { 5891 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5892 break; 5893 } 5894 performBootDexOpt(pkg, ++i, total); 5895 } 5896 } 5897 } 5898 5899 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5900 // Filter out packages that aren't recently used. 5901 // 5902 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5903 // should do a full dexopt. 5904 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5905 int total = pkgs.size(); 5906 int skipped = 0; 5907 long now = System.currentTimeMillis(); 5908 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5909 PackageParser.Package pkg = i.next(); 5910 long then = pkg.mLastPackageUsageTimeInMills; 5911 if (then + mDexOptLRUThresholdInMills < now) { 5912 if (DEBUG_DEXOPT) { 5913 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5914 ((then == 0) ? "never" : new Date(then))); 5915 } 5916 i.remove(); 5917 skipped++; 5918 } 5919 } 5920 if (DEBUG_DEXOPT) { 5921 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5922 } 5923 } 5924 } 5925 5926 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5927 List<ResolveInfo> ris = null; 5928 try { 5929 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5930 intent, null, 0, UserHandle.USER_OWNER); 5931 } catch (RemoteException e) { 5932 } 5933 ArraySet<String> pkgNames = new ArraySet<String>(); 5934 if (ris != null) { 5935 for (ResolveInfo ri : ris) { 5936 pkgNames.add(ri.activityInfo.packageName); 5937 } 5938 } 5939 return pkgNames; 5940 } 5941 5942 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5943 if (DEBUG_DEXOPT) { 5944 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5945 } 5946 if (!isFirstBoot()) { 5947 try { 5948 ActivityManagerNative.getDefault().showBootMessage( 5949 mContext.getResources().getString(R.string.android_upgrading_apk, 5950 curr, total), true); 5951 } catch (RemoteException e) { 5952 } 5953 } 5954 PackageParser.Package p = pkg; 5955 synchronized (mInstallLock) { 5956 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5957 false /* force dex */, false /* defer */, true /* include dependencies */); 5958 } 5959 } 5960 5961 @Override 5962 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5963 return performDexOpt(packageName, instructionSet, false); 5964 } 5965 5966 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5967 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5968 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5969 if (!dexopt && !updateUsage) { 5970 // We aren't going to dexopt or update usage, so bail early. 5971 return false; 5972 } 5973 PackageParser.Package p; 5974 final String targetInstructionSet; 5975 synchronized (mPackages) { 5976 p = mPackages.get(packageName); 5977 if (p == null) { 5978 return false; 5979 } 5980 if (updateUsage) { 5981 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5982 } 5983 mPackageUsage.write(false); 5984 if (!dexopt) { 5985 // We aren't going to dexopt, so bail early. 5986 return false; 5987 } 5988 5989 targetInstructionSet = instructionSet != null ? instructionSet : 5990 getPrimaryInstructionSet(p.applicationInfo); 5991 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5992 return false; 5993 } 5994 } 5995 5996 synchronized (mInstallLock) { 5997 final String[] instructionSets = new String[] { targetInstructionSet }; 5998 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5999 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6000 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6001 } 6002 } 6003 6004 public ArraySet<String> getPackagesThatNeedDexOpt() { 6005 ArraySet<String> pkgs = null; 6006 synchronized (mPackages) { 6007 for (PackageParser.Package p : mPackages.values()) { 6008 if (DEBUG_DEXOPT) { 6009 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6010 } 6011 if (!p.mDexOptPerformed.isEmpty()) { 6012 continue; 6013 } 6014 if (pkgs == null) { 6015 pkgs = new ArraySet<String>(); 6016 } 6017 pkgs.add(p.packageName); 6018 } 6019 } 6020 return pkgs; 6021 } 6022 6023 public void shutdown() { 6024 mPackageUsage.write(true); 6025 } 6026 6027 @Override 6028 public void forceDexOpt(String packageName) { 6029 enforceSystemOrRoot("forceDexOpt"); 6030 6031 PackageParser.Package pkg; 6032 synchronized (mPackages) { 6033 pkg = mPackages.get(packageName); 6034 if (pkg == null) { 6035 throw new IllegalArgumentException("Missing package: " + packageName); 6036 } 6037 } 6038 6039 synchronized (mInstallLock) { 6040 final String[] instructionSets = new String[] { 6041 getPrimaryInstructionSet(pkg.applicationInfo) }; 6042 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6043 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6044 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6045 throw new IllegalStateException("Failed to dexopt: " + res); 6046 } 6047 } 6048 } 6049 6050 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6051 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6052 Slog.w(TAG, "Unable to update from " + oldPkg.name 6053 + " to " + newPkg.packageName 6054 + ": old package not in system partition"); 6055 return false; 6056 } else if (mPackages.get(oldPkg.name) != null) { 6057 Slog.w(TAG, "Unable to update from " + oldPkg.name 6058 + " to " + newPkg.packageName 6059 + ": old package still exists"); 6060 return false; 6061 } 6062 return true; 6063 } 6064 6065 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6066 int[] users = sUserManager.getUserIds(); 6067 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6068 if (res < 0) { 6069 return res; 6070 } 6071 for (int user : users) { 6072 if (user != 0) { 6073 res = mInstaller.createUserData(volumeUuid, packageName, 6074 UserHandle.getUid(user, uid), user, seinfo); 6075 if (res < 0) { 6076 return res; 6077 } 6078 } 6079 } 6080 return res; 6081 } 6082 6083 private int removeDataDirsLI(String volumeUuid, String packageName) { 6084 int[] users = sUserManager.getUserIds(); 6085 int res = 0; 6086 for (int user : users) { 6087 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6088 if (resInner < 0) { 6089 res = resInner; 6090 } 6091 } 6092 6093 return res; 6094 } 6095 6096 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6097 int[] users = sUserManager.getUserIds(); 6098 int res = 0; 6099 for (int user : users) { 6100 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6101 if (resInner < 0) { 6102 res = resInner; 6103 } 6104 } 6105 return res; 6106 } 6107 6108 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6109 PackageParser.Package changingLib) { 6110 if (file.path != null) { 6111 usesLibraryFiles.add(file.path); 6112 return; 6113 } 6114 PackageParser.Package p = mPackages.get(file.apk); 6115 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6116 // If we are doing this while in the middle of updating a library apk, 6117 // then we need to make sure to use that new apk for determining the 6118 // dependencies here. (We haven't yet finished committing the new apk 6119 // to the package manager state.) 6120 if (p == null || p.packageName.equals(changingLib.packageName)) { 6121 p = changingLib; 6122 } 6123 } 6124 if (p != null) { 6125 usesLibraryFiles.addAll(p.getAllCodePaths()); 6126 } 6127 } 6128 6129 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6130 PackageParser.Package changingLib) throws PackageManagerException { 6131 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6132 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6133 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6134 for (int i=0; i<N; i++) { 6135 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6136 if (file == null) { 6137 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6138 "Package " + pkg.packageName + " requires unavailable shared library " 6139 + pkg.usesLibraries.get(i) + "; failing!"); 6140 } 6141 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6142 } 6143 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6144 for (int i=0; i<N; i++) { 6145 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6146 if (file == null) { 6147 Slog.w(TAG, "Package " + pkg.packageName 6148 + " desires unavailable shared library " 6149 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6150 } else { 6151 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6152 } 6153 } 6154 N = usesLibraryFiles.size(); 6155 if (N > 0) { 6156 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6157 } else { 6158 pkg.usesLibraryFiles = null; 6159 } 6160 } 6161 } 6162 6163 private static boolean hasString(List<String> list, List<String> which) { 6164 if (list == null) { 6165 return false; 6166 } 6167 for (int i=list.size()-1; i>=0; i--) { 6168 for (int j=which.size()-1; j>=0; j--) { 6169 if (which.get(j).equals(list.get(i))) { 6170 return true; 6171 } 6172 } 6173 } 6174 return false; 6175 } 6176 6177 private void updateAllSharedLibrariesLPw() { 6178 for (PackageParser.Package pkg : mPackages.values()) { 6179 try { 6180 updateSharedLibrariesLPw(pkg, null); 6181 } catch (PackageManagerException e) { 6182 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6183 } 6184 } 6185 } 6186 6187 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6188 PackageParser.Package changingPkg) { 6189 ArrayList<PackageParser.Package> res = null; 6190 for (PackageParser.Package pkg : mPackages.values()) { 6191 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6192 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6193 if (res == null) { 6194 res = new ArrayList<PackageParser.Package>(); 6195 } 6196 res.add(pkg); 6197 try { 6198 updateSharedLibrariesLPw(pkg, changingPkg); 6199 } catch (PackageManagerException e) { 6200 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6201 } 6202 } 6203 } 6204 return res; 6205 } 6206 6207 /** 6208 * Derive the value of the {@code cpuAbiOverride} based on the provided 6209 * value and an optional stored value from the package settings. 6210 */ 6211 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6212 String cpuAbiOverride = null; 6213 6214 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6215 cpuAbiOverride = null; 6216 } else if (abiOverride != null) { 6217 cpuAbiOverride = abiOverride; 6218 } else if (settings != null) { 6219 cpuAbiOverride = settings.cpuAbiOverrideString; 6220 } 6221 6222 return cpuAbiOverride; 6223 } 6224 6225 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6226 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6227 boolean success = false; 6228 try { 6229 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6230 currentTime, user); 6231 success = true; 6232 return res; 6233 } finally { 6234 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6235 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6236 } 6237 } 6238 } 6239 6240 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6241 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6242 final File scanFile = new File(pkg.codePath); 6243 if (pkg.applicationInfo.getCodePath() == null || 6244 pkg.applicationInfo.getResourcePath() == null) { 6245 // Bail out. The resource and code paths haven't been set. 6246 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6247 "Code and resource paths haven't been set correctly"); 6248 } 6249 6250 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6251 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6252 } else { 6253 // Only allow system apps to be flagged as core apps. 6254 pkg.coreApp = false; 6255 } 6256 6257 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6258 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6259 } 6260 6261 if (mCustomResolverComponentName != null && 6262 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6263 setUpCustomResolverActivity(pkg); 6264 } 6265 6266 if (pkg.packageName.equals("android")) { 6267 synchronized (mPackages) { 6268 if (mAndroidApplication != null) { 6269 Slog.w(TAG, "*************************************************"); 6270 Slog.w(TAG, "Core android package being redefined. Skipping."); 6271 Slog.w(TAG, " file=" + scanFile); 6272 Slog.w(TAG, "*************************************************"); 6273 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6274 "Core android package being redefined. Skipping."); 6275 } 6276 6277 // Set up information for our fall-back user intent resolution activity. 6278 mPlatformPackage = pkg; 6279 pkg.mVersionCode = mSdkVersion; 6280 mAndroidApplication = pkg.applicationInfo; 6281 6282 if (!mResolverReplaced) { 6283 mResolveActivity.applicationInfo = mAndroidApplication; 6284 mResolveActivity.name = ResolverActivity.class.getName(); 6285 mResolveActivity.packageName = mAndroidApplication.packageName; 6286 mResolveActivity.processName = "system:ui"; 6287 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6288 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6289 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6290 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6291 mResolveActivity.exported = true; 6292 mResolveActivity.enabled = true; 6293 mResolveInfo.activityInfo = mResolveActivity; 6294 mResolveInfo.priority = 0; 6295 mResolveInfo.preferredOrder = 0; 6296 mResolveInfo.match = 0; 6297 mResolveComponentName = new ComponentName( 6298 mAndroidApplication.packageName, mResolveActivity.name); 6299 } 6300 } 6301 } 6302 6303 if (DEBUG_PACKAGE_SCANNING) { 6304 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6305 Log.d(TAG, "Scanning package " + pkg.packageName); 6306 } 6307 6308 if (mPackages.containsKey(pkg.packageName) 6309 || mSharedLibraries.containsKey(pkg.packageName)) { 6310 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6311 "Application package " + pkg.packageName 6312 + " already installed. Skipping duplicate."); 6313 } 6314 6315 // If we're only installing presumed-existing packages, require that the 6316 // scanned APK is both already known and at the path previously established 6317 // for it. Previously unknown packages we pick up normally, but if we have an 6318 // a priori expectation about this package's install presence, enforce it. 6319 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6320 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6321 if (known != null) { 6322 if (DEBUG_PACKAGE_SCANNING) { 6323 Log.d(TAG, "Examining " + pkg.codePath 6324 + " and requiring known paths " + known.codePathString 6325 + " & " + known.resourcePathString); 6326 } 6327 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6328 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6329 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6330 "Application package " + pkg.packageName 6331 + " found at " + pkg.applicationInfo.getCodePath() 6332 + " but expected at " + known.codePathString + "; ignoring."); 6333 } 6334 } 6335 } 6336 6337 // Initialize package source and resource directories 6338 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6339 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6340 6341 SharedUserSetting suid = null; 6342 PackageSetting pkgSetting = null; 6343 6344 if (!isSystemApp(pkg)) { 6345 // Only system apps can use these features. 6346 pkg.mOriginalPackages = null; 6347 pkg.mRealPackage = null; 6348 pkg.mAdoptPermissions = null; 6349 } 6350 6351 // writer 6352 synchronized (mPackages) { 6353 if (pkg.mSharedUserId != null) { 6354 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6355 if (suid == null) { 6356 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6357 "Creating application package " + pkg.packageName 6358 + " for shared user failed"); 6359 } 6360 if (DEBUG_PACKAGE_SCANNING) { 6361 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6362 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6363 + "): packages=" + suid.packages); 6364 } 6365 } 6366 6367 // Check if we are renaming from an original package name. 6368 PackageSetting origPackage = null; 6369 String realName = null; 6370 if (pkg.mOriginalPackages != null) { 6371 // This package may need to be renamed to a previously 6372 // installed name. Let's check on that... 6373 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6374 if (pkg.mOriginalPackages.contains(renamed)) { 6375 // This package had originally been installed as the 6376 // original name, and we have already taken care of 6377 // transitioning to the new one. Just update the new 6378 // one to continue using the old name. 6379 realName = pkg.mRealPackage; 6380 if (!pkg.packageName.equals(renamed)) { 6381 // Callers into this function may have already taken 6382 // care of renaming the package; only do it here if 6383 // it is not already done. 6384 pkg.setPackageName(renamed); 6385 } 6386 6387 } else { 6388 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6389 if ((origPackage = mSettings.peekPackageLPr( 6390 pkg.mOriginalPackages.get(i))) != null) { 6391 // We do have the package already installed under its 6392 // original name... should we use it? 6393 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6394 // New package is not compatible with original. 6395 origPackage = null; 6396 continue; 6397 } else if (origPackage.sharedUser != null) { 6398 // Make sure uid is compatible between packages. 6399 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6400 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6401 + " to " + pkg.packageName + ": old uid " 6402 + origPackage.sharedUser.name 6403 + " differs from " + pkg.mSharedUserId); 6404 origPackage = null; 6405 continue; 6406 } 6407 } else { 6408 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6409 + pkg.packageName + " to old name " + origPackage.name); 6410 } 6411 break; 6412 } 6413 } 6414 } 6415 } 6416 6417 if (mTransferedPackages.contains(pkg.packageName)) { 6418 Slog.w(TAG, "Package " + pkg.packageName 6419 + " was transferred to another, but its .apk remains"); 6420 } 6421 6422 // Just create the setting, don't add it yet. For already existing packages 6423 // the PkgSetting exists already and doesn't have to be created. 6424 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6425 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6426 pkg.applicationInfo.primaryCpuAbi, 6427 pkg.applicationInfo.secondaryCpuAbi, 6428 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6429 user, false); 6430 if (pkgSetting == null) { 6431 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6432 "Creating application package " + pkg.packageName + " failed"); 6433 } 6434 6435 if (pkgSetting.origPackage != null) { 6436 // If we are first transitioning from an original package, 6437 // fix up the new package's name now. We need to do this after 6438 // looking up the package under its new name, so getPackageLP 6439 // can take care of fiddling things correctly. 6440 pkg.setPackageName(origPackage.name); 6441 6442 // File a report about this. 6443 String msg = "New package " + pkgSetting.realName 6444 + " renamed to replace old package " + pkgSetting.name; 6445 reportSettingsProblem(Log.WARN, msg); 6446 6447 // Make a note of it. 6448 mTransferedPackages.add(origPackage.name); 6449 6450 // No longer need to retain this. 6451 pkgSetting.origPackage = null; 6452 } 6453 6454 if (realName != null) { 6455 // Make a note of it. 6456 mTransferedPackages.add(pkg.packageName); 6457 } 6458 6459 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6460 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6461 } 6462 6463 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6464 // Check all shared libraries and map to their actual file path. 6465 // We only do this here for apps not on a system dir, because those 6466 // are the only ones that can fail an install due to this. We 6467 // will take care of the system apps by updating all of their 6468 // library paths after the scan is done. 6469 updateSharedLibrariesLPw(pkg, null); 6470 } 6471 6472 if (mFoundPolicyFile) { 6473 SELinuxMMAC.assignSeinfoValue(pkg); 6474 } 6475 6476 pkg.applicationInfo.uid = pkgSetting.appId; 6477 pkg.mExtras = pkgSetting; 6478 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6479 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6480 // We just determined the app is signed correctly, so bring 6481 // over the latest parsed certs. 6482 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6483 } else { 6484 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6485 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6486 "Package " + pkg.packageName + " upgrade keys do not match the " 6487 + "previously installed version"); 6488 } else { 6489 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6490 String msg = "System package " + pkg.packageName 6491 + " signature changed; retaining data."; 6492 reportSettingsProblem(Log.WARN, msg); 6493 } 6494 } 6495 } else { 6496 try { 6497 verifySignaturesLP(pkgSetting, pkg); 6498 // We just determined the app is signed correctly, so bring 6499 // over the latest parsed certs. 6500 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6501 } catch (PackageManagerException e) { 6502 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6503 throw e; 6504 } 6505 // The signature has changed, but this package is in the system 6506 // image... let's recover! 6507 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6508 // However... if this package is part of a shared user, but it 6509 // doesn't match the signature of the shared user, let's fail. 6510 // What this means is that you can't change the signatures 6511 // associated with an overall shared user, which doesn't seem all 6512 // that unreasonable. 6513 if (pkgSetting.sharedUser != null) { 6514 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6515 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6516 throw new PackageManagerException( 6517 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6518 "Signature mismatch for shared user : " 6519 + pkgSetting.sharedUser); 6520 } 6521 } 6522 // File a report about this. 6523 String msg = "System package " + pkg.packageName 6524 + " signature changed; retaining data."; 6525 reportSettingsProblem(Log.WARN, msg); 6526 } 6527 } 6528 // Verify that this new package doesn't have any content providers 6529 // that conflict with existing packages. Only do this if the 6530 // package isn't already installed, since we don't want to break 6531 // things that are installed. 6532 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6533 final int N = pkg.providers.size(); 6534 int i; 6535 for (i=0; i<N; i++) { 6536 PackageParser.Provider p = pkg.providers.get(i); 6537 if (p.info.authority != null) { 6538 String names[] = p.info.authority.split(";"); 6539 for (int j = 0; j < names.length; j++) { 6540 if (mProvidersByAuthority.containsKey(names[j])) { 6541 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6542 final String otherPackageName = 6543 ((other != null && other.getComponentName() != null) ? 6544 other.getComponentName().getPackageName() : "?"); 6545 throw new PackageManagerException( 6546 INSTALL_FAILED_CONFLICTING_PROVIDER, 6547 "Can't install because provider name " + names[j] 6548 + " (in package " + pkg.applicationInfo.packageName 6549 + ") is already used by " + otherPackageName); 6550 } 6551 } 6552 } 6553 } 6554 } 6555 6556 if (pkg.mAdoptPermissions != null) { 6557 // This package wants to adopt ownership of permissions from 6558 // another package. 6559 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6560 final String origName = pkg.mAdoptPermissions.get(i); 6561 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6562 if (orig != null) { 6563 if (verifyPackageUpdateLPr(orig, pkg)) { 6564 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6565 + pkg.packageName); 6566 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6567 } 6568 } 6569 } 6570 } 6571 } 6572 6573 final String pkgName = pkg.packageName; 6574 6575 final long scanFileTime = scanFile.lastModified(); 6576 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6577 pkg.applicationInfo.processName = fixProcessName( 6578 pkg.applicationInfo.packageName, 6579 pkg.applicationInfo.processName, 6580 pkg.applicationInfo.uid); 6581 6582 File dataPath; 6583 if (mPlatformPackage == pkg) { 6584 // The system package is special. 6585 dataPath = new File(Environment.getDataDirectory(), "system"); 6586 6587 pkg.applicationInfo.dataDir = dataPath.getPath(); 6588 6589 } else { 6590 // This is a normal package, need to make its data directory. 6591 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6592 UserHandle.USER_OWNER); 6593 6594 boolean uidError = false; 6595 if (dataPath.exists()) { 6596 int currentUid = 0; 6597 try { 6598 StructStat stat = Os.stat(dataPath.getPath()); 6599 currentUid = stat.st_uid; 6600 } catch (ErrnoException e) { 6601 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6602 } 6603 6604 // If we have mismatched owners for the data path, we have a problem. 6605 if (currentUid != pkg.applicationInfo.uid) { 6606 boolean recovered = false; 6607 if (currentUid == 0) { 6608 // The directory somehow became owned by root. Wow. 6609 // This is probably because the system was stopped while 6610 // installd was in the middle of messing with its libs 6611 // directory. Ask installd to fix that. 6612 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6613 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6614 if (ret >= 0) { 6615 recovered = true; 6616 String msg = "Package " + pkg.packageName 6617 + " unexpectedly changed to uid 0; recovered to " + 6618 + pkg.applicationInfo.uid; 6619 reportSettingsProblem(Log.WARN, msg); 6620 } 6621 } 6622 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6623 || (scanFlags&SCAN_BOOTING) != 0)) { 6624 // If this is a system app, we can at least delete its 6625 // current data so the application will still work. 6626 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6627 if (ret >= 0) { 6628 // TODO: Kill the processes first 6629 // Old data gone! 6630 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6631 ? "System package " : "Third party package "; 6632 String msg = prefix + pkg.packageName 6633 + " has changed from uid: " 6634 + currentUid + " to " 6635 + pkg.applicationInfo.uid + "; old data erased"; 6636 reportSettingsProblem(Log.WARN, msg); 6637 recovered = true; 6638 6639 // And now re-install the app. 6640 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6641 pkg.applicationInfo.seinfo); 6642 if (ret == -1) { 6643 // Ack should not happen! 6644 msg = prefix + pkg.packageName 6645 + " could not have data directory re-created after delete."; 6646 reportSettingsProblem(Log.WARN, msg); 6647 throw new PackageManagerException( 6648 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6649 } 6650 } 6651 if (!recovered) { 6652 mHasSystemUidErrors = true; 6653 } 6654 } else if (!recovered) { 6655 // If we allow this install to proceed, we will be broken. 6656 // Abort, abort! 6657 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6658 "scanPackageLI"); 6659 } 6660 if (!recovered) { 6661 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6662 + pkg.applicationInfo.uid + "/fs_" 6663 + currentUid; 6664 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6665 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6666 String msg = "Package " + pkg.packageName 6667 + " has mismatched uid: " 6668 + currentUid + " on disk, " 6669 + pkg.applicationInfo.uid + " in settings"; 6670 // writer 6671 synchronized (mPackages) { 6672 mSettings.mReadMessages.append(msg); 6673 mSettings.mReadMessages.append('\n'); 6674 uidError = true; 6675 if (!pkgSetting.uidError) { 6676 reportSettingsProblem(Log.ERROR, msg); 6677 } 6678 } 6679 } 6680 } 6681 pkg.applicationInfo.dataDir = dataPath.getPath(); 6682 if (mShouldRestoreconData) { 6683 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6684 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6685 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6686 } 6687 } else { 6688 if (DEBUG_PACKAGE_SCANNING) { 6689 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6690 Log.v(TAG, "Want this data dir: " + dataPath); 6691 } 6692 //invoke installer to do the actual installation 6693 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6694 pkg.applicationInfo.seinfo); 6695 if (ret < 0) { 6696 // Error from installer 6697 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6698 "Unable to create data dirs [errorCode=" + ret + "]"); 6699 } 6700 6701 if (dataPath.exists()) { 6702 pkg.applicationInfo.dataDir = dataPath.getPath(); 6703 } else { 6704 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6705 pkg.applicationInfo.dataDir = null; 6706 } 6707 } 6708 6709 pkgSetting.uidError = uidError; 6710 } 6711 6712 final String path = scanFile.getPath(); 6713 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6714 6715 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6716 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6717 6718 // Some system apps still use directory structure for native libraries 6719 // in which case we might end up not detecting abi solely based on apk 6720 // structure. Try to detect abi based on directory structure. 6721 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6722 pkg.applicationInfo.primaryCpuAbi == null) { 6723 setBundledAppAbisAndRoots(pkg, pkgSetting); 6724 setNativeLibraryPaths(pkg); 6725 } 6726 6727 } else { 6728 if ((scanFlags & SCAN_MOVE) != 0) { 6729 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6730 // but we already have this packages package info in the PackageSetting. We just 6731 // use that and derive the native library path based on the new codepath. 6732 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6733 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6734 } 6735 6736 // Set native library paths again. For moves, the path will be updated based on the 6737 // ABIs we've determined above. For non-moves, the path will be updated based on the 6738 // ABIs we determined during compilation, but the path will depend on the final 6739 // package path (after the rename away from the stage path). 6740 setNativeLibraryPaths(pkg); 6741 } 6742 6743 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6744 final int[] userIds = sUserManager.getUserIds(); 6745 synchronized (mInstallLock) { 6746 // Create a native library symlink only if we have native libraries 6747 // and if the native libraries are 32 bit libraries. We do not provide 6748 // this symlink for 64 bit libraries. 6749 if (pkg.applicationInfo.primaryCpuAbi != null && 6750 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6751 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6752 for (int userId : userIds) { 6753 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6754 nativeLibPath, userId) < 0) { 6755 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6756 "Failed linking native library dir (user=" + userId + ")"); 6757 } 6758 } 6759 } 6760 } 6761 6762 // This is a special case for the "system" package, where the ABI is 6763 // dictated by the zygote configuration (and init.rc). We should keep track 6764 // of this ABI so that we can deal with "normal" applications that run under 6765 // the same UID correctly. 6766 if (mPlatformPackage == pkg) { 6767 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6768 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6769 } 6770 6771 // If there's a mismatch between the abi-override in the package setting 6772 // and the abiOverride specified for the install. Warn about this because we 6773 // would've already compiled the app without taking the package setting into 6774 // account. 6775 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6776 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6777 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6778 " for package: " + pkg.packageName); 6779 } 6780 } 6781 6782 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6783 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6784 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6785 6786 // Copy the derived override back to the parsed package, so that we can 6787 // update the package settings accordingly. 6788 pkg.cpuAbiOverride = cpuAbiOverride; 6789 6790 if (DEBUG_ABI_SELECTION) { 6791 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6792 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6793 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6794 } 6795 6796 // Push the derived path down into PackageSettings so we know what to 6797 // clean up at uninstall time. 6798 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6799 6800 if (DEBUG_ABI_SELECTION) { 6801 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6802 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6803 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6804 } 6805 6806 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6807 // We don't do this here during boot because we can do it all 6808 // at once after scanning all existing packages. 6809 // 6810 // We also do this *before* we perform dexopt on this package, so that 6811 // we can avoid redundant dexopts, and also to make sure we've got the 6812 // code and package path correct. 6813 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6814 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6815 } 6816 6817 if ((scanFlags & SCAN_NO_DEX) == 0) { 6818 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6819 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6820 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6821 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6822 } 6823 } 6824 if (mFactoryTest && pkg.requestedPermissions.contains( 6825 android.Manifest.permission.FACTORY_TEST)) { 6826 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6827 } 6828 6829 ArrayList<PackageParser.Package> clientLibPkgs = null; 6830 6831 // writer 6832 synchronized (mPackages) { 6833 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6834 // Only system apps can add new shared libraries. 6835 if (pkg.libraryNames != null) { 6836 for (int i=0; i<pkg.libraryNames.size(); i++) { 6837 String name = pkg.libraryNames.get(i); 6838 boolean allowed = false; 6839 if (pkg.isUpdatedSystemApp()) { 6840 // New library entries can only be added through the 6841 // system image. This is important to get rid of a lot 6842 // of nasty edge cases: for example if we allowed a non- 6843 // system update of the app to add a library, then uninstalling 6844 // the update would make the library go away, and assumptions 6845 // we made such as through app install filtering would now 6846 // have allowed apps on the device which aren't compatible 6847 // with it. Better to just have the restriction here, be 6848 // conservative, and create many fewer cases that can negatively 6849 // impact the user experience. 6850 final PackageSetting sysPs = mSettings 6851 .getDisabledSystemPkgLPr(pkg.packageName); 6852 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6853 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6854 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6855 allowed = true; 6856 allowed = true; 6857 break; 6858 } 6859 } 6860 } 6861 } else { 6862 allowed = true; 6863 } 6864 if (allowed) { 6865 if (!mSharedLibraries.containsKey(name)) { 6866 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6867 } else if (!name.equals(pkg.packageName)) { 6868 Slog.w(TAG, "Package " + pkg.packageName + " library " 6869 + name + " already exists; skipping"); 6870 } 6871 } else { 6872 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6873 + name + " that is not declared on system image; skipping"); 6874 } 6875 } 6876 if ((scanFlags&SCAN_BOOTING) == 0) { 6877 // If we are not booting, we need to update any applications 6878 // that are clients of our shared library. If we are booting, 6879 // this will all be done once the scan is complete. 6880 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6881 } 6882 } 6883 } 6884 } 6885 6886 // We also need to dexopt any apps that are dependent on this library. Note that 6887 // if these fail, we should abort the install since installing the library will 6888 // result in some apps being broken. 6889 if (clientLibPkgs != null) { 6890 if ((scanFlags & SCAN_NO_DEX) == 0) { 6891 for (int i = 0; i < clientLibPkgs.size(); i++) { 6892 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6893 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6894 null /* instruction sets */, forceDex, 6895 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6896 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6897 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6898 "scanPackageLI failed to dexopt clientLibPkgs"); 6899 } 6900 } 6901 } 6902 } 6903 6904 // Also need to kill any apps that are dependent on the library. 6905 if (clientLibPkgs != null) { 6906 for (int i=0; i<clientLibPkgs.size(); i++) { 6907 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6908 killApplication(clientPkg.applicationInfo.packageName, 6909 clientPkg.applicationInfo.uid, "update lib"); 6910 } 6911 } 6912 6913 // Make sure we're not adding any bogus keyset info 6914 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6915 ksms.assertScannedPackageValid(pkg); 6916 6917 // writer 6918 synchronized (mPackages) { 6919 // We don't expect installation to fail beyond this point 6920 6921 // Add the new setting to mSettings 6922 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6923 // Add the new setting to mPackages 6924 mPackages.put(pkg.applicationInfo.packageName, pkg); 6925 // Make sure we don't accidentally delete its data. 6926 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6927 while (iter.hasNext()) { 6928 PackageCleanItem item = iter.next(); 6929 if (pkgName.equals(item.packageName)) { 6930 iter.remove(); 6931 } 6932 } 6933 6934 // Take care of first install / last update times. 6935 if (currentTime != 0) { 6936 if (pkgSetting.firstInstallTime == 0) { 6937 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6938 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6939 pkgSetting.lastUpdateTime = currentTime; 6940 } 6941 } else if (pkgSetting.firstInstallTime == 0) { 6942 // We need *something*. Take time time stamp of the file. 6943 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6944 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6945 if (scanFileTime != pkgSetting.timeStamp) { 6946 // A package on the system image has changed; consider this 6947 // to be an update. 6948 pkgSetting.lastUpdateTime = scanFileTime; 6949 } 6950 } 6951 6952 // Add the package's KeySets to the global KeySetManagerService 6953 ksms.addScannedPackageLPw(pkg); 6954 6955 int N = pkg.providers.size(); 6956 StringBuilder r = null; 6957 int i; 6958 for (i=0; i<N; i++) { 6959 PackageParser.Provider p = pkg.providers.get(i); 6960 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6961 p.info.processName, pkg.applicationInfo.uid); 6962 mProviders.addProvider(p); 6963 p.syncable = p.info.isSyncable; 6964 if (p.info.authority != null) { 6965 String names[] = p.info.authority.split(";"); 6966 p.info.authority = null; 6967 for (int j = 0; j < names.length; j++) { 6968 if (j == 1 && p.syncable) { 6969 // We only want the first authority for a provider to possibly be 6970 // syncable, so if we already added this provider using a different 6971 // authority clear the syncable flag. We copy the provider before 6972 // changing it because the mProviders object contains a reference 6973 // to a provider that we don't want to change. 6974 // Only do this for the second authority since the resulting provider 6975 // object can be the same for all future authorities for this provider. 6976 p = new PackageParser.Provider(p); 6977 p.syncable = false; 6978 } 6979 if (!mProvidersByAuthority.containsKey(names[j])) { 6980 mProvidersByAuthority.put(names[j], p); 6981 if (p.info.authority == null) { 6982 p.info.authority = names[j]; 6983 } else { 6984 p.info.authority = p.info.authority + ";" + names[j]; 6985 } 6986 if (DEBUG_PACKAGE_SCANNING) { 6987 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6988 Log.d(TAG, "Registered content provider: " + names[j] 6989 + ", className = " + p.info.name + ", isSyncable = " 6990 + p.info.isSyncable); 6991 } 6992 } else { 6993 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6994 Slog.w(TAG, "Skipping provider name " + names[j] + 6995 " (in package " + pkg.applicationInfo.packageName + 6996 "): name already used by " 6997 + ((other != null && other.getComponentName() != null) 6998 ? other.getComponentName().getPackageName() : "?")); 6999 } 7000 } 7001 } 7002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7003 if (r == null) { 7004 r = new StringBuilder(256); 7005 } else { 7006 r.append(' '); 7007 } 7008 r.append(p.info.name); 7009 } 7010 } 7011 if (r != null) { 7012 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7013 } 7014 7015 N = pkg.services.size(); 7016 r = null; 7017 for (i=0; i<N; i++) { 7018 PackageParser.Service s = pkg.services.get(i); 7019 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7020 s.info.processName, pkg.applicationInfo.uid); 7021 mServices.addService(s); 7022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7023 if (r == null) { 7024 r = new StringBuilder(256); 7025 } else { 7026 r.append(' '); 7027 } 7028 r.append(s.info.name); 7029 } 7030 } 7031 if (r != null) { 7032 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7033 } 7034 7035 N = pkg.receivers.size(); 7036 r = null; 7037 for (i=0; i<N; i++) { 7038 PackageParser.Activity a = pkg.receivers.get(i); 7039 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7040 a.info.processName, pkg.applicationInfo.uid); 7041 mReceivers.addActivity(a, "receiver"); 7042 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7043 if (r == null) { 7044 r = new StringBuilder(256); 7045 } else { 7046 r.append(' '); 7047 } 7048 r.append(a.info.name); 7049 } 7050 } 7051 if (r != null) { 7052 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7053 } 7054 7055 N = pkg.activities.size(); 7056 r = null; 7057 for (i=0; i<N; i++) { 7058 PackageParser.Activity a = pkg.activities.get(i); 7059 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7060 a.info.processName, pkg.applicationInfo.uid); 7061 mActivities.addActivity(a, "activity"); 7062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7063 if (r == null) { 7064 r = new StringBuilder(256); 7065 } else { 7066 r.append(' '); 7067 } 7068 r.append(a.info.name); 7069 } 7070 } 7071 if (r != null) { 7072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7073 } 7074 7075 N = pkg.permissionGroups.size(); 7076 r = null; 7077 for (i=0; i<N; i++) { 7078 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7079 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7080 if (cur == null) { 7081 mPermissionGroups.put(pg.info.name, pg); 7082 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7083 if (r == null) { 7084 r = new StringBuilder(256); 7085 } else { 7086 r.append(' '); 7087 } 7088 r.append(pg.info.name); 7089 } 7090 } else { 7091 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7092 + pg.info.packageName + " ignored: original from " 7093 + cur.info.packageName); 7094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7095 if (r == null) { 7096 r = new StringBuilder(256); 7097 } else { 7098 r.append(' '); 7099 } 7100 r.append("DUP:"); 7101 r.append(pg.info.name); 7102 } 7103 } 7104 } 7105 if (r != null) { 7106 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7107 } 7108 7109 N = pkg.permissions.size(); 7110 r = null; 7111 for (i=0; i<N; i++) { 7112 PackageParser.Permission p = pkg.permissions.get(i); 7113 7114 // Now that permission groups have a special meaning, we ignore permission 7115 // groups for legacy apps to prevent unexpected behavior. In particular, 7116 // permissions for one app being granted to someone just becuase they happen 7117 // to be in a group defined by another app (before this had no implications). 7118 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7119 p.group = mPermissionGroups.get(p.info.group); 7120 // Warn for a permission in an unknown group. 7121 if (p.info.group != null && p.group == null) { 7122 Slog.w(TAG, "Permission " + p.info.name + " from package " 7123 + p.info.packageName + " in an unknown group " + p.info.group); 7124 } 7125 } 7126 7127 ArrayMap<String, BasePermission> permissionMap = 7128 p.tree ? mSettings.mPermissionTrees 7129 : mSettings.mPermissions; 7130 BasePermission bp = permissionMap.get(p.info.name); 7131 7132 // Allow system apps to redefine non-system permissions 7133 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7134 final boolean currentOwnerIsSystem = (bp.perm != null 7135 && isSystemApp(bp.perm.owner)); 7136 if (isSystemApp(p.owner)) { 7137 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7138 // It's a built-in permission and no owner, take ownership now 7139 bp.packageSetting = pkgSetting; 7140 bp.perm = p; 7141 bp.uid = pkg.applicationInfo.uid; 7142 bp.sourcePackage = p.info.packageName; 7143 } else if (!currentOwnerIsSystem) { 7144 String msg = "New decl " + p.owner + " of permission " 7145 + p.info.name + " is system; overriding " + bp.sourcePackage; 7146 reportSettingsProblem(Log.WARN, msg); 7147 bp = null; 7148 } 7149 } 7150 } 7151 7152 if (bp == null) { 7153 bp = new BasePermission(p.info.name, p.info.packageName, 7154 BasePermission.TYPE_NORMAL); 7155 permissionMap.put(p.info.name, bp); 7156 } 7157 7158 if (bp.perm == null) { 7159 if (bp.sourcePackage == null 7160 || bp.sourcePackage.equals(p.info.packageName)) { 7161 BasePermission tree = findPermissionTreeLP(p.info.name); 7162 if (tree == null 7163 || tree.sourcePackage.equals(p.info.packageName)) { 7164 bp.packageSetting = pkgSetting; 7165 bp.perm = p; 7166 bp.uid = pkg.applicationInfo.uid; 7167 bp.sourcePackage = p.info.packageName; 7168 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7169 if (r == null) { 7170 r = new StringBuilder(256); 7171 } else { 7172 r.append(' '); 7173 } 7174 r.append(p.info.name); 7175 } 7176 } else { 7177 Slog.w(TAG, "Permission " + p.info.name + " from package " 7178 + p.info.packageName + " ignored: base tree " 7179 + tree.name + " is from package " 7180 + tree.sourcePackage); 7181 } 7182 } else { 7183 Slog.w(TAG, "Permission " + p.info.name + " from package " 7184 + p.info.packageName + " ignored: original from " 7185 + bp.sourcePackage); 7186 } 7187 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7188 if (r == null) { 7189 r = new StringBuilder(256); 7190 } else { 7191 r.append(' '); 7192 } 7193 r.append("DUP:"); 7194 r.append(p.info.name); 7195 } 7196 if (bp.perm == p) { 7197 bp.protectionLevel = p.info.protectionLevel; 7198 } 7199 } 7200 7201 if (r != null) { 7202 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7203 } 7204 7205 N = pkg.instrumentation.size(); 7206 r = null; 7207 for (i=0; i<N; i++) { 7208 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7209 a.info.packageName = pkg.applicationInfo.packageName; 7210 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7211 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7212 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7213 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7214 a.info.dataDir = pkg.applicationInfo.dataDir; 7215 7216 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7217 // need other information about the application, like the ABI and what not ? 7218 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7219 mInstrumentation.put(a.getComponentName(), a); 7220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7221 if (r == null) { 7222 r = new StringBuilder(256); 7223 } else { 7224 r.append(' '); 7225 } 7226 r.append(a.info.name); 7227 } 7228 } 7229 if (r != null) { 7230 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7231 } 7232 7233 if (pkg.protectedBroadcasts != null) { 7234 N = pkg.protectedBroadcasts.size(); 7235 for (i=0; i<N; i++) { 7236 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7237 } 7238 } 7239 7240 pkgSetting.setTimeStamp(scanFileTime); 7241 7242 // Create idmap files for pairs of (packages, overlay packages). 7243 // Note: "android", ie framework-res.apk, is handled by native layers. 7244 if (pkg.mOverlayTarget != null) { 7245 // This is an overlay package. 7246 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7247 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7248 mOverlays.put(pkg.mOverlayTarget, 7249 new ArrayMap<String, PackageParser.Package>()); 7250 } 7251 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7252 map.put(pkg.packageName, pkg); 7253 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7254 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7255 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7256 "scanPackageLI failed to createIdmap"); 7257 } 7258 } 7259 } else if (mOverlays.containsKey(pkg.packageName) && 7260 !pkg.packageName.equals("android")) { 7261 // This is a regular package, with one or more known overlay packages. 7262 createIdmapsForPackageLI(pkg); 7263 } 7264 } 7265 7266 return pkg; 7267 } 7268 7269 /** 7270 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7271 * is derived purely on the basis of the contents of {@code scanFile} and 7272 * {@code cpuAbiOverride}. 7273 * 7274 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7275 */ 7276 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7277 String cpuAbiOverride, boolean extractLibs) 7278 throws PackageManagerException { 7279 // TODO: We can probably be smarter about this stuff. For installed apps, 7280 // we can calculate this information at install time once and for all. For 7281 // system apps, we can probably assume that this information doesn't change 7282 // after the first boot scan. As things stand, we do lots of unnecessary work. 7283 7284 // Give ourselves some initial paths; we'll come back for another 7285 // pass once we've determined ABI below. 7286 setNativeLibraryPaths(pkg); 7287 7288 // We would never need to extract libs for forward-locked and external packages, 7289 // since the container service will do it for us. We shouldn't attempt to 7290 // extract libs from system app when it was not updated. 7291 if (pkg.isForwardLocked() || isExternal(pkg) || 7292 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7293 extractLibs = false; 7294 } 7295 7296 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7297 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7298 7299 NativeLibraryHelper.Handle handle = null; 7300 try { 7301 handle = NativeLibraryHelper.Handle.create(pkg); 7302 // TODO(multiArch): This can be null for apps that didn't go through the 7303 // usual installation process. We can calculate it again, like we 7304 // do during install time. 7305 // 7306 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7307 // unnecessary. 7308 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7309 7310 // Null out the abis so that they can be recalculated. 7311 pkg.applicationInfo.primaryCpuAbi = null; 7312 pkg.applicationInfo.secondaryCpuAbi = null; 7313 if (isMultiArch(pkg.applicationInfo)) { 7314 // Warn if we've set an abiOverride for multi-lib packages.. 7315 // By definition, we need to copy both 32 and 64 bit libraries for 7316 // such packages. 7317 if (pkg.cpuAbiOverride != null 7318 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7319 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7320 } 7321 7322 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7323 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7324 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7325 if (extractLibs) { 7326 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7327 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7328 useIsaSpecificSubdirs); 7329 } else { 7330 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7331 } 7332 } 7333 7334 maybeThrowExceptionForMultiArchCopy( 7335 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7336 7337 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7338 if (extractLibs) { 7339 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7340 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7341 useIsaSpecificSubdirs); 7342 } else { 7343 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7344 } 7345 } 7346 7347 maybeThrowExceptionForMultiArchCopy( 7348 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7349 7350 if (abi64 >= 0) { 7351 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7352 } 7353 7354 if (abi32 >= 0) { 7355 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7356 if (abi64 >= 0) { 7357 pkg.applicationInfo.secondaryCpuAbi = abi; 7358 } else { 7359 pkg.applicationInfo.primaryCpuAbi = abi; 7360 } 7361 } 7362 } else { 7363 String[] abiList = (cpuAbiOverride != null) ? 7364 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7365 7366 // Enable gross and lame hacks for apps that are built with old 7367 // SDK tools. We must scan their APKs for renderscript bitcode and 7368 // not launch them if it's present. Don't bother checking on devices 7369 // that don't have 64 bit support. 7370 boolean needsRenderScriptOverride = false; 7371 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7372 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7373 abiList = Build.SUPPORTED_32_BIT_ABIS; 7374 needsRenderScriptOverride = true; 7375 } 7376 7377 final int copyRet; 7378 if (extractLibs) { 7379 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7380 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7381 } else { 7382 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7383 } 7384 7385 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7386 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7387 "Error unpackaging native libs for app, errorCode=" + copyRet); 7388 } 7389 7390 if (copyRet >= 0) { 7391 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7392 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7393 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7394 } else if (needsRenderScriptOverride) { 7395 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7396 } 7397 } 7398 } catch (IOException ioe) { 7399 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7400 } finally { 7401 IoUtils.closeQuietly(handle); 7402 } 7403 7404 // Now that we've calculated the ABIs and determined if it's an internal app, 7405 // we will go ahead and populate the nativeLibraryPath. 7406 setNativeLibraryPaths(pkg); 7407 } 7408 7409 /** 7410 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7411 * i.e, so that all packages can be run inside a single process if required. 7412 * 7413 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7414 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7415 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7416 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7417 * updating a package that belongs to a shared user. 7418 * 7419 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7420 * adds unnecessary complexity. 7421 */ 7422 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7423 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7424 String requiredInstructionSet = null; 7425 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7426 requiredInstructionSet = VMRuntime.getInstructionSet( 7427 scannedPackage.applicationInfo.primaryCpuAbi); 7428 } 7429 7430 PackageSetting requirer = null; 7431 for (PackageSetting ps : packagesForUser) { 7432 // If packagesForUser contains scannedPackage, we skip it. This will happen 7433 // when scannedPackage is an update of an existing package. Without this check, 7434 // we will never be able to change the ABI of any package belonging to a shared 7435 // user, even if it's compatible with other packages. 7436 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7437 if (ps.primaryCpuAbiString == null) { 7438 continue; 7439 } 7440 7441 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7442 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7443 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7444 // this but there's not much we can do. 7445 String errorMessage = "Instruction set mismatch, " 7446 + ((requirer == null) ? "[caller]" : requirer) 7447 + " requires " + requiredInstructionSet + " whereas " + ps 7448 + " requires " + instructionSet; 7449 Slog.w(TAG, errorMessage); 7450 } 7451 7452 if (requiredInstructionSet == null) { 7453 requiredInstructionSet = instructionSet; 7454 requirer = ps; 7455 } 7456 } 7457 } 7458 7459 if (requiredInstructionSet != null) { 7460 String adjustedAbi; 7461 if (requirer != null) { 7462 // requirer != null implies that either scannedPackage was null or that scannedPackage 7463 // did not require an ABI, in which case we have to adjust scannedPackage to match 7464 // the ABI of the set (which is the same as requirer's ABI) 7465 adjustedAbi = requirer.primaryCpuAbiString; 7466 if (scannedPackage != null) { 7467 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7468 } 7469 } else { 7470 // requirer == null implies that we're updating all ABIs in the set to 7471 // match scannedPackage. 7472 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7473 } 7474 7475 for (PackageSetting ps : packagesForUser) { 7476 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7477 if (ps.primaryCpuAbiString != null) { 7478 continue; 7479 } 7480 7481 ps.primaryCpuAbiString = adjustedAbi; 7482 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7483 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7484 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7485 7486 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7487 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7488 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7489 ps.primaryCpuAbiString = null; 7490 ps.pkg.applicationInfo.primaryCpuAbi = null; 7491 return; 7492 } else { 7493 mInstaller.rmdex(ps.codePathString, 7494 getDexCodeInstructionSet(getPreferredInstructionSet())); 7495 } 7496 } 7497 } 7498 } 7499 } 7500 } 7501 7502 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7503 synchronized (mPackages) { 7504 mResolverReplaced = true; 7505 // Set up information for custom user intent resolution activity. 7506 mResolveActivity.applicationInfo = pkg.applicationInfo; 7507 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7508 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7509 mResolveActivity.processName = pkg.applicationInfo.packageName; 7510 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7511 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7512 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7513 mResolveActivity.theme = 0; 7514 mResolveActivity.exported = true; 7515 mResolveActivity.enabled = true; 7516 mResolveInfo.activityInfo = mResolveActivity; 7517 mResolveInfo.priority = 0; 7518 mResolveInfo.preferredOrder = 0; 7519 mResolveInfo.match = 0; 7520 mResolveComponentName = mCustomResolverComponentName; 7521 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7522 mResolveComponentName); 7523 } 7524 } 7525 7526 private static String calculateBundledApkRoot(final String codePathString) { 7527 final File codePath = new File(codePathString); 7528 final File codeRoot; 7529 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7530 codeRoot = Environment.getRootDirectory(); 7531 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7532 codeRoot = Environment.getOemDirectory(); 7533 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7534 codeRoot = Environment.getVendorDirectory(); 7535 } else { 7536 // Unrecognized code path; take its top real segment as the apk root: 7537 // e.g. /something/app/blah.apk => /something 7538 try { 7539 File f = codePath.getCanonicalFile(); 7540 File parent = f.getParentFile(); // non-null because codePath is a file 7541 File tmp; 7542 while ((tmp = parent.getParentFile()) != null) { 7543 f = parent; 7544 parent = tmp; 7545 } 7546 codeRoot = f; 7547 Slog.w(TAG, "Unrecognized code path " 7548 + codePath + " - using " + codeRoot); 7549 } catch (IOException e) { 7550 // Can't canonicalize the code path -- shenanigans? 7551 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7552 return Environment.getRootDirectory().getPath(); 7553 } 7554 } 7555 return codeRoot.getPath(); 7556 } 7557 7558 /** 7559 * Derive and set the location of native libraries for the given package, 7560 * which varies depending on where and how the package was installed. 7561 */ 7562 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7563 final ApplicationInfo info = pkg.applicationInfo; 7564 final String codePath = pkg.codePath; 7565 final File codeFile = new File(codePath); 7566 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7567 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7568 7569 info.nativeLibraryRootDir = null; 7570 info.nativeLibraryRootRequiresIsa = false; 7571 info.nativeLibraryDir = null; 7572 info.secondaryNativeLibraryDir = null; 7573 7574 if (isApkFile(codeFile)) { 7575 // Monolithic install 7576 if (bundledApp) { 7577 // If "/system/lib64/apkname" exists, assume that is the per-package 7578 // native library directory to use; otherwise use "/system/lib/apkname". 7579 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7580 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7581 getPrimaryInstructionSet(info)); 7582 7583 // This is a bundled system app so choose the path based on the ABI. 7584 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7585 // is just the default path. 7586 final String apkName = deriveCodePathName(codePath); 7587 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7588 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7589 apkName).getAbsolutePath(); 7590 7591 if (info.secondaryCpuAbi != null) { 7592 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7593 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7594 secondaryLibDir, apkName).getAbsolutePath(); 7595 } 7596 } else if (asecApp) { 7597 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7598 .getAbsolutePath(); 7599 } else { 7600 final String apkName = deriveCodePathName(codePath); 7601 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7602 .getAbsolutePath(); 7603 } 7604 7605 info.nativeLibraryRootRequiresIsa = false; 7606 info.nativeLibraryDir = info.nativeLibraryRootDir; 7607 } else { 7608 // Cluster install 7609 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7610 info.nativeLibraryRootRequiresIsa = true; 7611 7612 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7613 getPrimaryInstructionSet(info)).getAbsolutePath(); 7614 7615 if (info.secondaryCpuAbi != null) { 7616 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7617 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7618 } 7619 } 7620 } 7621 7622 /** 7623 * Calculate the abis and roots for a bundled app. These can uniquely 7624 * be determined from the contents of the system partition, i.e whether 7625 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7626 * of this information, and instead assume that the system was built 7627 * sensibly. 7628 */ 7629 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7630 PackageSetting pkgSetting) { 7631 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7632 7633 // If "/system/lib64/apkname" exists, assume that is the per-package 7634 // native library directory to use; otherwise use "/system/lib/apkname". 7635 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7636 setBundledAppAbi(pkg, apkRoot, apkName); 7637 // pkgSetting might be null during rescan following uninstall of updates 7638 // to a bundled app, so accommodate that possibility. The settings in 7639 // that case will be established later from the parsed package. 7640 // 7641 // If the settings aren't null, sync them up with what we've just derived. 7642 // note that apkRoot isn't stored in the package settings. 7643 if (pkgSetting != null) { 7644 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7645 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7646 } 7647 } 7648 7649 /** 7650 * Deduces the ABI of a bundled app and sets the relevant fields on the 7651 * parsed pkg object. 7652 * 7653 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7654 * under which system libraries are installed. 7655 * @param apkName the name of the installed package. 7656 */ 7657 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7658 final File codeFile = new File(pkg.codePath); 7659 7660 final boolean has64BitLibs; 7661 final boolean has32BitLibs; 7662 if (isApkFile(codeFile)) { 7663 // Monolithic install 7664 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7665 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7666 } else { 7667 // Cluster install 7668 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7669 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7670 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7671 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7672 has64BitLibs = (new File(rootDir, isa)).exists(); 7673 } else { 7674 has64BitLibs = false; 7675 } 7676 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7677 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7678 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7679 has32BitLibs = (new File(rootDir, isa)).exists(); 7680 } else { 7681 has32BitLibs = false; 7682 } 7683 } 7684 7685 if (has64BitLibs && !has32BitLibs) { 7686 // The package has 64 bit libs, but not 32 bit libs. Its primary 7687 // ABI should be 64 bit. We can safely assume here that the bundled 7688 // native libraries correspond to the most preferred ABI in the list. 7689 7690 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7691 pkg.applicationInfo.secondaryCpuAbi = null; 7692 } else if (has32BitLibs && !has64BitLibs) { 7693 // The package has 32 bit libs but not 64 bit libs. Its primary 7694 // ABI should be 32 bit. 7695 7696 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7697 pkg.applicationInfo.secondaryCpuAbi = null; 7698 } else if (has32BitLibs && has64BitLibs) { 7699 // The application has both 64 and 32 bit bundled libraries. We check 7700 // here that the app declares multiArch support, and warn if it doesn't. 7701 // 7702 // We will be lenient here and record both ABIs. The primary will be the 7703 // ABI that's higher on the list, i.e, a device that's configured to prefer 7704 // 64 bit apps will see a 64 bit primary ABI, 7705 7706 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7707 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7708 } 7709 7710 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7711 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7712 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7713 } else { 7714 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7715 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7716 } 7717 } else { 7718 pkg.applicationInfo.primaryCpuAbi = null; 7719 pkg.applicationInfo.secondaryCpuAbi = null; 7720 } 7721 } 7722 7723 private void killApplication(String pkgName, int appId, String reason) { 7724 // Request the ActivityManager to kill the process(only for existing packages) 7725 // so that we do not end up in a confused state while the user is still using the older 7726 // version of the application while the new one gets installed. 7727 IActivityManager am = ActivityManagerNative.getDefault(); 7728 if (am != null) { 7729 try { 7730 am.killApplicationWithAppId(pkgName, appId, reason); 7731 } catch (RemoteException e) { 7732 } 7733 } 7734 } 7735 7736 void removePackageLI(PackageSetting ps, boolean chatty) { 7737 if (DEBUG_INSTALL) { 7738 if (chatty) 7739 Log.d(TAG, "Removing package " + ps.name); 7740 } 7741 7742 // writer 7743 synchronized (mPackages) { 7744 mPackages.remove(ps.name); 7745 final PackageParser.Package pkg = ps.pkg; 7746 if (pkg != null) { 7747 cleanPackageDataStructuresLILPw(pkg, chatty); 7748 } 7749 } 7750 } 7751 7752 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7753 if (DEBUG_INSTALL) { 7754 if (chatty) 7755 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7756 } 7757 7758 // writer 7759 synchronized (mPackages) { 7760 mPackages.remove(pkg.applicationInfo.packageName); 7761 cleanPackageDataStructuresLILPw(pkg, chatty); 7762 } 7763 } 7764 7765 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7766 int N = pkg.providers.size(); 7767 StringBuilder r = null; 7768 int i; 7769 for (i=0; i<N; i++) { 7770 PackageParser.Provider p = pkg.providers.get(i); 7771 mProviders.removeProvider(p); 7772 if (p.info.authority == null) { 7773 7774 /* There was another ContentProvider with this authority when 7775 * this app was installed so this authority is null, 7776 * Ignore it as we don't have to unregister the provider. 7777 */ 7778 continue; 7779 } 7780 String names[] = p.info.authority.split(";"); 7781 for (int j = 0; j < names.length; j++) { 7782 if (mProvidersByAuthority.get(names[j]) == p) { 7783 mProvidersByAuthority.remove(names[j]); 7784 if (DEBUG_REMOVE) { 7785 if (chatty) 7786 Log.d(TAG, "Unregistered content provider: " + names[j] 7787 + ", className = " + p.info.name + ", isSyncable = " 7788 + p.info.isSyncable); 7789 } 7790 } 7791 } 7792 if (DEBUG_REMOVE && chatty) { 7793 if (r == null) { 7794 r = new StringBuilder(256); 7795 } else { 7796 r.append(' '); 7797 } 7798 r.append(p.info.name); 7799 } 7800 } 7801 if (r != null) { 7802 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7803 } 7804 7805 N = pkg.services.size(); 7806 r = null; 7807 for (i=0; i<N; i++) { 7808 PackageParser.Service s = pkg.services.get(i); 7809 mServices.removeService(s); 7810 if (chatty) { 7811 if (r == null) { 7812 r = new StringBuilder(256); 7813 } else { 7814 r.append(' '); 7815 } 7816 r.append(s.info.name); 7817 } 7818 } 7819 if (r != null) { 7820 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7821 } 7822 7823 N = pkg.receivers.size(); 7824 r = null; 7825 for (i=0; i<N; i++) { 7826 PackageParser.Activity a = pkg.receivers.get(i); 7827 mReceivers.removeActivity(a, "receiver"); 7828 if (DEBUG_REMOVE && chatty) { 7829 if (r == null) { 7830 r = new StringBuilder(256); 7831 } else { 7832 r.append(' '); 7833 } 7834 r.append(a.info.name); 7835 } 7836 } 7837 if (r != null) { 7838 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7839 } 7840 7841 N = pkg.activities.size(); 7842 r = null; 7843 for (i=0; i<N; i++) { 7844 PackageParser.Activity a = pkg.activities.get(i); 7845 mActivities.removeActivity(a, "activity"); 7846 if (DEBUG_REMOVE && chatty) { 7847 if (r == null) { 7848 r = new StringBuilder(256); 7849 } else { 7850 r.append(' '); 7851 } 7852 r.append(a.info.name); 7853 } 7854 } 7855 if (r != null) { 7856 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7857 } 7858 7859 N = pkg.permissions.size(); 7860 r = null; 7861 for (i=0; i<N; i++) { 7862 PackageParser.Permission p = pkg.permissions.get(i); 7863 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7864 if (bp == null) { 7865 bp = mSettings.mPermissionTrees.get(p.info.name); 7866 } 7867 if (bp != null && bp.perm == p) { 7868 bp.perm = null; 7869 if (DEBUG_REMOVE && chatty) { 7870 if (r == null) { 7871 r = new StringBuilder(256); 7872 } else { 7873 r.append(' '); 7874 } 7875 r.append(p.info.name); 7876 } 7877 } 7878 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7879 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7880 if (appOpPerms != null) { 7881 appOpPerms.remove(pkg.packageName); 7882 } 7883 } 7884 } 7885 if (r != null) { 7886 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7887 } 7888 7889 N = pkg.requestedPermissions.size(); 7890 r = null; 7891 for (i=0; i<N; i++) { 7892 String perm = pkg.requestedPermissions.get(i); 7893 BasePermission bp = mSettings.mPermissions.get(perm); 7894 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7895 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7896 if (appOpPerms != null) { 7897 appOpPerms.remove(pkg.packageName); 7898 if (appOpPerms.isEmpty()) { 7899 mAppOpPermissionPackages.remove(perm); 7900 } 7901 } 7902 } 7903 } 7904 if (r != null) { 7905 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7906 } 7907 7908 N = pkg.instrumentation.size(); 7909 r = null; 7910 for (i=0; i<N; i++) { 7911 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7912 mInstrumentation.remove(a.getComponentName()); 7913 if (DEBUG_REMOVE && chatty) { 7914 if (r == null) { 7915 r = new StringBuilder(256); 7916 } else { 7917 r.append(' '); 7918 } 7919 r.append(a.info.name); 7920 } 7921 } 7922 if (r != null) { 7923 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7924 } 7925 7926 r = null; 7927 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7928 // Only system apps can hold shared libraries. 7929 if (pkg.libraryNames != null) { 7930 for (i=0; i<pkg.libraryNames.size(); i++) { 7931 String name = pkg.libraryNames.get(i); 7932 SharedLibraryEntry cur = mSharedLibraries.get(name); 7933 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7934 mSharedLibraries.remove(name); 7935 if (DEBUG_REMOVE && chatty) { 7936 if (r == null) { 7937 r = new StringBuilder(256); 7938 } else { 7939 r.append(' '); 7940 } 7941 r.append(name); 7942 } 7943 } 7944 } 7945 } 7946 } 7947 if (r != null) { 7948 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7949 } 7950 } 7951 7952 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7953 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7954 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7955 return true; 7956 } 7957 } 7958 return false; 7959 } 7960 7961 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7962 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7963 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7964 7965 private void updatePermissionsLPw(String changingPkg, 7966 PackageParser.Package pkgInfo, int flags) { 7967 // Make sure there are no dangling permission trees. 7968 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7969 while (it.hasNext()) { 7970 final BasePermission bp = it.next(); 7971 if (bp.packageSetting == null) { 7972 // We may not yet have parsed the package, so just see if 7973 // we still know about its settings. 7974 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7975 } 7976 if (bp.packageSetting == null) { 7977 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7978 + " from package " + bp.sourcePackage); 7979 it.remove(); 7980 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7981 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7982 Slog.i(TAG, "Removing old permission tree: " + bp.name 7983 + " from package " + bp.sourcePackage); 7984 flags |= UPDATE_PERMISSIONS_ALL; 7985 it.remove(); 7986 } 7987 } 7988 } 7989 7990 // Make sure all dynamic permissions have been assigned to a package, 7991 // and make sure there are no dangling permissions. 7992 it = mSettings.mPermissions.values().iterator(); 7993 while (it.hasNext()) { 7994 final BasePermission bp = it.next(); 7995 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7996 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7997 + bp.name + " pkg=" + bp.sourcePackage 7998 + " info=" + bp.pendingInfo); 7999 if (bp.packageSetting == null && bp.pendingInfo != null) { 8000 final BasePermission tree = findPermissionTreeLP(bp.name); 8001 if (tree != null && tree.perm != null) { 8002 bp.packageSetting = tree.packageSetting; 8003 bp.perm = new PackageParser.Permission(tree.perm.owner, 8004 new PermissionInfo(bp.pendingInfo)); 8005 bp.perm.info.packageName = tree.perm.info.packageName; 8006 bp.perm.info.name = bp.name; 8007 bp.uid = tree.uid; 8008 } 8009 } 8010 } 8011 if (bp.packageSetting == null) { 8012 // We may not yet have parsed the package, so just see if 8013 // we still know about its settings. 8014 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8015 } 8016 if (bp.packageSetting == null) { 8017 Slog.w(TAG, "Removing dangling permission: " + bp.name 8018 + " from package " + bp.sourcePackage); 8019 it.remove(); 8020 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8021 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8022 Slog.i(TAG, "Removing old permission: " + bp.name 8023 + " from package " + bp.sourcePackage); 8024 flags |= UPDATE_PERMISSIONS_ALL; 8025 it.remove(); 8026 } 8027 } 8028 } 8029 8030 // Now update the permissions for all packages, in particular 8031 // replace the granted permissions of the system packages. 8032 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8033 for (PackageParser.Package pkg : mPackages.values()) { 8034 if (pkg != pkgInfo) { 8035 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8036 changingPkg); 8037 } 8038 } 8039 } 8040 8041 if (pkgInfo != null) { 8042 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8043 } 8044 } 8045 8046 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8047 String packageOfInterest) { 8048 // IMPORTANT: There are two types of permissions: install and runtime. 8049 // Install time permissions are granted when the app is installed to 8050 // all device users and users added in the future. Runtime permissions 8051 // are granted at runtime explicitly to specific users. Normal and signature 8052 // protected permissions are install time permissions. Dangerous permissions 8053 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8054 // otherwise they are runtime permissions. This function does not manage 8055 // runtime permissions except for the case an app targeting Lollipop MR1 8056 // being upgraded to target a newer SDK, in which case dangerous permissions 8057 // are transformed from install time to runtime ones. 8058 8059 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8060 if (ps == null) { 8061 return; 8062 } 8063 8064 PermissionsState permissionsState = ps.getPermissionsState(); 8065 PermissionsState origPermissions = permissionsState; 8066 8067 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8068 8069 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8070 8071 boolean changedInstallPermission = false; 8072 8073 if (replace) { 8074 ps.installPermissionsFixed = false; 8075 if (!ps.isSharedUser()) { 8076 origPermissions = new PermissionsState(permissionsState); 8077 permissionsState.reset(); 8078 } 8079 } 8080 8081 permissionsState.setGlobalGids(mGlobalGids); 8082 8083 final int N = pkg.requestedPermissions.size(); 8084 for (int i=0; i<N; i++) { 8085 final String name = pkg.requestedPermissions.get(i); 8086 final BasePermission bp = mSettings.mPermissions.get(name); 8087 8088 if (DEBUG_INSTALL) { 8089 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8090 } 8091 8092 if (bp == null || bp.packageSetting == null) { 8093 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8094 Slog.w(TAG, "Unknown permission " + name 8095 + " in package " + pkg.packageName); 8096 } 8097 continue; 8098 } 8099 8100 final String perm = bp.name; 8101 boolean allowedSig = false; 8102 int grant = GRANT_DENIED; 8103 8104 // Keep track of app op permissions. 8105 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8106 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8107 if (pkgs == null) { 8108 pkgs = new ArraySet<>(); 8109 mAppOpPermissionPackages.put(bp.name, pkgs); 8110 } 8111 pkgs.add(pkg.packageName); 8112 } 8113 8114 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8115 switch (level) { 8116 case PermissionInfo.PROTECTION_NORMAL: { 8117 // For all apps normal permissions are install time ones. 8118 grant = GRANT_INSTALL; 8119 } break; 8120 8121 case PermissionInfo.PROTECTION_DANGEROUS: { 8122 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8123 // For legacy apps dangerous permissions are install time ones. 8124 grant = GRANT_INSTALL_LEGACY; 8125 } else if (origPermissions.hasInstallPermission(bp.name)) { 8126 // For legacy apps that became modern, install becomes runtime. 8127 grant = GRANT_UPGRADE; 8128 } else { 8129 // For modern apps keep runtime permissions unchanged. 8130 grant = GRANT_RUNTIME; 8131 } 8132 } break; 8133 8134 case PermissionInfo.PROTECTION_SIGNATURE: { 8135 // For all apps signature permissions are install time ones. 8136 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8137 if (allowedSig) { 8138 grant = GRANT_INSTALL; 8139 } 8140 } break; 8141 } 8142 8143 if (DEBUG_INSTALL) { 8144 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8145 } 8146 8147 if (grant != GRANT_DENIED) { 8148 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8149 // If this is an existing, non-system package, then 8150 // we can't add any new permissions to it. 8151 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8152 // Except... if this is a permission that was added 8153 // to the platform (note: need to only do this when 8154 // updating the platform). 8155 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8156 grant = GRANT_DENIED; 8157 } 8158 } 8159 } 8160 8161 switch (grant) { 8162 case GRANT_INSTALL: { 8163 // Revoke this as runtime permission to handle the case of 8164 // a runtime permission being downgraded to an install one. 8165 for (int userId : UserManagerService.getInstance().getUserIds()) { 8166 if (origPermissions.getRuntimePermissionState( 8167 bp.name, userId) != null) { 8168 // Revoke the runtime permission and clear the flags. 8169 origPermissions.revokeRuntimePermission(bp, userId); 8170 origPermissions.updatePermissionFlags(bp, userId, 8171 PackageManager.MASK_PERMISSION_FLAGS, 0); 8172 // If we revoked a permission permission, we have to write. 8173 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8174 changedRuntimePermissionUserIds, userId); 8175 } 8176 } 8177 // Grant an install permission. 8178 if (permissionsState.grantInstallPermission(bp) != 8179 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8180 changedInstallPermission = true; 8181 } 8182 } break; 8183 8184 case GRANT_INSTALL_LEGACY: { 8185 // Grant an install permission. 8186 if (permissionsState.grantInstallPermission(bp) != 8187 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8188 changedInstallPermission = true; 8189 } 8190 } break; 8191 8192 case GRANT_RUNTIME: { 8193 // Grant previously granted runtime permissions. 8194 for (int userId : UserManagerService.getInstance().getUserIds()) { 8195 PermissionState permissionState = origPermissions 8196 .getRuntimePermissionState(bp.name, userId); 8197 final int flags = permissionState != null 8198 ? permissionState.getFlags() : 0; 8199 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8200 if (permissionsState.grantRuntimePermission(bp, userId) == 8201 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8202 // If we cannot put the permission as it was, we have to write. 8203 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8204 changedRuntimePermissionUserIds, userId); 8205 } 8206 } 8207 // Propagate the permission flags. 8208 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8209 } 8210 } break; 8211 8212 case GRANT_UPGRADE: { 8213 // Grant runtime permissions for a previously held install permission. 8214 PermissionState permissionState = origPermissions 8215 .getInstallPermissionState(bp.name); 8216 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8217 8218 if (origPermissions.revokeInstallPermission(bp) 8219 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8220 // We will be transferring the permission flags, so clear them. 8221 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8222 PackageManager.MASK_PERMISSION_FLAGS, 0); 8223 changedInstallPermission = true; 8224 } 8225 8226 // If the permission is not to be promoted to runtime we ignore it and 8227 // also its other flags as they are not applicable to install permissions. 8228 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8229 for (int userId : currentUserIds) { 8230 if (permissionsState.grantRuntimePermission(bp, userId) != 8231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8232 // Transfer the permission flags. 8233 permissionsState.updatePermissionFlags(bp, userId, 8234 flags, flags); 8235 // If we granted the permission, we have to write. 8236 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8237 changedRuntimePermissionUserIds, userId); 8238 } 8239 } 8240 } 8241 } break; 8242 8243 default: { 8244 if (packageOfInterest == null 8245 || packageOfInterest.equals(pkg.packageName)) { 8246 Slog.w(TAG, "Not granting permission " + perm 8247 + " to package " + pkg.packageName 8248 + " because it was previously installed without"); 8249 } 8250 } break; 8251 } 8252 } else { 8253 if (permissionsState.revokeInstallPermission(bp) != 8254 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8255 // Also drop the permission flags. 8256 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8257 PackageManager.MASK_PERMISSION_FLAGS, 0); 8258 changedInstallPermission = true; 8259 Slog.i(TAG, "Un-granting permission " + perm 8260 + " from package " + pkg.packageName 8261 + " (protectionLevel=" + bp.protectionLevel 8262 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8263 + ")"); 8264 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8265 // Don't print warning for app op permissions, since it is fine for them 8266 // not to be granted, there is a UI for the user to decide. 8267 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8268 Slog.w(TAG, "Not granting permission " + perm 8269 + " to package " + pkg.packageName 8270 + " (protectionLevel=" + bp.protectionLevel 8271 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8272 + ")"); 8273 } 8274 } 8275 } 8276 } 8277 8278 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8279 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8280 // This is the first that we have heard about this package, so the 8281 // permissions we have now selected are fixed until explicitly 8282 // changed. 8283 ps.installPermissionsFixed = true; 8284 } 8285 8286 // Persist the runtime permissions state for users with changes. 8287 for (int userId : changedRuntimePermissionUserIds) { 8288 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8289 } 8290 } 8291 8292 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8293 boolean allowed = false; 8294 final int NP = PackageParser.NEW_PERMISSIONS.length; 8295 for (int ip=0; ip<NP; ip++) { 8296 final PackageParser.NewPermissionInfo npi 8297 = PackageParser.NEW_PERMISSIONS[ip]; 8298 if (npi.name.equals(perm) 8299 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8300 allowed = true; 8301 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8302 + pkg.packageName); 8303 break; 8304 } 8305 } 8306 return allowed; 8307 } 8308 8309 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8310 BasePermission bp, PermissionsState origPermissions) { 8311 boolean allowed; 8312 allowed = (compareSignatures( 8313 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8314 == PackageManager.SIGNATURE_MATCH) 8315 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8316 == PackageManager.SIGNATURE_MATCH); 8317 if (!allowed && (bp.protectionLevel 8318 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8319 if (isSystemApp(pkg)) { 8320 // For updated system applications, a system permission 8321 // is granted only if it had been defined by the original application. 8322 if (pkg.isUpdatedSystemApp()) { 8323 final PackageSetting sysPs = mSettings 8324 .getDisabledSystemPkgLPr(pkg.packageName); 8325 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8326 // If the original was granted this permission, we take 8327 // that grant decision as read and propagate it to the 8328 // update. 8329 if (sysPs.isPrivileged()) { 8330 allowed = true; 8331 } 8332 } else { 8333 // The system apk may have been updated with an older 8334 // version of the one on the data partition, but which 8335 // granted a new system permission that it didn't have 8336 // before. In this case we do want to allow the app to 8337 // now get the new permission if the ancestral apk is 8338 // privileged to get it. 8339 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8340 for (int j=0; 8341 j<sysPs.pkg.requestedPermissions.size(); j++) { 8342 if (perm.equals( 8343 sysPs.pkg.requestedPermissions.get(j))) { 8344 allowed = true; 8345 break; 8346 } 8347 } 8348 } 8349 } 8350 } else { 8351 allowed = isPrivilegedApp(pkg); 8352 } 8353 } 8354 } 8355 if (!allowed && (bp.protectionLevel 8356 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8357 // For development permissions, a development permission 8358 // is granted only if it was already granted. 8359 allowed = origPermissions.hasInstallPermission(perm); 8360 } 8361 return allowed; 8362 } 8363 8364 final class ActivityIntentResolver 8365 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8366 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8367 boolean defaultOnly, int userId) { 8368 if (!sUserManager.exists(userId)) return null; 8369 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8370 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8371 } 8372 8373 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8374 int userId) { 8375 if (!sUserManager.exists(userId)) return null; 8376 mFlags = flags; 8377 return super.queryIntent(intent, resolvedType, 8378 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8379 } 8380 8381 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8382 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8383 if (!sUserManager.exists(userId)) return null; 8384 if (packageActivities == null) { 8385 return null; 8386 } 8387 mFlags = flags; 8388 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8389 final int N = packageActivities.size(); 8390 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8391 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8392 8393 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8394 for (int i = 0; i < N; ++i) { 8395 intentFilters = packageActivities.get(i).intents; 8396 if (intentFilters != null && intentFilters.size() > 0) { 8397 PackageParser.ActivityIntentInfo[] array = 8398 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8399 intentFilters.toArray(array); 8400 listCut.add(array); 8401 } 8402 } 8403 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8404 } 8405 8406 public final void addActivity(PackageParser.Activity a, String type) { 8407 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8408 mActivities.put(a.getComponentName(), a); 8409 if (DEBUG_SHOW_INFO) 8410 Log.v( 8411 TAG, " " + type + " " + 8412 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8413 if (DEBUG_SHOW_INFO) 8414 Log.v(TAG, " Class=" + a.info.name); 8415 final int NI = a.intents.size(); 8416 for (int j=0; j<NI; j++) { 8417 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8418 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8419 intent.setPriority(0); 8420 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8421 + a.className + " with priority > 0, forcing to 0"); 8422 } 8423 if (DEBUG_SHOW_INFO) { 8424 Log.v(TAG, " IntentFilter:"); 8425 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8426 } 8427 if (!intent.debugCheck()) { 8428 Log.w(TAG, "==> For Activity " + a.info.name); 8429 } 8430 addFilter(intent); 8431 } 8432 } 8433 8434 public final void removeActivity(PackageParser.Activity a, String type) { 8435 mActivities.remove(a.getComponentName()); 8436 if (DEBUG_SHOW_INFO) { 8437 Log.v(TAG, " " + type + " " 8438 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8439 : a.info.name) + ":"); 8440 Log.v(TAG, " Class=" + a.info.name); 8441 } 8442 final int NI = a.intents.size(); 8443 for (int j=0; j<NI; j++) { 8444 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8445 if (DEBUG_SHOW_INFO) { 8446 Log.v(TAG, " IntentFilter:"); 8447 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8448 } 8449 removeFilter(intent); 8450 } 8451 } 8452 8453 @Override 8454 protected boolean allowFilterResult( 8455 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8456 ActivityInfo filterAi = filter.activity.info; 8457 for (int i=dest.size()-1; i>=0; i--) { 8458 ActivityInfo destAi = dest.get(i).activityInfo; 8459 if (destAi.name == filterAi.name 8460 && destAi.packageName == filterAi.packageName) { 8461 return false; 8462 } 8463 } 8464 return true; 8465 } 8466 8467 @Override 8468 protected ActivityIntentInfo[] newArray(int size) { 8469 return new ActivityIntentInfo[size]; 8470 } 8471 8472 @Override 8473 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8474 if (!sUserManager.exists(userId)) return true; 8475 PackageParser.Package p = filter.activity.owner; 8476 if (p != null) { 8477 PackageSetting ps = (PackageSetting)p.mExtras; 8478 if (ps != null) { 8479 // System apps are never considered stopped for purposes of 8480 // filtering, because there may be no way for the user to 8481 // actually re-launch them. 8482 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8483 && ps.getStopped(userId); 8484 } 8485 } 8486 return false; 8487 } 8488 8489 @Override 8490 protected boolean isPackageForFilter(String packageName, 8491 PackageParser.ActivityIntentInfo info) { 8492 return packageName.equals(info.activity.owner.packageName); 8493 } 8494 8495 @Override 8496 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8497 int match, int userId) { 8498 if (!sUserManager.exists(userId)) return null; 8499 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8500 return null; 8501 } 8502 final PackageParser.Activity activity = info.activity; 8503 if (mSafeMode && (activity.info.applicationInfo.flags 8504 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8505 return null; 8506 } 8507 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8508 if (ps == null) { 8509 return null; 8510 } 8511 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8512 ps.readUserState(userId), userId); 8513 if (ai == null) { 8514 return null; 8515 } 8516 final ResolveInfo res = new ResolveInfo(); 8517 res.activityInfo = ai; 8518 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8519 res.filter = info; 8520 } 8521 if (info != null) { 8522 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8523 } 8524 res.priority = info.getPriority(); 8525 res.preferredOrder = activity.owner.mPreferredOrder; 8526 //System.out.println("Result: " + res.activityInfo.className + 8527 // " = " + res.priority); 8528 res.match = match; 8529 res.isDefault = info.hasDefault; 8530 res.labelRes = info.labelRes; 8531 res.nonLocalizedLabel = info.nonLocalizedLabel; 8532 if (userNeedsBadging(userId)) { 8533 res.noResourceId = true; 8534 } else { 8535 res.icon = info.icon; 8536 } 8537 res.iconResourceId = info.icon; 8538 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8539 return res; 8540 } 8541 8542 @Override 8543 protected void sortResults(List<ResolveInfo> results) { 8544 Collections.sort(results, mResolvePrioritySorter); 8545 } 8546 8547 @Override 8548 protected void dumpFilter(PrintWriter out, String prefix, 8549 PackageParser.ActivityIntentInfo filter) { 8550 out.print(prefix); out.print( 8551 Integer.toHexString(System.identityHashCode(filter.activity))); 8552 out.print(' '); 8553 filter.activity.printComponentShortName(out); 8554 out.print(" filter "); 8555 out.println(Integer.toHexString(System.identityHashCode(filter))); 8556 } 8557 8558 @Override 8559 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8560 return filter.activity; 8561 } 8562 8563 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8564 PackageParser.Activity activity = (PackageParser.Activity)label; 8565 out.print(prefix); out.print( 8566 Integer.toHexString(System.identityHashCode(activity))); 8567 out.print(' '); 8568 activity.printComponentShortName(out); 8569 if (count > 1) { 8570 out.print(" ("); out.print(count); out.print(" filters)"); 8571 } 8572 out.println(); 8573 } 8574 8575// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8576// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8577// final List<ResolveInfo> retList = Lists.newArrayList(); 8578// while (i.hasNext()) { 8579// final ResolveInfo resolveInfo = i.next(); 8580// if (isEnabledLP(resolveInfo.activityInfo)) { 8581// retList.add(resolveInfo); 8582// } 8583// } 8584// return retList; 8585// } 8586 8587 // Keys are String (activity class name), values are Activity. 8588 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8589 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8590 private int mFlags; 8591 } 8592 8593 private final class ServiceIntentResolver 8594 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8595 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8596 boolean defaultOnly, int userId) { 8597 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8598 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8599 } 8600 8601 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8602 int userId) { 8603 if (!sUserManager.exists(userId)) return null; 8604 mFlags = flags; 8605 return super.queryIntent(intent, resolvedType, 8606 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8607 } 8608 8609 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8610 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8611 if (!sUserManager.exists(userId)) return null; 8612 if (packageServices == null) { 8613 return null; 8614 } 8615 mFlags = flags; 8616 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8617 final int N = packageServices.size(); 8618 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8619 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8620 8621 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8622 for (int i = 0; i < N; ++i) { 8623 intentFilters = packageServices.get(i).intents; 8624 if (intentFilters != null && intentFilters.size() > 0) { 8625 PackageParser.ServiceIntentInfo[] array = 8626 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8627 intentFilters.toArray(array); 8628 listCut.add(array); 8629 } 8630 } 8631 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8632 } 8633 8634 public final void addService(PackageParser.Service s) { 8635 mServices.put(s.getComponentName(), s); 8636 if (DEBUG_SHOW_INFO) { 8637 Log.v(TAG, " " 8638 + (s.info.nonLocalizedLabel != null 8639 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8640 Log.v(TAG, " Class=" + s.info.name); 8641 } 8642 final int NI = s.intents.size(); 8643 int j; 8644 for (j=0; j<NI; j++) { 8645 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8646 if (DEBUG_SHOW_INFO) { 8647 Log.v(TAG, " IntentFilter:"); 8648 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8649 } 8650 if (!intent.debugCheck()) { 8651 Log.w(TAG, "==> For Service " + s.info.name); 8652 } 8653 addFilter(intent); 8654 } 8655 } 8656 8657 public final void removeService(PackageParser.Service s) { 8658 mServices.remove(s.getComponentName()); 8659 if (DEBUG_SHOW_INFO) { 8660 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8661 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8662 Log.v(TAG, " Class=" + s.info.name); 8663 } 8664 final int NI = s.intents.size(); 8665 int j; 8666 for (j=0; j<NI; j++) { 8667 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8668 if (DEBUG_SHOW_INFO) { 8669 Log.v(TAG, " IntentFilter:"); 8670 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8671 } 8672 removeFilter(intent); 8673 } 8674 } 8675 8676 @Override 8677 protected boolean allowFilterResult( 8678 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8679 ServiceInfo filterSi = filter.service.info; 8680 for (int i=dest.size()-1; i>=0; i--) { 8681 ServiceInfo destAi = dest.get(i).serviceInfo; 8682 if (destAi.name == filterSi.name 8683 && destAi.packageName == filterSi.packageName) { 8684 return false; 8685 } 8686 } 8687 return true; 8688 } 8689 8690 @Override 8691 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8692 return new PackageParser.ServiceIntentInfo[size]; 8693 } 8694 8695 @Override 8696 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8697 if (!sUserManager.exists(userId)) return true; 8698 PackageParser.Package p = filter.service.owner; 8699 if (p != null) { 8700 PackageSetting ps = (PackageSetting)p.mExtras; 8701 if (ps != null) { 8702 // System apps are never considered stopped for purposes of 8703 // filtering, because there may be no way for the user to 8704 // actually re-launch them. 8705 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8706 && ps.getStopped(userId); 8707 } 8708 } 8709 return false; 8710 } 8711 8712 @Override 8713 protected boolean isPackageForFilter(String packageName, 8714 PackageParser.ServiceIntentInfo info) { 8715 return packageName.equals(info.service.owner.packageName); 8716 } 8717 8718 @Override 8719 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8720 int match, int userId) { 8721 if (!sUserManager.exists(userId)) return null; 8722 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8723 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8724 return null; 8725 } 8726 final PackageParser.Service service = info.service; 8727 if (mSafeMode && (service.info.applicationInfo.flags 8728 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8729 return null; 8730 } 8731 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8732 if (ps == null) { 8733 return null; 8734 } 8735 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8736 ps.readUserState(userId), userId); 8737 if (si == null) { 8738 return null; 8739 } 8740 final ResolveInfo res = new ResolveInfo(); 8741 res.serviceInfo = si; 8742 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8743 res.filter = filter; 8744 } 8745 res.priority = info.getPriority(); 8746 res.preferredOrder = service.owner.mPreferredOrder; 8747 res.match = match; 8748 res.isDefault = info.hasDefault; 8749 res.labelRes = info.labelRes; 8750 res.nonLocalizedLabel = info.nonLocalizedLabel; 8751 res.icon = info.icon; 8752 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8753 return res; 8754 } 8755 8756 @Override 8757 protected void sortResults(List<ResolveInfo> results) { 8758 Collections.sort(results, mResolvePrioritySorter); 8759 } 8760 8761 @Override 8762 protected void dumpFilter(PrintWriter out, String prefix, 8763 PackageParser.ServiceIntentInfo filter) { 8764 out.print(prefix); out.print( 8765 Integer.toHexString(System.identityHashCode(filter.service))); 8766 out.print(' '); 8767 filter.service.printComponentShortName(out); 8768 out.print(" filter "); 8769 out.println(Integer.toHexString(System.identityHashCode(filter))); 8770 } 8771 8772 @Override 8773 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8774 return filter.service; 8775 } 8776 8777 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8778 PackageParser.Service service = (PackageParser.Service)label; 8779 out.print(prefix); out.print( 8780 Integer.toHexString(System.identityHashCode(service))); 8781 out.print(' '); 8782 service.printComponentShortName(out); 8783 if (count > 1) { 8784 out.print(" ("); out.print(count); out.print(" filters)"); 8785 } 8786 out.println(); 8787 } 8788 8789// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8790// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8791// final List<ResolveInfo> retList = Lists.newArrayList(); 8792// while (i.hasNext()) { 8793// final ResolveInfo resolveInfo = (ResolveInfo) i; 8794// if (isEnabledLP(resolveInfo.serviceInfo)) { 8795// retList.add(resolveInfo); 8796// } 8797// } 8798// return retList; 8799// } 8800 8801 // Keys are String (activity class name), values are Activity. 8802 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8803 = new ArrayMap<ComponentName, PackageParser.Service>(); 8804 private int mFlags; 8805 }; 8806 8807 private final class ProviderIntentResolver 8808 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8809 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8810 boolean defaultOnly, int userId) { 8811 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8812 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8813 } 8814 8815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8816 int userId) { 8817 if (!sUserManager.exists(userId)) 8818 return null; 8819 mFlags = flags; 8820 return super.queryIntent(intent, resolvedType, 8821 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8822 } 8823 8824 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8825 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8826 if (!sUserManager.exists(userId)) 8827 return null; 8828 if (packageProviders == null) { 8829 return null; 8830 } 8831 mFlags = flags; 8832 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8833 final int N = packageProviders.size(); 8834 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8835 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8836 8837 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8838 for (int i = 0; i < N; ++i) { 8839 intentFilters = packageProviders.get(i).intents; 8840 if (intentFilters != null && intentFilters.size() > 0) { 8841 PackageParser.ProviderIntentInfo[] array = 8842 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8843 intentFilters.toArray(array); 8844 listCut.add(array); 8845 } 8846 } 8847 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8848 } 8849 8850 public final void addProvider(PackageParser.Provider p) { 8851 if (mProviders.containsKey(p.getComponentName())) { 8852 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8853 return; 8854 } 8855 8856 mProviders.put(p.getComponentName(), p); 8857 if (DEBUG_SHOW_INFO) { 8858 Log.v(TAG, " " 8859 + (p.info.nonLocalizedLabel != null 8860 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8861 Log.v(TAG, " Class=" + p.info.name); 8862 } 8863 final int NI = p.intents.size(); 8864 int j; 8865 for (j = 0; j < NI; j++) { 8866 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8867 if (DEBUG_SHOW_INFO) { 8868 Log.v(TAG, " IntentFilter:"); 8869 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8870 } 8871 if (!intent.debugCheck()) { 8872 Log.w(TAG, "==> For Provider " + p.info.name); 8873 } 8874 addFilter(intent); 8875 } 8876 } 8877 8878 public final void removeProvider(PackageParser.Provider p) { 8879 mProviders.remove(p.getComponentName()); 8880 if (DEBUG_SHOW_INFO) { 8881 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8882 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8883 Log.v(TAG, " Class=" + p.info.name); 8884 } 8885 final int NI = p.intents.size(); 8886 int j; 8887 for (j = 0; j < NI; j++) { 8888 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8889 if (DEBUG_SHOW_INFO) { 8890 Log.v(TAG, " IntentFilter:"); 8891 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8892 } 8893 removeFilter(intent); 8894 } 8895 } 8896 8897 @Override 8898 protected boolean allowFilterResult( 8899 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8900 ProviderInfo filterPi = filter.provider.info; 8901 for (int i = dest.size() - 1; i >= 0; i--) { 8902 ProviderInfo destPi = dest.get(i).providerInfo; 8903 if (destPi.name == filterPi.name 8904 && destPi.packageName == filterPi.packageName) { 8905 return false; 8906 } 8907 } 8908 return true; 8909 } 8910 8911 @Override 8912 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8913 return new PackageParser.ProviderIntentInfo[size]; 8914 } 8915 8916 @Override 8917 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8918 if (!sUserManager.exists(userId)) 8919 return true; 8920 PackageParser.Package p = filter.provider.owner; 8921 if (p != null) { 8922 PackageSetting ps = (PackageSetting) p.mExtras; 8923 if (ps != null) { 8924 // System apps are never considered stopped for purposes of 8925 // filtering, because there may be no way for the user to 8926 // actually re-launch them. 8927 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8928 && ps.getStopped(userId); 8929 } 8930 } 8931 return false; 8932 } 8933 8934 @Override 8935 protected boolean isPackageForFilter(String packageName, 8936 PackageParser.ProviderIntentInfo info) { 8937 return packageName.equals(info.provider.owner.packageName); 8938 } 8939 8940 @Override 8941 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8942 int match, int userId) { 8943 if (!sUserManager.exists(userId)) 8944 return null; 8945 final PackageParser.ProviderIntentInfo info = filter; 8946 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8947 return null; 8948 } 8949 final PackageParser.Provider provider = info.provider; 8950 if (mSafeMode && (provider.info.applicationInfo.flags 8951 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8952 return null; 8953 } 8954 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8955 if (ps == null) { 8956 return null; 8957 } 8958 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8959 ps.readUserState(userId), userId); 8960 if (pi == null) { 8961 return null; 8962 } 8963 final ResolveInfo res = new ResolveInfo(); 8964 res.providerInfo = pi; 8965 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8966 res.filter = filter; 8967 } 8968 res.priority = info.getPriority(); 8969 res.preferredOrder = provider.owner.mPreferredOrder; 8970 res.match = match; 8971 res.isDefault = info.hasDefault; 8972 res.labelRes = info.labelRes; 8973 res.nonLocalizedLabel = info.nonLocalizedLabel; 8974 res.icon = info.icon; 8975 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8976 return res; 8977 } 8978 8979 @Override 8980 protected void sortResults(List<ResolveInfo> results) { 8981 Collections.sort(results, mResolvePrioritySorter); 8982 } 8983 8984 @Override 8985 protected void dumpFilter(PrintWriter out, String prefix, 8986 PackageParser.ProviderIntentInfo filter) { 8987 out.print(prefix); 8988 out.print( 8989 Integer.toHexString(System.identityHashCode(filter.provider))); 8990 out.print(' '); 8991 filter.provider.printComponentShortName(out); 8992 out.print(" filter "); 8993 out.println(Integer.toHexString(System.identityHashCode(filter))); 8994 } 8995 8996 @Override 8997 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8998 return filter.provider; 8999 } 9000 9001 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9002 PackageParser.Provider provider = (PackageParser.Provider)label; 9003 out.print(prefix); out.print( 9004 Integer.toHexString(System.identityHashCode(provider))); 9005 out.print(' '); 9006 provider.printComponentShortName(out); 9007 if (count > 1) { 9008 out.print(" ("); out.print(count); out.print(" filters)"); 9009 } 9010 out.println(); 9011 } 9012 9013 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9014 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9015 private int mFlags; 9016 }; 9017 9018 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9019 new Comparator<ResolveInfo>() { 9020 public int compare(ResolveInfo r1, ResolveInfo r2) { 9021 int v1 = r1.priority; 9022 int v2 = r2.priority; 9023 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9024 if (v1 != v2) { 9025 return (v1 > v2) ? -1 : 1; 9026 } 9027 v1 = r1.preferredOrder; 9028 v2 = r2.preferredOrder; 9029 if (v1 != v2) { 9030 return (v1 > v2) ? -1 : 1; 9031 } 9032 if (r1.isDefault != r2.isDefault) { 9033 return r1.isDefault ? -1 : 1; 9034 } 9035 v1 = r1.match; 9036 v2 = r2.match; 9037 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9038 if (v1 != v2) { 9039 return (v1 > v2) ? -1 : 1; 9040 } 9041 if (r1.system != r2.system) { 9042 return r1.system ? -1 : 1; 9043 } 9044 return 0; 9045 } 9046 }; 9047 9048 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9049 new Comparator<ProviderInfo>() { 9050 public int compare(ProviderInfo p1, ProviderInfo p2) { 9051 final int v1 = p1.initOrder; 9052 final int v2 = p2.initOrder; 9053 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9054 } 9055 }; 9056 9057 final void sendPackageBroadcast(final String action, final String pkg, 9058 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9059 final int[] userIds) { 9060 mHandler.post(new Runnable() { 9061 @Override 9062 public void run() { 9063 try { 9064 final IActivityManager am = ActivityManagerNative.getDefault(); 9065 if (am == null) return; 9066 final int[] resolvedUserIds; 9067 if (userIds == null) { 9068 resolvedUserIds = am.getRunningUserIds(); 9069 } else { 9070 resolvedUserIds = userIds; 9071 } 9072 for (int id : resolvedUserIds) { 9073 final Intent intent = new Intent(action, 9074 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9075 if (extras != null) { 9076 intent.putExtras(extras); 9077 } 9078 if (targetPkg != null) { 9079 intent.setPackage(targetPkg); 9080 } 9081 // Modify the UID when posting to other users 9082 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9083 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9084 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9085 intent.putExtra(Intent.EXTRA_UID, uid); 9086 } 9087 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9088 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9089 if (DEBUG_BROADCASTS) { 9090 RuntimeException here = new RuntimeException("here"); 9091 here.fillInStackTrace(); 9092 Slog.d(TAG, "Sending to user " + id + ": " 9093 + intent.toShortString(false, true, false, false) 9094 + " " + intent.getExtras(), here); 9095 } 9096 am.broadcastIntent(null, intent, null, finishedReceiver, 9097 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9098 null, finishedReceiver != null, false, id); 9099 } 9100 } catch (RemoteException ex) { 9101 } 9102 } 9103 }); 9104 } 9105 9106 /** 9107 * Check if the external storage media is available. This is true if there 9108 * is a mounted external storage medium or if the external storage is 9109 * emulated. 9110 */ 9111 private boolean isExternalMediaAvailable() { 9112 return mMediaMounted || Environment.isExternalStorageEmulated(); 9113 } 9114 9115 @Override 9116 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9117 // writer 9118 synchronized (mPackages) { 9119 if (!isExternalMediaAvailable()) { 9120 // If the external storage is no longer mounted at this point, 9121 // the caller may not have been able to delete all of this 9122 // packages files and can not delete any more. Bail. 9123 return null; 9124 } 9125 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9126 if (lastPackage != null) { 9127 pkgs.remove(lastPackage); 9128 } 9129 if (pkgs.size() > 0) { 9130 return pkgs.get(0); 9131 } 9132 } 9133 return null; 9134 } 9135 9136 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9137 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9138 userId, andCode ? 1 : 0, packageName); 9139 if (mSystemReady) { 9140 msg.sendToTarget(); 9141 } else { 9142 if (mPostSystemReadyMessages == null) { 9143 mPostSystemReadyMessages = new ArrayList<>(); 9144 } 9145 mPostSystemReadyMessages.add(msg); 9146 } 9147 } 9148 9149 void startCleaningPackages() { 9150 // reader 9151 synchronized (mPackages) { 9152 if (!isExternalMediaAvailable()) { 9153 return; 9154 } 9155 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9156 return; 9157 } 9158 } 9159 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9160 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9161 IActivityManager am = ActivityManagerNative.getDefault(); 9162 if (am != null) { 9163 try { 9164 am.startService(null, intent, null, UserHandle.USER_OWNER); 9165 } catch (RemoteException e) { 9166 } 9167 } 9168 } 9169 9170 @Override 9171 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9172 int installFlags, String installerPackageName, VerificationParams verificationParams, 9173 String packageAbiOverride) { 9174 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9175 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9176 } 9177 9178 @Override 9179 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9180 int installFlags, String installerPackageName, VerificationParams verificationParams, 9181 String packageAbiOverride, int userId) { 9182 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9183 9184 final int callingUid = Binder.getCallingUid(); 9185 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9186 9187 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9188 try { 9189 if (observer != null) { 9190 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9191 } 9192 } catch (RemoteException re) { 9193 } 9194 return; 9195 } 9196 9197 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9198 installFlags |= PackageManager.INSTALL_FROM_ADB; 9199 9200 } else { 9201 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9202 // about installerPackageName. 9203 9204 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9205 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9206 } 9207 9208 UserHandle user; 9209 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9210 user = UserHandle.ALL; 9211 } else { 9212 user = new UserHandle(userId); 9213 } 9214 9215 // Only system components can circumvent runtime permissions when installing. 9216 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9217 && mContext.checkCallingOrSelfPermission(Manifest.permission 9218 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9219 throw new SecurityException("You need the " 9220 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9221 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9222 } 9223 9224 verificationParams.setInstallerUid(callingUid); 9225 9226 final File originFile = new File(originPath); 9227 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9228 9229 final Message msg = mHandler.obtainMessage(INIT_COPY); 9230 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9231 null, verificationParams, user, packageAbiOverride); 9232 mHandler.sendMessage(msg); 9233 } 9234 9235 void installStage(String packageName, File stagedDir, String stagedCid, 9236 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9237 String installerPackageName, int installerUid, UserHandle user) { 9238 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9239 params.referrerUri, installerUid, null); 9240 verifParams.setInstallerUid(installerUid); 9241 9242 final OriginInfo origin; 9243 if (stagedDir != null) { 9244 origin = OriginInfo.fromStagedFile(stagedDir); 9245 } else { 9246 origin = OriginInfo.fromStagedContainer(stagedCid); 9247 } 9248 9249 final Message msg = mHandler.obtainMessage(INIT_COPY); 9250 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9251 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9252 mHandler.sendMessage(msg); 9253 } 9254 9255 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9256 Bundle extras = new Bundle(1); 9257 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9258 9259 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9260 packageName, extras, null, null, new int[] {userId}); 9261 try { 9262 IActivityManager am = ActivityManagerNative.getDefault(); 9263 final boolean isSystem = 9264 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9265 if (isSystem && am.isUserRunning(userId, false)) { 9266 // The just-installed/enabled app is bundled on the system, so presumed 9267 // to be able to run automatically without needing an explicit launch. 9268 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9269 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9270 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9271 .setPackage(packageName); 9272 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9273 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9274 } 9275 } catch (RemoteException e) { 9276 // shouldn't happen 9277 Slog.w(TAG, "Unable to bootstrap installed package", e); 9278 } 9279 } 9280 9281 @Override 9282 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9283 int userId) { 9284 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9285 PackageSetting pkgSetting; 9286 final int uid = Binder.getCallingUid(); 9287 enforceCrossUserPermission(uid, userId, true, true, 9288 "setApplicationHiddenSetting for user " + userId); 9289 9290 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9291 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9292 return false; 9293 } 9294 9295 long callingId = Binder.clearCallingIdentity(); 9296 try { 9297 boolean sendAdded = false; 9298 boolean sendRemoved = false; 9299 // writer 9300 synchronized (mPackages) { 9301 pkgSetting = mSettings.mPackages.get(packageName); 9302 if (pkgSetting == null) { 9303 return false; 9304 } 9305 if (pkgSetting.getHidden(userId) != hidden) { 9306 pkgSetting.setHidden(hidden, userId); 9307 mSettings.writePackageRestrictionsLPr(userId); 9308 if (hidden) { 9309 sendRemoved = true; 9310 } else { 9311 sendAdded = true; 9312 } 9313 } 9314 } 9315 if (sendAdded) { 9316 sendPackageAddedForUser(packageName, pkgSetting, userId); 9317 return true; 9318 } 9319 if (sendRemoved) { 9320 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9321 "hiding pkg"); 9322 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9323 } 9324 } finally { 9325 Binder.restoreCallingIdentity(callingId); 9326 } 9327 return false; 9328 } 9329 9330 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9331 int userId) { 9332 final PackageRemovedInfo info = new PackageRemovedInfo(); 9333 info.removedPackage = packageName; 9334 info.removedUsers = new int[] {userId}; 9335 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9336 info.sendBroadcast(false, false, false); 9337 } 9338 9339 /** 9340 * Returns true if application is not found or there was an error. Otherwise it returns 9341 * the hidden state of the package for the given user. 9342 */ 9343 @Override 9344 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9346 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9347 false, "getApplicationHidden for user " + userId); 9348 PackageSetting pkgSetting; 9349 long callingId = Binder.clearCallingIdentity(); 9350 try { 9351 // writer 9352 synchronized (mPackages) { 9353 pkgSetting = mSettings.mPackages.get(packageName); 9354 if (pkgSetting == null) { 9355 return true; 9356 } 9357 return pkgSetting.getHidden(userId); 9358 } 9359 } finally { 9360 Binder.restoreCallingIdentity(callingId); 9361 } 9362 } 9363 9364 /** 9365 * @hide 9366 */ 9367 @Override 9368 public int installExistingPackageAsUser(String packageName, int userId) { 9369 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9370 null); 9371 PackageSetting pkgSetting; 9372 final int uid = Binder.getCallingUid(); 9373 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9374 + userId); 9375 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9376 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9377 } 9378 9379 long callingId = Binder.clearCallingIdentity(); 9380 try { 9381 boolean sendAdded = false; 9382 9383 // writer 9384 synchronized (mPackages) { 9385 pkgSetting = mSettings.mPackages.get(packageName); 9386 if (pkgSetting == null) { 9387 return PackageManager.INSTALL_FAILED_INVALID_URI; 9388 } 9389 if (!pkgSetting.getInstalled(userId)) { 9390 pkgSetting.setInstalled(true, userId); 9391 pkgSetting.setHidden(false, userId); 9392 mSettings.writePackageRestrictionsLPr(userId); 9393 sendAdded = true; 9394 } 9395 } 9396 9397 if (sendAdded) { 9398 sendPackageAddedForUser(packageName, pkgSetting, userId); 9399 } 9400 } finally { 9401 Binder.restoreCallingIdentity(callingId); 9402 } 9403 9404 return PackageManager.INSTALL_SUCCEEDED; 9405 } 9406 9407 boolean isUserRestricted(int userId, String restrictionKey) { 9408 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9409 if (restrictions.getBoolean(restrictionKey, false)) { 9410 Log.w(TAG, "User is restricted: " + restrictionKey); 9411 return true; 9412 } 9413 return false; 9414 } 9415 9416 @Override 9417 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9418 mContext.enforceCallingOrSelfPermission( 9419 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9420 "Only package verification agents can verify applications"); 9421 9422 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9423 final PackageVerificationResponse response = new PackageVerificationResponse( 9424 verificationCode, Binder.getCallingUid()); 9425 msg.arg1 = id; 9426 msg.obj = response; 9427 mHandler.sendMessage(msg); 9428 } 9429 9430 @Override 9431 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9432 long millisecondsToDelay) { 9433 mContext.enforceCallingOrSelfPermission( 9434 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9435 "Only package verification agents can extend verification timeouts"); 9436 9437 final PackageVerificationState state = mPendingVerification.get(id); 9438 final PackageVerificationResponse response = new PackageVerificationResponse( 9439 verificationCodeAtTimeout, Binder.getCallingUid()); 9440 9441 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9442 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9443 } 9444 if (millisecondsToDelay < 0) { 9445 millisecondsToDelay = 0; 9446 } 9447 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9448 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9449 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9450 } 9451 9452 if ((state != null) && !state.timeoutExtended()) { 9453 state.extendTimeout(); 9454 9455 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9456 msg.arg1 = id; 9457 msg.obj = response; 9458 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9459 } 9460 } 9461 9462 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9463 int verificationCode, UserHandle user) { 9464 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9465 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9466 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9467 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9468 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9469 9470 mContext.sendBroadcastAsUser(intent, user, 9471 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9472 } 9473 9474 private ComponentName matchComponentForVerifier(String packageName, 9475 List<ResolveInfo> receivers) { 9476 ActivityInfo targetReceiver = null; 9477 9478 final int NR = receivers.size(); 9479 for (int i = 0; i < NR; i++) { 9480 final ResolveInfo info = receivers.get(i); 9481 if (info.activityInfo == null) { 9482 continue; 9483 } 9484 9485 if (packageName.equals(info.activityInfo.packageName)) { 9486 targetReceiver = info.activityInfo; 9487 break; 9488 } 9489 } 9490 9491 if (targetReceiver == null) { 9492 return null; 9493 } 9494 9495 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9496 } 9497 9498 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9499 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9500 if (pkgInfo.verifiers.length == 0) { 9501 return null; 9502 } 9503 9504 final int N = pkgInfo.verifiers.length; 9505 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9506 for (int i = 0; i < N; i++) { 9507 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9508 9509 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9510 receivers); 9511 if (comp == null) { 9512 continue; 9513 } 9514 9515 final int verifierUid = getUidForVerifier(verifierInfo); 9516 if (verifierUid == -1) { 9517 continue; 9518 } 9519 9520 if (DEBUG_VERIFY) { 9521 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9522 + " with the correct signature"); 9523 } 9524 sufficientVerifiers.add(comp); 9525 verificationState.addSufficientVerifier(verifierUid); 9526 } 9527 9528 return sufficientVerifiers; 9529 } 9530 9531 private int getUidForVerifier(VerifierInfo verifierInfo) { 9532 synchronized (mPackages) { 9533 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9534 if (pkg == null) { 9535 return -1; 9536 } else if (pkg.mSignatures.length != 1) { 9537 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9538 + " has more than one signature; ignoring"); 9539 return -1; 9540 } 9541 9542 /* 9543 * If the public key of the package's signature does not match 9544 * our expected public key, then this is a different package and 9545 * we should skip. 9546 */ 9547 9548 final byte[] expectedPublicKey; 9549 try { 9550 final Signature verifierSig = pkg.mSignatures[0]; 9551 final PublicKey publicKey = verifierSig.getPublicKey(); 9552 expectedPublicKey = publicKey.getEncoded(); 9553 } catch (CertificateException e) { 9554 return -1; 9555 } 9556 9557 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9558 9559 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9560 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9561 + " does not have the expected public key; ignoring"); 9562 return -1; 9563 } 9564 9565 return pkg.applicationInfo.uid; 9566 } 9567 } 9568 9569 @Override 9570 public void finishPackageInstall(int token) { 9571 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9572 9573 if (DEBUG_INSTALL) { 9574 Slog.v(TAG, "BM finishing package install for " + token); 9575 } 9576 9577 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9578 mHandler.sendMessage(msg); 9579 } 9580 9581 /** 9582 * Get the verification agent timeout. 9583 * 9584 * @return verification timeout in milliseconds 9585 */ 9586 private long getVerificationTimeout() { 9587 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9588 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9589 DEFAULT_VERIFICATION_TIMEOUT); 9590 } 9591 9592 /** 9593 * Get the default verification agent response code. 9594 * 9595 * @return default verification response code 9596 */ 9597 private int getDefaultVerificationResponse() { 9598 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9599 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9600 DEFAULT_VERIFICATION_RESPONSE); 9601 } 9602 9603 /** 9604 * Check whether or not package verification has been enabled. 9605 * 9606 * @return true if verification should be performed 9607 */ 9608 private boolean isVerificationEnabled(int userId, int installFlags) { 9609 if (!DEFAULT_VERIFY_ENABLE) { 9610 return false; 9611 } 9612 9613 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9614 9615 // Check if installing from ADB 9616 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9617 // Do not run verification in a test harness environment 9618 if (ActivityManager.isRunningInTestHarness()) { 9619 return false; 9620 } 9621 if (ensureVerifyAppsEnabled) { 9622 return true; 9623 } 9624 // Check if the developer does not want package verification for ADB installs 9625 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9626 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9627 return false; 9628 } 9629 } 9630 9631 if (ensureVerifyAppsEnabled) { 9632 return true; 9633 } 9634 9635 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9636 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9637 } 9638 9639 @Override 9640 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9641 throws RemoteException { 9642 mContext.enforceCallingOrSelfPermission( 9643 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9644 "Only intentfilter verification agents can verify applications"); 9645 9646 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9647 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9648 Binder.getCallingUid(), verificationCode, failedDomains); 9649 msg.arg1 = id; 9650 msg.obj = response; 9651 mHandler.sendMessage(msg); 9652 } 9653 9654 @Override 9655 public int getIntentVerificationStatus(String packageName, int userId) { 9656 synchronized (mPackages) { 9657 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9658 } 9659 } 9660 9661 @Override 9662 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9663 mContext.enforceCallingOrSelfPermission( 9664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9665 9666 boolean result = false; 9667 synchronized (mPackages) { 9668 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9669 } 9670 if (result) { 9671 scheduleWritePackageRestrictionsLocked(userId); 9672 } 9673 return result; 9674 } 9675 9676 @Override 9677 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9678 synchronized (mPackages) { 9679 return mSettings.getIntentFilterVerificationsLPr(packageName); 9680 } 9681 } 9682 9683 @Override 9684 public List<IntentFilter> getAllIntentFilters(String packageName) { 9685 if (TextUtils.isEmpty(packageName)) { 9686 return Collections.<IntentFilter>emptyList(); 9687 } 9688 synchronized (mPackages) { 9689 PackageParser.Package pkg = mPackages.get(packageName); 9690 if (pkg == null || pkg.activities == null) { 9691 return Collections.<IntentFilter>emptyList(); 9692 } 9693 final int count = pkg.activities.size(); 9694 ArrayList<IntentFilter> result = new ArrayList<>(); 9695 for (int n=0; n<count; n++) { 9696 PackageParser.Activity activity = pkg.activities.get(n); 9697 if (activity.intents != null || activity.intents.size() > 0) { 9698 result.addAll(activity.intents); 9699 } 9700 } 9701 return result; 9702 } 9703 } 9704 9705 @Override 9706 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9707 mContext.enforceCallingOrSelfPermission( 9708 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9709 9710 synchronized (mPackages) { 9711 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9712 if (packageName != null) { 9713 result |= updateIntentVerificationStatus(packageName, 9714 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9715 UserHandle.myUserId()); 9716 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9717 packageName, userId); 9718 } 9719 return result; 9720 } 9721 } 9722 9723 @Override 9724 public String getDefaultBrowserPackageName(int userId) { 9725 synchronized (mPackages) { 9726 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9727 } 9728 } 9729 9730 /** 9731 * Get the "allow unknown sources" setting. 9732 * 9733 * @return the current "allow unknown sources" setting 9734 */ 9735 private int getUnknownSourcesSettings() { 9736 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9737 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9738 -1); 9739 } 9740 9741 @Override 9742 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9743 final int uid = Binder.getCallingUid(); 9744 // writer 9745 synchronized (mPackages) { 9746 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9747 if (targetPackageSetting == null) { 9748 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9749 } 9750 9751 PackageSetting installerPackageSetting; 9752 if (installerPackageName != null) { 9753 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9754 if (installerPackageSetting == null) { 9755 throw new IllegalArgumentException("Unknown installer package: " 9756 + installerPackageName); 9757 } 9758 } else { 9759 installerPackageSetting = null; 9760 } 9761 9762 Signature[] callerSignature; 9763 Object obj = mSettings.getUserIdLPr(uid); 9764 if (obj != null) { 9765 if (obj instanceof SharedUserSetting) { 9766 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9767 } else if (obj instanceof PackageSetting) { 9768 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9769 } else { 9770 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9771 } 9772 } else { 9773 throw new SecurityException("Unknown calling uid " + uid); 9774 } 9775 9776 // Verify: can't set installerPackageName to a package that is 9777 // not signed with the same cert as the caller. 9778 if (installerPackageSetting != null) { 9779 if (compareSignatures(callerSignature, 9780 installerPackageSetting.signatures.mSignatures) 9781 != PackageManager.SIGNATURE_MATCH) { 9782 throw new SecurityException( 9783 "Caller does not have same cert as new installer package " 9784 + installerPackageName); 9785 } 9786 } 9787 9788 // Verify: if target already has an installer package, it must 9789 // be signed with the same cert as the caller. 9790 if (targetPackageSetting.installerPackageName != null) { 9791 PackageSetting setting = mSettings.mPackages.get( 9792 targetPackageSetting.installerPackageName); 9793 // If the currently set package isn't valid, then it's always 9794 // okay to change it. 9795 if (setting != null) { 9796 if (compareSignatures(callerSignature, 9797 setting.signatures.mSignatures) 9798 != PackageManager.SIGNATURE_MATCH) { 9799 throw new SecurityException( 9800 "Caller does not have same cert as old installer package " 9801 + targetPackageSetting.installerPackageName); 9802 } 9803 } 9804 } 9805 9806 // Okay! 9807 targetPackageSetting.installerPackageName = installerPackageName; 9808 scheduleWriteSettingsLocked(); 9809 } 9810 } 9811 9812 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9813 // Queue up an async operation since the package installation may take a little while. 9814 mHandler.post(new Runnable() { 9815 public void run() { 9816 mHandler.removeCallbacks(this); 9817 // Result object to be returned 9818 PackageInstalledInfo res = new PackageInstalledInfo(); 9819 res.returnCode = currentStatus; 9820 res.uid = -1; 9821 res.pkg = null; 9822 res.removedInfo = new PackageRemovedInfo(); 9823 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9824 args.doPreInstall(res.returnCode); 9825 synchronized (mInstallLock) { 9826 installPackageLI(args, res); 9827 } 9828 args.doPostInstall(res.returnCode, res.uid); 9829 } 9830 9831 // A restore should be performed at this point if (a) the install 9832 // succeeded, (b) the operation is not an update, and (c) the new 9833 // package has not opted out of backup participation. 9834 final boolean update = res.removedInfo.removedPackage != null; 9835 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9836 boolean doRestore = !update 9837 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9838 9839 // Set up the post-install work request bookkeeping. This will be used 9840 // and cleaned up by the post-install event handling regardless of whether 9841 // there's a restore pass performed. Token values are >= 1. 9842 int token; 9843 if (mNextInstallToken < 0) mNextInstallToken = 1; 9844 token = mNextInstallToken++; 9845 9846 PostInstallData data = new PostInstallData(args, res); 9847 mRunningInstalls.put(token, data); 9848 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9849 9850 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9851 // Pass responsibility to the Backup Manager. It will perform a 9852 // restore if appropriate, then pass responsibility back to the 9853 // Package Manager to run the post-install observer callbacks 9854 // and broadcasts. 9855 IBackupManager bm = IBackupManager.Stub.asInterface( 9856 ServiceManager.getService(Context.BACKUP_SERVICE)); 9857 if (bm != null) { 9858 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9859 + " to BM for possible restore"); 9860 try { 9861 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9862 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9863 } else { 9864 doRestore = false; 9865 } 9866 } catch (RemoteException e) { 9867 // can't happen; the backup manager is local 9868 } catch (Exception e) { 9869 Slog.e(TAG, "Exception trying to enqueue restore", e); 9870 doRestore = false; 9871 } 9872 } else { 9873 Slog.e(TAG, "Backup Manager not found!"); 9874 doRestore = false; 9875 } 9876 } 9877 9878 if (!doRestore) { 9879 // No restore possible, or the Backup Manager was mysteriously not 9880 // available -- just fire the post-install work request directly. 9881 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9882 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9883 mHandler.sendMessage(msg); 9884 } 9885 } 9886 }); 9887 } 9888 9889 private abstract class HandlerParams { 9890 private static final int MAX_RETRIES = 4; 9891 9892 /** 9893 * Number of times startCopy() has been attempted and had a non-fatal 9894 * error. 9895 */ 9896 private int mRetries = 0; 9897 9898 /** User handle for the user requesting the information or installation. */ 9899 private final UserHandle mUser; 9900 9901 HandlerParams(UserHandle user) { 9902 mUser = user; 9903 } 9904 9905 UserHandle getUser() { 9906 return mUser; 9907 } 9908 9909 final boolean startCopy() { 9910 boolean res; 9911 try { 9912 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9913 9914 if (++mRetries > MAX_RETRIES) { 9915 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9916 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9917 handleServiceError(); 9918 return false; 9919 } else { 9920 handleStartCopy(); 9921 res = true; 9922 } 9923 } catch (RemoteException e) { 9924 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9925 mHandler.sendEmptyMessage(MCS_RECONNECT); 9926 res = false; 9927 } 9928 handleReturnCode(); 9929 return res; 9930 } 9931 9932 final void serviceError() { 9933 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9934 handleServiceError(); 9935 handleReturnCode(); 9936 } 9937 9938 abstract void handleStartCopy() throws RemoteException; 9939 abstract void handleServiceError(); 9940 abstract void handleReturnCode(); 9941 } 9942 9943 class MeasureParams extends HandlerParams { 9944 private final PackageStats mStats; 9945 private boolean mSuccess; 9946 9947 private final IPackageStatsObserver mObserver; 9948 9949 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9950 super(new UserHandle(stats.userHandle)); 9951 mObserver = observer; 9952 mStats = stats; 9953 } 9954 9955 @Override 9956 public String toString() { 9957 return "MeasureParams{" 9958 + Integer.toHexString(System.identityHashCode(this)) 9959 + " " + mStats.packageName + "}"; 9960 } 9961 9962 @Override 9963 void handleStartCopy() throws RemoteException { 9964 synchronized (mInstallLock) { 9965 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9966 } 9967 9968 if (mSuccess) { 9969 final boolean mounted; 9970 if (Environment.isExternalStorageEmulated()) { 9971 mounted = true; 9972 } else { 9973 final String status = Environment.getExternalStorageState(); 9974 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9975 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9976 } 9977 9978 if (mounted) { 9979 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9980 9981 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9982 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9983 9984 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9985 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9986 9987 // Always subtract cache size, since it's a subdirectory 9988 mStats.externalDataSize -= mStats.externalCacheSize; 9989 9990 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9991 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9992 9993 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9994 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9995 } 9996 } 9997 } 9998 9999 @Override 10000 void handleReturnCode() { 10001 if (mObserver != null) { 10002 try { 10003 mObserver.onGetStatsCompleted(mStats, mSuccess); 10004 } catch (RemoteException e) { 10005 Slog.i(TAG, "Observer no longer exists."); 10006 } 10007 } 10008 } 10009 10010 @Override 10011 void handleServiceError() { 10012 Slog.e(TAG, "Could not measure application " + mStats.packageName 10013 + " external storage"); 10014 } 10015 } 10016 10017 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10018 throws RemoteException { 10019 long result = 0; 10020 for (File path : paths) { 10021 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10022 } 10023 return result; 10024 } 10025 10026 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10027 for (File path : paths) { 10028 try { 10029 mcs.clearDirectory(path.getAbsolutePath()); 10030 } catch (RemoteException e) { 10031 } 10032 } 10033 } 10034 10035 static class OriginInfo { 10036 /** 10037 * Location where install is coming from, before it has been 10038 * copied/renamed into place. This could be a single monolithic APK 10039 * file, or a cluster directory. This location may be untrusted. 10040 */ 10041 final File file; 10042 final String cid; 10043 10044 /** 10045 * Flag indicating that {@link #file} or {@link #cid} has already been 10046 * staged, meaning downstream users don't need to defensively copy the 10047 * contents. 10048 */ 10049 final boolean staged; 10050 10051 /** 10052 * Flag indicating that {@link #file} or {@link #cid} is an already 10053 * installed app that is being moved. 10054 */ 10055 final boolean existing; 10056 10057 final String resolvedPath; 10058 final File resolvedFile; 10059 10060 static OriginInfo fromNothing() { 10061 return new OriginInfo(null, null, false, false); 10062 } 10063 10064 static OriginInfo fromUntrustedFile(File file) { 10065 return new OriginInfo(file, null, false, false); 10066 } 10067 10068 static OriginInfo fromExistingFile(File file) { 10069 return new OriginInfo(file, null, false, true); 10070 } 10071 10072 static OriginInfo fromStagedFile(File file) { 10073 return new OriginInfo(file, null, true, false); 10074 } 10075 10076 static OriginInfo fromStagedContainer(String cid) { 10077 return new OriginInfo(null, cid, true, false); 10078 } 10079 10080 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10081 this.file = file; 10082 this.cid = cid; 10083 this.staged = staged; 10084 this.existing = existing; 10085 10086 if (cid != null) { 10087 resolvedPath = PackageHelper.getSdDir(cid); 10088 resolvedFile = new File(resolvedPath); 10089 } else if (file != null) { 10090 resolvedPath = file.getAbsolutePath(); 10091 resolvedFile = file; 10092 } else { 10093 resolvedPath = null; 10094 resolvedFile = null; 10095 } 10096 } 10097 } 10098 10099 class MoveInfo { 10100 final int moveId; 10101 final String fromUuid; 10102 final String toUuid; 10103 final String packageName; 10104 final String dataAppName; 10105 final int appId; 10106 final String seinfo; 10107 10108 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10109 String dataAppName, int appId, String seinfo) { 10110 this.moveId = moveId; 10111 this.fromUuid = fromUuid; 10112 this.toUuid = toUuid; 10113 this.packageName = packageName; 10114 this.dataAppName = dataAppName; 10115 this.appId = appId; 10116 this.seinfo = seinfo; 10117 } 10118 } 10119 10120 class InstallParams extends HandlerParams { 10121 final OriginInfo origin; 10122 final MoveInfo move; 10123 final IPackageInstallObserver2 observer; 10124 int installFlags; 10125 final String installerPackageName; 10126 final String volumeUuid; 10127 final VerificationParams verificationParams; 10128 private InstallArgs mArgs; 10129 private int mRet; 10130 final String packageAbiOverride; 10131 10132 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10133 int installFlags, String installerPackageName, String volumeUuid, 10134 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10135 super(user); 10136 this.origin = origin; 10137 this.move = move; 10138 this.observer = observer; 10139 this.installFlags = installFlags; 10140 this.installerPackageName = installerPackageName; 10141 this.volumeUuid = volumeUuid; 10142 this.verificationParams = verificationParams; 10143 this.packageAbiOverride = packageAbiOverride; 10144 } 10145 10146 @Override 10147 public String toString() { 10148 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10149 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10150 } 10151 10152 public ManifestDigest getManifestDigest() { 10153 if (verificationParams == null) { 10154 return null; 10155 } 10156 return verificationParams.getManifestDigest(); 10157 } 10158 10159 private int installLocationPolicy(PackageInfoLite pkgLite) { 10160 String packageName = pkgLite.packageName; 10161 int installLocation = pkgLite.installLocation; 10162 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10163 // reader 10164 synchronized (mPackages) { 10165 PackageParser.Package pkg = mPackages.get(packageName); 10166 if (pkg != null) { 10167 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10168 // Check for downgrading. 10169 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10170 try { 10171 checkDowngrade(pkg, pkgLite); 10172 } catch (PackageManagerException e) { 10173 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10174 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10175 } 10176 } 10177 // Check for updated system application. 10178 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10179 if (onSd) { 10180 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10181 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10182 } 10183 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10184 } else { 10185 if (onSd) { 10186 // Install flag overrides everything. 10187 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10188 } 10189 // If current upgrade specifies particular preference 10190 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10191 // Application explicitly specified internal. 10192 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10193 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10194 // App explictly prefers external. Let policy decide 10195 } else { 10196 // Prefer previous location 10197 if (isExternal(pkg)) { 10198 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10199 } 10200 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10201 } 10202 } 10203 } else { 10204 // Invalid install. Return error code 10205 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10206 } 10207 } 10208 } 10209 // All the special cases have been taken care of. 10210 // Return result based on recommended install location. 10211 if (onSd) { 10212 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10213 } 10214 return pkgLite.recommendedInstallLocation; 10215 } 10216 10217 /* 10218 * Invoke remote method to get package information and install 10219 * location values. Override install location based on default 10220 * policy if needed and then create install arguments based 10221 * on the install location. 10222 */ 10223 public void handleStartCopy() throws RemoteException { 10224 int ret = PackageManager.INSTALL_SUCCEEDED; 10225 10226 // If we're already staged, we've firmly committed to an install location 10227 if (origin.staged) { 10228 if (origin.file != null) { 10229 installFlags |= PackageManager.INSTALL_INTERNAL; 10230 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10231 } else if (origin.cid != null) { 10232 installFlags |= PackageManager.INSTALL_EXTERNAL; 10233 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10234 } else { 10235 throw new IllegalStateException("Invalid stage location"); 10236 } 10237 } 10238 10239 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10240 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10241 10242 PackageInfoLite pkgLite = null; 10243 10244 if (onInt && onSd) { 10245 // Check if both bits are set. 10246 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10247 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10248 } else { 10249 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10250 packageAbiOverride); 10251 10252 /* 10253 * If we have too little free space, try to free cache 10254 * before giving up. 10255 */ 10256 if (!origin.staged && pkgLite.recommendedInstallLocation 10257 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10258 // TODO: focus freeing disk space on the target device 10259 final StorageManager storage = StorageManager.from(mContext); 10260 final long lowThreshold = storage.getStorageLowBytes( 10261 Environment.getDataDirectory()); 10262 10263 final long sizeBytes = mContainerService.calculateInstalledSize( 10264 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10265 10266 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10267 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10268 installFlags, packageAbiOverride); 10269 } 10270 10271 /* 10272 * The cache free must have deleted the file we 10273 * downloaded to install. 10274 * 10275 * TODO: fix the "freeCache" call to not delete 10276 * the file we care about. 10277 */ 10278 if (pkgLite.recommendedInstallLocation 10279 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10280 pkgLite.recommendedInstallLocation 10281 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10282 } 10283 } 10284 } 10285 10286 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10287 int loc = pkgLite.recommendedInstallLocation; 10288 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10289 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10290 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10291 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10292 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10293 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10294 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10295 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10296 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10297 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10298 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10299 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10300 } else { 10301 // Override with defaults if needed. 10302 loc = installLocationPolicy(pkgLite); 10303 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10304 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10305 } else if (!onSd && !onInt) { 10306 // Override install location with flags 10307 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10308 // Set the flag to install on external media. 10309 installFlags |= PackageManager.INSTALL_EXTERNAL; 10310 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10311 } else { 10312 // Make sure the flag for installing on external 10313 // media is unset 10314 installFlags |= PackageManager.INSTALL_INTERNAL; 10315 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10316 } 10317 } 10318 } 10319 } 10320 10321 final InstallArgs args = createInstallArgs(this); 10322 mArgs = args; 10323 10324 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10325 /* 10326 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10327 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10328 */ 10329 int userIdentifier = getUser().getIdentifier(); 10330 if (userIdentifier == UserHandle.USER_ALL 10331 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10332 userIdentifier = UserHandle.USER_OWNER; 10333 } 10334 10335 /* 10336 * Determine if we have any installed package verifiers. If we 10337 * do, then we'll defer to them to verify the packages. 10338 */ 10339 final int requiredUid = mRequiredVerifierPackage == null ? -1 10340 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10341 if (!origin.existing && requiredUid != -1 10342 && isVerificationEnabled(userIdentifier, installFlags)) { 10343 final Intent verification = new Intent( 10344 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10345 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10346 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10347 PACKAGE_MIME_TYPE); 10348 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10349 10350 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10351 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10352 0 /* TODO: Which userId? */); 10353 10354 if (DEBUG_VERIFY) { 10355 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10356 + verification.toString() + " with " + pkgLite.verifiers.length 10357 + " optional verifiers"); 10358 } 10359 10360 final int verificationId = mPendingVerificationToken++; 10361 10362 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10363 10364 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10365 installerPackageName); 10366 10367 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10368 installFlags); 10369 10370 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10371 pkgLite.packageName); 10372 10373 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10374 pkgLite.versionCode); 10375 10376 if (verificationParams != null) { 10377 if (verificationParams.getVerificationURI() != null) { 10378 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10379 verificationParams.getVerificationURI()); 10380 } 10381 if (verificationParams.getOriginatingURI() != null) { 10382 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10383 verificationParams.getOriginatingURI()); 10384 } 10385 if (verificationParams.getReferrer() != null) { 10386 verification.putExtra(Intent.EXTRA_REFERRER, 10387 verificationParams.getReferrer()); 10388 } 10389 if (verificationParams.getOriginatingUid() >= 0) { 10390 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10391 verificationParams.getOriginatingUid()); 10392 } 10393 if (verificationParams.getInstallerUid() >= 0) { 10394 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10395 verificationParams.getInstallerUid()); 10396 } 10397 } 10398 10399 final PackageVerificationState verificationState = new PackageVerificationState( 10400 requiredUid, args); 10401 10402 mPendingVerification.append(verificationId, verificationState); 10403 10404 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10405 receivers, verificationState); 10406 10407 /* 10408 * If any sufficient verifiers were listed in the package 10409 * manifest, attempt to ask them. 10410 */ 10411 if (sufficientVerifiers != null) { 10412 final int N = sufficientVerifiers.size(); 10413 if (N == 0) { 10414 Slog.i(TAG, "Additional verifiers required, but none installed."); 10415 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10416 } else { 10417 for (int i = 0; i < N; i++) { 10418 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10419 10420 final Intent sufficientIntent = new Intent(verification); 10421 sufficientIntent.setComponent(verifierComponent); 10422 10423 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10424 } 10425 } 10426 } 10427 10428 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10429 mRequiredVerifierPackage, receivers); 10430 if (ret == PackageManager.INSTALL_SUCCEEDED 10431 && mRequiredVerifierPackage != null) { 10432 /* 10433 * Send the intent to the required verification agent, 10434 * but only start the verification timeout after the 10435 * target BroadcastReceivers have run. 10436 */ 10437 verification.setComponent(requiredVerifierComponent); 10438 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10439 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10440 new BroadcastReceiver() { 10441 @Override 10442 public void onReceive(Context context, Intent intent) { 10443 final Message msg = mHandler 10444 .obtainMessage(CHECK_PENDING_VERIFICATION); 10445 msg.arg1 = verificationId; 10446 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10447 } 10448 }, null, 0, null, null); 10449 10450 /* 10451 * We don't want the copy to proceed until verification 10452 * succeeds, so null out this field. 10453 */ 10454 mArgs = null; 10455 } 10456 } else { 10457 /* 10458 * No package verification is enabled, so immediately start 10459 * the remote call to initiate copy using temporary file. 10460 */ 10461 ret = args.copyApk(mContainerService, true); 10462 } 10463 } 10464 10465 mRet = ret; 10466 } 10467 10468 @Override 10469 void handleReturnCode() { 10470 // If mArgs is null, then MCS couldn't be reached. When it 10471 // reconnects, it will try again to install. At that point, this 10472 // will succeed. 10473 if (mArgs != null) { 10474 processPendingInstall(mArgs, mRet); 10475 } 10476 } 10477 10478 @Override 10479 void handleServiceError() { 10480 mArgs = createInstallArgs(this); 10481 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10482 } 10483 10484 public boolean isForwardLocked() { 10485 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10486 } 10487 } 10488 10489 /** 10490 * Used during creation of InstallArgs 10491 * 10492 * @param installFlags package installation flags 10493 * @return true if should be installed on external storage 10494 */ 10495 private static boolean installOnExternalAsec(int installFlags) { 10496 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10497 return false; 10498 } 10499 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10500 return true; 10501 } 10502 return false; 10503 } 10504 10505 /** 10506 * Used during creation of InstallArgs 10507 * 10508 * @param installFlags package installation flags 10509 * @return true if should be installed as forward locked 10510 */ 10511 private static boolean installForwardLocked(int installFlags) { 10512 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10513 } 10514 10515 private InstallArgs createInstallArgs(InstallParams params) { 10516 if (params.move != null) { 10517 return new MoveInstallArgs(params); 10518 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10519 return new AsecInstallArgs(params); 10520 } else { 10521 return new FileInstallArgs(params); 10522 } 10523 } 10524 10525 /** 10526 * Create args that describe an existing installed package. Typically used 10527 * when cleaning up old installs, or used as a move source. 10528 */ 10529 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10530 String resourcePath, String[] instructionSets) { 10531 final boolean isInAsec; 10532 if (installOnExternalAsec(installFlags)) { 10533 /* Apps on SD card are always in ASEC containers. */ 10534 isInAsec = true; 10535 } else if (installForwardLocked(installFlags) 10536 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10537 /* 10538 * Forward-locked apps are only in ASEC containers if they're the 10539 * new style 10540 */ 10541 isInAsec = true; 10542 } else { 10543 isInAsec = false; 10544 } 10545 10546 if (isInAsec) { 10547 return new AsecInstallArgs(codePath, instructionSets, 10548 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10549 } else { 10550 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10551 } 10552 } 10553 10554 static abstract class InstallArgs { 10555 /** @see InstallParams#origin */ 10556 final OriginInfo origin; 10557 /** @see InstallParams#move */ 10558 final MoveInfo move; 10559 10560 final IPackageInstallObserver2 observer; 10561 // Always refers to PackageManager flags only 10562 final int installFlags; 10563 final String installerPackageName; 10564 final String volumeUuid; 10565 final ManifestDigest manifestDigest; 10566 final UserHandle user; 10567 final String abiOverride; 10568 10569 // The list of instruction sets supported by this app. This is currently 10570 // only used during the rmdex() phase to clean up resources. We can get rid of this 10571 // if we move dex files under the common app path. 10572 /* nullable */ String[] instructionSets; 10573 10574 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10575 int installFlags, String installerPackageName, String volumeUuid, 10576 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10577 String abiOverride) { 10578 this.origin = origin; 10579 this.move = move; 10580 this.installFlags = installFlags; 10581 this.observer = observer; 10582 this.installerPackageName = installerPackageName; 10583 this.volumeUuid = volumeUuid; 10584 this.manifestDigest = manifestDigest; 10585 this.user = user; 10586 this.instructionSets = instructionSets; 10587 this.abiOverride = abiOverride; 10588 } 10589 10590 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10591 abstract int doPreInstall(int status); 10592 10593 /** 10594 * Rename package into final resting place. All paths on the given 10595 * scanned package should be updated to reflect the rename. 10596 */ 10597 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10598 abstract int doPostInstall(int status, int uid); 10599 10600 /** @see PackageSettingBase#codePathString */ 10601 abstract String getCodePath(); 10602 /** @see PackageSettingBase#resourcePathString */ 10603 abstract String getResourcePath(); 10604 10605 // Need installer lock especially for dex file removal. 10606 abstract void cleanUpResourcesLI(); 10607 abstract boolean doPostDeleteLI(boolean delete); 10608 10609 /** 10610 * Called before the source arguments are copied. This is used mostly 10611 * for MoveParams when it needs to read the source file to put it in the 10612 * destination. 10613 */ 10614 int doPreCopy() { 10615 return PackageManager.INSTALL_SUCCEEDED; 10616 } 10617 10618 /** 10619 * Called after the source arguments are copied. This is used mostly for 10620 * MoveParams when it needs to read the source file to put it in the 10621 * destination. 10622 * 10623 * @return 10624 */ 10625 int doPostCopy(int uid) { 10626 return PackageManager.INSTALL_SUCCEEDED; 10627 } 10628 10629 protected boolean isFwdLocked() { 10630 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10631 } 10632 10633 protected boolean isExternalAsec() { 10634 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10635 } 10636 10637 UserHandle getUser() { 10638 return user; 10639 } 10640 } 10641 10642 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10643 if (!allCodePaths.isEmpty()) { 10644 if (instructionSets == null) { 10645 throw new IllegalStateException("instructionSet == null"); 10646 } 10647 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10648 for (String codePath : allCodePaths) { 10649 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10650 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10651 if (retCode < 0) { 10652 Slog.w(TAG, "Couldn't remove dex file for package: " 10653 + " at location " + codePath + ", retcode=" + retCode); 10654 // we don't consider this to be a failure of the core package deletion 10655 } 10656 } 10657 } 10658 } 10659 } 10660 10661 /** 10662 * Logic to handle installation of non-ASEC applications, including copying 10663 * and renaming logic. 10664 */ 10665 class FileInstallArgs extends InstallArgs { 10666 private File codeFile; 10667 private File resourceFile; 10668 10669 // Example topology: 10670 // /data/app/com.example/base.apk 10671 // /data/app/com.example/split_foo.apk 10672 // /data/app/com.example/lib/arm/libfoo.so 10673 // /data/app/com.example/lib/arm64/libfoo.so 10674 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10675 10676 /** New install */ 10677 FileInstallArgs(InstallParams params) { 10678 super(params.origin, params.move, params.observer, params.installFlags, 10679 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10680 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10681 if (isFwdLocked()) { 10682 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10683 } 10684 } 10685 10686 /** Existing install */ 10687 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10688 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10689 null); 10690 this.codeFile = (codePath != null) ? new File(codePath) : null; 10691 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10692 } 10693 10694 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10695 if (origin.staged) { 10696 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10697 codeFile = origin.file; 10698 resourceFile = origin.file; 10699 return PackageManager.INSTALL_SUCCEEDED; 10700 } 10701 10702 try { 10703 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10704 codeFile = tempDir; 10705 resourceFile = tempDir; 10706 } catch (IOException e) { 10707 Slog.w(TAG, "Failed to create copy file: " + e); 10708 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10709 } 10710 10711 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10712 @Override 10713 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10714 if (!FileUtils.isValidExtFilename(name)) { 10715 throw new IllegalArgumentException("Invalid filename: " + name); 10716 } 10717 try { 10718 final File file = new File(codeFile, name); 10719 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10720 O_RDWR | O_CREAT, 0644); 10721 Os.chmod(file.getAbsolutePath(), 0644); 10722 return new ParcelFileDescriptor(fd); 10723 } catch (ErrnoException e) { 10724 throw new RemoteException("Failed to open: " + e.getMessage()); 10725 } 10726 } 10727 }; 10728 10729 int ret = PackageManager.INSTALL_SUCCEEDED; 10730 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10731 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10732 Slog.e(TAG, "Failed to copy package"); 10733 return ret; 10734 } 10735 10736 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10737 NativeLibraryHelper.Handle handle = null; 10738 try { 10739 handle = NativeLibraryHelper.Handle.create(codeFile); 10740 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10741 abiOverride); 10742 } catch (IOException e) { 10743 Slog.e(TAG, "Copying native libraries failed", e); 10744 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10745 } finally { 10746 IoUtils.closeQuietly(handle); 10747 } 10748 10749 return ret; 10750 } 10751 10752 int doPreInstall(int status) { 10753 if (status != PackageManager.INSTALL_SUCCEEDED) { 10754 cleanUp(); 10755 } 10756 return status; 10757 } 10758 10759 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10760 if (status != PackageManager.INSTALL_SUCCEEDED) { 10761 cleanUp(); 10762 return false; 10763 } 10764 10765 final File targetDir = codeFile.getParentFile(); 10766 final File beforeCodeFile = codeFile; 10767 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10768 10769 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10770 try { 10771 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10772 } catch (ErrnoException e) { 10773 Slog.w(TAG, "Failed to rename", e); 10774 return false; 10775 } 10776 10777 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10778 Slog.w(TAG, "Failed to restorecon"); 10779 return false; 10780 } 10781 10782 // Reflect the rename internally 10783 codeFile = afterCodeFile; 10784 resourceFile = afterCodeFile; 10785 10786 // Reflect the rename in scanned details 10787 pkg.codePath = afterCodeFile.getAbsolutePath(); 10788 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10789 pkg.baseCodePath); 10790 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10791 pkg.splitCodePaths); 10792 10793 // Reflect the rename in app info 10794 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10795 pkg.applicationInfo.setCodePath(pkg.codePath); 10796 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10797 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10798 pkg.applicationInfo.setResourcePath(pkg.codePath); 10799 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10800 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10801 10802 return true; 10803 } 10804 10805 int doPostInstall(int status, int uid) { 10806 if (status != PackageManager.INSTALL_SUCCEEDED) { 10807 cleanUp(); 10808 } 10809 return status; 10810 } 10811 10812 @Override 10813 String getCodePath() { 10814 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10815 } 10816 10817 @Override 10818 String getResourcePath() { 10819 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10820 } 10821 10822 private boolean cleanUp() { 10823 if (codeFile == null || !codeFile.exists()) { 10824 return false; 10825 } 10826 10827 if (codeFile.isDirectory()) { 10828 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10829 } else { 10830 codeFile.delete(); 10831 } 10832 10833 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10834 resourceFile.delete(); 10835 } 10836 10837 return true; 10838 } 10839 10840 void cleanUpResourcesLI() { 10841 // Try enumerating all code paths before deleting 10842 List<String> allCodePaths = Collections.EMPTY_LIST; 10843 if (codeFile != null && codeFile.exists()) { 10844 try { 10845 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10846 allCodePaths = pkg.getAllCodePaths(); 10847 } catch (PackageParserException e) { 10848 // Ignored; we tried our best 10849 } 10850 } 10851 10852 cleanUp(); 10853 removeDexFiles(allCodePaths, instructionSets); 10854 } 10855 10856 boolean doPostDeleteLI(boolean delete) { 10857 // XXX err, shouldn't we respect the delete flag? 10858 cleanUpResourcesLI(); 10859 return true; 10860 } 10861 } 10862 10863 private boolean isAsecExternal(String cid) { 10864 final String asecPath = PackageHelper.getSdFilesystem(cid); 10865 return !asecPath.startsWith(mAsecInternalPath); 10866 } 10867 10868 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10869 PackageManagerException { 10870 if (copyRet < 0) { 10871 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10872 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10873 throw new PackageManagerException(copyRet, message); 10874 } 10875 } 10876 } 10877 10878 /** 10879 * Extract the MountService "container ID" from the full code path of an 10880 * .apk. 10881 */ 10882 static String cidFromCodePath(String fullCodePath) { 10883 int eidx = fullCodePath.lastIndexOf("/"); 10884 String subStr1 = fullCodePath.substring(0, eidx); 10885 int sidx = subStr1.lastIndexOf("/"); 10886 return subStr1.substring(sidx+1, eidx); 10887 } 10888 10889 /** 10890 * Logic to handle installation of ASEC applications, including copying and 10891 * renaming logic. 10892 */ 10893 class AsecInstallArgs extends InstallArgs { 10894 static final String RES_FILE_NAME = "pkg.apk"; 10895 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10896 10897 String cid; 10898 String packagePath; 10899 String resourcePath; 10900 10901 /** New install */ 10902 AsecInstallArgs(InstallParams params) { 10903 super(params.origin, params.move, params.observer, params.installFlags, 10904 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10905 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10906 } 10907 10908 /** Existing install */ 10909 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10910 boolean isExternal, boolean isForwardLocked) { 10911 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10912 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10913 instructionSets, null); 10914 // Hackily pretend we're still looking at a full code path 10915 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10916 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10917 } 10918 10919 // Extract cid from fullCodePath 10920 int eidx = fullCodePath.lastIndexOf("/"); 10921 String subStr1 = fullCodePath.substring(0, eidx); 10922 int sidx = subStr1.lastIndexOf("/"); 10923 cid = subStr1.substring(sidx+1, eidx); 10924 setMountPath(subStr1); 10925 } 10926 10927 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10928 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10929 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10930 instructionSets, null); 10931 this.cid = cid; 10932 setMountPath(PackageHelper.getSdDir(cid)); 10933 } 10934 10935 void createCopyFile() { 10936 cid = mInstallerService.allocateExternalStageCidLegacy(); 10937 } 10938 10939 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10940 if (origin.staged) { 10941 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10942 cid = origin.cid; 10943 setMountPath(PackageHelper.getSdDir(cid)); 10944 return PackageManager.INSTALL_SUCCEEDED; 10945 } 10946 10947 if (temp) { 10948 createCopyFile(); 10949 } else { 10950 /* 10951 * Pre-emptively destroy the container since it's destroyed if 10952 * copying fails due to it existing anyway. 10953 */ 10954 PackageHelper.destroySdDir(cid); 10955 } 10956 10957 final String newMountPath = imcs.copyPackageToContainer( 10958 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10959 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10960 10961 if (newMountPath != null) { 10962 setMountPath(newMountPath); 10963 return PackageManager.INSTALL_SUCCEEDED; 10964 } else { 10965 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10966 } 10967 } 10968 10969 @Override 10970 String getCodePath() { 10971 return packagePath; 10972 } 10973 10974 @Override 10975 String getResourcePath() { 10976 return resourcePath; 10977 } 10978 10979 int doPreInstall(int status) { 10980 if (status != PackageManager.INSTALL_SUCCEEDED) { 10981 // Destroy container 10982 PackageHelper.destroySdDir(cid); 10983 } else { 10984 boolean mounted = PackageHelper.isContainerMounted(cid); 10985 if (!mounted) { 10986 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10987 Process.SYSTEM_UID); 10988 if (newMountPath != null) { 10989 setMountPath(newMountPath); 10990 } else { 10991 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10992 } 10993 } 10994 } 10995 return status; 10996 } 10997 10998 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10999 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11000 String newMountPath = null; 11001 if (PackageHelper.isContainerMounted(cid)) { 11002 // Unmount the container 11003 if (!PackageHelper.unMountSdDir(cid)) { 11004 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11005 return false; 11006 } 11007 } 11008 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11009 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11010 " which might be stale. Will try to clean up."); 11011 // Clean up the stale container and proceed to recreate. 11012 if (!PackageHelper.destroySdDir(newCacheId)) { 11013 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11014 return false; 11015 } 11016 // Successfully cleaned up stale container. Try to rename again. 11017 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11018 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11019 + " inspite of cleaning it up."); 11020 return false; 11021 } 11022 } 11023 if (!PackageHelper.isContainerMounted(newCacheId)) { 11024 Slog.w(TAG, "Mounting container " + newCacheId); 11025 newMountPath = PackageHelper.mountSdDir(newCacheId, 11026 getEncryptKey(), Process.SYSTEM_UID); 11027 } else { 11028 newMountPath = PackageHelper.getSdDir(newCacheId); 11029 } 11030 if (newMountPath == null) { 11031 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11032 return false; 11033 } 11034 Log.i(TAG, "Succesfully renamed " + cid + 11035 " to " + newCacheId + 11036 " at new path: " + newMountPath); 11037 cid = newCacheId; 11038 11039 final File beforeCodeFile = new File(packagePath); 11040 setMountPath(newMountPath); 11041 final File afterCodeFile = new File(packagePath); 11042 11043 // Reflect the rename in scanned details 11044 pkg.codePath = afterCodeFile.getAbsolutePath(); 11045 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11046 pkg.baseCodePath); 11047 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11048 pkg.splitCodePaths); 11049 11050 // Reflect the rename in app info 11051 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11052 pkg.applicationInfo.setCodePath(pkg.codePath); 11053 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11054 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11055 pkg.applicationInfo.setResourcePath(pkg.codePath); 11056 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11057 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11058 11059 return true; 11060 } 11061 11062 private void setMountPath(String mountPath) { 11063 final File mountFile = new File(mountPath); 11064 11065 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11066 if (monolithicFile.exists()) { 11067 packagePath = monolithicFile.getAbsolutePath(); 11068 if (isFwdLocked()) { 11069 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11070 } else { 11071 resourcePath = packagePath; 11072 } 11073 } else { 11074 packagePath = mountFile.getAbsolutePath(); 11075 resourcePath = packagePath; 11076 } 11077 } 11078 11079 int doPostInstall(int status, int uid) { 11080 if (status != PackageManager.INSTALL_SUCCEEDED) { 11081 cleanUp(); 11082 } else { 11083 final int groupOwner; 11084 final String protectedFile; 11085 if (isFwdLocked()) { 11086 groupOwner = UserHandle.getSharedAppGid(uid); 11087 protectedFile = RES_FILE_NAME; 11088 } else { 11089 groupOwner = -1; 11090 protectedFile = null; 11091 } 11092 11093 if (uid < Process.FIRST_APPLICATION_UID 11094 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11095 Slog.e(TAG, "Failed to finalize " + cid); 11096 PackageHelper.destroySdDir(cid); 11097 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11098 } 11099 11100 boolean mounted = PackageHelper.isContainerMounted(cid); 11101 if (!mounted) { 11102 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11103 } 11104 } 11105 return status; 11106 } 11107 11108 private void cleanUp() { 11109 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11110 11111 // Destroy secure container 11112 PackageHelper.destroySdDir(cid); 11113 } 11114 11115 private List<String> getAllCodePaths() { 11116 final File codeFile = new File(getCodePath()); 11117 if (codeFile != null && codeFile.exists()) { 11118 try { 11119 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11120 return pkg.getAllCodePaths(); 11121 } catch (PackageParserException e) { 11122 // Ignored; we tried our best 11123 } 11124 } 11125 return Collections.EMPTY_LIST; 11126 } 11127 11128 void cleanUpResourcesLI() { 11129 // Enumerate all code paths before deleting 11130 cleanUpResourcesLI(getAllCodePaths()); 11131 } 11132 11133 private void cleanUpResourcesLI(List<String> allCodePaths) { 11134 cleanUp(); 11135 removeDexFiles(allCodePaths, instructionSets); 11136 } 11137 11138 String getPackageName() { 11139 return getAsecPackageName(cid); 11140 } 11141 11142 boolean doPostDeleteLI(boolean delete) { 11143 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11144 final List<String> allCodePaths = getAllCodePaths(); 11145 boolean mounted = PackageHelper.isContainerMounted(cid); 11146 if (mounted) { 11147 // Unmount first 11148 if (PackageHelper.unMountSdDir(cid)) { 11149 mounted = false; 11150 } 11151 } 11152 if (!mounted && delete) { 11153 cleanUpResourcesLI(allCodePaths); 11154 } 11155 return !mounted; 11156 } 11157 11158 @Override 11159 int doPreCopy() { 11160 if (isFwdLocked()) { 11161 if (!PackageHelper.fixSdPermissions(cid, 11162 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11163 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11164 } 11165 } 11166 11167 return PackageManager.INSTALL_SUCCEEDED; 11168 } 11169 11170 @Override 11171 int doPostCopy(int uid) { 11172 if (isFwdLocked()) { 11173 if (uid < Process.FIRST_APPLICATION_UID 11174 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11175 RES_FILE_NAME)) { 11176 Slog.e(TAG, "Failed to finalize " + cid); 11177 PackageHelper.destroySdDir(cid); 11178 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11179 } 11180 } 11181 11182 return PackageManager.INSTALL_SUCCEEDED; 11183 } 11184 } 11185 11186 /** 11187 * Logic to handle movement of existing installed applications. 11188 */ 11189 class MoveInstallArgs extends InstallArgs { 11190 private File codeFile; 11191 private File resourceFile; 11192 11193 /** New install */ 11194 MoveInstallArgs(InstallParams params) { 11195 super(params.origin, params.move, params.observer, params.installFlags, 11196 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11197 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11198 } 11199 11200 int copyApk(IMediaContainerService imcs, boolean temp) { 11201 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11202 + move.fromUuid + " to " + move.toUuid); 11203 synchronized (mInstaller) { 11204 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11205 move.dataAppName, move.appId, move.seinfo) != 0) { 11206 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11207 } 11208 } 11209 11210 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11211 resourceFile = codeFile; 11212 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11213 11214 return PackageManager.INSTALL_SUCCEEDED; 11215 } 11216 11217 int doPreInstall(int status) { 11218 if (status != PackageManager.INSTALL_SUCCEEDED) { 11219 cleanUp(); 11220 } 11221 return status; 11222 } 11223 11224 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11225 if (status != PackageManager.INSTALL_SUCCEEDED) { 11226 cleanUp(); 11227 return false; 11228 } 11229 11230 // Reflect the move in app info 11231 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11232 pkg.applicationInfo.setCodePath(pkg.codePath); 11233 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11234 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11235 pkg.applicationInfo.setResourcePath(pkg.codePath); 11236 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11237 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11238 11239 return true; 11240 } 11241 11242 int doPostInstall(int status, int uid) { 11243 if (status != PackageManager.INSTALL_SUCCEEDED) { 11244 cleanUp(); 11245 } 11246 return status; 11247 } 11248 11249 @Override 11250 String getCodePath() { 11251 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11252 } 11253 11254 @Override 11255 String getResourcePath() { 11256 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11257 } 11258 11259 private boolean cleanUp() { 11260 if (codeFile == null || !codeFile.exists()) { 11261 return false; 11262 } 11263 11264 if (codeFile.isDirectory()) { 11265 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11266 } else { 11267 codeFile.delete(); 11268 } 11269 11270 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11271 resourceFile.delete(); 11272 } 11273 11274 return true; 11275 } 11276 11277 void cleanUpResourcesLI() { 11278 cleanUp(); 11279 } 11280 11281 boolean doPostDeleteLI(boolean delete) { 11282 // XXX err, shouldn't we respect the delete flag? 11283 cleanUpResourcesLI(); 11284 return true; 11285 } 11286 } 11287 11288 static String getAsecPackageName(String packageCid) { 11289 int idx = packageCid.lastIndexOf("-"); 11290 if (idx == -1) { 11291 return packageCid; 11292 } 11293 return packageCid.substring(0, idx); 11294 } 11295 11296 // Utility method used to create code paths based on package name and available index. 11297 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11298 String idxStr = ""; 11299 int idx = 1; 11300 // Fall back to default value of idx=1 if prefix is not 11301 // part of oldCodePath 11302 if (oldCodePath != null) { 11303 String subStr = oldCodePath; 11304 // Drop the suffix right away 11305 if (suffix != null && subStr.endsWith(suffix)) { 11306 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11307 } 11308 // If oldCodePath already contains prefix find out the 11309 // ending index to either increment or decrement. 11310 int sidx = subStr.lastIndexOf(prefix); 11311 if (sidx != -1) { 11312 subStr = subStr.substring(sidx + prefix.length()); 11313 if (subStr != null) { 11314 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11315 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11316 } 11317 try { 11318 idx = Integer.parseInt(subStr); 11319 if (idx <= 1) { 11320 idx++; 11321 } else { 11322 idx--; 11323 } 11324 } catch(NumberFormatException e) { 11325 } 11326 } 11327 } 11328 } 11329 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11330 return prefix + idxStr; 11331 } 11332 11333 private File getNextCodePath(File targetDir, String packageName) { 11334 int suffix = 1; 11335 File result; 11336 do { 11337 result = new File(targetDir, packageName + "-" + suffix); 11338 suffix++; 11339 } while (result.exists()); 11340 return result; 11341 } 11342 11343 // Utility method that returns the relative package path with respect 11344 // to the installation directory. Like say for /data/data/com.test-1.apk 11345 // string com.test-1 is returned. 11346 static String deriveCodePathName(String codePath) { 11347 if (codePath == null) { 11348 return null; 11349 } 11350 final File codeFile = new File(codePath); 11351 final String name = codeFile.getName(); 11352 if (codeFile.isDirectory()) { 11353 return name; 11354 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11355 final int lastDot = name.lastIndexOf('.'); 11356 return name.substring(0, lastDot); 11357 } else { 11358 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11359 return null; 11360 } 11361 } 11362 11363 class PackageInstalledInfo { 11364 String name; 11365 int uid; 11366 // The set of users that originally had this package installed. 11367 int[] origUsers; 11368 // The set of users that now have this package installed. 11369 int[] newUsers; 11370 PackageParser.Package pkg; 11371 int returnCode; 11372 String returnMsg; 11373 PackageRemovedInfo removedInfo; 11374 11375 public void setError(int code, String msg) { 11376 returnCode = code; 11377 returnMsg = msg; 11378 Slog.w(TAG, msg); 11379 } 11380 11381 public void setError(String msg, PackageParserException e) { 11382 returnCode = e.error; 11383 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11384 Slog.w(TAG, msg, e); 11385 } 11386 11387 public void setError(String msg, PackageManagerException e) { 11388 returnCode = e.error; 11389 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11390 Slog.w(TAG, msg, e); 11391 } 11392 11393 // In some error cases we want to convey more info back to the observer 11394 String origPackage; 11395 String origPermission; 11396 } 11397 11398 /* 11399 * Install a non-existing package. 11400 */ 11401 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11402 UserHandle user, String installerPackageName, String volumeUuid, 11403 PackageInstalledInfo res) { 11404 // Remember this for later, in case we need to rollback this install 11405 String pkgName = pkg.packageName; 11406 11407 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11408 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11409 UserHandle.USER_OWNER).exists(); 11410 synchronized(mPackages) { 11411 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11412 // A package with the same name is already installed, though 11413 // it has been renamed to an older name. The package we 11414 // are trying to install should be installed as an update to 11415 // the existing one, but that has not been requested, so bail. 11416 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11417 + " without first uninstalling package running as " 11418 + mSettings.mRenamedPackages.get(pkgName)); 11419 return; 11420 } 11421 if (mPackages.containsKey(pkgName)) { 11422 // Don't allow installation over an existing package with the same name. 11423 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11424 + " without first uninstalling."); 11425 return; 11426 } 11427 } 11428 11429 try { 11430 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11431 System.currentTimeMillis(), user); 11432 11433 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11434 // delete the partially installed application. the data directory will have to be 11435 // restored if it was already existing 11436 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11437 // remove package from internal structures. Note that we want deletePackageX to 11438 // delete the package data and cache directories that it created in 11439 // scanPackageLocked, unless those directories existed before we even tried to 11440 // install. 11441 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11442 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11443 res.removedInfo, true); 11444 } 11445 11446 } catch (PackageManagerException e) { 11447 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11448 } 11449 } 11450 11451 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11452 // Can't rotate keys during boot or if sharedUser. 11453 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11454 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11455 return false; 11456 } 11457 // app is using upgradeKeySets; make sure all are valid 11458 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11459 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11460 for (int i = 0; i < upgradeKeySets.length; i++) { 11461 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11462 Slog.wtf(TAG, "Package " 11463 + (oldPs.name != null ? oldPs.name : "<null>") 11464 + " contains upgrade-key-set reference to unknown key-set: " 11465 + upgradeKeySets[i] 11466 + " reverting to signatures check."); 11467 return false; 11468 } 11469 } 11470 return true; 11471 } 11472 11473 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11474 // Upgrade keysets are being used. Determine if new package has a superset of the 11475 // required keys. 11476 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11478 for (int i = 0; i < upgradeKeySets.length; i++) { 11479 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11480 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11481 return true; 11482 } 11483 } 11484 return false; 11485 } 11486 11487 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11488 UserHandle user, String installerPackageName, String volumeUuid, 11489 PackageInstalledInfo res) { 11490 final PackageParser.Package oldPackage; 11491 final String pkgName = pkg.packageName; 11492 final int[] allUsers; 11493 final boolean[] perUserInstalled; 11494 final boolean weFroze; 11495 11496 // First find the old package info and check signatures 11497 synchronized(mPackages) { 11498 oldPackage = mPackages.get(pkgName); 11499 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11500 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11501 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11502 if(!checkUpgradeKeySetLP(ps, pkg)) { 11503 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11504 "New package not signed by keys specified by upgrade-keysets: " 11505 + pkgName); 11506 return; 11507 } 11508 } else { 11509 // default to original signature matching 11510 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11511 != PackageManager.SIGNATURE_MATCH) { 11512 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11513 "New package has a different signature: " + pkgName); 11514 return; 11515 } 11516 } 11517 11518 // In case of rollback, remember per-user/profile install state 11519 allUsers = sUserManager.getUserIds(); 11520 perUserInstalled = new boolean[allUsers.length]; 11521 for (int i = 0; i < allUsers.length; i++) { 11522 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11523 } 11524 11525 // Mark the app as frozen to prevent launching during the upgrade 11526 // process, and then kill all running instances 11527 if (!ps.frozen) { 11528 ps.frozen = true; 11529 weFroze = true; 11530 } else { 11531 weFroze = false; 11532 } 11533 } 11534 11535 // Now that we're guarded by frozen state, kill app during upgrade 11536 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11537 11538 try { 11539 boolean sysPkg = (isSystemApp(oldPackage)); 11540 if (sysPkg) { 11541 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11542 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11543 } else { 11544 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11545 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11546 } 11547 } finally { 11548 // Regardless of success or failure of upgrade steps above, always 11549 // unfreeze the package if we froze it 11550 if (weFroze) { 11551 unfreezePackage(pkgName); 11552 } 11553 } 11554 } 11555 11556 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11557 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11558 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11559 String volumeUuid, PackageInstalledInfo res) { 11560 String pkgName = deletedPackage.packageName; 11561 boolean deletedPkg = true; 11562 boolean updatedSettings = false; 11563 11564 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11565 + deletedPackage); 11566 long origUpdateTime; 11567 if (pkg.mExtras != null) { 11568 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11569 } else { 11570 origUpdateTime = 0; 11571 } 11572 11573 // First delete the existing package while retaining the data directory 11574 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11575 res.removedInfo, true)) { 11576 // If the existing package wasn't successfully deleted 11577 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11578 deletedPkg = false; 11579 } else { 11580 // Successfully deleted the old package; proceed with replace. 11581 11582 // If deleted package lived in a container, give users a chance to 11583 // relinquish resources before killing. 11584 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11585 if (DEBUG_INSTALL) { 11586 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11587 } 11588 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11589 final ArrayList<String> pkgList = new ArrayList<String>(1); 11590 pkgList.add(deletedPackage.applicationInfo.packageName); 11591 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11592 } 11593 11594 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11595 try { 11596 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11597 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11598 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11599 perUserInstalled, res, user); 11600 updatedSettings = true; 11601 } catch (PackageManagerException e) { 11602 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11603 } 11604 } 11605 11606 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11607 // remove package from internal structures. Note that we want deletePackageX to 11608 // delete the package data and cache directories that it created in 11609 // scanPackageLocked, unless those directories existed before we even tried to 11610 // install. 11611 if(updatedSettings) { 11612 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11613 deletePackageLI( 11614 pkgName, null, true, allUsers, perUserInstalled, 11615 PackageManager.DELETE_KEEP_DATA, 11616 res.removedInfo, true); 11617 } 11618 // Since we failed to install the new package we need to restore the old 11619 // package that we deleted. 11620 if (deletedPkg) { 11621 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11622 File restoreFile = new File(deletedPackage.codePath); 11623 // Parse old package 11624 boolean oldExternal = isExternal(deletedPackage); 11625 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11626 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11627 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11628 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11629 try { 11630 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11631 } catch (PackageManagerException e) { 11632 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11633 + e.getMessage()); 11634 return; 11635 } 11636 // Restore of old package succeeded. Update permissions. 11637 // writer 11638 synchronized (mPackages) { 11639 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11640 UPDATE_PERMISSIONS_ALL); 11641 // can downgrade to reader 11642 mSettings.writeLPr(); 11643 } 11644 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11645 } 11646 } 11647 } 11648 11649 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11650 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11651 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11652 String volumeUuid, PackageInstalledInfo res) { 11653 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11654 + ", old=" + deletedPackage); 11655 boolean disabledSystem = false; 11656 boolean updatedSettings = false; 11657 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11658 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11659 != 0) { 11660 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11661 } 11662 String packageName = deletedPackage.packageName; 11663 if (packageName == null) { 11664 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11665 "Attempt to delete null packageName."); 11666 return; 11667 } 11668 PackageParser.Package oldPkg; 11669 PackageSetting oldPkgSetting; 11670 // reader 11671 synchronized (mPackages) { 11672 oldPkg = mPackages.get(packageName); 11673 oldPkgSetting = mSettings.mPackages.get(packageName); 11674 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11675 (oldPkgSetting == null)) { 11676 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11677 "Couldn't find package:" + packageName + " information"); 11678 return; 11679 } 11680 } 11681 11682 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11683 res.removedInfo.removedPackage = packageName; 11684 // Remove existing system package 11685 removePackageLI(oldPkgSetting, true); 11686 // writer 11687 synchronized (mPackages) { 11688 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11689 if (!disabledSystem && deletedPackage != null) { 11690 // We didn't need to disable the .apk as a current system package, 11691 // which means we are replacing another update that is already 11692 // installed. We need to make sure to delete the older one's .apk. 11693 res.removedInfo.args = createInstallArgsForExisting(0, 11694 deletedPackage.applicationInfo.getCodePath(), 11695 deletedPackage.applicationInfo.getResourcePath(), 11696 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11697 } else { 11698 res.removedInfo.args = null; 11699 } 11700 } 11701 11702 // Successfully disabled the old package. Now proceed with re-installation 11703 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11704 11705 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11706 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11707 11708 PackageParser.Package newPackage = null; 11709 try { 11710 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11711 if (newPackage.mExtras != null) { 11712 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11713 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11714 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11715 11716 // is the update attempting to change shared user? that isn't going to work... 11717 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11718 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11719 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11720 + " to " + newPkgSetting.sharedUser); 11721 updatedSettings = true; 11722 } 11723 } 11724 11725 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11726 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11727 perUserInstalled, res, user); 11728 updatedSettings = true; 11729 } 11730 11731 } catch (PackageManagerException e) { 11732 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11733 } 11734 11735 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11736 // Re installation failed. Restore old information 11737 // Remove new pkg information 11738 if (newPackage != null) { 11739 removeInstalledPackageLI(newPackage, true); 11740 } 11741 // Add back the old system package 11742 try { 11743 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11744 } catch (PackageManagerException e) { 11745 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11746 } 11747 // Restore the old system information in Settings 11748 synchronized (mPackages) { 11749 if (disabledSystem) { 11750 mSettings.enableSystemPackageLPw(packageName); 11751 } 11752 if (updatedSettings) { 11753 mSettings.setInstallerPackageName(packageName, 11754 oldPkgSetting.installerPackageName); 11755 } 11756 mSettings.writeLPr(); 11757 } 11758 } 11759 } 11760 11761 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11762 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11763 UserHandle user) { 11764 String pkgName = newPackage.packageName; 11765 synchronized (mPackages) { 11766 //write settings. the installStatus will be incomplete at this stage. 11767 //note that the new package setting would have already been 11768 //added to mPackages. It hasn't been persisted yet. 11769 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11770 mSettings.writeLPr(); 11771 } 11772 11773 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11774 11775 synchronized (mPackages) { 11776 updatePermissionsLPw(newPackage.packageName, newPackage, 11777 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11778 ? UPDATE_PERMISSIONS_ALL : 0)); 11779 // For system-bundled packages, we assume that installing an upgraded version 11780 // of the package implies that the user actually wants to run that new code, 11781 // so we enable the package. 11782 PackageSetting ps = mSettings.mPackages.get(pkgName); 11783 if (ps != null) { 11784 if (isSystemApp(newPackage)) { 11785 // NB: implicit assumption that system package upgrades apply to all users 11786 if (DEBUG_INSTALL) { 11787 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11788 } 11789 if (res.origUsers != null) { 11790 for (int userHandle : res.origUsers) { 11791 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11792 userHandle, installerPackageName); 11793 } 11794 } 11795 // Also convey the prior install/uninstall state 11796 if (allUsers != null && perUserInstalled != null) { 11797 for (int i = 0; i < allUsers.length; i++) { 11798 if (DEBUG_INSTALL) { 11799 Slog.d(TAG, " user " + allUsers[i] 11800 + " => " + perUserInstalled[i]); 11801 } 11802 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11803 } 11804 // these install state changes will be persisted in the 11805 // upcoming call to mSettings.writeLPr(). 11806 } 11807 } 11808 // It's implied that when a user requests installation, they want the app to be 11809 // installed and enabled. 11810 int userId = user.getIdentifier(); 11811 if (userId != UserHandle.USER_ALL) { 11812 ps.setInstalled(true, userId); 11813 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11814 } 11815 } 11816 res.name = pkgName; 11817 res.uid = newPackage.applicationInfo.uid; 11818 res.pkg = newPackage; 11819 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11820 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11821 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11822 //to update install status 11823 mSettings.writeLPr(); 11824 } 11825 } 11826 11827 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11828 final int installFlags = args.installFlags; 11829 final String installerPackageName = args.installerPackageName; 11830 final String volumeUuid = args.volumeUuid; 11831 final File tmpPackageFile = new File(args.getCodePath()); 11832 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11833 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11834 || (args.volumeUuid != null)); 11835 boolean replace = false; 11836 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11837 if (args.move != null) { 11838 // moving a complete application; perfom an initial scan on the new install location 11839 scanFlags |= SCAN_INITIAL; 11840 } 11841 // Result object to be returned 11842 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11843 11844 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11845 // Retrieve PackageSettings and parse package 11846 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11847 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11848 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11849 PackageParser pp = new PackageParser(); 11850 pp.setSeparateProcesses(mSeparateProcesses); 11851 pp.setDisplayMetrics(mMetrics); 11852 11853 final PackageParser.Package pkg; 11854 try { 11855 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11856 } catch (PackageParserException e) { 11857 res.setError("Failed parse during installPackageLI", e); 11858 return; 11859 } 11860 11861 // Mark that we have an install time CPU ABI override. 11862 pkg.cpuAbiOverride = args.abiOverride; 11863 11864 String pkgName = res.name = pkg.packageName; 11865 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11866 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11867 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11868 return; 11869 } 11870 } 11871 11872 try { 11873 pp.collectCertificates(pkg, parseFlags); 11874 pp.collectManifestDigest(pkg); 11875 } catch (PackageParserException e) { 11876 res.setError("Failed collect during installPackageLI", e); 11877 return; 11878 } 11879 11880 /* If the installer passed in a manifest digest, compare it now. */ 11881 if (args.manifestDigest != null) { 11882 if (DEBUG_INSTALL) { 11883 final String parsedManifest = pkg.manifestDigest == null ? "null" 11884 : pkg.manifestDigest.toString(); 11885 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11886 + parsedManifest); 11887 } 11888 11889 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11890 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11891 return; 11892 } 11893 } else if (DEBUG_INSTALL) { 11894 final String parsedManifest = pkg.manifestDigest == null 11895 ? "null" : pkg.manifestDigest.toString(); 11896 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11897 } 11898 11899 // Get rid of all references to package scan path via parser. 11900 pp = null; 11901 String oldCodePath = null; 11902 boolean systemApp = false; 11903 synchronized (mPackages) { 11904 // Check if installing already existing package 11905 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11906 String oldName = mSettings.mRenamedPackages.get(pkgName); 11907 if (pkg.mOriginalPackages != null 11908 && pkg.mOriginalPackages.contains(oldName) 11909 && mPackages.containsKey(oldName)) { 11910 // This package is derived from an original package, 11911 // and this device has been updating from that original 11912 // name. We must continue using the original name, so 11913 // rename the new package here. 11914 pkg.setPackageName(oldName); 11915 pkgName = pkg.packageName; 11916 replace = true; 11917 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11918 + oldName + " pkgName=" + pkgName); 11919 } else if (mPackages.containsKey(pkgName)) { 11920 // This package, under its official name, already exists 11921 // on the device; we should replace it. 11922 replace = true; 11923 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11924 } 11925 11926 // Prevent apps opting out from runtime permissions 11927 if (replace) { 11928 PackageParser.Package oldPackage = mPackages.get(pkgName); 11929 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11930 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11931 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11932 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11933 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11934 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11935 + " doesn't support runtime permissions but the old" 11936 + " target SDK " + oldTargetSdk + " does."); 11937 return; 11938 } 11939 } 11940 } 11941 11942 PackageSetting ps = mSettings.mPackages.get(pkgName); 11943 if (ps != null) { 11944 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11945 11946 // Quick sanity check that we're signed correctly if updating; 11947 // we'll check this again later when scanning, but we want to 11948 // bail early here before tripping over redefined permissions. 11949 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11950 if (!checkUpgradeKeySetLP(ps, pkg)) { 11951 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11952 + pkg.packageName + " upgrade keys do not match the " 11953 + "previously installed version"); 11954 return; 11955 } 11956 } else { 11957 try { 11958 verifySignaturesLP(ps, pkg); 11959 } catch (PackageManagerException e) { 11960 res.setError(e.error, e.getMessage()); 11961 return; 11962 } 11963 } 11964 11965 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11966 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11967 systemApp = (ps.pkg.applicationInfo.flags & 11968 ApplicationInfo.FLAG_SYSTEM) != 0; 11969 } 11970 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11971 } 11972 11973 // Check whether the newly-scanned package wants to define an already-defined perm 11974 int N = pkg.permissions.size(); 11975 for (int i = N-1; i >= 0; i--) { 11976 PackageParser.Permission perm = pkg.permissions.get(i); 11977 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11978 if (bp != null) { 11979 // If the defining package is signed with our cert, it's okay. This 11980 // also includes the "updating the same package" case, of course. 11981 // "updating same package" could also involve key-rotation. 11982 final boolean sigsOk; 11983 if (bp.sourcePackage.equals(pkg.packageName) 11984 && (bp.packageSetting instanceof PackageSetting) 11985 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11986 scanFlags))) { 11987 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11988 } else { 11989 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11990 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11991 } 11992 if (!sigsOk) { 11993 // If the owning package is the system itself, we log but allow 11994 // install to proceed; we fail the install on all other permission 11995 // redefinitions. 11996 if (!bp.sourcePackage.equals("android")) { 11997 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11998 + pkg.packageName + " attempting to redeclare permission " 11999 + perm.info.name + " already owned by " + bp.sourcePackage); 12000 res.origPermission = perm.info.name; 12001 res.origPackage = bp.sourcePackage; 12002 return; 12003 } else { 12004 Slog.w(TAG, "Package " + pkg.packageName 12005 + " attempting to redeclare system permission " 12006 + perm.info.name + "; ignoring new declaration"); 12007 pkg.permissions.remove(i); 12008 } 12009 } 12010 } 12011 } 12012 12013 } 12014 12015 if (systemApp && onExternal) { 12016 // Disable updates to system apps on sdcard 12017 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12018 "Cannot install updates to system apps on sdcard"); 12019 return; 12020 } 12021 12022 if (args.move != null) { 12023 // We did an in-place move, so dex is ready to roll 12024 scanFlags |= SCAN_NO_DEX; 12025 scanFlags |= SCAN_MOVE; 12026 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12027 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12028 scanFlags |= SCAN_NO_DEX; 12029 12030 try { 12031 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12032 true /* extract libs */); 12033 } catch (PackageManagerException pme) { 12034 Slog.e(TAG, "Error deriving application ABI", pme); 12035 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12036 return; 12037 } 12038 12039 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12040 int result = mPackageDexOptimizer 12041 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12042 false /* defer */, false /* inclDependencies */); 12043 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12044 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12045 return; 12046 } 12047 } 12048 12049 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12050 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12051 return; 12052 } 12053 12054 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12055 12056 if (replace) { 12057 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12058 installerPackageName, volumeUuid, res); 12059 } else { 12060 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12061 args.user, installerPackageName, volumeUuid, res); 12062 } 12063 synchronized (mPackages) { 12064 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12065 if (ps != null) { 12066 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12067 } 12068 } 12069 } 12070 12071 private void startIntentFilterVerifications(int userId, boolean replacing, 12072 PackageParser.Package pkg) { 12073 if (mIntentFilterVerifierComponent == null) { 12074 Slog.w(TAG, "No IntentFilter verification will not be done as " 12075 + "there is no IntentFilterVerifier available!"); 12076 return; 12077 } 12078 12079 final int verifierUid = getPackageUid( 12080 mIntentFilterVerifierComponent.getPackageName(), 12081 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12082 12083 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12084 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12085 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12086 mHandler.sendMessage(msg); 12087 } 12088 12089 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12090 PackageParser.Package pkg) { 12091 int size = pkg.activities.size(); 12092 if (size == 0) { 12093 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12094 "No activity, so no need to verify any IntentFilter!"); 12095 return; 12096 } 12097 12098 final boolean hasDomainURLs = hasDomainURLs(pkg); 12099 if (!hasDomainURLs) { 12100 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12101 "No domain URLs, so no need to verify any IntentFilter!"); 12102 return; 12103 } 12104 12105 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12106 + " if any IntentFilter from the " + size 12107 + " Activities needs verification ..."); 12108 12109 int count = 0; 12110 final String packageName = pkg.packageName; 12111 12112 synchronized (mPackages) { 12113 // If this is a new install and we see that we've already run verification for this 12114 // package, we have nothing to do: it means the state was restored from backup. 12115 if (!replacing) { 12116 IntentFilterVerificationInfo ivi = 12117 mSettings.getIntentFilterVerificationLPr(packageName); 12118 if (ivi != null) { 12119 if (DEBUG_DOMAIN_VERIFICATION) { 12120 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12121 + ivi.getStatusString()); 12122 } 12123 return; 12124 } 12125 } 12126 12127 // If any filters need to be verified, then all need to be. 12128 boolean needToVerify = false; 12129 for (PackageParser.Activity a : pkg.activities) { 12130 for (ActivityIntentInfo filter : a.intents) { 12131 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12132 if (DEBUG_DOMAIN_VERIFICATION) { 12133 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12134 } 12135 needToVerify = true; 12136 break; 12137 } 12138 } 12139 } 12140 12141 if (needToVerify) { 12142 final int verificationId = mIntentFilterVerificationToken++; 12143 for (PackageParser.Activity a : pkg.activities) { 12144 for (ActivityIntentInfo filter : a.intents) { 12145 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12146 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12147 "Verification needed for IntentFilter:" + filter.toString()); 12148 mIntentFilterVerifier.addOneIntentFilterVerification( 12149 verifierUid, userId, verificationId, filter, packageName); 12150 count++; 12151 } 12152 } 12153 } 12154 } 12155 } 12156 12157 if (count > 0) { 12158 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12159 + " IntentFilter verification" + (count > 1 ? "s" : "") 12160 + " for userId:" + userId); 12161 mIntentFilterVerifier.startVerifications(userId); 12162 } else { 12163 if (DEBUG_DOMAIN_VERIFICATION) { 12164 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12165 } 12166 } 12167 } 12168 12169 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12170 final ComponentName cn = filter.activity.getComponentName(); 12171 final String packageName = cn.getPackageName(); 12172 12173 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12174 packageName); 12175 if (ivi == null) { 12176 return true; 12177 } 12178 int status = ivi.getStatus(); 12179 switch (status) { 12180 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12181 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12182 return true; 12183 12184 default: 12185 // Nothing to do 12186 return false; 12187 } 12188 } 12189 12190 private static boolean isMultiArch(PackageSetting ps) { 12191 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12192 } 12193 12194 private static boolean isMultiArch(ApplicationInfo info) { 12195 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12196 } 12197 12198 private static boolean isExternal(PackageParser.Package pkg) { 12199 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12200 } 12201 12202 private static boolean isExternal(PackageSetting ps) { 12203 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12204 } 12205 12206 private static boolean isExternal(ApplicationInfo info) { 12207 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12208 } 12209 12210 private static boolean isSystemApp(PackageParser.Package pkg) { 12211 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12212 } 12213 12214 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12215 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12216 } 12217 12218 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12219 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12220 } 12221 12222 private static boolean isSystemApp(PackageSetting ps) { 12223 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12224 } 12225 12226 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12227 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12228 } 12229 12230 private int packageFlagsToInstallFlags(PackageSetting ps) { 12231 int installFlags = 0; 12232 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12233 // This existing package was an external ASEC install when we have 12234 // the external flag without a UUID 12235 installFlags |= PackageManager.INSTALL_EXTERNAL; 12236 } 12237 if (ps.isForwardLocked()) { 12238 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12239 } 12240 return installFlags; 12241 } 12242 12243 private void deleteTempPackageFiles() { 12244 final FilenameFilter filter = new FilenameFilter() { 12245 public boolean accept(File dir, String name) { 12246 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12247 } 12248 }; 12249 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12250 file.delete(); 12251 } 12252 } 12253 12254 @Override 12255 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12256 int flags) { 12257 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12258 flags); 12259 } 12260 12261 @Override 12262 public void deletePackage(final String packageName, 12263 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12264 mContext.enforceCallingOrSelfPermission( 12265 android.Manifest.permission.DELETE_PACKAGES, null); 12266 final int uid = Binder.getCallingUid(); 12267 if (UserHandle.getUserId(uid) != userId) { 12268 mContext.enforceCallingPermission( 12269 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12270 "deletePackage for user " + userId); 12271 } 12272 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12273 try { 12274 observer.onPackageDeleted(packageName, 12275 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12276 } catch (RemoteException re) { 12277 } 12278 return; 12279 } 12280 12281 boolean uninstallBlocked = false; 12282 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12283 int[] users = sUserManager.getUserIds(); 12284 for (int i = 0; i < users.length; ++i) { 12285 if (getBlockUninstallForUser(packageName, users[i])) { 12286 uninstallBlocked = true; 12287 break; 12288 } 12289 } 12290 } else { 12291 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12292 } 12293 if (uninstallBlocked) { 12294 try { 12295 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12296 null); 12297 } catch (RemoteException re) { 12298 } 12299 return; 12300 } 12301 12302 if (DEBUG_REMOVE) { 12303 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12304 } 12305 // Queue up an async operation since the package deletion may take a little while. 12306 mHandler.post(new Runnable() { 12307 public void run() { 12308 mHandler.removeCallbacks(this); 12309 final int returnCode = deletePackageX(packageName, userId, flags); 12310 if (observer != null) { 12311 try { 12312 observer.onPackageDeleted(packageName, returnCode, null); 12313 } catch (RemoteException e) { 12314 Log.i(TAG, "Observer no longer exists."); 12315 } //end catch 12316 } //end if 12317 } //end run 12318 }); 12319 } 12320 12321 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12322 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12323 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12324 try { 12325 if (dpm != null) { 12326 if (dpm.isDeviceOwner(packageName)) { 12327 return true; 12328 } 12329 int[] users; 12330 if (userId == UserHandle.USER_ALL) { 12331 users = sUserManager.getUserIds(); 12332 } else { 12333 users = new int[]{userId}; 12334 } 12335 for (int i = 0; i < users.length; ++i) { 12336 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12337 return true; 12338 } 12339 } 12340 } 12341 } catch (RemoteException e) { 12342 } 12343 return false; 12344 } 12345 12346 /** 12347 * This method is an internal method that could be get invoked either 12348 * to delete an installed package or to clean up a failed installation. 12349 * After deleting an installed package, a broadcast is sent to notify any 12350 * listeners that the package has been installed. For cleaning up a failed 12351 * installation, the broadcast is not necessary since the package's 12352 * installation wouldn't have sent the initial broadcast either 12353 * The key steps in deleting a package are 12354 * deleting the package information in internal structures like mPackages, 12355 * deleting the packages base directories through installd 12356 * updating mSettings to reflect current status 12357 * persisting settings for later use 12358 * sending a broadcast if necessary 12359 */ 12360 private int deletePackageX(String packageName, int userId, int flags) { 12361 final PackageRemovedInfo info = new PackageRemovedInfo(); 12362 final boolean res; 12363 12364 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12365 ? UserHandle.ALL : new UserHandle(userId); 12366 12367 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12368 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12369 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12370 } 12371 12372 boolean removedForAllUsers = false; 12373 boolean systemUpdate = false; 12374 12375 // for the uninstall-updates case and restricted profiles, remember the per- 12376 // userhandle installed state 12377 int[] allUsers; 12378 boolean[] perUserInstalled; 12379 synchronized (mPackages) { 12380 PackageSetting ps = mSettings.mPackages.get(packageName); 12381 allUsers = sUserManager.getUserIds(); 12382 perUserInstalled = new boolean[allUsers.length]; 12383 for (int i = 0; i < allUsers.length; i++) { 12384 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12385 } 12386 } 12387 12388 synchronized (mInstallLock) { 12389 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12390 res = deletePackageLI(packageName, removeForUser, 12391 true, allUsers, perUserInstalled, 12392 flags | REMOVE_CHATTY, info, true); 12393 systemUpdate = info.isRemovedPackageSystemUpdate; 12394 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12395 removedForAllUsers = true; 12396 } 12397 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12398 + " removedForAllUsers=" + removedForAllUsers); 12399 } 12400 12401 if (res) { 12402 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12403 12404 // If the removed package was a system update, the old system package 12405 // was re-enabled; we need to broadcast this information 12406 if (systemUpdate) { 12407 Bundle extras = new Bundle(1); 12408 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12409 ? info.removedAppId : info.uid); 12410 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12411 12412 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12413 extras, null, null, null); 12414 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12415 extras, null, null, null); 12416 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12417 null, packageName, null, null); 12418 } 12419 } 12420 // Force a gc here. 12421 Runtime.getRuntime().gc(); 12422 // Delete the resources here after sending the broadcast to let 12423 // other processes clean up before deleting resources. 12424 if (info.args != null) { 12425 synchronized (mInstallLock) { 12426 info.args.doPostDeleteLI(true); 12427 } 12428 } 12429 12430 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12431 } 12432 12433 class PackageRemovedInfo { 12434 String removedPackage; 12435 int uid = -1; 12436 int removedAppId = -1; 12437 int[] removedUsers = null; 12438 boolean isRemovedPackageSystemUpdate = false; 12439 // Clean up resources deleted packages. 12440 InstallArgs args = null; 12441 12442 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12443 Bundle extras = new Bundle(1); 12444 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12445 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12446 if (replacing) { 12447 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12448 } 12449 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12450 if (removedPackage != null) { 12451 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12452 extras, null, null, removedUsers); 12453 if (fullRemove && !replacing) { 12454 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12455 extras, null, null, removedUsers); 12456 } 12457 } 12458 if (removedAppId >= 0) { 12459 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12460 removedUsers); 12461 } 12462 } 12463 } 12464 12465 /* 12466 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12467 * flag is not set, the data directory is removed as well. 12468 * make sure this flag is set for partially installed apps. If not its meaningless to 12469 * delete a partially installed application. 12470 */ 12471 private void removePackageDataLI(PackageSetting ps, 12472 int[] allUserHandles, boolean[] perUserInstalled, 12473 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12474 String packageName = ps.name; 12475 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12476 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12477 // Retrieve object to delete permissions for shared user later on 12478 final PackageSetting deletedPs; 12479 // reader 12480 synchronized (mPackages) { 12481 deletedPs = mSettings.mPackages.get(packageName); 12482 if (outInfo != null) { 12483 outInfo.removedPackage = packageName; 12484 outInfo.removedUsers = deletedPs != null 12485 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12486 : null; 12487 } 12488 } 12489 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12490 removeDataDirsLI(ps.volumeUuid, packageName); 12491 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12492 } 12493 // writer 12494 synchronized (mPackages) { 12495 if (deletedPs != null) { 12496 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12497 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12498 clearDefaultBrowserIfNeeded(packageName); 12499 if (outInfo != null) { 12500 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12501 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12502 } 12503 updatePermissionsLPw(deletedPs.name, null, 0); 12504 if (deletedPs.sharedUser != null) { 12505 // Remove permissions associated with package. Since runtime 12506 // permissions are per user we have to kill the removed package 12507 // or packages running under the shared user of the removed 12508 // package if revoking the permissions requested only by the removed 12509 // package is successful and this causes a change in gids. 12510 for (int userId : UserManagerService.getInstance().getUserIds()) { 12511 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12512 userId); 12513 if (userIdToKill == UserHandle.USER_ALL 12514 || userIdToKill >= UserHandle.USER_OWNER) { 12515 // If gids changed for this user, kill all affected packages. 12516 mHandler.post(new Runnable() { 12517 @Override 12518 public void run() { 12519 // This has to happen with no lock held. 12520 killSettingPackagesForUser(deletedPs, userIdToKill, 12521 KILL_APP_REASON_GIDS_CHANGED); 12522 } 12523 }); 12524 break; 12525 } 12526 } 12527 } 12528 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12529 } 12530 // make sure to preserve per-user disabled state if this removal was just 12531 // a downgrade of a system app to the factory package 12532 if (allUserHandles != null && perUserInstalled != null) { 12533 if (DEBUG_REMOVE) { 12534 Slog.d(TAG, "Propagating install state across downgrade"); 12535 } 12536 for (int i = 0; i < allUserHandles.length; i++) { 12537 if (DEBUG_REMOVE) { 12538 Slog.d(TAG, " user " + allUserHandles[i] 12539 + " => " + perUserInstalled[i]); 12540 } 12541 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12542 } 12543 } 12544 } 12545 // can downgrade to reader 12546 if (writeSettings) { 12547 // Save settings now 12548 mSettings.writeLPr(); 12549 } 12550 } 12551 if (outInfo != null) { 12552 // A user ID was deleted here. Go through all users and remove it 12553 // from KeyStore. 12554 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12555 } 12556 } 12557 12558 static boolean locationIsPrivileged(File path) { 12559 try { 12560 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12561 .getCanonicalPath(); 12562 return path.getCanonicalPath().startsWith(privilegedAppDir); 12563 } catch (IOException e) { 12564 Slog.e(TAG, "Unable to access code path " + path); 12565 } 12566 return false; 12567 } 12568 12569 /* 12570 * Tries to delete system package. 12571 */ 12572 private boolean deleteSystemPackageLI(PackageSetting newPs, 12573 int[] allUserHandles, boolean[] perUserInstalled, 12574 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12575 final boolean applyUserRestrictions 12576 = (allUserHandles != null) && (perUserInstalled != null); 12577 PackageSetting disabledPs = null; 12578 // Confirm if the system package has been updated 12579 // An updated system app can be deleted. This will also have to restore 12580 // the system pkg from system partition 12581 // reader 12582 synchronized (mPackages) { 12583 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12584 } 12585 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12586 + " disabledPs=" + disabledPs); 12587 if (disabledPs == null) { 12588 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12589 return false; 12590 } else if (DEBUG_REMOVE) { 12591 Slog.d(TAG, "Deleting system pkg from data partition"); 12592 } 12593 if (DEBUG_REMOVE) { 12594 if (applyUserRestrictions) { 12595 Slog.d(TAG, "Remembering install states:"); 12596 for (int i = 0; i < allUserHandles.length; i++) { 12597 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12598 } 12599 } 12600 } 12601 // Delete the updated package 12602 outInfo.isRemovedPackageSystemUpdate = true; 12603 if (disabledPs.versionCode < newPs.versionCode) { 12604 // Delete data for downgrades 12605 flags &= ~PackageManager.DELETE_KEEP_DATA; 12606 } else { 12607 // Preserve data by setting flag 12608 flags |= PackageManager.DELETE_KEEP_DATA; 12609 } 12610 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12611 allUserHandles, perUserInstalled, outInfo, writeSettings); 12612 if (!ret) { 12613 return false; 12614 } 12615 // writer 12616 synchronized (mPackages) { 12617 // Reinstate the old system package 12618 mSettings.enableSystemPackageLPw(newPs.name); 12619 // Remove any native libraries from the upgraded package. 12620 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12621 } 12622 // Install the system package 12623 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12624 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12625 if (locationIsPrivileged(disabledPs.codePath)) { 12626 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12627 } 12628 12629 final PackageParser.Package newPkg; 12630 try { 12631 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12632 } catch (PackageManagerException e) { 12633 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12634 return false; 12635 } 12636 12637 // writer 12638 synchronized (mPackages) { 12639 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12640 updatePermissionsLPw(newPkg.packageName, newPkg, 12641 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12642 if (applyUserRestrictions) { 12643 if (DEBUG_REMOVE) { 12644 Slog.d(TAG, "Propagating install state across reinstall"); 12645 } 12646 for (int i = 0; i < allUserHandles.length; i++) { 12647 if (DEBUG_REMOVE) { 12648 Slog.d(TAG, " user " + allUserHandles[i] 12649 + " => " + perUserInstalled[i]); 12650 } 12651 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12652 } 12653 // Regardless of writeSettings we need to ensure that this restriction 12654 // state propagation is persisted 12655 mSettings.writeAllUsersPackageRestrictionsLPr(); 12656 } 12657 // can downgrade to reader here 12658 if (writeSettings) { 12659 mSettings.writeLPr(); 12660 } 12661 } 12662 return true; 12663 } 12664 12665 private boolean deleteInstalledPackageLI(PackageSetting ps, 12666 boolean deleteCodeAndResources, int flags, 12667 int[] allUserHandles, boolean[] perUserInstalled, 12668 PackageRemovedInfo outInfo, boolean writeSettings) { 12669 if (outInfo != null) { 12670 outInfo.uid = ps.appId; 12671 } 12672 12673 // Delete package data from internal structures and also remove data if flag is set 12674 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12675 12676 // Delete application code and resources 12677 if (deleteCodeAndResources && (outInfo != null)) { 12678 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12679 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12680 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12681 } 12682 return true; 12683 } 12684 12685 @Override 12686 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12687 int userId) { 12688 mContext.enforceCallingOrSelfPermission( 12689 android.Manifest.permission.DELETE_PACKAGES, null); 12690 synchronized (mPackages) { 12691 PackageSetting ps = mSettings.mPackages.get(packageName); 12692 if (ps == null) { 12693 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12694 return false; 12695 } 12696 if (!ps.getInstalled(userId)) { 12697 // Can't block uninstall for an app that is not installed or enabled. 12698 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12699 return false; 12700 } 12701 ps.setBlockUninstall(blockUninstall, userId); 12702 mSettings.writePackageRestrictionsLPr(userId); 12703 } 12704 return true; 12705 } 12706 12707 @Override 12708 public boolean getBlockUninstallForUser(String packageName, int userId) { 12709 synchronized (mPackages) { 12710 PackageSetting ps = mSettings.mPackages.get(packageName); 12711 if (ps == null) { 12712 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12713 return false; 12714 } 12715 return ps.getBlockUninstall(userId); 12716 } 12717 } 12718 12719 /* 12720 * This method handles package deletion in general 12721 */ 12722 private boolean deletePackageLI(String packageName, UserHandle user, 12723 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12724 int flags, PackageRemovedInfo outInfo, 12725 boolean writeSettings) { 12726 if (packageName == null) { 12727 Slog.w(TAG, "Attempt to delete null packageName."); 12728 return false; 12729 } 12730 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12731 PackageSetting ps; 12732 boolean dataOnly = false; 12733 int removeUser = -1; 12734 int appId = -1; 12735 synchronized (mPackages) { 12736 ps = mSettings.mPackages.get(packageName); 12737 if (ps == null) { 12738 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12739 return false; 12740 } 12741 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12742 && user.getIdentifier() != UserHandle.USER_ALL) { 12743 // The caller is asking that the package only be deleted for a single 12744 // user. To do this, we just mark its uninstalled state and delete 12745 // its data. If this is a system app, we only allow this to happen if 12746 // they have set the special DELETE_SYSTEM_APP which requests different 12747 // semantics than normal for uninstalling system apps. 12748 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12749 ps.setUserState(user.getIdentifier(), 12750 COMPONENT_ENABLED_STATE_DEFAULT, 12751 false, //installed 12752 true, //stopped 12753 true, //notLaunched 12754 false, //hidden 12755 null, null, null, 12756 false, // blockUninstall 12757 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12758 if (!isSystemApp(ps)) { 12759 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12760 // Other user still have this package installed, so all 12761 // we need to do is clear this user's data and save that 12762 // it is uninstalled. 12763 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12764 removeUser = user.getIdentifier(); 12765 appId = ps.appId; 12766 scheduleWritePackageRestrictionsLocked(removeUser); 12767 } else { 12768 // We need to set it back to 'installed' so the uninstall 12769 // broadcasts will be sent correctly. 12770 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12771 ps.setInstalled(true, user.getIdentifier()); 12772 } 12773 } else { 12774 // This is a system app, so we assume that the 12775 // other users still have this package installed, so all 12776 // we need to do is clear this user's data and save that 12777 // it is uninstalled. 12778 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12779 removeUser = user.getIdentifier(); 12780 appId = ps.appId; 12781 scheduleWritePackageRestrictionsLocked(removeUser); 12782 } 12783 } 12784 } 12785 12786 if (removeUser >= 0) { 12787 // From above, we determined that we are deleting this only 12788 // for a single user. Continue the work here. 12789 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12790 if (outInfo != null) { 12791 outInfo.removedPackage = packageName; 12792 outInfo.removedAppId = appId; 12793 outInfo.removedUsers = new int[] {removeUser}; 12794 } 12795 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12796 removeKeystoreDataIfNeeded(removeUser, appId); 12797 schedulePackageCleaning(packageName, removeUser, false); 12798 synchronized (mPackages) { 12799 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12800 scheduleWritePackageRestrictionsLocked(removeUser); 12801 } 12802 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12803 removeUser); 12804 } 12805 return true; 12806 } 12807 12808 if (dataOnly) { 12809 // Delete application data first 12810 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12811 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12812 return true; 12813 } 12814 12815 boolean ret = false; 12816 if (isSystemApp(ps)) { 12817 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12818 // When an updated system application is deleted we delete the existing resources as well and 12819 // fall back to existing code in system partition 12820 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12821 flags, outInfo, writeSettings); 12822 } else { 12823 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12824 // Kill application pre-emptively especially for apps on sd. 12825 killApplication(packageName, ps.appId, "uninstall pkg"); 12826 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12827 allUserHandles, perUserInstalled, 12828 outInfo, writeSettings); 12829 } 12830 12831 return ret; 12832 } 12833 12834 private final class ClearStorageConnection implements ServiceConnection { 12835 IMediaContainerService mContainerService; 12836 12837 @Override 12838 public void onServiceConnected(ComponentName name, IBinder service) { 12839 synchronized (this) { 12840 mContainerService = IMediaContainerService.Stub.asInterface(service); 12841 notifyAll(); 12842 } 12843 } 12844 12845 @Override 12846 public void onServiceDisconnected(ComponentName name) { 12847 } 12848 } 12849 12850 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12851 final boolean mounted; 12852 if (Environment.isExternalStorageEmulated()) { 12853 mounted = true; 12854 } else { 12855 final String status = Environment.getExternalStorageState(); 12856 12857 mounted = status.equals(Environment.MEDIA_MOUNTED) 12858 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12859 } 12860 12861 if (!mounted) { 12862 return; 12863 } 12864 12865 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12866 int[] users; 12867 if (userId == UserHandle.USER_ALL) { 12868 users = sUserManager.getUserIds(); 12869 } else { 12870 users = new int[] { userId }; 12871 } 12872 final ClearStorageConnection conn = new ClearStorageConnection(); 12873 if (mContext.bindServiceAsUser( 12874 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12875 try { 12876 for (int curUser : users) { 12877 long timeout = SystemClock.uptimeMillis() + 5000; 12878 synchronized (conn) { 12879 long now = SystemClock.uptimeMillis(); 12880 while (conn.mContainerService == null && now < timeout) { 12881 try { 12882 conn.wait(timeout - now); 12883 } catch (InterruptedException e) { 12884 } 12885 } 12886 } 12887 if (conn.mContainerService == null) { 12888 return; 12889 } 12890 12891 final UserEnvironment userEnv = new UserEnvironment(curUser); 12892 clearDirectory(conn.mContainerService, 12893 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12894 if (allData) { 12895 clearDirectory(conn.mContainerService, 12896 userEnv.buildExternalStorageAppDataDirs(packageName)); 12897 clearDirectory(conn.mContainerService, 12898 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12899 } 12900 } 12901 } finally { 12902 mContext.unbindService(conn); 12903 } 12904 } 12905 } 12906 12907 @Override 12908 public void clearApplicationUserData(final String packageName, 12909 final IPackageDataObserver observer, final int userId) { 12910 mContext.enforceCallingOrSelfPermission( 12911 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12912 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12913 // Queue up an async operation since the package deletion may take a little while. 12914 mHandler.post(new Runnable() { 12915 public void run() { 12916 mHandler.removeCallbacks(this); 12917 final boolean succeeded; 12918 synchronized (mInstallLock) { 12919 succeeded = clearApplicationUserDataLI(packageName, userId); 12920 } 12921 clearExternalStorageDataSync(packageName, userId, true); 12922 if (succeeded) { 12923 // invoke DeviceStorageMonitor's update method to clear any notifications 12924 DeviceStorageMonitorInternal 12925 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12926 if (dsm != null) { 12927 dsm.checkMemory(); 12928 } 12929 } 12930 if(observer != null) { 12931 try { 12932 observer.onRemoveCompleted(packageName, succeeded); 12933 } catch (RemoteException e) { 12934 Log.i(TAG, "Observer no longer exists."); 12935 } 12936 } //end if observer 12937 } //end run 12938 }); 12939 } 12940 12941 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12942 if (packageName == null) { 12943 Slog.w(TAG, "Attempt to delete null packageName."); 12944 return false; 12945 } 12946 12947 // Try finding details about the requested package 12948 PackageParser.Package pkg; 12949 synchronized (mPackages) { 12950 pkg = mPackages.get(packageName); 12951 if (pkg == null) { 12952 final PackageSetting ps = mSettings.mPackages.get(packageName); 12953 if (ps != null) { 12954 pkg = ps.pkg; 12955 } 12956 } 12957 12958 if (pkg == null) { 12959 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12960 return false; 12961 } 12962 12963 PackageSetting ps = (PackageSetting) pkg.mExtras; 12964 PermissionsState permissionsState = ps.getPermissionsState(); 12965 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12966 } 12967 12968 // Always delete data directories for package, even if we found no other 12969 // record of app. This helps users recover from UID mismatches without 12970 // resorting to a full data wipe. 12971 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12972 if (retCode < 0) { 12973 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12974 return false; 12975 } 12976 12977 final int appId = pkg.applicationInfo.uid; 12978 removeKeystoreDataIfNeeded(userId, appId); 12979 12980 // Create a native library symlink only if we have native libraries 12981 // and if the native libraries are 32 bit libraries. We do not provide 12982 // this symlink for 64 bit libraries. 12983 if (pkg.applicationInfo.primaryCpuAbi != null && 12984 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12985 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12986 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12987 nativeLibPath, userId) < 0) { 12988 Slog.w(TAG, "Failed linking native library dir"); 12989 return false; 12990 } 12991 } 12992 12993 return true; 12994 } 12995 12996 12997 /** 12998 * Revokes granted runtime permissions and clears resettable flags 12999 * which are flags that can be set by a user interaction. 13000 * 13001 * @param permissionsState The permission state to reset. 13002 * @param userId The device user for which to do a reset. 13003 */ 13004 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13005 PermissionsState permissionsState, int userId) { 13006 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13007 | PackageManager.FLAG_PERMISSION_USER_FIXED 13008 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13009 13010 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13011 } 13012 13013 /** 13014 * Revokes granted runtime permissions and clears all flags. 13015 * 13016 * @param permissionsState The permission state to reset. 13017 * @param userId The device user for which to do a reset. 13018 */ 13019 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13020 PermissionsState permissionsState, int userId) { 13021 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13022 PackageManager.MASK_PERMISSION_FLAGS); 13023 } 13024 13025 /** 13026 * Revokes granted runtime permissions and clears certain flags. 13027 * 13028 * @param permissionsState The permission state to reset. 13029 * @param userId The device user for which to do a reset. 13030 * @param flags The flags that is going to be reset. 13031 */ 13032 private void revokeRuntimePermissionsAndClearFlagsLocked( 13033 PermissionsState permissionsState, final int userId, int flags) { 13034 boolean needsWrite = false; 13035 13036 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13037 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13038 if (bp != null) { 13039 permissionsState.revokeRuntimePermission(bp, userId); 13040 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13041 needsWrite = true; 13042 } 13043 } 13044 13045 // Ensure default permissions are never cleared. 13046 mHandler.post(new Runnable() { 13047 @Override 13048 public void run() { 13049 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13050 } 13051 }); 13052 13053 if (needsWrite) { 13054 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13055 } 13056 } 13057 13058 /** 13059 * Remove entries from the keystore daemon. Will only remove it if the 13060 * {@code appId} is valid. 13061 */ 13062 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13063 if (appId < 0) { 13064 return; 13065 } 13066 13067 final KeyStore keyStore = KeyStore.getInstance(); 13068 if (keyStore != null) { 13069 if (userId == UserHandle.USER_ALL) { 13070 for (final int individual : sUserManager.getUserIds()) { 13071 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13072 } 13073 } else { 13074 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13075 } 13076 } else { 13077 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13078 } 13079 } 13080 13081 @Override 13082 public void deleteApplicationCacheFiles(final String packageName, 13083 final IPackageDataObserver observer) { 13084 mContext.enforceCallingOrSelfPermission( 13085 android.Manifest.permission.DELETE_CACHE_FILES, null); 13086 // Queue up an async operation since the package deletion may take a little while. 13087 final int userId = UserHandle.getCallingUserId(); 13088 mHandler.post(new Runnable() { 13089 public void run() { 13090 mHandler.removeCallbacks(this); 13091 final boolean succeded; 13092 synchronized (mInstallLock) { 13093 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13094 } 13095 clearExternalStorageDataSync(packageName, userId, false); 13096 if (observer != null) { 13097 try { 13098 observer.onRemoveCompleted(packageName, succeded); 13099 } catch (RemoteException e) { 13100 Log.i(TAG, "Observer no longer exists."); 13101 } 13102 } //end if observer 13103 } //end run 13104 }); 13105 } 13106 13107 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13108 if (packageName == null) { 13109 Slog.w(TAG, "Attempt to delete null packageName."); 13110 return false; 13111 } 13112 PackageParser.Package p; 13113 synchronized (mPackages) { 13114 p = mPackages.get(packageName); 13115 } 13116 if (p == null) { 13117 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13118 return false; 13119 } 13120 final ApplicationInfo applicationInfo = p.applicationInfo; 13121 if (applicationInfo == null) { 13122 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13123 return false; 13124 } 13125 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13126 if (retCode < 0) { 13127 Slog.w(TAG, "Couldn't remove cache files for package: " 13128 + packageName + " u" + userId); 13129 return false; 13130 } 13131 return true; 13132 } 13133 13134 @Override 13135 public void getPackageSizeInfo(final String packageName, int userHandle, 13136 final IPackageStatsObserver observer) { 13137 mContext.enforceCallingOrSelfPermission( 13138 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13139 if (packageName == null) { 13140 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13141 } 13142 13143 PackageStats stats = new PackageStats(packageName, userHandle); 13144 13145 /* 13146 * Queue up an async operation since the package measurement may take a 13147 * little while. 13148 */ 13149 Message msg = mHandler.obtainMessage(INIT_COPY); 13150 msg.obj = new MeasureParams(stats, observer); 13151 mHandler.sendMessage(msg); 13152 } 13153 13154 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13155 PackageStats pStats) { 13156 if (packageName == null) { 13157 Slog.w(TAG, "Attempt to get size of null packageName."); 13158 return false; 13159 } 13160 PackageParser.Package p; 13161 boolean dataOnly = false; 13162 String libDirRoot = null; 13163 String asecPath = null; 13164 PackageSetting ps = null; 13165 synchronized (mPackages) { 13166 p = mPackages.get(packageName); 13167 ps = mSettings.mPackages.get(packageName); 13168 if(p == null) { 13169 dataOnly = true; 13170 if((ps == null) || (ps.pkg == null)) { 13171 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13172 return false; 13173 } 13174 p = ps.pkg; 13175 } 13176 if (ps != null) { 13177 libDirRoot = ps.legacyNativeLibraryPathString; 13178 } 13179 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13180 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13181 if (secureContainerId != null) { 13182 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13183 } 13184 } 13185 } 13186 String publicSrcDir = null; 13187 if(!dataOnly) { 13188 final ApplicationInfo applicationInfo = p.applicationInfo; 13189 if (applicationInfo == null) { 13190 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13191 return false; 13192 } 13193 if (p.isForwardLocked()) { 13194 publicSrcDir = applicationInfo.getBaseResourcePath(); 13195 } 13196 } 13197 // TODO: extend to measure size of split APKs 13198 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13199 // not just the first level. 13200 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13201 // just the primary. 13202 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13203 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13204 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13205 if (res < 0) { 13206 return false; 13207 } 13208 13209 // Fix-up for forward-locked applications in ASEC containers. 13210 if (!isExternal(p)) { 13211 pStats.codeSize += pStats.externalCodeSize; 13212 pStats.externalCodeSize = 0L; 13213 } 13214 13215 return true; 13216 } 13217 13218 13219 @Override 13220 public void addPackageToPreferred(String packageName) { 13221 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13222 } 13223 13224 @Override 13225 public void removePackageFromPreferred(String packageName) { 13226 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13227 } 13228 13229 @Override 13230 public List<PackageInfo> getPreferredPackages(int flags) { 13231 return new ArrayList<PackageInfo>(); 13232 } 13233 13234 private int getUidTargetSdkVersionLockedLPr(int uid) { 13235 Object obj = mSettings.getUserIdLPr(uid); 13236 if (obj instanceof SharedUserSetting) { 13237 final SharedUserSetting sus = (SharedUserSetting) obj; 13238 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13239 final Iterator<PackageSetting> it = sus.packages.iterator(); 13240 while (it.hasNext()) { 13241 final PackageSetting ps = it.next(); 13242 if (ps.pkg != null) { 13243 int v = ps.pkg.applicationInfo.targetSdkVersion; 13244 if (v < vers) vers = v; 13245 } 13246 } 13247 return vers; 13248 } else if (obj instanceof PackageSetting) { 13249 final PackageSetting ps = (PackageSetting) obj; 13250 if (ps.pkg != null) { 13251 return ps.pkg.applicationInfo.targetSdkVersion; 13252 } 13253 } 13254 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13255 } 13256 13257 @Override 13258 public void addPreferredActivity(IntentFilter filter, int match, 13259 ComponentName[] set, ComponentName activity, int userId) { 13260 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13261 "Adding preferred"); 13262 } 13263 13264 private void addPreferredActivityInternal(IntentFilter filter, int match, 13265 ComponentName[] set, ComponentName activity, boolean always, int userId, 13266 String opname) { 13267 // writer 13268 int callingUid = Binder.getCallingUid(); 13269 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13270 if (filter.countActions() == 0) { 13271 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13272 return; 13273 } 13274 synchronized (mPackages) { 13275 if (mContext.checkCallingOrSelfPermission( 13276 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13277 != PackageManager.PERMISSION_GRANTED) { 13278 if (getUidTargetSdkVersionLockedLPr(callingUid) 13279 < Build.VERSION_CODES.FROYO) { 13280 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13281 + callingUid); 13282 return; 13283 } 13284 mContext.enforceCallingOrSelfPermission( 13285 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13286 } 13287 13288 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13289 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13290 + userId + ":"); 13291 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13292 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13293 scheduleWritePackageRestrictionsLocked(userId); 13294 } 13295 } 13296 13297 @Override 13298 public void replacePreferredActivity(IntentFilter filter, int match, 13299 ComponentName[] set, ComponentName activity, int userId) { 13300 if (filter.countActions() != 1) { 13301 throw new IllegalArgumentException( 13302 "replacePreferredActivity expects filter to have only 1 action."); 13303 } 13304 if (filter.countDataAuthorities() != 0 13305 || filter.countDataPaths() != 0 13306 || filter.countDataSchemes() > 1 13307 || filter.countDataTypes() != 0) { 13308 throw new IllegalArgumentException( 13309 "replacePreferredActivity expects filter to have no data authorities, " + 13310 "paths, or types; and at most one scheme."); 13311 } 13312 13313 final int callingUid = Binder.getCallingUid(); 13314 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13315 synchronized (mPackages) { 13316 if (mContext.checkCallingOrSelfPermission( 13317 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13318 != PackageManager.PERMISSION_GRANTED) { 13319 if (getUidTargetSdkVersionLockedLPr(callingUid) 13320 < Build.VERSION_CODES.FROYO) { 13321 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13322 + Binder.getCallingUid()); 13323 return; 13324 } 13325 mContext.enforceCallingOrSelfPermission( 13326 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13327 } 13328 13329 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13330 if (pir != null) { 13331 // Get all of the existing entries that exactly match this filter. 13332 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13333 if (existing != null && existing.size() == 1) { 13334 PreferredActivity cur = existing.get(0); 13335 if (DEBUG_PREFERRED) { 13336 Slog.i(TAG, "Checking replace of preferred:"); 13337 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13338 if (!cur.mPref.mAlways) { 13339 Slog.i(TAG, " -- CUR; not mAlways!"); 13340 } else { 13341 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13342 Slog.i(TAG, " -- CUR: mSet=" 13343 + Arrays.toString(cur.mPref.mSetComponents)); 13344 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13345 Slog.i(TAG, " -- NEW: mMatch=" 13346 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13347 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13348 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13349 } 13350 } 13351 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13352 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13353 && cur.mPref.sameSet(set)) { 13354 // Setting the preferred activity to what it happens to be already 13355 if (DEBUG_PREFERRED) { 13356 Slog.i(TAG, "Replacing with same preferred activity " 13357 + cur.mPref.mShortComponent + " for user " 13358 + userId + ":"); 13359 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13360 } 13361 return; 13362 } 13363 } 13364 13365 if (existing != null) { 13366 if (DEBUG_PREFERRED) { 13367 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13368 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13369 } 13370 for (int i = 0; i < existing.size(); i++) { 13371 PreferredActivity pa = existing.get(i); 13372 if (DEBUG_PREFERRED) { 13373 Slog.i(TAG, "Removing existing preferred activity " 13374 + pa.mPref.mComponent + ":"); 13375 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13376 } 13377 pir.removeFilter(pa); 13378 } 13379 } 13380 } 13381 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13382 "Replacing preferred"); 13383 } 13384 } 13385 13386 @Override 13387 public void clearPackagePreferredActivities(String packageName) { 13388 final int uid = Binder.getCallingUid(); 13389 // writer 13390 synchronized (mPackages) { 13391 PackageParser.Package pkg = mPackages.get(packageName); 13392 if (pkg == null || pkg.applicationInfo.uid != uid) { 13393 if (mContext.checkCallingOrSelfPermission( 13394 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13395 != PackageManager.PERMISSION_GRANTED) { 13396 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13397 < Build.VERSION_CODES.FROYO) { 13398 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13399 + Binder.getCallingUid()); 13400 return; 13401 } 13402 mContext.enforceCallingOrSelfPermission( 13403 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13404 } 13405 } 13406 13407 int user = UserHandle.getCallingUserId(); 13408 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13409 scheduleWritePackageRestrictionsLocked(user); 13410 } 13411 } 13412 } 13413 13414 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13415 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13416 ArrayList<PreferredActivity> removed = null; 13417 boolean changed = false; 13418 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13419 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13420 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13421 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13422 continue; 13423 } 13424 Iterator<PreferredActivity> it = pir.filterIterator(); 13425 while (it.hasNext()) { 13426 PreferredActivity pa = it.next(); 13427 // Mark entry for removal only if it matches the package name 13428 // and the entry is of type "always". 13429 if (packageName == null || 13430 (pa.mPref.mComponent.getPackageName().equals(packageName) 13431 && pa.mPref.mAlways)) { 13432 if (removed == null) { 13433 removed = new ArrayList<PreferredActivity>(); 13434 } 13435 removed.add(pa); 13436 } 13437 } 13438 if (removed != null) { 13439 for (int j=0; j<removed.size(); j++) { 13440 PreferredActivity pa = removed.get(j); 13441 pir.removeFilter(pa); 13442 } 13443 changed = true; 13444 } 13445 } 13446 return changed; 13447 } 13448 13449 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13450 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13451 if (userId == UserHandle.USER_ALL) { 13452 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13453 sUserManager.getUserIds())) { 13454 for (int oneUserId : sUserManager.getUserIds()) { 13455 scheduleWritePackageRestrictionsLocked(oneUserId); 13456 } 13457 } 13458 } else { 13459 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13460 scheduleWritePackageRestrictionsLocked(userId); 13461 } 13462 } 13463 } 13464 13465 13466 void clearDefaultBrowserIfNeeded(String packageName) { 13467 for (int oneUserId : sUserManager.getUserIds()) { 13468 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13469 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13470 if (packageName.equals(defaultBrowserPackageName)) { 13471 setDefaultBrowserPackageName(null, oneUserId); 13472 } 13473 } 13474 } 13475 13476 @Override 13477 public void resetPreferredActivities(int userId) { 13478 mContext.enforceCallingOrSelfPermission( 13479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13480 // writer 13481 synchronized (mPackages) { 13482 clearPackagePreferredActivitiesLPw(null, userId); 13483 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13484 applyFactoryDefaultBrowserLPw(userId); 13485 13486 scheduleWritePackageRestrictionsLocked(userId); 13487 } 13488 } 13489 13490 @Override 13491 public int getPreferredActivities(List<IntentFilter> outFilters, 13492 List<ComponentName> outActivities, String packageName) { 13493 13494 int num = 0; 13495 final int userId = UserHandle.getCallingUserId(); 13496 // reader 13497 synchronized (mPackages) { 13498 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13499 if (pir != null) { 13500 final Iterator<PreferredActivity> it = pir.filterIterator(); 13501 while (it.hasNext()) { 13502 final PreferredActivity pa = it.next(); 13503 if (packageName == null 13504 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13505 && pa.mPref.mAlways)) { 13506 if (outFilters != null) { 13507 outFilters.add(new IntentFilter(pa)); 13508 } 13509 if (outActivities != null) { 13510 outActivities.add(pa.mPref.mComponent); 13511 } 13512 } 13513 } 13514 } 13515 } 13516 13517 return num; 13518 } 13519 13520 @Override 13521 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13522 int userId) { 13523 int callingUid = Binder.getCallingUid(); 13524 if (callingUid != Process.SYSTEM_UID) { 13525 throw new SecurityException( 13526 "addPersistentPreferredActivity can only be run by the system"); 13527 } 13528 if (filter.countActions() == 0) { 13529 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13530 return; 13531 } 13532 synchronized (mPackages) { 13533 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13534 " :"); 13535 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13536 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13537 new PersistentPreferredActivity(filter, activity)); 13538 scheduleWritePackageRestrictionsLocked(userId); 13539 } 13540 } 13541 13542 @Override 13543 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13544 int callingUid = Binder.getCallingUid(); 13545 if (callingUid != Process.SYSTEM_UID) { 13546 throw new SecurityException( 13547 "clearPackagePersistentPreferredActivities can only be run by the system"); 13548 } 13549 ArrayList<PersistentPreferredActivity> removed = null; 13550 boolean changed = false; 13551 synchronized (mPackages) { 13552 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13553 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13554 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13555 .valueAt(i); 13556 if (userId != thisUserId) { 13557 continue; 13558 } 13559 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13560 while (it.hasNext()) { 13561 PersistentPreferredActivity ppa = it.next(); 13562 // Mark entry for removal only if it matches the package name. 13563 if (ppa.mComponent.getPackageName().equals(packageName)) { 13564 if (removed == null) { 13565 removed = new ArrayList<PersistentPreferredActivity>(); 13566 } 13567 removed.add(ppa); 13568 } 13569 } 13570 if (removed != null) { 13571 for (int j=0; j<removed.size(); j++) { 13572 PersistentPreferredActivity ppa = removed.get(j); 13573 ppir.removeFilter(ppa); 13574 } 13575 changed = true; 13576 } 13577 } 13578 13579 if (changed) { 13580 scheduleWritePackageRestrictionsLocked(userId); 13581 } 13582 } 13583 } 13584 13585 /** 13586 * Common machinery for picking apart a restored XML blob and passing 13587 * it to a caller-supplied functor to be applied to the running system. 13588 */ 13589 private void restoreFromXml(XmlPullParser parser, int userId, 13590 String expectedStartTag, BlobXmlRestorer functor) 13591 throws IOException, XmlPullParserException { 13592 int type; 13593 while ((type = parser.next()) != XmlPullParser.START_TAG 13594 && type != XmlPullParser.END_DOCUMENT) { 13595 } 13596 if (type != XmlPullParser.START_TAG) { 13597 // oops didn't find a start tag?! 13598 if (DEBUG_BACKUP) { 13599 Slog.e(TAG, "Didn't find start tag during restore"); 13600 } 13601 return; 13602 } 13603 13604 // this is supposed to be TAG_PREFERRED_BACKUP 13605 if (!expectedStartTag.equals(parser.getName())) { 13606 if (DEBUG_BACKUP) { 13607 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13608 } 13609 return; 13610 } 13611 13612 // skip interfering stuff, then we're aligned with the backing implementation 13613 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13614 functor.apply(parser, userId); 13615 } 13616 13617 private interface BlobXmlRestorer { 13618 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13619 } 13620 13621 /** 13622 * Non-Binder method, support for the backup/restore mechanism: write the 13623 * full set of preferred activities in its canonical XML format. Returns the 13624 * XML output as a byte array, or null if there is none. 13625 */ 13626 @Override 13627 public byte[] getPreferredActivityBackup(int userId) { 13628 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13629 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13630 } 13631 13632 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13633 try { 13634 final XmlSerializer serializer = new FastXmlSerializer(); 13635 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13636 serializer.startDocument(null, true); 13637 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13638 13639 synchronized (mPackages) { 13640 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13641 } 13642 13643 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13644 serializer.endDocument(); 13645 serializer.flush(); 13646 } catch (Exception e) { 13647 if (DEBUG_BACKUP) { 13648 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13649 } 13650 return null; 13651 } 13652 13653 return dataStream.toByteArray(); 13654 } 13655 13656 @Override 13657 public void restorePreferredActivities(byte[] backup, int userId) { 13658 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13659 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13660 } 13661 13662 try { 13663 final XmlPullParser parser = Xml.newPullParser(); 13664 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13665 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13666 new BlobXmlRestorer() { 13667 @Override 13668 public void apply(XmlPullParser parser, int userId) 13669 throws XmlPullParserException, IOException { 13670 synchronized (mPackages) { 13671 mSettings.readPreferredActivitiesLPw(parser, userId); 13672 } 13673 } 13674 } ); 13675 } catch (Exception e) { 13676 if (DEBUG_BACKUP) { 13677 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13678 } 13679 } 13680 } 13681 13682 /** 13683 * Non-Binder method, support for the backup/restore mechanism: write the 13684 * default browser (etc) settings in its canonical XML format. Returns the default 13685 * browser XML representation as a byte array, or null if there is none. 13686 */ 13687 @Override 13688 public byte[] getDefaultAppsBackup(int userId) { 13689 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13690 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13691 } 13692 13693 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13694 try { 13695 final XmlSerializer serializer = new FastXmlSerializer(); 13696 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13697 serializer.startDocument(null, true); 13698 serializer.startTag(null, TAG_DEFAULT_APPS); 13699 13700 synchronized (mPackages) { 13701 mSettings.writeDefaultAppsLPr(serializer, userId); 13702 } 13703 13704 serializer.endTag(null, TAG_DEFAULT_APPS); 13705 serializer.endDocument(); 13706 serializer.flush(); 13707 } catch (Exception e) { 13708 if (DEBUG_BACKUP) { 13709 Slog.e(TAG, "Unable to write default apps for backup", e); 13710 } 13711 return null; 13712 } 13713 13714 return dataStream.toByteArray(); 13715 } 13716 13717 @Override 13718 public void restoreDefaultApps(byte[] backup, int userId) { 13719 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13720 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13721 } 13722 13723 try { 13724 final XmlPullParser parser = Xml.newPullParser(); 13725 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13726 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13727 new BlobXmlRestorer() { 13728 @Override 13729 public void apply(XmlPullParser parser, int userId) 13730 throws XmlPullParserException, IOException { 13731 synchronized (mPackages) { 13732 mSettings.readDefaultAppsLPw(parser, userId); 13733 } 13734 } 13735 } ); 13736 } catch (Exception e) { 13737 if (DEBUG_BACKUP) { 13738 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13739 } 13740 } 13741 } 13742 13743 @Override 13744 public byte[] getIntentFilterVerificationBackup(int userId) { 13745 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13746 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13747 } 13748 13749 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13750 try { 13751 final XmlSerializer serializer = new FastXmlSerializer(); 13752 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13753 serializer.startDocument(null, true); 13754 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13755 13756 synchronized (mPackages) { 13757 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13758 } 13759 13760 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13761 serializer.endDocument(); 13762 serializer.flush(); 13763 } catch (Exception e) { 13764 if (DEBUG_BACKUP) { 13765 Slog.e(TAG, "Unable to write default apps for backup", e); 13766 } 13767 return null; 13768 } 13769 13770 return dataStream.toByteArray(); 13771 } 13772 13773 @Override 13774 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13775 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13776 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13777 } 13778 13779 try { 13780 final XmlPullParser parser = Xml.newPullParser(); 13781 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13782 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13783 new BlobXmlRestorer() { 13784 @Override 13785 public void apply(XmlPullParser parser, int userId) 13786 throws XmlPullParserException, IOException { 13787 synchronized (mPackages) { 13788 mSettings.readAllDomainVerificationsLPr(parser, userId); 13789 mSettings.writeLPr(); 13790 } 13791 } 13792 } ); 13793 } catch (Exception e) { 13794 if (DEBUG_BACKUP) { 13795 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13796 } 13797 } 13798 } 13799 13800 @Override 13801 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13802 int sourceUserId, int targetUserId, int flags) { 13803 mContext.enforceCallingOrSelfPermission( 13804 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13805 int callingUid = Binder.getCallingUid(); 13806 enforceOwnerRights(ownerPackage, callingUid); 13807 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13808 if (intentFilter.countActions() == 0) { 13809 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13810 return; 13811 } 13812 synchronized (mPackages) { 13813 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13814 ownerPackage, targetUserId, flags); 13815 CrossProfileIntentResolver resolver = 13816 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13817 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13818 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13819 if (existing != null) { 13820 int size = existing.size(); 13821 for (int i = 0; i < size; i++) { 13822 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13823 return; 13824 } 13825 } 13826 } 13827 resolver.addFilter(newFilter); 13828 scheduleWritePackageRestrictionsLocked(sourceUserId); 13829 } 13830 } 13831 13832 @Override 13833 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13834 mContext.enforceCallingOrSelfPermission( 13835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13836 int callingUid = Binder.getCallingUid(); 13837 enforceOwnerRights(ownerPackage, callingUid); 13838 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13839 synchronized (mPackages) { 13840 CrossProfileIntentResolver resolver = 13841 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13842 ArraySet<CrossProfileIntentFilter> set = 13843 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13844 for (CrossProfileIntentFilter filter : set) { 13845 if (filter.getOwnerPackage().equals(ownerPackage)) { 13846 resolver.removeFilter(filter); 13847 } 13848 } 13849 scheduleWritePackageRestrictionsLocked(sourceUserId); 13850 } 13851 } 13852 13853 // Enforcing that callingUid is owning pkg on userId 13854 private void enforceOwnerRights(String pkg, int callingUid) { 13855 // The system owns everything. 13856 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13857 return; 13858 } 13859 int callingUserId = UserHandle.getUserId(callingUid); 13860 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13861 if (pi == null) { 13862 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13863 + callingUserId); 13864 } 13865 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13866 throw new SecurityException("Calling uid " + callingUid 13867 + " does not own package " + pkg); 13868 } 13869 } 13870 13871 @Override 13872 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13873 Intent intent = new Intent(Intent.ACTION_MAIN); 13874 intent.addCategory(Intent.CATEGORY_HOME); 13875 13876 final int callingUserId = UserHandle.getCallingUserId(); 13877 List<ResolveInfo> list = queryIntentActivities(intent, null, 13878 PackageManager.GET_META_DATA, callingUserId); 13879 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13880 true, false, false, callingUserId); 13881 13882 allHomeCandidates.clear(); 13883 if (list != null) { 13884 for (ResolveInfo ri : list) { 13885 allHomeCandidates.add(ri); 13886 } 13887 } 13888 return (preferred == null || preferred.activityInfo == null) 13889 ? null 13890 : new ComponentName(preferred.activityInfo.packageName, 13891 preferred.activityInfo.name); 13892 } 13893 13894 @Override 13895 public void setApplicationEnabledSetting(String appPackageName, 13896 int newState, int flags, int userId, String callingPackage) { 13897 if (!sUserManager.exists(userId)) return; 13898 if (callingPackage == null) { 13899 callingPackage = Integer.toString(Binder.getCallingUid()); 13900 } 13901 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13902 } 13903 13904 @Override 13905 public void setComponentEnabledSetting(ComponentName componentName, 13906 int newState, int flags, int userId) { 13907 if (!sUserManager.exists(userId)) return; 13908 setEnabledSetting(componentName.getPackageName(), 13909 componentName.getClassName(), newState, flags, userId, null); 13910 } 13911 13912 private void setEnabledSetting(final String packageName, String className, int newState, 13913 final int flags, int userId, String callingPackage) { 13914 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13915 || newState == COMPONENT_ENABLED_STATE_ENABLED 13916 || newState == COMPONENT_ENABLED_STATE_DISABLED 13917 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13918 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13919 throw new IllegalArgumentException("Invalid new component state: " 13920 + newState); 13921 } 13922 PackageSetting pkgSetting; 13923 final int uid = Binder.getCallingUid(); 13924 final int permission = mContext.checkCallingOrSelfPermission( 13925 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13926 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13927 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13928 boolean sendNow = false; 13929 boolean isApp = (className == null); 13930 String componentName = isApp ? packageName : className; 13931 int packageUid = -1; 13932 ArrayList<String> components; 13933 13934 // writer 13935 synchronized (mPackages) { 13936 pkgSetting = mSettings.mPackages.get(packageName); 13937 if (pkgSetting == null) { 13938 if (className == null) { 13939 throw new IllegalArgumentException( 13940 "Unknown package: " + packageName); 13941 } 13942 throw new IllegalArgumentException( 13943 "Unknown component: " + packageName 13944 + "/" + className); 13945 } 13946 // Allow root and verify that userId is not being specified by a different user 13947 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13948 throw new SecurityException( 13949 "Permission Denial: attempt to change component state from pid=" 13950 + Binder.getCallingPid() 13951 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13952 } 13953 if (className == null) { 13954 // We're dealing with an application/package level state change 13955 if (pkgSetting.getEnabled(userId) == newState) { 13956 // Nothing to do 13957 return; 13958 } 13959 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13960 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13961 // Don't care about who enables an app. 13962 callingPackage = null; 13963 } 13964 pkgSetting.setEnabled(newState, userId, callingPackage); 13965 // pkgSetting.pkg.mSetEnabled = newState; 13966 } else { 13967 // We're dealing with a component level state change 13968 // First, verify that this is a valid class name. 13969 PackageParser.Package pkg = pkgSetting.pkg; 13970 if (pkg == null || !pkg.hasComponentClassName(className)) { 13971 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13972 throw new IllegalArgumentException("Component class " + className 13973 + " does not exist in " + packageName); 13974 } else { 13975 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13976 + className + " does not exist in " + packageName); 13977 } 13978 } 13979 switch (newState) { 13980 case COMPONENT_ENABLED_STATE_ENABLED: 13981 if (!pkgSetting.enableComponentLPw(className, userId)) { 13982 return; 13983 } 13984 break; 13985 case COMPONENT_ENABLED_STATE_DISABLED: 13986 if (!pkgSetting.disableComponentLPw(className, userId)) { 13987 return; 13988 } 13989 break; 13990 case COMPONENT_ENABLED_STATE_DEFAULT: 13991 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13992 return; 13993 } 13994 break; 13995 default: 13996 Slog.e(TAG, "Invalid new component state: " + newState); 13997 return; 13998 } 13999 } 14000 scheduleWritePackageRestrictionsLocked(userId); 14001 components = mPendingBroadcasts.get(userId, packageName); 14002 final boolean newPackage = components == null; 14003 if (newPackage) { 14004 components = new ArrayList<String>(); 14005 } 14006 if (!components.contains(componentName)) { 14007 components.add(componentName); 14008 } 14009 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14010 sendNow = true; 14011 // Purge entry from pending broadcast list if another one exists already 14012 // since we are sending one right away. 14013 mPendingBroadcasts.remove(userId, packageName); 14014 } else { 14015 if (newPackage) { 14016 mPendingBroadcasts.put(userId, packageName, components); 14017 } 14018 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14019 // Schedule a message 14020 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14021 } 14022 } 14023 } 14024 14025 long callingId = Binder.clearCallingIdentity(); 14026 try { 14027 if (sendNow) { 14028 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14029 sendPackageChangedBroadcast(packageName, 14030 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14031 } 14032 } finally { 14033 Binder.restoreCallingIdentity(callingId); 14034 } 14035 } 14036 14037 private void sendPackageChangedBroadcast(String packageName, 14038 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14039 if (DEBUG_INSTALL) 14040 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14041 + componentNames); 14042 Bundle extras = new Bundle(4); 14043 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14044 String nameList[] = new String[componentNames.size()]; 14045 componentNames.toArray(nameList); 14046 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14047 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14048 extras.putInt(Intent.EXTRA_UID, packageUid); 14049 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14050 new int[] {UserHandle.getUserId(packageUid)}); 14051 } 14052 14053 @Override 14054 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14055 if (!sUserManager.exists(userId)) return; 14056 final int uid = Binder.getCallingUid(); 14057 final int permission = mContext.checkCallingOrSelfPermission( 14058 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14059 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14060 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14061 // writer 14062 synchronized (mPackages) { 14063 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14064 allowedByPermission, uid, userId)) { 14065 scheduleWritePackageRestrictionsLocked(userId); 14066 } 14067 } 14068 } 14069 14070 @Override 14071 public String getInstallerPackageName(String packageName) { 14072 // reader 14073 synchronized (mPackages) { 14074 return mSettings.getInstallerPackageNameLPr(packageName); 14075 } 14076 } 14077 14078 @Override 14079 public int getApplicationEnabledSetting(String packageName, int userId) { 14080 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14081 int uid = Binder.getCallingUid(); 14082 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14083 // reader 14084 synchronized (mPackages) { 14085 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14086 } 14087 } 14088 14089 @Override 14090 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14091 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14092 int uid = Binder.getCallingUid(); 14093 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14094 // reader 14095 synchronized (mPackages) { 14096 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14097 } 14098 } 14099 14100 @Override 14101 public void enterSafeMode() { 14102 enforceSystemOrRoot("Only the system can request entering safe mode"); 14103 14104 if (!mSystemReady) { 14105 mSafeMode = true; 14106 } 14107 } 14108 14109 @Override 14110 public void systemReady() { 14111 mSystemReady = true; 14112 14113 // Read the compatibilty setting when the system is ready. 14114 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14115 mContext.getContentResolver(), 14116 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14117 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14118 if (DEBUG_SETTINGS) { 14119 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14120 } 14121 14122 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14123 14124 synchronized (mPackages) { 14125 // Verify that all of the preferred activity components actually 14126 // exist. It is possible for applications to be updated and at 14127 // that point remove a previously declared activity component that 14128 // had been set as a preferred activity. We try to clean this up 14129 // the next time we encounter that preferred activity, but it is 14130 // possible for the user flow to never be able to return to that 14131 // situation so here we do a sanity check to make sure we haven't 14132 // left any junk around. 14133 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14134 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14135 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14136 removed.clear(); 14137 for (PreferredActivity pa : pir.filterSet()) { 14138 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14139 removed.add(pa); 14140 } 14141 } 14142 if (removed.size() > 0) { 14143 for (int r=0; r<removed.size(); r++) { 14144 PreferredActivity pa = removed.get(r); 14145 Slog.w(TAG, "Removing dangling preferred activity: " 14146 + pa.mPref.mComponent); 14147 pir.removeFilter(pa); 14148 } 14149 mSettings.writePackageRestrictionsLPr( 14150 mSettings.mPreferredActivities.keyAt(i)); 14151 } 14152 } 14153 14154 for (int userId : UserManagerService.getInstance().getUserIds()) { 14155 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14156 grantPermissionsUserIds = ArrayUtils.appendInt( 14157 grantPermissionsUserIds, userId); 14158 } 14159 } 14160 } 14161 sUserManager.systemReady(); 14162 14163 // If we upgraded grant all default permissions before kicking off. 14164 for (int userId : grantPermissionsUserIds) { 14165 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14166 } 14167 14168 // Kick off any messages waiting for system ready 14169 if (mPostSystemReadyMessages != null) { 14170 for (Message msg : mPostSystemReadyMessages) { 14171 msg.sendToTarget(); 14172 } 14173 mPostSystemReadyMessages = null; 14174 } 14175 14176 // Watch for external volumes that come and go over time 14177 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14178 storage.registerListener(mStorageListener); 14179 14180 mInstallerService.systemReady(); 14181 mPackageDexOptimizer.systemReady(); 14182 } 14183 14184 @Override 14185 public boolean isSafeMode() { 14186 return mSafeMode; 14187 } 14188 14189 @Override 14190 public boolean hasSystemUidErrors() { 14191 return mHasSystemUidErrors; 14192 } 14193 14194 static String arrayToString(int[] array) { 14195 StringBuffer buf = new StringBuffer(128); 14196 buf.append('['); 14197 if (array != null) { 14198 for (int i=0; i<array.length; i++) { 14199 if (i > 0) buf.append(", "); 14200 buf.append(array[i]); 14201 } 14202 } 14203 buf.append(']'); 14204 return buf.toString(); 14205 } 14206 14207 static class DumpState { 14208 public static final int DUMP_LIBS = 1 << 0; 14209 public static final int DUMP_FEATURES = 1 << 1; 14210 public static final int DUMP_RESOLVERS = 1 << 2; 14211 public static final int DUMP_PERMISSIONS = 1 << 3; 14212 public static final int DUMP_PACKAGES = 1 << 4; 14213 public static final int DUMP_SHARED_USERS = 1 << 5; 14214 public static final int DUMP_MESSAGES = 1 << 6; 14215 public static final int DUMP_PROVIDERS = 1 << 7; 14216 public static final int DUMP_VERIFIERS = 1 << 8; 14217 public static final int DUMP_PREFERRED = 1 << 9; 14218 public static final int DUMP_PREFERRED_XML = 1 << 10; 14219 public static final int DUMP_KEYSETS = 1 << 11; 14220 public static final int DUMP_VERSION = 1 << 12; 14221 public static final int DUMP_INSTALLS = 1 << 13; 14222 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14223 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14224 14225 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14226 14227 private int mTypes; 14228 14229 private int mOptions; 14230 14231 private boolean mTitlePrinted; 14232 14233 private SharedUserSetting mSharedUser; 14234 14235 public boolean isDumping(int type) { 14236 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14237 return true; 14238 } 14239 14240 return (mTypes & type) != 0; 14241 } 14242 14243 public void setDump(int type) { 14244 mTypes |= type; 14245 } 14246 14247 public boolean isOptionEnabled(int option) { 14248 return (mOptions & option) != 0; 14249 } 14250 14251 public void setOptionEnabled(int option) { 14252 mOptions |= option; 14253 } 14254 14255 public boolean onTitlePrinted() { 14256 final boolean printed = mTitlePrinted; 14257 mTitlePrinted = true; 14258 return printed; 14259 } 14260 14261 public boolean getTitlePrinted() { 14262 return mTitlePrinted; 14263 } 14264 14265 public void setTitlePrinted(boolean enabled) { 14266 mTitlePrinted = enabled; 14267 } 14268 14269 public SharedUserSetting getSharedUser() { 14270 return mSharedUser; 14271 } 14272 14273 public void setSharedUser(SharedUserSetting user) { 14274 mSharedUser = user; 14275 } 14276 } 14277 14278 @Override 14279 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14280 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14281 != PackageManager.PERMISSION_GRANTED) { 14282 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14283 + Binder.getCallingPid() 14284 + ", uid=" + Binder.getCallingUid() 14285 + " without permission " 14286 + android.Manifest.permission.DUMP); 14287 return; 14288 } 14289 14290 DumpState dumpState = new DumpState(); 14291 boolean fullPreferred = false; 14292 boolean checkin = false; 14293 14294 String packageName = null; 14295 ArraySet<String> permissionNames = null; 14296 14297 int opti = 0; 14298 while (opti < args.length) { 14299 String opt = args[opti]; 14300 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14301 break; 14302 } 14303 opti++; 14304 14305 if ("-a".equals(opt)) { 14306 // Right now we only know how to print all. 14307 } else if ("-h".equals(opt)) { 14308 pw.println("Package manager dump options:"); 14309 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14310 pw.println(" --checkin: dump for a checkin"); 14311 pw.println(" -f: print details of intent filters"); 14312 pw.println(" -h: print this help"); 14313 pw.println(" cmd may be one of:"); 14314 pw.println(" l[ibraries]: list known shared libraries"); 14315 pw.println(" f[ibraries]: list device features"); 14316 pw.println(" k[eysets]: print known keysets"); 14317 pw.println(" r[esolvers]: dump intent resolvers"); 14318 pw.println(" perm[issions]: dump permissions"); 14319 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14320 pw.println(" pref[erred]: print preferred package settings"); 14321 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14322 pw.println(" prov[iders]: dump content providers"); 14323 pw.println(" p[ackages]: dump installed packages"); 14324 pw.println(" s[hared-users]: dump shared user IDs"); 14325 pw.println(" m[essages]: print collected runtime messages"); 14326 pw.println(" v[erifiers]: print package verifier info"); 14327 pw.println(" version: print database version info"); 14328 pw.println(" write: write current settings now"); 14329 pw.println(" <package.name>: info about given package"); 14330 pw.println(" installs: details about install sessions"); 14331 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14332 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14333 return; 14334 } else if ("--checkin".equals(opt)) { 14335 checkin = true; 14336 } else if ("-f".equals(opt)) { 14337 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14338 } else { 14339 pw.println("Unknown argument: " + opt + "; use -h for help"); 14340 } 14341 } 14342 14343 // Is the caller requesting to dump a particular piece of data? 14344 if (opti < args.length) { 14345 String cmd = args[opti]; 14346 opti++; 14347 // Is this a package name? 14348 if ("android".equals(cmd) || cmd.contains(".")) { 14349 packageName = cmd; 14350 // When dumping a single package, we always dump all of its 14351 // filter information since the amount of data will be reasonable. 14352 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14353 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14354 dumpState.setDump(DumpState.DUMP_LIBS); 14355 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14356 dumpState.setDump(DumpState.DUMP_FEATURES); 14357 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14358 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14359 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14360 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14361 } else if ("permission".equals(cmd)) { 14362 if (opti >= args.length) { 14363 pw.println("Error: permission requires permission name"); 14364 return; 14365 } 14366 permissionNames = new ArraySet<>(); 14367 while (opti < args.length) { 14368 permissionNames.add(args[opti]); 14369 opti++; 14370 } 14371 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14372 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14373 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14374 dumpState.setDump(DumpState.DUMP_PREFERRED); 14375 } else if ("preferred-xml".equals(cmd)) { 14376 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14377 if (opti < args.length && "--full".equals(args[opti])) { 14378 fullPreferred = true; 14379 opti++; 14380 } 14381 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14382 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14383 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14384 dumpState.setDump(DumpState.DUMP_PACKAGES); 14385 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14386 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14387 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14388 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14389 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14390 dumpState.setDump(DumpState.DUMP_MESSAGES); 14391 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14392 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14393 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14394 || "intent-filter-verifiers".equals(cmd)) { 14395 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14396 } else if ("version".equals(cmd)) { 14397 dumpState.setDump(DumpState.DUMP_VERSION); 14398 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14399 dumpState.setDump(DumpState.DUMP_KEYSETS); 14400 } else if ("installs".equals(cmd)) { 14401 dumpState.setDump(DumpState.DUMP_INSTALLS); 14402 } else if ("write".equals(cmd)) { 14403 synchronized (mPackages) { 14404 mSettings.writeLPr(); 14405 pw.println("Settings written."); 14406 return; 14407 } 14408 } 14409 } 14410 14411 if (checkin) { 14412 pw.println("vers,1"); 14413 } 14414 14415 // reader 14416 synchronized (mPackages) { 14417 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14418 if (!checkin) { 14419 if (dumpState.onTitlePrinted()) 14420 pw.println(); 14421 pw.println("Database versions:"); 14422 pw.print(" SDK Version:"); 14423 pw.print(" internal="); 14424 pw.print(mSettings.mInternalSdkPlatform); 14425 pw.print(" external="); 14426 pw.println(mSettings.mExternalSdkPlatform); 14427 pw.print(" DB Version:"); 14428 pw.print(" internal="); 14429 pw.print(mSettings.mInternalDatabaseVersion); 14430 pw.print(" external="); 14431 pw.println(mSettings.mExternalDatabaseVersion); 14432 } 14433 } 14434 14435 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14436 if (!checkin) { 14437 if (dumpState.onTitlePrinted()) 14438 pw.println(); 14439 pw.println("Verifiers:"); 14440 pw.print(" Required: "); 14441 pw.print(mRequiredVerifierPackage); 14442 pw.print(" (uid="); 14443 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14444 pw.println(")"); 14445 } else if (mRequiredVerifierPackage != null) { 14446 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14447 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14448 } 14449 } 14450 14451 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14452 packageName == null) { 14453 if (mIntentFilterVerifierComponent != null) { 14454 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14455 if (!checkin) { 14456 if (dumpState.onTitlePrinted()) 14457 pw.println(); 14458 pw.println("Intent Filter Verifier:"); 14459 pw.print(" Using: "); 14460 pw.print(verifierPackageName); 14461 pw.print(" (uid="); 14462 pw.print(getPackageUid(verifierPackageName, 0)); 14463 pw.println(")"); 14464 } else if (verifierPackageName != null) { 14465 pw.print("ifv,"); pw.print(verifierPackageName); 14466 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14467 } 14468 } else { 14469 pw.println(); 14470 pw.println("No Intent Filter Verifier available!"); 14471 } 14472 } 14473 14474 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14475 boolean printedHeader = false; 14476 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14477 while (it.hasNext()) { 14478 String name = it.next(); 14479 SharedLibraryEntry ent = mSharedLibraries.get(name); 14480 if (!checkin) { 14481 if (!printedHeader) { 14482 if (dumpState.onTitlePrinted()) 14483 pw.println(); 14484 pw.println("Libraries:"); 14485 printedHeader = true; 14486 } 14487 pw.print(" "); 14488 } else { 14489 pw.print("lib,"); 14490 } 14491 pw.print(name); 14492 if (!checkin) { 14493 pw.print(" -> "); 14494 } 14495 if (ent.path != null) { 14496 if (!checkin) { 14497 pw.print("(jar) "); 14498 pw.print(ent.path); 14499 } else { 14500 pw.print(",jar,"); 14501 pw.print(ent.path); 14502 } 14503 } else { 14504 if (!checkin) { 14505 pw.print("(apk) "); 14506 pw.print(ent.apk); 14507 } else { 14508 pw.print(",apk,"); 14509 pw.print(ent.apk); 14510 } 14511 } 14512 pw.println(); 14513 } 14514 } 14515 14516 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14517 if (dumpState.onTitlePrinted()) 14518 pw.println(); 14519 if (!checkin) { 14520 pw.println("Features:"); 14521 } 14522 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14523 while (it.hasNext()) { 14524 String name = it.next(); 14525 if (!checkin) { 14526 pw.print(" "); 14527 } else { 14528 pw.print("feat,"); 14529 } 14530 pw.println(name); 14531 } 14532 } 14533 14534 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14535 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14536 : "Activity Resolver Table:", " ", packageName, 14537 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14538 dumpState.setTitlePrinted(true); 14539 } 14540 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14541 : "Receiver Resolver Table:", " ", packageName, 14542 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14543 dumpState.setTitlePrinted(true); 14544 } 14545 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14546 : "Service Resolver Table:", " ", packageName, 14547 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14548 dumpState.setTitlePrinted(true); 14549 } 14550 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14551 : "Provider Resolver Table:", " ", packageName, 14552 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14553 dumpState.setTitlePrinted(true); 14554 } 14555 } 14556 14557 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14558 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14559 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14560 int user = mSettings.mPreferredActivities.keyAt(i); 14561 if (pir.dump(pw, 14562 dumpState.getTitlePrinted() 14563 ? "\nPreferred Activities User " + user + ":" 14564 : "Preferred Activities User " + user + ":", " ", 14565 packageName, true, false)) { 14566 dumpState.setTitlePrinted(true); 14567 } 14568 } 14569 } 14570 14571 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14572 pw.flush(); 14573 FileOutputStream fout = new FileOutputStream(fd); 14574 BufferedOutputStream str = new BufferedOutputStream(fout); 14575 XmlSerializer serializer = new FastXmlSerializer(); 14576 try { 14577 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14578 serializer.startDocument(null, true); 14579 serializer.setFeature( 14580 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14581 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14582 serializer.endDocument(); 14583 serializer.flush(); 14584 } catch (IllegalArgumentException e) { 14585 pw.println("Failed writing: " + e); 14586 } catch (IllegalStateException e) { 14587 pw.println("Failed writing: " + e); 14588 } catch (IOException e) { 14589 pw.println("Failed writing: " + e); 14590 } 14591 } 14592 14593 if (!checkin 14594 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14595 && packageName == null) { 14596 pw.println(); 14597 int count = mSettings.mPackages.size(); 14598 if (count == 0) { 14599 pw.println("No domain preferred apps!"); 14600 pw.println(); 14601 } else { 14602 final String prefix = " "; 14603 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14604 if (allPackageSettings.size() == 0) { 14605 pw.println("No domain preferred apps!"); 14606 pw.println(); 14607 } else { 14608 pw.println("Domain preferred apps status:"); 14609 pw.println(); 14610 count = 0; 14611 for (PackageSetting ps : allPackageSettings) { 14612 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14613 if (ivi == null || ivi.getPackageName() == null) continue; 14614 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14615 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14616 pw.println(prefix + "Status: " + ivi.getStatusString()); 14617 pw.println(); 14618 count++; 14619 } 14620 if (count == 0) { 14621 pw.println(prefix + "No domain preferred app status!"); 14622 pw.println(); 14623 } 14624 for (int userId : sUserManager.getUserIds()) { 14625 pw.println("Domain preferred apps for User " + userId + ":"); 14626 pw.println(); 14627 count = 0; 14628 for (PackageSetting ps : allPackageSettings) { 14629 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14630 if (ivi == null || ivi.getPackageName() == null) { 14631 continue; 14632 } 14633 final int status = ps.getDomainVerificationStatusForUser(userId); 14634 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14635 continue; 14636 } 14637 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14638 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14639 String statusStr = IntentFilterVerificationInfo. 14640 getStatusStringFromValue(status); 14641 pw.println(prefix + "Status: " + statusStr); 14642 pw.println(); 14643 count++; 14644 } 14645 if (count == 0) { 14646 pw.println(prefix + "No domain preferred apps!"); 14647 pw.println(); 14648 } 14649 } 14650 } 14651 } 14652 } 14653 14654 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14655 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14656 if (packageName == null && permissionNames == null) { 14657 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14658 if (iperm == 0) { 14659 if (dumpState.onTitlePrinted()) 14660 pw.println(); 14661 pw.println("AppOp Permissions:"); 14662 } 14663 pw.print(" AppOp Permission "); 14664 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14665 pw.println(":"); 14666 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14667 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14668 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14669 } 14670 } 14671 } 14672 } 14673 14674 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14675 boolean printedSomething = false; 14676 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14677 if (packageName != null && !packageName.equals(p.info.packageName)) { 14678 continue; 14679 } 14680 if (!printedSomething) { 14681 if (dumpState.onTitlePrinted()) 14682 pw.println(); 14683 pw.println("Registered ContentProviders:"); 14684 printedSomething = true; 14685 } 14686 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14687 pw.print(" "); pw.println(p.toString()); 14688 } 14689 printedSomething = false; 14690 for (Map.Entry<String, PackageParser.Provider> entry : 14691 mProvidersByAuthority.entrySet()) { 14692 PackageParser.Provider p = entry.getValue(); 14693 if (packageName != null && !packageName.equals(p.info.packageName)) { 14694 continue; 14695 } 14696 if (!printedSomething) { 14697 if (dumpState.onTitlePrinted()) 14698 pw.println(); 14699 pw.println("ContentProvider Authorities:"); 14700 printedSomething = true; 14701 } 14702 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14703 pw.print(" "); pw.println(p.toString()); 14704 if (p.info != null && p.info.applicationInfo != null) { 14705 final String appInfo = p.info.applicationInfo.toString(); 14706 pw.print(" applicationInfo="); pw.println(appInfo); 14707 } 14708 } 14709 } 14710 14711 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14712 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14713 } 14714 14715 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14716 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14717 } 14718 14719 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14720 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14721 } 14722 14723 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14724 // XXX should handle packageName != null by dumping only install data that 14725 // the given package is involved with. 14726 if (dumpState.onTitlePrinted()) pw.println(); 14727 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14728 } 14729 14730 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14731 if (dumpState.onTitlePrinted()) pw.println(); 14732 mSettings.dumpReadMessagesLPr(pw, dumpState); 14733 14734 pw.println(); 14735 pw.println("Package warning messages:"); 14736 BufferedReader in = null; 14737 String line = null; 14738 try { 14739 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14740 while ((line = in.readLine()) != null) { 14741 if (line.contains("ignored: updated version")) continue; 14742 pw.println(line); 14743 } 14744 } catch (IOException ignored) { 14745 } finally { 14746 IoUtils.closeQuietly(in); 14747 } 14748 } 14749 14750 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14751 BufferedReader in = null; 14752 String line = null; 14753 try { 14754 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14755 while ((line = in.readLine()) != null) { 14756 if (line.contains("ignored: updated version")) continue; 14757 pw.print("msg,"); 14758 pw.println(line); 14759 } 14760 } catch (IOException ignored) { 14761 } finally { 14762 IoUtils.closeQuietly(in); 14763 } 14764 } 14765 } 14766 } 14767 14768 // ------- apps on sdcard specific code ------- 14769 static final boolean DEBUG_SD_INSTALL = false; 14770 14771 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14772 14773 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14774 14775 private boolean mMediaMounted = false; 14776 14777 static String getEncryptKey() { 14778 try { 14779 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14780 SD_ENCRYPTION_KEYSTORE_NAME); 14781 if (sdEncKey == null) { 14782 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14783 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14784 if (sdEncKey == null) { 14785 Slog.e(TAG, "Failed to create encryption keys"); 14786 return null; 14787 } 14788 } 14789 return sdEncKey; 14790 } catch (NoSuchAlgorithmException nsae) { 14791 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14792 return null; 14793 } catch (IOException ioe) { 14794 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14795 return null; 14796 } 14797 } 14798 14799 /* 14800 * Update media status on PackageManager. 14801 */ 14802 @Override 14803 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14804 int callingUid = Binder.getCallingUid(); 14805 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14806 throw new SecurityException("Media status can only be updated by the system"); 14807 } 14808 // reader; this apparently protects mMediaMounted, but should probably 14809 // be a different lock in that case. 14810 synchronized (mPackages) { 14811 Log.i(TAG, "Updating external media status from " 14812 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14813 + (mediaStatus ? "mounted" : "unmounted")); 14814 if (DEBUG_SD_INSTALL) 14815 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14816 + ", mMediaMounted=" + mMediaMounted); 14817 if (mediaStatus == mMediaMounted) { 14818 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14819 : 0, -1); 14820 mHandler.sendMessage(msg); 14821 return; 14822 } 14823 mMediaMounted = mediaStatus; 14824 } 14825 // Queue up an async operation since the package installation may take a 14826 // little while. 14827 mHandler.post(new Runnable() { 14828 public void run() { 14829 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14830 } 14831 }); 14832 } 14833 14834 /** 14835 * Called by MountService when the initial ASECs to scan are available. 14836 * Should block until all the ASEC containers are finished being scanned. 14837 */ 14838 public void scanAvailableAsecs() { 14839 updateExternalMediaStatusInner(true, false, false); 14840 if (mShouldRestoreconData) { 14841 SELinuxMMAC.setRestoreconDone(); 14842 mShouldRestoreconData = false; 14843 } 14844 } 14845 14846 /* 14847 * Collect information of applications on external media, map them against 14848 * existing containers and update information based on current mount status. 14849 * Please note that we always have to report status if reportStatus has been 14850 * set to true especially when unloading packages. 14851 */ 14852 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14853 boolean externalStorage) { 14854 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14855 int[] uidArr = EmptyArray.INT; 14856 14857 final String[] list = PackageHelper.getSecureContainerList(); 14858 if (ArrayUtils.isEmpty(list)) { 14859 Log.i(TAG, "No secure containers found"); 14860 } else { 14861 // Process list of secure containers and categorize them 14862 // as active or stale based on their package internal state. 14863 14864 // reader 14865 synchronized (mPackages) { 14866 for (String cid : list) { 14867 // Leave stages untouched for now; installer service owns them 14868 if (PackageInstallerService.isStageName(cid)) continue; 14869 14870 if (DEBUG_SD_INSTALL) 14871 Log.i(TAG, "Processing container " + cid); 14872 String pkgName = getAsecPackageName(cid); 14873 if (pkgName == null) { 14874 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14875 continue; 14876 } 14877 if (DEBUG_SD_INSTALL) 14878 Log.i(TAG, "Looking for pkg : " + pkgName); 14879 14880 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14881 if (ps == null) { 14882 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14883 continue; 14884 } 14885 14886 /* 14887 * Skip packages that are not external if we're unmounting 14888 * external storage. 14889 */ 14890 if (externalStorage && !isMounted && !isExternal(ps)) { 14891 continue; 14892 } 14893 14894 final AsecInstallArgs args = new AsecInstallArgs(cid, 14895 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14896 // The package status is changed only if the code path 14897 // matches between settings and the container id. 14898 if (ps.codePathString != null 14899 && ps.codePathString.startsWith(args.getCodePath())) { 14900 if (DEBUG_SD_INSTALL) { 14901 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14902 + " at code path: " + ps.codePathString); 14903 } 14904 14905 // We do have a valid package installed on sdcard 14906 processCids.put(args, ps.codePathString); 14907 final int uid = ps.appId; 14908 if (uid != -1) { 14909 uidArr = ArrayUtils.appendInt(uidArr, uid); 14910 } 14911 } else { 14912 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14913 + ps.codePathString); 14914 } 14915 } 14916 } 14917 14918 Arrays.sort(uidArr); 14919 } 14920 14921 // Process packages with valid entries. 14922 if (isMounted) { 14923 if (DEBUG_SD_INSTALL) 14924 Log.i(TAG, "Loading packages"); 14925 loadMediaPackages(processCids, uidArr); 14926 startCleaningPackages(); 14927 mInstallerService.onSecureContainersAvailable(); 14928 } else { 14929 if (DEBUG_SD_INSTALL) 14930 Log.i(TAG, "Unloading packages"); 14931 unloadMediaPackages(processCids, uidArr, reportStatus); 14932 } 14933 } 14934 14935 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14936 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14937 final int size = infos.size(); 14938 final String[] packageNames = new String[size]; 14939 final int[] packageUids = new int[size]; 14940 for (int i = 0; i < size; i++) { 14941 final ApplicationInfo info = infos.get(i); 14942 packageNames[i] = info.packageName; 14943 packageUids[i] = info.uid; 14944 } 14945 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14946 finishedReceiver); 14947 } 14948 14949 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14950 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14951 sendResourcesChangedBroadcast(mediaStatus, replacing, 14952 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14953 } 14954 14955 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14956 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14957 int size = pkgList.length; 14958 if (size > 0) { 14959 // Send broadcasts here 14960 Bundle extras = new Bundle(); 14961 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14962 if (uidArr != null) { 14963 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14964 } 14965 if (replacing) { 14966 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14967 } 14968 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14969 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14970 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14971 } 14972 } 14973 14974 /* 14975 * Look at potentially valid container ids from processCids If package 14976 * information doesn't match the one on record or package scanning fails, 14977 * the cid is added to list of removeCids. We currently don't delete stale 14978 * containers. 14979 */ 14980 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14981 ArrayList<String> pkgList = new ArrayList<String>(); 14982 Set<AsecInstallArgs> keys = processCids.keySet(); 14983 14984 for (AsecInstallArgs args : keys) { 14985 String codePath = processCids.get(args); 14986 if (DEBUG_SD_INSTALL) 14987 Log.i(TAG, "Loading container : " + args.cid); 14988 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14989 try { 14990 // Make sure there are no container errors first. 14991 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14992 Slog.e(TAG, "Failed to mount cid : " + args.cid 14993 + " when installing from sdcard"); 14994 continue; 14995 } 14996 // Check code path here. 14997 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14998 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14999 + " does not match one in settings " + codePath); 15000 continue; 15001 } 15002 // Parse package 15003 int parseFlags = mDefParseFlags; 15004 if (args.isExternalAsec()) { 15005 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15006 } 15007 if (args.isFwdLocked()) { 15008 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15009 } 15010 15011 synchronized (mInstallLock) { 15012 PackageParser.Package pkg = null; 15013 try { 15014 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15015 } catch (PackageManagerException e) { 15016 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15017 } 15018 // Scan the package 15019 if (pkg != null) { 15020 /* 15021 * TODO why is the lock being held? doPostInstall is 15022 * called in other places without the lock. This needs 15023 * to be straightened out. 15024 */ 15025 // writer 15026 synchronized (mPackages) { 15027 retCode = PackageManager.INSTALL_SUCCEEDED; 15028 pkgList.add(pkg.packageName); 15029 // Post process args 15030 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15031 pkg.applicationInfo.uid); 15032 } 15033 } else { 15034 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15035 } 15036 } 15037 15038 } finally { 15039 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15040 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15041 } 15042 } 15043 } 15044 // writer 15045 synchronized (mPackages) { 15046 // If the platform SDK has changed since the last time we booted, 15047 // we need to re-grant app permission to catch any new ones that 15048 // appear. This is really a hack, and means that apps can in some 15049 // cases get permissions that the user didn't initially explicitly 15050 // allow... it would be nice to have some better way to handle 15051 // this situation. 15052 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15053 if (regrantPermissions) 15054 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15055 + mSdkVersion + "; regranting permissions for external storage"); 15056 mSettings.mExternalSdkPlatform = mSdkVersion; 15057 15058 // Make sure group IDs have been assigned, and any permission 15059 // changes in other apps are accounted for 15060 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15061 | (regrantPermissions 15062 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15063 : 0)); 15064 15065 mSettings.updateExternalDatabaseVersion(); 15066 15067 // can downgrade to reader 15068 // Persist settings 15069 mSettings.writeLPr(); 15070 } 15071 // Send a broadcast to let everyone know we are done processing 15072 if (pkgList.size() > 0) { 15073 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15074 } 15075 } 15076 15077 /* 15078 * Utility method to unload a list of specified containers 15079 */ 15080 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15081 // Just unmount all valid containers. 15082 for (AsecInstallArgs arg : cidArgs) { 15083 synchronized (mInstallLock) { 15084 arg.doPostDeleteLI(false); 15085 } 15086 } 15087 } 15088 15089 /* 15090 * Unload packages mounted on external media. This involves deleting package 15091 * data from internal structures, sending broadcasts about diabled packages, 15092 * gc'ing to free up references, unmounting all secure containers 15093 * corresponding to packages on external media, and posting a 15094 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15095 * that we always have to post this message if status has been requested no 15096 * matter what. 15097 */ 15098 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15099 final boolean reportStatus) { 15100 if (DEBUG_SD_INSTALL) 15101 Log.i(TAG, "unloading media packages"); 15102 ArrayList<String> pkgList = new ArrayList<String>(); 15103 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15104 final Set<AsecInstallArgs> keys = processCids.keySet(); 15105 for (AsecInstallArgs args : keys) { 15106 String pkgName = args.getPackageName(); 15107 if (DEBUG_SD_INSTALL) 15108 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15109 // Delete package internally 15110 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15111 synchronized (mInstallLock) { 15112 boolean res = deletePackageLI(pkgName, null, false, null, null, 15113 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15114 if (res) { 15115 pkgList.add(pkgName); 15116 } else { 15117 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15118 failedList.add(args); 15119 } 15120 } 15121 } 15122 15123 // reader 15124 synchronized (mPackages) { 15125 // We didn't update the settings after removing each package; 15126 // write them now for all packages. 15127 mSettings.writeLPr(); 15128 } 15129 15130 // We have to absolutely send UPDATED_MEDIA_STATUS only 15131 // after confirming that all the receivers processed the ordered 15132 // broadcast when packages get disabled, force a gc to clean things up. 15133 // and unload all the containers. 15134 if (pkgList.size() > 0) { 15135 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15136 new IIntentReceiver.Stub() { 15137 public void performReceive(Intent intent, int resultCode, String data, 15138 Bundle extras, boolean ordered, boolean sticky, 15139 int sendingUser) throws RemoteException { 15140 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15141 reportStatus ? 1 : 0, 1, keys); 15142 mHandler.sendMessage(msg); 15143 } 15144 }); 15145 } else { 15146 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15147 keys); 15148 mHandler.sendMessage(msg); 15149 } 15150 } 15151 15152 private void loadPrivatePackages(VolumeInfo vol) { 15153 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15154 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15155 synchronized (mInstallLock) { 15156 synchronized (mPackages) { 15157 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15158 for (PackageSetting ps : packages) { 15159 final PackageParser.Package pkg; 15160 try { 15161 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15162 loaded.add(pkg.applicationInfo); 15163 } catch (PackageManagerException e) { 15164 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15165 } 15166 } 15167 15168 // TODO: regrant any permissions that changed based since original install 15169 15170 mSettings.writeLPr(); 15171 } 15172 } 15173 15174 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15175 sendResourcesChangedBroadcast(true, false, loaded, null); 15176 } 15177 15178 private void unloadPrivatePackages(VolumeInfo vol) { 15179 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15180 synchronized (mInstallLock) { 15181 synchronized (mPackages) { 15182 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15183 for (PackageSetting ps : packages) { 15184 if (ps.pkg == null) continue; 15185 15186 final ApplicationInfo info = ps.pkg.applicationInfo; 15187 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15188 if (deletePackageLI(ps.name, null, false, null, null, 15189 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15190 unloaded.add(info); 15191 } else { 15192 Slog.w(TAG, "Failed to unload " + ps.codePath); 15193 } 15194 } 15195 15196 mSettings.writeLPr(); 15197 } 15198 } 15199 15200 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15201 sendResourcesChangedBroadcast(false, false, unloaded, null); 15202 } 15203 15204 private void unfreezePackage(String packageName) { 15205 synchronized (mPackages) { 15206 final PackageSetting ps = mSettings.mPackages.get(packageName); 15207 if (ps != null) { 15208 ps.frozen = false; 15209 } 15210 } 15211 } 15212 15213 @Override 15214 public int movePackage(final String packageName, final String volumeUuid) { 15215 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15216 15217 final int moveId = mNextMoveId.getAndIncrement(); 15218 try { 15219 movePackageInternal(packageName, volumeUuid, moveId); 15220 } catch (PackageManagerException e) { 15221 Slog.w(TAG, "Failed to move " + packageName, e); 15222 mMoveCallbacks.notifyStatusChanged(moveId, 15223 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15224 } 15225 return moveId; 15226 } 15227 15228 private void movePackageInternal(final String packageName, final String volumeUuid, 15229 final int moveId) throws PackageManagerException { 15230 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15231 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15232 final PackageManager pm = mContext.getPackageManager(); 15233 15234 final boolean currentAsec; 15235 final String currentVolumeUuid; 15236 final File codeFile; 15237 final String installerPackageName; 15238 final String packageAbiOverride; 15239 final int appId; 15240 final String seinfo; 15241 final String label; 15242 15243 // reader 15244 synchronized (mPackages) { 15245 final PackageParser.Package pkg = mPackages.get(packageName); 15246 final PackageSetting ps = mSettings.mPackages.get(packageName); 15247 if (pkg == null || ps == null) { 15248 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15249 } 15250 15251 if (pkg.applicationInfo.isSystemApp()) { 15252 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15253 "Cannot move system application"); 15254 } 15255 15256 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15257 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15258 "Package already moved to " + volumeUuid); 15259 } 15260 15261 final File probe = new File(pkg.codePath); 15262 final File probeOat = new File(probe, "oat"); 15263 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15264 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15265 "Move only supported for modern cluster style installs"); 15266 } 15267 15268 if (ps.frozen) { 15269 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15270 "Failed to move already frozen package"); 15271 } 15272 ps.frozen = true; 15273 15274 currentAsec = pkg.applicationInfo.isForwardLocked() 15275 || pkg.applicationInfo.isExternalAsec(); 15276 currentVolumeUuid = ps.volumeUuid; 15277 codeFile = new File(pkg.codePath); 15278 installerPackageName = ps.installerPackageName; 15279 packageAbiOverride = ps.cpuAbiOverrideString; 15280 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15281 seinfo = pkg.applicationInfo.seinfo; 15282 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15283 } 15284 15285 // Now that we're guarded by frozen state, kill app during move 15286 killApplication(packageName, appId, "move pkg"); 15287 15288 final Bundle extras = new Bundle(); 15289 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15290 extras.putString(Intent.EXTRA_TITLE, label); 15291 mMoveCallbacks.notifyCreated(moveId, extras); 15292 15293 int installFlags; 15294 final boolean moveCompleteApp; 15295 final File measurePath; 15296 15297 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15298 installFlags = INSTALL_INTERNAL; 15299 moveCompleteApp = !currentAsec; 15300 measurePath = Environment.getDataAppDirectory(volumeUuid); 15301 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15302 installFlags = INSTALL_EXTERNAL; 15303 moveCompleteApp = false; 15304 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15305 } else { 15306 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15307 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15308 || !volume.isMountedWritable()) { 15309 unfreezePackage(packageName); 15310 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15311 "Move location not mounted private volume"); 15312 } 15313 15314 Preconditions.checkState(!currentAsec); 15315 15316 installFlags = INSTALL_INTERNAL; 15317 moveCompleteApp = true; 15318 measurePath = Environment.getDataAppDirectory(volumeUuid); 15319 } 15320 15321 final PackageStats stats = new PackageStats(null, -1); 15322 synchronized (mInstaller) { 15323 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15324 unfreezePackage(packageName); 15325 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15326 "Failed to measure package size"); 15327 } 15328 } 15329 15330 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15331 + stats.dataSize); 15332 15333 final long startFreeBytes = measurePath.getFreeSpace(); 15334 final long sizeBytes; 15335 if (moveCompleteApp) { 15336 sizeBytes = stats.codeSize + stats.dataSize; 15337 } else { 15338 sizeBytes = stats.codeSize; 15339 } 15340 15341 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15342 unfreezePackage(packageName); 15343 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15344 "Not enough free space to move"); 15345 } 15346 15347 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15348 15349 final CountDownLatch installedLatch = new CountDownLatch(1); 15350 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15351 @Override 15352 public void onUserActionRequired(Intent intent) throws RemoteException { 15353 throw new IllegalStateException(); 15354 } 15355 15356 @Override 15357 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15358 Bundle extras) throws RemoteException { 15359 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15360 + PackageManager.installStatusToString(returnCode, msg)); 15361 15362 installedLatch.countDown(); 15363 15364 // Regardless of success or failure of the move operation, 15365 // always unfreeze the package 15366 unfreezePackage(packageName); 15367 15368 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15369 switch (status) { 15370 case PackageInstaller.STATUS_SUCCESS: 15371 mMoveCallbacks.notifyStatusChanged(moveId, 15372 PackageManager.MOVE_SUCCEEDED); 15373 break; 15374 case PackageInstaller.STATUS_FAILURE_STORAGE: 15375 mMoveCallbacks.notifyStatusChanged(moveId, 15376 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15377 break; 15378 default: 15379 mMoveCallbacks.notifyStatusChanged(moveId, 15380 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15381 break; 15382 } 15383 } 15384 }; 15385 15386 final MoveInfo move; 15387 if (moveCompleteApp) { 15388 // Kick off a thread to report progress estimates 15389 new Thread() { 15390 @Override 15391 public void run() { 15392 while (true) { 15393 try { 15394 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15395 break; 15396 } 15397 } catch (InterruptedException ignored) { 15398 } 15399 15400 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15401 final int progress = 10 + (int) MathUtils.constrain( 15402 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15403 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15404 } 15405 } 15406 }.start(); 15407 15408 final String dataAppName = codeFile.getName(); 15409 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15410 dataAppName, appId, seinfo); 15411 } else { 15412 move = null; 15413 } 15414 15415 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15416 15417 final Message msg = mHandler.obtainMessage(INIT_COPY); 15418 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15419 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15420 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15421 mHandler.sendMessage(msg); 15422 } 15423 15424 @Override 15425 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15426 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15427 15428 final int realMoveId = mNextMoveId.getAndIncrement(); 15429 final Bundle extras = new Bundle(); 15430 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15431 mMoveCallbacks.notifyCreated(realMoveId, extras); 15432 15433 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15434 @Override 15435 public void onCreated(int moveId, Bundle extras) { 15436 // Ignored 15437 } 15438 15439 @Override 15440 public void onStatusChanged(int moveId, int status, long estMillis) { 15441 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15442 } 15443 }; 15444 15445 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15446 storage.setPrimaryStorageUuid(volumeUuid, callback); 15447 return realMoveId; 15448 } 15449 15450 @Override 15451 public int getMoveStatus(int moveId) { 15452 mContext.enforceCallingOrSelfPermission( 15453 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15454 return mMoveCallbacks.mLastStatus.get(moveId); 15455 } 15456 15457 @Override 15458 public void registerMoveCallback(IPackageMoveObserver callback) { 15459 mContext.enforceCallingOrSelfPermission( 15460 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15461 mMoveCallbacks.register(callback); 15462 } 15463 15464 @Override 15465 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15466 mContext.enforceCallingOrSelfPermission( 15467 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15468 mMoveCallbacks.unregister(callback); 15469 } 15470 15471 @Override 15472 public boolean setInstallLocation(int loc) { 15473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15474 null); 15475 if (getInstallLocation() == loc) { 15476 return true; 15477 } 15478 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15479 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15480 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15481 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15482 return true; 15483 } 15484 return false; 15485 } 15486 15487 @Override 15488 public int getInstallLocation() { 15489 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15490 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15491 PackageHelper.APP_INSTALL_AUTO); 15492 } 15493 15494 /** Called by UserManagerService */ 15495 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15496 mDirtyUsers.remove(userHandle); 15497 mSettings.removeUserLPw(userHandle); 15498 mPendingBroadcasts.remove(userHandle); 15499 if (mInstaller != null) { 15500 // Technically, we shouldn't be doing this with the package lock 15501 // held. However, this is very rare, and there is already so much 15502 // other disk I/O going on, that we'll let it slide for now. 15503 final StorageManager storage = StorageManager.from(mContext); 15504 final List<VolumeInfo> vols = storage.getVolumes(); 15505 for (VolumeInfo vol : vols) { 15506 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15507 final String volumeUuid = vol.getFsUuid(); 15508 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15509 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15510 } 15511 } 15512 } 15513 mUserNeedsBadging.delete(userHandle); 15514 removeUnusedPackagesLILPw(userManager, userHandle); 15515 } 15516 15517 /** 15518 * We're removing userHandle and would like to remove any downloaded packages 15519 * that are no longer in use by any other user. 15520 * @param userHandle the user being removed 15521 */ 15522 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15523 final boolean DEBUG_CLEAN_APKS = false; 15524 int [] users = userManager.getUserIdsLPr(); 15525 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15526 while (psit.hasNext()) { 15527 PackageSetting ps = psit.next(); 15528 if (ps.pkg == null) { 15529 continue; 15530 } 15531 final String packageName = ps.pkg.packageName; 15532 // Skip over if system app 15533 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15534 continue; 15535 } 15536 if (DEBUG_CLEAN_APKS) { 15537 Slog.i(TAG, "Checking package " + packageName); 15538 } 15539 boolean keep = false; 15540 for (int i = 0; i < users.length; i++) { 15541 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15542 keep = true; 15543 if (DEBUG_CLEAN_APKS) { 15544 Slog.i(TAG, " Keeping package " + packageName + " for user " 15545 + users[i]); 15546 } 15547 break; 15548 } 15549 } 15550 if (!keep) { 15551 if (DEBUG_CLEAN_APKS) { 15552 Slog.i(TAG, " Removing package " + packageName); 15553 } 15554 mHandler.post(new Runnable() { 15555 public void run() { 15556 deletePackageX(packageName, userHandle, 0); 15557 } //end run 15558 }); 15559 } 15560 } 15561 } 15562 15563 /** Called by UserManagerService */ 15564 void createNewUserLILPw(int userHandle, File path) { 15565 if (mInstaller != null) { 15566 mInstaller.createUserConfig(userHandle); 15567 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15568 applyFactoryDefaultBrowserLPw(userHandle); 15569 } 15570 } 15571 15572 void newUserCreatedLILPw(final int userHandle) { 15573 // We cannot grant the default permissions with a lock held as 15574 // we query providers from other components for default handlers 15575 // such as enabled IMEs, etc. 15576 mHandler.post(new Runnable() { 15577 @Override 15578 public void run() { 15579 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15580 } 15581 }); 15582 } 15583 15584 @Override 15585 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15586 mContext.enforceCallingOrSelfPermission( 15587 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15588 "Only package verification agents can read the verifier device identity"); 15589 15590 synchronized (mPackages) { 15591 return mSettings.getVerifierDeviceIdentityLPw(); 15592 } 15593 } 15594 15595 @Override 15596 public void setPermissionEnforced(String permission, boolean enforced) { 15597 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15598 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15599 synchronized (mPackages) { 15600 if (mSettings.mReadExternalStorageEnforced == null 15601 || mSettings.mReadExternalStorageEnforced != enforced) { 15602 mSettings.mReadExternalStorageEnforced = enforced; 15603 mSettings.writeLPr(); 15604 } 15605 } 15606 // kill any non-foreground processes so we restart them and 15607 // grant/revoke the GID. 15608 final IActivityManager am = ActivityManagerNative.getDefault(); 15609 if (am != null) { 15610 final long token = Binder.clearCallingIdentity(); 15611 try { 15612 am.killProcessesBelowForeground("setPermissionEnforcement"); 15613 } catch (RemoteException e) { 15614 } finally { 15615 Binder.restoreCallingIdentity(token); 15616 } 15617 } 15618 } else { 15619 throw new IllegalArgumentException("No selective enforcement for " + permission); 15620 } 15621 } 15622 15623 @Override 15624 @Deprecated 15625 public boolean isPermissionEnforced(String permission) { 15626 return true; 15627 } 15628 15629 @Override 15630 public boolean isStorageLow() { 15631 final long token = Binder.clearCallingIdentity(); 15632 try { 15633 final DeviceStorageMonitorInternal 15634 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15635 if (dsm != null) { 15636 return dsm.isMemoryLow(); 15637 } else { 15638 return false; 15639 } 15640 } finally { 15641 Binder.restoreCallingIdentity(token); 15642 } 15643 } 15644 15645 @Override 15646 public IPackageInstaller getPackageInstaller() { 15647 return mInstallerService; 15648 } 15649 15650 private boolean userNeedsBadging(int userId) { 15651 int index = mUserNeedsBadging.indexOfKey(userId); 15652 if (index < 0) { 15653 final UserInfo userInfo; 15654 final long token = Binder.clearCallingIdentity(); 15655 try { 15656 userInfo = sUserManager.getUserInfo(userId); 15657 } finally { 15658 Binder.restoreCallingIdentity(token); 15659 } 15660 final boolean b; 15661 if (userInfo != null && userInfo.isManagedProfile()) { 15662 b = true; 15663 } else { 15664 b = false; 15665 } 15666 mUserNeedsBadging.put(userId, b); 15667 return b; 15668 } 15669 return mUserNeedsBadging.valueAt(index); 15670 } 15671 15672 @Override 15673 public KeySet getKeySetByAlias(String packageName, String alias) { 15674 if (packageName == null || alias == null) { 15675 return null; 15676 } 15677 synchronized(mPackages) { 15678 final PackageParser.Package pkg = mPackages.get(packageName); 15679 if (pkg == null) { 15680 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15681 throw new IllegalArgumentException("Unknown package: " + packageName); 15682 } 15683 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15684 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15685 } 15686 } 15687 15688 @Override 15689 public KeySet getSigningKeySet(String packageName) { 15690 if (packageName == null) { 15691 return null; 15692 } 15693 synchronized(mPackages) { 15694 final PackageParser.Package pkg = mPackages.get(packageName); 15695 if (pkg == null) { 15696 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15697 throw new IllegalArgumentException("Unknown package: " + packageName); 15698 } 15699 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15700 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15701 throw new SecurityException("May not access signing KeySet of other apps."); 15702 } 15703 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15704 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15705 } 15706 } 15707 15708 @Override 15709 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15710 if (packageName == null || ks == null) { 15711 return false; 15712 } 15713 synchronized(mPackages) { 15714 final PackageParser.Package pkg = mPackages.get(packageName); 15715 if (pkg == null) { 15716 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15717 throw new IllegalArgumentException("Unknown package: " + packageName); 15718 } 15719 IBinder ksh = ks.getToken(); 15720 if (ksh instanceof KeySetHandle) { 15721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15722 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15723 } 15724 return false; 15725 } 15726 } 15727 15728 @Override 15729 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15730 if (packageName == null || ks == null) { 15731 return false; 15732 } 15733 synchronized(mPackages) { 15734 final PackageParser.Package pkg = mPackages.get(packageName); 15735 if (pkg == null) { 15736 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15737 throw new IllegalArgumentException("Unknown package: " + packageName); 15738 } 15739 IBinder ksh = ks.getToken(); 15740 if (ksh instanceof KeySetHandle) { 15741 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15742 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15743 } 15744 return false; 15745 } 15746 } 15747 15748 public void getUsageStatsIfNoPackageUsageInfo() { 15749 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15750 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15751 if (usm == null) { 15752 throw new IllegalStateException("UsageStatsManager must be initialized"); 15753 } 15754 long now = System.currentTimeMillis(); 15755 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15756 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15757 String packageName = entry.getKey(); 15758 PackageParser.Package pkg = mPackages.get(packageName); 15759 if (pkg == null) { 15760 continue; 15761 } 15762 UsageStats usage = entry.getValue(); 15763 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15764 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15765 } 15766 } 15767 } 15768 15769 /** 15770 * Check and throw if the given before/after packages would be considered a 15771 * downgrade. 15772 */ 15773 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15774 throws PackageManagerException { 15775 if (after.versionCode < before.mVersionCode) { 15776 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15777 "Update version code " + after.versionCode + " is older than current " 15778 + before.mVersionCode); 15779 } else if (after.versionCode == before.mVersionCode) { 15780 if (after.baseRevisionCode < before.baseRevisionCode) { 15781 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15782 "Update base revision code " + after.baseRevisionCode 15783 + " is older than current " + before.baseRevisionCode); 15784 } 15785 15786 if (!ArrayUtils.isEmpty(after.splitNames)) { 15787 for (int i = 0; i < after.splitNames.length; i++) { 15788 final String splitName = after.splitNames[i]; 15789 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15790 if (j != -1) { 15791 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15792 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15793 "Update split " + splitName + " revision code " 15794 + after.splitRevisionCodes[i] + " is older than current " 15795 + before.splitRevisionCodes[j]); 15796 } 15797 } 15798 } 15799 } 15800 } 15801 } 15802 15803 private static class MoveCallbacks extends Handler { 15804 private static final int MSG_CREATED = 1; 15805 private static final int MSG_STATUS_CHANGED = 2; 15806 15807 private final RemoteCallbackList<IPackageMoveObserver> 15808 mCallbacks = new RemoteCallbackList<>(); 15809 15810 private final SparseIntArray mLastStatus = new SparseIntArray(); 15811 15812 public MoveCallbacks(Looper looper) { 15813 super(looper); 15814 } 15815 15816 public void register(IPackageMoveObserver callback) { 15817 mCallbacks.register(callback); 15818 } 15819 15820 public void unregister(IPackageMoveObserver callback) { 15821 mCallbacks.unregister(callback); 15822 } 15823 15824 @Override 15825 public void handleMessage(Message msg) { 15826 final SomeArgs args = (SomeArgs) msg.obj; 15827 final int n = mCallbacks.beginBroadcast(); 15828 for (int i = 0; i < n; i++) { 15829 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15830 try { 15831 invokeCallback(callback, msg.what, args); 15832 } catch (RemoteException ignored) { 15833 } 15834 } 15835 mCallbacks.finishBroadcast(); 15836 args.recycle(); 15837 } 15838 15839 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15840 throws RemoteException { 15841 switch (what) { 15842 case MSG_CREATED: { 15843 callback.onCreated(args.argi1, (Bundle) args.arg2); 15844 break; 15845 } 15846 case MSG_STATUS_CHANGED: { 15847 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15848 break; 15849 } 15850 } 15851 } 15852 15853 private void notifyCreated(int moveId, Bundle extras) { 15854 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15855 15856 final SomeArgs args = SomeArgs.obtain(); 15857 args.argi1 = moveId; 15858 args.arg2 = extras; 15859 obtainMessage(MSG_CREATED, args).sendToTarget(); 15860 } 15861 15862 private void notifyStatusChanged(int moveId, int status) { 15863 notifyStatusChanged(moveId, status, -1); 15864 } 15865 15866 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15867 Slog.v(TAG, "Move " + moveId + " status " + status); 15868 15869 final SomeArgs args = SomeArgs.obtain(); 15870 args.argi1 = moveId; 15871 args.argi2 = status; 15872 args.arg3 = estMillis; 15873 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15874 15875 synchronized (mLastStatus) { 15876 mLastStatus.put(moveId, status); 15877 } 15878 } 15879 } 15880 15881 private final class OnPermissionChangeListeners extends Handler { 15882 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15883 15884 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15885 new RemoteCallbackList<>(); 15886 15887 public OnPermissionChangeListeners(Looper looper) { 15888 super(looper); 15889 } 15890 15891 @Override 15892 public void handleMessage(Message msg) { 15893 switch (msg.what) { 15894 case MSG_ON_PERMISSIONS_CHANGED: { 15895 final int uid = msg.arg1; 15896 handleOnPermissionsChanged(uid); 15897 } break; 15898 } 15899 } 15900 15901 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15902 mPermissionListeners.register(listener); 15903 15904 } 15905 15906 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15907 mPermissionListeners.unregister(listener); 15908 } 15909 15910 public void onPermissionsChanged(int uid) { 15911 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15912 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15913 } 15914 } 15915 15916 private void handleOnPermissionsChanged(int uid) { 15917 final int count = mPermissionListeners.beginBroadcast(); 15918 try { 15919 for (int i = 0; i < count; i++) { 15920 IOnPermissionsChangeListener callback = mPermissionListeners 15921 .getBroadcastItem(i); 15922 try { 15923 callback.onPermissionsChanged(uid); 15924 } catch (RemoteException e) { 15925 Log.e(TAG, "Permission listener is dead", e); 15926 } 15927 } 15928 } finally { 15929 mPermissionListeners.finishBroadcast(); 15930 } 15931 } 15932 } 15933 15934 private class PackageManagerInternalImpl extends PackageManagerInternal { 15935 @Override 15936 public void setLocationPackagesProvider(PackagesProvider provider) { 15937 synchronized (mPackages) { 15938 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15939 } 15940 } 15941 15942 @Override 15943 public void setImePackagesProvider(PackagesProvider provider) { 15944 synchronized (mPackages) { 15945 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15946 } 15947 } 15948 15949 @Override 15950 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15951 synchronized (mPackages) { 15952 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15953 } 15954 } 15955 15956 @Override 15957 public void setSmsAppPackagesProvider(PackagesProvider provider) { 15958 synchronized (mPackages) { 15959 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 15960 } 15961 } 15962 15963 @Override 15964 public void setDialerAppPackagesProvider(PackagesProvider provider) { 15965 synchronized (mPackages) { 15966 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 15967 } 15968 } 15969 15970 @Override 15971 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 15972 synchronized (mPackages) { 15973 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 15974 } 15975 } 15976 15977 @Override 15978 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 15979 synchronized (mPackages) { 15980 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 15981 packageName, userId); 15982 } 15983 } 15984 15985 @Override 15986 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 15987 synchronized (mPackages) { 15988 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 15989 packageName, userId); 15990 } 15991 } 15992 } 15993 15994 @Override 15995 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 15996 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 15997 synchronized (mPackages) { 15998 final long identity = Binder.clearCallingIdentity(); 15999 try { 16000 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16001 packageNames, userId); 16002 } finally { 16003 Binder.restoreCallingIdentity(identity); 16004 } 16005 } 16006 } 16007 16008 private static void enforceSystemOrPhoneCaller(String tag) { 16009 int callingUid = Binder.getCallingUid(); 16010 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16011 throw new SecurityException( 16012 "Cannot call " + tag + " from UID " + callingUid); 16013 } 16014 } 16015} 16016