PackageManagerService.java revision 3453e081e0a94bbb0b8c1d58ce4ccdbf2e53639e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.os.storage.VolumeRecord; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArrayMap; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.MathUtils; 175import android.util.PrintStreamPrinter; 176import android.util.Slog; 177import android.util.SparseArray; 178import android.util.SparseBooleanArray; 179import android.util.SparseIntArray; 180import android.util.Xml; 181import android.view.Display; 182 183import dalvik.system.DexFile; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187import libcore.util.EmptyArray; 188 189import com.android.internal.R; 190import com.android.internal.app.IMediaContainerService; 191import com.android.internal.app.ResolverActivity; 192import com.android.internal.content.NativeLibraryHelper; 193import com.android.internal.content.PackageHelper; 194import com.android.internal.os.IParcelFileDescriptorFactory; 195import com.android.internal.os.SomeArgs; 196import com.android.internal.util.ArrayUtils; 197import com.android.internal.util.FastPrintWriter; 198import com.android.internal.util.FastXmlSerializer; 199import com.android.internal.util.IndentingPrintWriter; 200import com.android.internal.util.Preconditions; 201import com.android.server.EventLogTags; 202import com.android.server.FgThread; 203import com.android.server.IntentResolver; 204import com.android.server.LocalServices; 205import com.android.server.ServiceThread; 206import com.android.server.SystemConfig; 207import com.android.server.Watchdog; 208import com.android.server.pm.Settings.DatabaseVersion; 209import com.android.server.storage.DeviceStorageMonitorInternal; 210 211import org.xmlpull.v1.XmlPullParser; 212import org.xmlpull.v1.XmlSerializer; 213 214import java.io.BufferedInputStream; 215import java.io.BufferedOutputStream; 216import java.io.BufferedReader; 217import java.io.ByteArrayInputStream; 218import java.io.ByteArrayOutputStream; 219import java.io.File; 220import java.io.FileDescriptor; 221import java.io.FileNotFoundException; 222import java.io.FileOutputStream; 223import java.io.FileReader; 224import java.io.FilenameFilter; 225import java.io.IOException; 226import java.io.InputStream; 227import java.io.PrintWriter; 228import java.nio.charset.StandardCharsets; 229import java.security.NoSuchAlgorithmException; 230import java.security.PublicKey; 231import java.security.cert.CertificateEncodingException; 232import java.security.cert.CertificateException; 233import java.text.SimpleDateFormat; 234import java.util.ArrayList; 235import java.util.Arrays; 236import java.util.Collection; 237import java.util.Collections; 238import java.util.Comparator; 239import java.util.Date; 240import java.util.Iterator; 241import java.util.List; 242import java.util.Map; 243import java.util.Objects; 244import java.util.Set; 245import java.util.concurrent.CountDownLatch; 246import java.util.concurrent.TimeUnit; 247import java.util.concurrent.atomic.AtomicBoolean; 248import java.util.concurrent.atomic.AtomicInteger; 249import java.util.concurrent.atomic.AtomicLong; 250 251/** 252 * Keep track of all those .apks everywhere. 253 * 254 * This is very central to the platform's security; please run the unit 255 * tests whenever making modifications here: 256 * 257mmm frameworks/base/tests/AndroidTests 258adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 259adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 260 * 261 * {@hide} 262 */ 263public class PackageManagerService extends IPackageManager.Stub { 264 static final String TAG = "PackageManager"; 265 static final boolean DEBUG_SETTINGS = false; 266 static final boolean DEBUG_PREFERRED = false; 267 static final boolean DEBUG_UPGRADE = false; 268 private static final boolean DEBUG_BACKUP = true; 269 private static final boolean DEBUG_INSTALL = false; 270 private static final boolean DEBUG_REMOVE = false; 271 private static final boolean DEBUG_BROADCASTS = false; 272 private static final boolean DEBUG_SHOW_INFO = false; 273 private static final boolean DEBUG_PACKAGE_INFO = false; 274 private static final boolean DEBUG_INTENT_MATCHING = false; 275 private static final boolean DEBUG_PACKAGE_SCANNING = false; 276 private static final boolean DEBUG_VERIFY = false; 277 private static final boolean DEBUG_DEXOPT = false; 278 private static final boolean DEBUG_ABI_SELECTION = false; 279 280 private static final int RADIO_UID = Process.PHONE_UID; 281 private static final int LOG_UID = Process.LOG_UID; 282 private static final int NFC_UID = Process.NFC_UID; 283 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 284 private static final int SHELL_UID = Process.SHELL_UID; 285 286 // Cap the size of permission trees that 3rd party apps can define 287 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 288 289 // Suffix used during package installation when copying/moving 290 // package apks to install directory. 291 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 292 293 static final int SCAN_NO_DEX = 1<<1; 294 static final int SCAN_FORCE_DEX = 1<<2; 295 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 296 static final int SCAN_NEW_INSTALL = 1<<4; 297 static final int SCAN_NO_PATHS = 1<<5; 298 static final int SCAN_UPDATE_TIME = 1<<6; 299 static final int SCAN_DEFER_DEX = 1<<7; 300 static final int SCAN_BOOTING = 1<<8; 301 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 302 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 303 static final int SCAN_REQUIRE_KNOWN = 1<<12; 304 305 static final int REMOVE_CHATTY = 1<<16; 306 307 /** 308 * Timeout (in milliseconds) after which the watchdog should declare that 309 * our handler thread is wedged. The usual default for such things is one 310 * minute but we sometimes do very lengthy I/O operations on this thread, 311 * such as installing multi-gigabyte applications, so ours needs to be longer. 312 */ 313 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 314 315 /** 316 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 317 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 318 * settings entry if available, otherwise we use the hardcoded default. If it's been 319 * more than this long since the last fstrim, we force one during the boot sequence. 320 * 321 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 322 * one gets run at the next available charging+idle time. This final mandatory 323 * no-fstrim check kicks in only of the other scheduling criteria is never met. 324 */ 325 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 326 327 /** 328 * Whether verification is enabled by default. 329 */ 330 private static final boolean DEFAULT_VERIFY_ENABLE = true; 331 332 /** 333 * The default maximum time to wait for the verification agent to return in 334 * milliseconds. 335 */ 336 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 337 338 /** 339 * The default response for package verification timeout. 340 * 341 * This can be either PackageManager.VERIFICATION_ALLOW or 342 * PackageManager.VERIFICATION_REJECT. 343 */ 344 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 345 346 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 347 348 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 349 DEFAULT_CONTAINER_PACKAGE, 350 "com.android.defcontainer.DefaultContainerService"); 351 352 private static final String KILL_APP_REASON_GIDS_CHANGED = 353 "permission grant or revoke changed gids"; 354 355 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 356 "permissions revoked"; 357 358 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 359 360 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 361 362 /** Permission grant: not grant the permission. */ 363 private static final int GRANT_DENIED = 1; 364 365 /** Permission grant: grant the permission as an install permission. */ 366 private static final int GRANT_INSTALL = 2; 367 368 /** Permission grant: grant the permission as a runtime one. */ 369 private static final int GRANT_RUNTIME = 3; 370 371 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 372 private static final int GRANT_UPGRADE = 4; 373 374 final ServiceThread mHandlerThread; 375 376 final PackageHandler mHandler; 377 378 /** 379 * Messages for {@link #mHandler} that need to wait for system ready before 380 * being dispatched. 381 */ 382 private ArrayList<Message> mPostSystemReadyMessages; 383 384 final int mSdkVersion = Build.VERSION.SDK_INT; 385 386 final Context mContext; 387 final boolean mFactoryTest; 388 final boolean mOnlyCore; 389 final boolean mLazyDexOpt; 390 final long mDexOptLRUThresholdInMills; 391 final DisplayMetrics mMetrics; 392 final int mDefParseFlags; 393 final String[] mSeparateProcesses; 394 final boolean mIsUpgrade; 395 396 // This is where all application persistent data goes. 397 final File mAppDataDir; 398 399 // This is where all application persistent data goes for secondary users. 400 final File mUserAppDataDir; 401 402 /** The location for ASEC container files on internal storage. */ 403 final String mAsecInternalPath; 404 405 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 406 // LOCK HELD. Can be called with mInstallLock held. 407 final Installer mInstaller; 408 409 /** Directory where installed third-party apps stored */ 410 final File mAppInstallDir; 411 412 /** 413 * Directory to which applications installed internally have their 414 * 32 bit native libraries copied. 415 */ 416 private File mAppLib32InstallDir; 417 418 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 419 // apps. 420 final File mDrmAppPrivateInstallDir; 421 422 // ---------------------------------------------------------------- 423 424 // Lock for state used when installing and doing other long running 425 // operations. Methods that must be called with this lock held have 426 // the suffix "LI". 427 final Object mInstallLock = new Object(); 428 429 // ---------------------------------------------------------------- 430 431 // Keys are String (package name), values are Package. This also serves 432 // as the lock for the global state. Methods that must be called with 433 // this lock held have the prefix "LP". 434 final ArrayMap<String, PackageParser.Package> mPackages = 435 new ArrayMap<String, PackageParser.Package>(); 436 437 // Tracks available target package names -> overlay package paths. 438 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 439 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 440 441 final Settings mSettings; 442 boolean mRestoredSettings; 443 444 // System configuration read by SystemConfig. 445 final int[] mGlobalGids; 446 final SparseArray<ArraySet<String>> mSystemPermissions; 447 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 448 449 // If mac_permissions.xml was found for seinfo labeling. 450 boolean mFoundPolicyFile; 451 452 // If a recursive restorecon of /data/data/<pkg> is needed. 453 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 454 455 public static final class SharedLibraryEntry { 456 public final String path; 457 public final String apk; 458 459 SharedLibraryEntry(String _path, String _apk) { 460 path = _path; 461 apk = _apk; 462 } 463 } 464 465 // Currently known shared libraries. 466 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 467 new ArrayMap<String, SharedLibraryEntry>(); 468 469 // All available activities, for your resolving pleasure. 470 final ActivityIntentResolver mActivities = 471 new ActivityIntentResolver(); 472 473 // All available receivers, for your resolving pleasure. 474 final ActivityIntentResolver mReceivers = 475 new ActivityIntentResolver(); 476 477 // All available services, for your resolving pleasure. 478 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 479 480 // All available providers, for your resolving pleasure. 481 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 482 483 // Mapping from provider base names (first directory in content URI codePath) 484 // to the provider information. 485 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 486 new ArrayMap<String, PackageParser.Provider>(); 487 488 // Mapping from instrumentation class names to info about them. 489 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 490 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 491 492 // Mapping from permission names to info about them. 493 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 494 new ArrayMap<String, PackageParser.PermissionGroup>(); 495 496 // Packages whose data we have transfered into another package, thus 497 // should no longer exist. 498 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 499 500 // Broadcast actions that are only available to the system. 501 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 502 503 /** List of packages waiting for verification. */ 504 final SparseArray<PackageVerificationState> mPendingVerification 505 = new SparseArray<PackageVerificationState>(); 506 507 /** Set of packages associated with each app op permission. */ 508 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 509 510 final PackageInstallerService mInstallerService; 511 512 private final PackageDexOptimizer mPackageDexOptimizer; 513 514 private AtomicInteger mNextMoveId = new AtomicInteger(); 515 private final MoveCallbacks mMoveCallbacks; 516 517 // Cache of users who need badging. 518 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 519 520 /** Token for keys in mPendingVerification. */ 521 private int mPendingVerificationToken = 0; 522 523 volatile boolean mSystemReady; 524 volatile boolean mSafeMode; 525 volatile boolean mHasSystemUidErrors; 526 527 ApplicationInfo mAndroidApplication; 528 final ActivityInfo mResolveActivity = new ActivityInfo(); 529 final ResolveInfo mResolveInfo = new ResolveInfo(); 530 ComponentName mResolveComponentName; 531 PackageParser.Package mPlatformPackage; 532 ComponentName mCustomResolverComponentName; 533 534 boolean mResolverReplaced = false; 535 536 private final ComponentName mIntentFilterVerifierComponent; 537 private int mIntentFilterVerificationToken = 0; 538 539 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 540 = new SparseArray<IntentFilterVerificationState>(); 541 542 private interface IntentFilterVerifier<T extends IntentFilter> { 543 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 544 T filter, String packageName); 545 void startVerifications(int userId); 546 void receiveVerificationResponse(int verificationId); 547 } 548 549 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 550 private Context mContext; 551 private ComponentName mIntentFilterVerifierComponent; 552 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 553 554 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 555 mContext = context; 556 mIntentFilterVerifierComponent = verifierComponent; 557 } 558 559 private String getDefaultScheme() { 560 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 561 return IntentFilter.SCHEME_HTTP; 562 } 563 564 @Override 565 public void startVerifications(int userId) { 566 // Launch verifications requests 567 int count = mCurrentIntentFilterVerifications.size(); 568 for (int n=0; n<count; n++) { 569 int verificationId = mCurrentIntentFilterVerifications.get(n); 570 final IntentFilterVerificationState ivs = 571 mIntentFilterVerificationStates.get(verificationId); 572 573 String packageName = ivs.getPackageName(); 574 575 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 576 final int filterCount = filters.size(); 577 ArraySet<String> domainsSet = new ArraySet<>(); 578 for (int m=0; m<filterCount; m++) { 579 PackageParser.ActivityIntentInfo filter = filters.get(m); 580 domainsSet.addAll(filter.getHostsList()); 581 } 582 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 583 synchronized (mPackages) { 584 if (mSettings.createIntentFilterVerificationIfNeededLPw( 585 packageName, domainsList) != null) { 586 scheduleWriteSettingsLocked(); 587 } 588 } 589 sendVerificationRequest(userId, verificationId, ivs); 590 } 591 mCurrentIntentFilterVerifications.clear(); 592 } 593 594 private void sendVerificationRequest(int userId, int verificationId, 595 IntentFilterVerificationState ivs) { 596 597 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 598 verificationIntent.putExtra( 599 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 600 verificationId); 601 verificationIntent.putExtra( 602 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 603 getDefaultScheme()); 604 verificationIntent.putExtra( 605 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 606 ivs.getHostsString()); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 609 ivs.getPackageName()); 610 verificationIntent.setComponent(mIntentFilterVerifierComponent); 611 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 612 613 UserHandle user = new UserHandle(userId); 614 mContext.sendBroadcastAsUser(verificationIntent, user); 615 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 616 } 617 618 public void receiveVerificationResponse(int verificationId) { 619 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 620 621 final boolean verified = ivs.isVerified(); 622 623 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 624 final int count = filters.size(); 625 for (int n=0; n<count; n++) { 626 PackageParser.ActivityIntentInfo filter = filters.get(n); 627 filter.setVerified(verified); 628 629 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 630 + verified + " and hosts:" + ivs.getHostsString()); 631 } 632 633 mIntentFilterVerificationStates.remove(verificationId); 634 635 final String packageName = ivs.getPackageName(); 636 IntentFilterVerificationInfo ivi = null; 637 638 synchronized (mPackages) { 639 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 640 } 641 if (ivi == null) { 642 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 643 + verificationId + " packageName:" + packageName); 644 return; 645 } 646 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 647 + verificationId); 648 649 synchronized (mPackages) { 650 if (verified) { 651 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 652 } else { 653 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 654 } 655 scheduleWriteSettingsLocked(); 656 657 final int userId = ivs.getUserId(); 658 if (userId != UserHandle.USER_ALL) { 659 final int userStatus = 660 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 661 662 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 663 boolean needUpdate = false; 664 665 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 666 // already been set by the User thru the Disambiguation dialog 667 switch (userStatus) { 668 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 669 if (verified) { 670 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 671 } else { 672 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 673 } 674 needUpdate = true; 675 break; 676 677 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 678 if (verified) { 679 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 680 needUpdate = true; 681 } 682 break; 683 684 default: 685 // Nothing to do 686 } 687 688 if (needUpdate) { 689 mSettings.updateIntentFilterVerificationStatusLPw( 690 packageName, updatedStatus, userId); 691 scheduleWritePackageRestrictionsLocked(userId); 692 } 693 } 694 } 695 } 696 697 @Override 698 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 699 ActivityIntentInfo filter, String packageName) { 700 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 701 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 702 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 703 return false; 704 } 705 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 706 if (ivs == null) { 707 ivs = createDomainVerificationState(verifierId, userId, verificationId, 708 packageName); 709 } 710 if (!hasValidDomains(filter)) { 711 return false; 712 } 713 ivs.addFilter(filter); 714 return true; 715 } 716 717 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 718 int userId, int verificationId, String packageName) { 719 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 720 verifierId, userId, packageName); 721 ivs.setPendingState(); 722 synchronized (mPackages) { 723 mIntentFilterVerificationStates.append(verificationId, ivs); 724 mCurrentIntentFilterVerifications.add(verificationId); 725 } 726 return ivs; 727 } 728 } 729 730 private static boolean hasValidDomains(ActivityIntentInfo filter) { 731 return hasValidDomains(filter, true); 732 } 733 734 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 735 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 736 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 737 if (!hasHTTPorHTTPS) { 738 if (logging) { 739 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 740 } 741 return false; 742 } 743 return true; 744 } 745 746 private IntentFilterVerifier mIntentFilterVerifier; 747 748 // Set of pending broadcasts for aggregating enable/disable of components. 749 static class PendingPackageBroadcasts { 750 // for each user id, a map of <package name -> components within that package> 751 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 752 753 public PendingPackageBroadcasts() { 754 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 755 } 756 757 public ArrayList<String> get(int userId, String packageName) { 758 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 759 return packages.get(packageName); 760 } 761 762 public void put(int userId, String packageName, ArrayList<String> components) { 763 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 764 packages.put(packageName, components); 765 } 766 767 public void remove(int userId, String packageName) { 768 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 769 if (packages != null) { 770 packages.remove(packageName); 771 } 772 } 773 774 public void remove(int userId) { 775 mUidMap.remove(userId); 776 } 777 778 public int userIdCount() { 779 return mUidMap.size(); 780 } 781 782 public int userIdAt(int n) { 783 return mUidMap.keyAt(n); 784 } 785 786 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 787 return mUidMap.get(userId); 788 } 789 790 public int size() { 791 // total number of pending broadcast entries across all userIds 792 int num = 0; 793 for (int i = 0; i< mUidMap.size(); i++) { 794 num += mUidMap.valueAt(i).size(); 795 } 796 return num; 797 } 798 799 public void clear() { 800 mUidMap.clear(); 801 } 802 803 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 804 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 805 if (map == null) { 806 map = new ArrayMap<String, ArrayList<String>>(); 807 mUidMap.put(userId, map); 808 } 809 return map; 810 } 811 } 812 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 813 814 // Service Connection to remote media container service to copy 815 // package uri's from external media onto secure containers 816 // or internal storage. 817 private IMediaContainerService mContainerService = null; 818 819 static final int SEND_PENDING_BROADCAST = 1; 820 static final int MCS_BOUND = 3; 821 static final int END_COPY = 4; 822 static final int INIT_COPY = 5; 823 static final int MCS_UNBIND = 6; 824 static final int START_CLEANING_PACKAGE = 7; 825 static final int FIND_INSTALL_LOC = 8; 826 static final int POST_INSTALL = 9; 827 static final int MCS_RECONNECT = 10; 828 static final int MCS_GIVE_UP = 11; 829 static final int UPDATED_MEDIA_STATUS = 12; 830 static final int WRITE_SETTINGS = 13; 831 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 832 static final int PACKAGE_VERIFIED = 15; 833 static final int CHECK_PENDING_VERIFICATION = 16; 834 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 835 static final int INTENT_FILTER_VERIFIED = 18; 836 837 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 838 839 // Delay time in millisecs 840 static final int BROADCAST_DELAY = 10 * 1000; 841 842 static UserManagerService sUserManager; 843 844 // Stores a list of users whose package restrictions file needs to be updated 845 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 846 847 final private DefaultContainerConnection mDefContainerConn = 848 new DefaultContainerConnection(); 849 class DefaultContainerConnection implements ServiceConnection { 850 public void onServiceConnected(ComponentName name, IBinder service) { 851 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 852 IMediaContainerService imcs = 853 IMediaContainerService.Stub.asInterface(service); 854 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 855 } 856 857 public void onServiceDisconnected(ComponentName name) { 858 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 859 } 860 }; 861 862 // Recordkeeping of restore-after-install operations that are currently in flight 863 // between the Package Manager and the Backup Manager 864 class PostInstallData { 865 public InstallArgs args; 866 public PackageInstalledInfo res; 867 868 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 869 args = _a; 870 res = _r; 871 } 872 }; 873 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 874 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 875 876 // backup/restore of preferred activity state 877 private static final String TAG_PREFERRED_BACKUP = "pa"; 878 879 private final String mRequiredVerifierPackage; 880 881 private final PackageUsage mPackageUsage = new PackageUsage(); 882 883 private class PackageUsage { 884 private static final int WRITE_INTERVAL 885 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 886 887 private final Object mFileLock = new Object(); 888 private final AtomicLong mLastWritten = new AtomicLong(0); 889 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 890 891 private boolean mIsHistoricalPackageUsageAvailable = true; 892 893 boolean isHistoricalPackageUsageAvailable() { 894 return mIsHistoricalPackageUsageAvailable; 895 } 896 897 void write(boolean force) { 898 if (force) { 899 writeInternal(); 900 return; 901 } 902 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 903 && !DEBUG_DEXOPT) { 904 return; 905 } 906 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 907 new Thread("PackageUsage_DiskWriter") { 908 @Override 909 public void run() { 910 try { 911 writeInternal(); 912 } finally { 913 mBackgroundWriteRunning.set(false); 914 } 915 } 916 }.start(); 917 } 918 } 919 920 private void writeInternal() { 921 synchronized (mPackages) { 922 synchronized (mFileLock) { 923 AtomicFile file = getFile(); 924 FileOutputStream f = null; 925 try { 926 f = file.startWrite(); 927 BufferedOutputStream out = new BufferedOutputStream(f); 928 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 929 StringBuilder sb = new StringBuilder(); 930 for (PackageParser.Package pkg : mPackages.values()) { 931 if (pkg.mLastPackageUsageTimeInMills == 0) { 932 continue; 933 } 934 sb.setLength(0); 935 sb.append(pkg.packageName); 936 sb.append(' '); 937 sb.append((long)pkg.mLastPackageUsageTimeInMills); 938 sb.append('\n'); 939 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 940 } 941 out.flush(); 942 file.finishWrite(f); 943 } catch (IOException e) { 944 if (f != null) { 945 file.failWrite(f); 946 } 947 Log.e(TAG, "Failed to write package usage times", e); 948 } 949 } 950 } 951 mLastWritten.set(SystemClock.elapsedRealtime()); 952 } 953 954 void readLP() { 955 synchronized (mFileLock) { 956 AtomicFile file = getFile(); 957 BufferedInputStream in = null; 958 try { 959 in = new BufferedInputStream(file.openRead()); 960 StringBuffer sb = new StringBuffer(); 961 while (true) { 962 String packageName = readToken(in, sb, ' '); 963 if (packageName == null) { 964 break; 965 } 966 String timeInMillisString = readToken(in, sb, '\n'); 967 if (timeInMillisString == null) { 968 throw new IOException("Failed to find last usage time for package " 969 + packageName); 970 } 971 PackageParser.Package pkg = mPackages.get(packageName); 972 if (pkg == null) { 973 continue; 974 } 975 long timeInMillis; 976 try { 977 timeInMillis = Long.parseLong(timeInMillisString.toString()); 978 } catch (NumberFormatException e) { 979 throw new IOException("Failed to parse " + timeInMillisString 980 + " as a long.", e); 981 } 982 pkg.mLastPackageUsageTimeInMills = timeInMillis; 983 } 984 } catch (FileNotFoundException expected) { 985 mIsHistoricalPackageUsageAvailable = false; 986 } catch (IOException e) { 987 Log.w(TAG, "Failed to read package usage times", e); 988 } finally { 989 IoUtils.closeQuietly(in); 990 } 991 } 992 mLastWritten.set(SystemClock.elapsedRealtime()); 993 } 994 995 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 996 throws IOException { 997 sb.setLength(0); 998 while (true) { 999 int ch = in.read(); 1000 if (ch == -1) { 1001 if (sb.length() == 0) { 1002 return null; 1003 } 1004 throw new IOException("Unexpected EOF"); 1005 } 1006 if (ch == endOfToken) { 1007 return sb.toString(); 1008 } 1009 sb.append((char)ch); 1010 } 1011 } 1012 1013 private AtomicFile getFile() { 1014 File dataDir = Environment.getDataDirectory(); 1015 File systemDir = new File(dataDir, "system"); 1016 File fname = new File(systemDir, "package-usage.list"); 1017 return new AtomicFile(fname); 1018 } 1019 } 1020 1021 class PackageHandler extends Handler { 1022 private boolean mBound = false; 1023 final ArrayList<HandlerParams> mPendingInstalls = 1024 new ArrayList<HandlerParams>(); 1025 1026 private boolean connectToService() { 1027 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1028 " DefaultContainerService"); 1029 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1030 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1031 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1032 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1034 mBound = true; 1035 return true; 1036 } 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1038 return false; 1039 } 1040 1041 private void disconnectService() { 1042 mContainerService = null; 1043 mBound = false; 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1045 mContext.unbindService(mDefContainerConn); 1046 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1047 } 1048 1049 PackageHandler(Looper looper) { 1050 super(looper); 1051 } 1052 1053 public void handleMessage(Message msg) { 1054 try { 1055 doHandleMessage(msg); 1056 } finally { 1057 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1058 } 1059 } 1060 1061 void doHandleMessage(Message msg) { 1062 switch (msg.what) { 1063 case INIT_COPY: { 1064 HandlerParams params = (HandlerParams) msg.obj; 1065 int idx = mPendingInstalls.size(); 1066 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1067 // If a bind was already initiated we dont really 1068 // need to do anything. The pending install 1069 // will be processed later on. 1070 if (!mBound) { 1071 // If this is the only one pending we might 1072 // have to bind to the service again. 1073 if (!connectToService()) { 1074 Slog.e(TAG, "Failed to bind to media container service"); 1075 params.serviceError(); 1076 return; 1077 } else { 1078 // Once we bind to the service, the first 1079 // pending request will be processed. 1080 mPendingInstalls.add(idx, params); 1081 } 1082 } else { 1083 mPendingInstalls.add(idx, params); 1084 // Already bound to the service. Just make 1085 // sure we trigger off processing the first request. 1086 if (idx == 0) { 1087 mHandler.sendEmptyMessage(MCS_BOUND); 1088 } 1089 } 1090 break; 1091 } 1092 case MCS_BOUND: { 1093 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1094 if (msg.obj != null) { 1095 mContainerService = (IMediaContainerService) msg.obj; 1096 } 1097 if (mContainerService == null) { 1098 // Something seriously wrong. Bail out 1099 Slog.e(TAG, "Cannot bind to media container service"); 1100 for (HandlerParams params : mPendingInstalls) { 1101 // Indicate service bind error 1102 params.serviceError(); 1103 } 1104 mPendingInstalls.clear(); 1105 } else if (mPendingInstalls.size() > 0) { 1106 HandlerParams params = mPendingInstalls.get(0); 1107 if (params != null) { 1108 if (params.startCopy()) { 1109 // We are done... look for more work or to 1110 // go idle. 1111 if (DEBUG_SD_INSTALL) Log.i(TAG, 1112 "Checking for more work or unbind..."); 1113 // Delete pending install 1114 if (mPendingInstalls.size() > 0) { 1115 mPendingInstalls.remove(0); 1116 } 1117 if (mPendingInstalls.size() == 0) { 1118 if (mBound) { 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, 1120 "Posting delayed MCS_UNBIND"); 1121 removeMessages(MCS_UNBIND); 1122 Message ubmsg = obtainMessage(MCS_UNBIND); 1123 // Unbind after a little delay, to avoid 1124 // continual thrashing. 1125 sendMessageDelayed(ubmsg, 10000); 1126 } 1127 } else { 1128 // There are more pending requests in queue. 1129 // Just post MCS_BOUND message to trigger processing 1130 // of next pending install. 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Posting MCS_BOUND for next work"); 1133 mHandler.sendEmptyMessage(MCS_BOUND); 1134 } 1135 } 1136 } 1137 } else { 1138 // Should never happen ideally. 1139 Slog.w(TAG, "Empty queue"); 1140 } 1141 break; 1142 } 1143 case MCS_RECONNECT: { 1144 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1145 if (mPendingInstalls.size() > 0) { 1146 if (mBound) { 1147 disconnectService(); 1148 } 1149 if (!connectToService()) { 1150 Slog.e(TAG, "Failed to bind to media container service"); 1151 for (HandlerParams params : mPendingInstalls) { 1152 // Indicate service bind error 1153 params.serviceError(); 1154 } 1155 mPendingInstalls.clear(); 1156 } 1157 } 1158 break; 1159 } 1160 case MCS_UNBIND: { 1161 // If there is no actual work left, then time to unbind. 1162 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1163 1164 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1165 if (mBound) { 1166 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1167 1168 disconnectService(); 1169 } 1170 } else if (mPendingInstalls.size() > 0) { 1171 // There are more pending requests in queue. 1172 // Just post MCS_BOUND message to trigger processing 1173 // of next pending install. 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 1177 break; 1178 } 1179 case MCS_GIVE_UP: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1181 mPendingInstalls.remove(0); 1182 break; 1183 } 1184 case SEND_PENDING_BROADCAST: { 1185 String packages[]; 1186 ArrayList<String> components[]; 1187 int size = 0; 1188 int uids[]; 1189 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1190 synchronized (mPackages) { 1191 if (mPendingBroadcasts == null) { 1192 return; 1193 } 1194 size = mPendingBroadcasts.size(); 1195 if (size <= 0) { 1196 // Nothing to be done. Just return 1197 return; 1198 } 1199 packages = new String[size]; 1200 components = new ArrayList[size]; 1201 uids = new int[size]; 1202 int i = 0; // filling out the above arrays 1203 1204 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1205 int packageUserId = mPendingBroadcasts.userIdAt(n); 1206 Iterator<Map.Entry<String, ArrayList<String>>> it 1207 = mPendingBroadcasts.packagesForUserId(packageUserId) 1208 .entrySet().iterator(); 1209 while (it.hasNext() && i < size) { 1210 Map.Entry<String, ArrayList<String>> ent = it.next(); 1211 packages[i] = ent.getKey(); 1212 components[i] = ent.getValue(); 1213 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1214 uids[i] = (ps != null) 1215 ? UserHandle.getUid(packageUserId, ps.appId) 1216 : -1; 1217 i++; 1218 } 1219 } 1220 size = i; 1221 mPendingBroadcasts.clear(); 1222 } 1223 // Send broadcasts 1224 for (int i = 0; i < size; i++) { 1225 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1226 } 1227 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1228 break; 1229 } 1230 case START_CLEANING_PACKAGE: { 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1232 final String packageName = (String)msg.obj; 1233 final int userId = msg.arg1; 1234 final boolean andCode = msg.arg2 != 0; 1235 synchronized (mPackages) { 1236 if (userId == UserHandle.USER_ALL) { 1237 int[] users = sUserManager.getUserIds(); 1238 for (int user : users) { 1239 mSettings.addPackageToCleanLPw( 1240 new PackageCleanItem(user, packageName, andCode)); 1241 } 1242 } else { 1243 mSettings.addPackageToCleanLPw( 1244 new PackageCleanItem(userId, packageName, andCode)); 1245 } 1246 } 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1248 startCleaningPackages(); 1249 } break; 1250 case POST_INSTALL: { 1251 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1252 PostInstallData data = mRunningInstalls.get(msg.arg1); 1253 mRunningInstalls.delete(msg.arg1); 1254 boolean deleteOld = false; 1255 1256 if (data != null) { 1257 InstallArgs args = data.args; 1258 PackageInstalledInfo res = data.res; 1259 1260 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1261 res.removedInfo.sendBroadcast(false, true, false); 1262 Bundle extras = new Bundle(1); 1263 extras.putInt(Intent.EXTRA_UID, res.uid); 1264 1265 // Now that we successfully installed the package, grant runtime 1266 // permissions if requested before broadcasting the install. 1267 if ((args.installFlags 1268 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1269 grantRequestedRuntimePermissions(res.pkg, 1270 args.user.getIdentifier()); 1271 } 1272 1273 // Determine the set of users who are adding this 1274 // package for the first time vs. those who are seeing 1275 // an update. 1276 int[] firstUsers; 1277 int[] updateUsers = new int[0]; 1278 if (res.origUsers == null || res.origUsers.length == 0) { 1279 firstUsers = res.newUsers; 1280 } else { 1281 firstUsers = new int[0]; 1282 for (int i=0; i<res.newUsers.length; i++) { 1283 int user = res.newUsers[i]; 1284 boolean isNew = true; 1285 for (int j=0; j<res.origUsers.length; j++) { 1286 if (res.origUsers[j] == user) { 1287 isNew = false; 1288 break; 1289 } 1290 } 1291 if (isNew) { 1292 int[] newFirst = new int[firstUsers.length+1]; 1293 System.arraycopy(firstUsers, 0, newFirst, 0, 1294 firstUsers.length); 1295 newFirst[firstUsers.length] = user; 1296 firstUsers = newFirst; 1297 } else { 1298 int[] newUpdate = new int[updateUsers.length+1]; 1299 System.arraycopy(updateUsers, 0, newUpdate, 0, 1300 updateUsers.length); 1301 newUpdate[updateUsers.length] = user; 1302 updateUsers = newUpdate; 1303 } 1304 } 1305 } 1306 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1307 res.pkg.applicationInfo.packageName, 1308 extras, null, null, firstUsers); 1309 final boolean update = res.removedInfo.removedPackage != null; 1310 if (update) { 1311 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1312 } 1313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1314 res.pkg.applicationInfo.packageName, 1315 extras, null, null, updateUsers); 1316 if (update) { 1317 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1318 res.pkg.applicationInfo.packageName, 1319 extras, null, null, updateUsers); 1320 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1321 null, null, 1322 res.pkg.applicationInfo.packageName, null, updateUsers); 1323 1324 // treat asec-hosted packages like removable media on upgrade 1325 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1326 if (DEBUG_INSTALL) { 1327 Slog.i(TAG, "upgrading pkg " + res.pkg 1328 + " is ASEC-hosted -> AVAILABLE"); 1329 } 1330 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1331 ArrayList<String> pkgList = new ArrayList<String>(1); 1332 pkgList.add(res.pkg.applicationInfo.packageName); 1333 sendResourcesChangedBroadcast(true, true, 1334 pkgList,uidArray, null); 1335 } 1336 } 1337 if (res.removedInfo.args != null) { 1338 // Remove the replaced package's older resources safely now 1339 deleteOld = true; 1340 } 1341 1342 // Log current value of "unknown sources" setting 1343 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1344 getUnknownSourcesSettings()); 1345 } 1346 // Force a gc to clear up things 1347 Runtime.getRuntime().gc(); 1348 // We delete after a gc for applications on sdcard. 1349 if (deleteOld) { 1350 synchronized (mInstallLock) { 1351 res.removedInfo.args.doPostDeleteLI(true); 1352 } 1353 } 1354 if (args.observer != null) { 1355 try { 1356 Bundle extras = extrasForInstallResult(res); 1357 args.observer.onPackageInstalled(res.name, res.returnCode, 1358 res.returnMsg, extras); 1359 } catch (RemoteException e) { 1360 Slog.i(TAG, "Observer no longer exists."); 1361 } 1362 } 1363 } else { 1364 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1365 } 1366 } break; 1367 case UPDATED_MEDIA_STATUS: { 1368 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1369 boolean reportStatus = msg.arg1 == 1; 1370 boolean doGc = msg.arg2 == 1; 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1372 if (doGc) { 1373 // Force a gc to clear up stale containers. 1374 Runtime.getRuntime().gc(); 1375 } 1376 if (msg.obj != null) { 1377 @SuppressWarnings("unchecked") 1378 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1379 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1380 // Unload containers 1381 unloadAllContainers(args); 1382 } 1383 if (reportStatus) { 1384 try { 1385 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1386 PackageHelper.getMountService().finishMediaUpdate(); 1387 } catch (RemoteException e) { 1388 Log.e(TAG, "MountService not running?"); 1389 } 1390 } 1391 } break; 1392 case WRITE_SETTINGS: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 synchronized (mPackages) { 1395 removeMessages(WRITE_SETTINGS); 1396 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1397 mSettings.writeLPr(); 1398 mDirtyUsers.clear(); 1399 } 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1401 } break; 1402 case WRITE_PACKAGE_RESTRICTIONS: { 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1404 synchronized (mPackages) { 1405 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1406 for (int userId : mDirtyUsers) { 1407 mSettings.writePackageRestrictionsLPr(userId); 1408 } 1409 mDirtyUsers.clear(); 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 } break; 1413 case CHECK_PENDING_VERIFICATION: { 1414 final int verificationId = msg.arg1; 1415 final PackageVerificationState state = mPendingVerification.get(verificationId); 1416 1417 if ((state != null) && !state.timeoutExtended()) { 1418 final InstallArgs args = state.getInstallArgs(); 1419 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1420 1421 Slog.i(TAG, "Verification timed out for " + originUri); 1422 mPendingVerification.remove(verificationId); 1423 1424 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1425 1426 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1427 Slog.i(TAG, "Continuing with installation of " + originUri); 1428 state.setVerifierResponse(Binder.getCallingUid(), 1429 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1430 broadcastPackageVerified(verificationId, originUri, 1431 PackageManager.VERIFICATION_ALLOW, 1432 state.getInstallArgs().getUser()); 1433 try { 1434 ret = args.copyApk(mContainerService, true); 1435 } catch (RemoteException e) { 1436 Slog.e(TAG, "Could not contact the ContainerService"); 1437 } 1438 } else { 1439 broadcastPackageVerified(verificationId, originUri, 1440 PackageManager.VERIFICATION_REJECT, 1441 state.getInstallArgs().getUser()); 1442 } 1443 1444 processPendingInstall(args, ret); 1445 mHandler.sendEmptyMessage(MCS_UNBIND); 1446 } 1447 break; 1448 } 1449 case PACKAGE_VERIFIED: { 1450 final int verificationId = msg.arg1; 1451 1452 final PackageVerificationState state = mPendingVerification.get(verificationId); 1453 if (state == null) { 1454 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1455 break; 1456 } 1457 1458 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1459 1460 state.setVerifierResponse(response.callerUid, response.code); 1461 1462 if (state.isVerificationComplete()) { 1463 mPendingVerification.remove(verificationId); 1464 1465 final InstallArgs args = state.getInstallArgs(); 1466 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1467 1468 int ret; 1469 if (state.isInstallAllowed()) { 1470 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1471 broadcastPackageVerified(verificationId, originUri, 1472 response.code, state.getInstallArgs().getUser()); 1473 try { 1474 ret = args.copyApk(mContainerService, true); 1475 } catch (RemoteException e) { 1476 Slog.e(TAG, "Could not contact the ContainerService"); 1477 } 1478 } else { 1479 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1480 } 1481 1482 processPendingInstall(args, ret); 1483 1484 mHandler.sendEmptyMessage(MCS_UNBIND); 1485 } 1486 1487 break; 1488 } 1489 case START_INTENT_FILTER_VERIFICATIONS: { 1490 int userId = msg.arg1; 1491 int verifierUid = msg.arg2; 1492 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1493 1494 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1495 break; 1496 } 1497 case INTENT_FILTER_VERIFIED: { 1498 final int verificationId = msg.arg1; 1499 1500 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1501 verificationId); 1502 if (state == null) { 1503 Slog.w(TAG, "Invalid IntentFilter verification token " 1504 + verificationId + " received"); 1505 break; 1506 } 1507 1508 final int userId = state.getUserId(); 1509 1510 Slog.d(TAG, "Processing IntentFilter verification with token:" 1511 + verificationId + " and userId:" + userId); 1512 1513 final IntentFilterVerificationResponse response = 1514 (IntentFilterVerificationResponse) msg.obj; 1515 1516 state.setVerifierResponse(response.callerUid, response.code); 1517 1518 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1519 + " and userId:" + userId 1520 + " is settings verifier response with response code:" 1521 + response.code); 1522 1523 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1524 Slog.d(TAG, "Domains failing verification: " 1525 + response.getFailedDomainsString()); 1526 } 1527 1528 if (state.isVerificationComplete()) { 1529 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1530 } else { 1531 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1532 + " was not said to be complete"); 1533 } 1534 1535 break; 1536 } 1537 } 1538 } 1539 } 1540 1541 private StorageEventListener mStorageListener = new StorageEventListener() { 1542 @Override 1543 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1544 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1545 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1546 // TODO: ensure that private directories exist for all active users 1547 // TODO: remove user data whose serial number doesn't match 1548 loadPrivatePackages(vol); 1549 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1550 unloadPrivatePackages(vol); 1551 } 1552 } 1553 1554 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1555 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1556 updateExternalMediaStatus(true, false); 1557 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1558 updateExternalMediaStatus(false, false); 1559 } 1560 } 1561 } 1562 1563 @Override 1564 public void onVolumeForgotten(String fsUuid) { 1565 // TODO: remove all packages hosted on this uuid 1566 } 1567 }; 1568 1569 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1570 if (userId >= UserHandle.USER_OWNER) { 1571 grantRequestedRuntimePermissionsForUser(pkg, userId); 1572 } else if (userId == UserHandle.USER_ALL) { 1573 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1574 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1575 } 1576 } 1577 } 1578 1579 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1580 SettingBase sb = (SettingBase) pkg.mExtras; 1581 if (sb == null) { 1582 return; 1583 } 1584 1585 PermissionsState permissionsState = sb.getPermissionsState(); 1586 1587 for (String permission : pkg.requestedPermissions) { 1588 BasePermission bp = mSettings.mPermissions.get(permission); 1589 if (bp != null && bp.isRuntime()) { 1590 permissionsState.grantRuntimePermission(bp, userId); 1591 } 1592 } 1593 } 1594 1595 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1596 Bundle extras = null; 1597 switch (res.returnCode) { 1598 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1599 extras = new Bundle(); 1600 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1601 res.origPermission); 1602 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1603 res.origPackage); 1604 break; 1605 } 1606 case PackageManager.INSTALL_SUCCEEDED: { 1607 extras = new Bundle(); 1608 extras.putBoolean(Intent.EXTRA_REPLACING, 1609 res.removedInfo != null && res.removedInfo.removedPackage != null); 1610 break; 1611 } 1612 } 1613 return extras; 1614 } 1615 1616 void scheduleWriteSettingsLocked() { 1617 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1618 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1619 } 1620 } 1621 1622 void scheduleWritePackageRestrictionsLocked(int userId) { 1623 if (!sUserManager.exists(userId)) return; 1624 mDirtyUsers.add(userId); 1625 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1626 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1627 } 1628 } 1629 1630 public static PackageManagerService main(Context context, Installer installer, 1631 boolean factoryTest, boolean onlyCore) { 1632 PackageManagerService m = new PackageManagerService(context, installer, 1633 factoryTest, onlyCore); 1634 ServiceManager.addService("package", m); 1635 return m; 1636 } 1637 1638 static String[] splitString(String str, char sep) { 1639 int count = 1; 1640 int i = 0; 1641 while ((i=str.indexOf(sep, i)) >= 0) { 1642 count++; 1643 i++; 1644 } 1645 1646 String[] res = new String[count]; 1647 i=0; 1648 count = 0; 1649 int lastI=0; 1650 while ((i=str.indexOf(sep, i)) >= 0) { 1651 res[count] = str.substring(lastI, i); 1652 count++; 1653 i++; 1654 lastI = i; 1655 } 1656 res[count] = str.substring(lastI, str.length()); 1657 return res; 1658 } 1659 1660 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1661 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1662 Context.DISPLAY_SERVICE); 1663 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1664 } 1665 1666 public PackageManagerService(Context context, Installer installer, 1667 boolean factoryTest, boolean onlyCore) { 1668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1669 SystemClock.uptimeMillis()); 1670 1671 if (mSdkVersion <= 0) { 1672 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1673 } 1674 1675 mContext = context; 1676 mFactoryTest = factoryTest; 1677 mOnlyCore = onlyCore; 1678 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1679 mMetrics = new DisplayMetrics(); 1680 mSettings = new Settings(mPackages); 1681 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1682 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1683 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1684 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1685 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1686 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1687 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1688 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1689 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 1694 // TODO: add a property to control this? 1695 long dexOptLRUThresholdInMinutes; 1696 if (mLazyDexOpt) { 1697 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1698 } else { 1699 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1700 } 1701 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1702 1703 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1704 if (separateProcesses != null && separateProcesses.length() > 0) { 1705 if ("*".equals(separateProcesses)) { 1706 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1707 mSeparateProcesses = null; 1708 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1709 } else { 1710 mDefParseFlags = 0; 1711 mSeparateProcesses = separateProcesses.split(","); 1712 Slog.w(TAG, "Running with debug.separate_processes: " 1713 + separateProcesses); 1714 } 1715 } else { 1716 mDefParseFlags = 0; 1717 mSeparateProcesses = null; 1718 } 1719 1720 mInstaller = installer; 1721 mPackageDexOptimizer = new PackageDexOptimizer(this); 1722 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1723 1724 getDefaultDisplayMetrics(context, mMetrics); 1725 1726 SystemConfig systemConfig = SystemConfig.getInstance(); 1727 mGlobalGids = systemConfig.getGlobalGids(); 1728 mSystemPermissions = systemConfig.getSystemPermissions(); 1729 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1730 1731 synchronized (mInstallLock) { 1732 // writer 1733 synchronized (mPackages) { 1734 mHandlerThread = new ServiceThread(TAG, 1735 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1736 mHandlerThread.start(); 1737 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1738 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1739 1740 File dataDir = Environment.getDataDirectory(); 1741 mAppDataDir = new File(dataDir, "data"); 1742 mAppInstallDir = new File(dataDir, "app"); 1743 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1744 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1745 mUserAppDataDir = new File(dataDir, "user"); 1746 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1747 1748 sUserManager = new UserManagerService(context, this, 1749 mInstallLock, mPackages); 1750 1751 // Propagate permission configuration in to package manager. 1752 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1753 = systemConfig.getPermissions(); 1754 for (int i=0; i<permConfig.size(); i++) { 1755 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1756 BasePermission bp = mSettings.mPermissions.get(perm.name); 1757 if (bp == null) { 1758 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1759 mSettings.mPermissions.put(perm.name, bp); 1760 } 1761 if (perm.gids != null) { 1762 bp.setGids(perm.gids, perm.perUser); 1763 } 1764 } 1765 1766 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1767 for (int i=0; i<libConfig.size(); i++) { 1768 mSharedLibraries.put(libConfig.keyAt(i), 1769 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1770 } 1771 1772 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1773 1774 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1775 mSdkVersion, mOnlyCore); 1776 1777 String customResolverActivity = Resources.getSystem().getString( 1778 R.string.config_customResolverActivity); 1779 if (TextUtils.isEmpty(customResolverActivity)) { 1780 customResolverActivity = null; 1781 } else { 1782 mCustomResolverComponentName = ComponentName.unflattenFromString( 1783 customResolverActivity); 1784 } 1785 1786 long startTime = SystemClock.uptimeMillis(); 1787 1788 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1789 startTime); 1790 1791 // Set flag to monitor and not change apk file paths when 1792 // scanning install directories. 1793 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1794 1795 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1796 1797 /** 1798 * Add everything in the in the boot class path to the 1799 * list of process files because dexopt will have been run 1800 * if necessary during zygote startup. 1801 */ 1802 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1803 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1804 1805 if (bootClassPath != null) { 1806 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1807 for (String element : bootClassPathElements) { 1808 alreadyDexOpted.add(element); 1809 } 1810 } else { 1811 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1812 } 1813 1814 if (systemServerClassPath != null) { 1815 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1816 for (String element : systemServerClassPathElements) { 1817 alreadyDexOpted.add(element); 1818 } 1819 } else { 1820 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1821 } 1822 1823 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1824 final String[] dexCodeInstructionSets = 1825 getDexCodeInstructionSets( 1826 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1827 1828 /** 1829 * Ensure all external libraries have had dexopt run on them. 1830 */ 1831 if (mSharedLibraries.size() > 0) { 1832 // NOTE: For now, we're compiling these system "shared libraries" 1833 // (and framework jars) into all available architectures. It's possible 1834 // to compile them only when we come across an app that uses them (there's 1835 // already logic for that in scanPackageLI) but that adds some complexity. 1836 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1837 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1838 final String lib = libEntry.path; 1839 if (lib == null) { 1840 continue; 1841 } 1842 1843 try { 1844 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1845 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1846 alreadyDexOpted.add(lib); 1847 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1848 } 1849 } catch (FileNotFoundException e) { 1850 Slog.w(TAG, "Library not found: " + lib); 1851 } catch (IOException e) { 1852 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1853 + e.getMessage()); 1854 } 1855 } 1856 } 1857 } 1858 1859 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1860 1861 // Gross hack for now: we know this file doesn't contain any 1862 // code, so don't dexopt it to avoid the resulting log spew. 1863 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1864 1865 // Gross hack for now: we know this file is only part of 1866 // the boot class path for art, so don't dexopt it to 1867 // avoid the resulting log spew. 1868 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1869 1870 /** 1871 * And there are a number of commands implemented in Java, which 1872 * we currently need to do the dexopt on so that they can be 1873 * run from a non-root shell. 1874 */ 1875 String[] frameworkFiles = frameworkDir.list(); 1876 if (frameworkFiles != null) { 1877 // TODO: We could compile these only for the most preferred ABI. We should 1878 // first double check that the dex files for these commands are not referenced 1879 // by other system apps. 1880 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1881 for (int i=0; i<frameworkFiles.length; i++) { 1882 File libPath = new File(frameworkDir, frameworkFiles[i]); 1883 String path = libPath.getPath(); 1884 // Skip the file if we already did it. 1885 if (alreadyDexOpted.contains(path)) { 1886 continue; 1887 } 1888 // Skip the file if it is not a type we want to dexopt. 1889 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1890 continue; 1891 } 1892 try { 1893 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1894 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1895 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1896 } 1897 } catch (FileNotFoundException e) { 1898 Slog.w(TAG, "Jar not found: " + path); 1899 } catch (IOException e) { 1900 Slog.w(TAG, "Exception reading jar: " + path, e); 1901 } 1902 } 1903 } 1904 } 1905 1906 // Collect vendor overlay packages. 1907 // (Do this before scanning any apps.) 1908 // For security and version matching reason, only consider 1909 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1910 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1911 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1912 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1913 1914 // Find base frameworks (resource packages without code). 1915 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1916 | PackageParser.PARSE_IS_SYSTEM_DIR 1917 | PackageParser.PARSE_IS_PRIVILEGED, 1918 scanFlags | SCAN_NO_DEX, 0); 1919 1920 // Collected privileged system packages. 1921 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1922 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1923 | PackageParser.PARSE_IS_SYSTEM_DIR 1924 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1925 1926 // Collect ordinary system packages. 1927 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1928 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1930 1931 // Collect all vendor packages. 1932 File vendorAppDir = new File("/vendor/app"); 1933 try { 1934 vendorAppDir = vendorAppDir.getCanonicalFile(); 1935 } catch (IOException e) { 1936 // failed to look up canonical path, continue with original one 1937 } 1938 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1940 1941 // Collect all OEM packages. 1942 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1943 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1944 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1945 1946 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1947 mInstaller.moveFiles(); 1948 1949 // Prune any system packages that no longer exist. 1950 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1951 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1952 if (!mOnlyCore) { 1953 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1954 while (psit.hasNext()) { 1955 PackageSetting ps = psit.next(); 1956 1957 /* 1958 * If this is not a system app, it can't be a 1959 * disable system app. 1960 */ 1961 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1962 continue; 1963 } 1964 1965 /* 1966 * If the package is scanned, it's not erased. 1967 */ 1968 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1969 if (scannedPkg != null) { 1970 /* 1971 * If the system app is both scanned and in the 1972 * disabled packages list, then it must have been 1973 * added via OTA. Remove it from the currently 1974 * scanned package so the previously user-installed 1975 * application can be scanned. 1976 */ 1977 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1978 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1979 + ps.name + "; removing system app. Last known codePath=" 1980 + ps.codePathString + ", installStatus=" + ps.installStatus 1981 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1982 + scannedPkg.mVersionCode); 1983 removePackageLI(ps, true); 1984 expectingBetter.put(ps.name, ps.codePath); 1985 } 1986 1987 continue; 1988 } 1989 1990 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1991 psit.remove(); 1992 logCriticalInfo(Log.WARN, "System package " + ps.name 1993 + " no longer exists; wiping its data"); 1994 removeDataDirsLI(null, ps.name); 1995 } else { 1996 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1997 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1998 possiblyDeletedUpdatedSystemApps.add(ps.name); 1999 } 2000 } 2001 } 2002 } 2003 2004 //look for any incomplete package installations 2005 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2006 //clean up list 2007 for(int i = 0; i < deletePkgsList.size(); i++) { 2008 //clean up here 2009 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2010 } 2011 //delete tmp files 2012 deleteTempPackageFiles(); 2013 2014 // Remove any shared userIDs that have no associated packages 2015 mSettings.pruneSharedUsersLPw(); 2016 2017 if (!mOnlyCore) { 2018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2019 SystemClock.uptimeMillis()); 2020 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2021 2022 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2023 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2024 2025 /** 2026 * Remove disable package settings for any updated system 2027 * apps that were removed via an OTA. If they're not a 2028 * previously-updated app, remove them completely. 2029 * Otherwise, just revoke their system-level permissions. 2030 */ 2031 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2032 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2033 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2034 2035 String msg; 2036 if (deletedPkg == null) { 2037 msg = "Updated system package " + deletedAppName 2038 + " no longer exists; wiping its data"; 2039 removeDataDirsLI(null, deletedAppName); 2040 } else { 2041 msg = "Updated system app + " + deletedAppName 2042 + " no longer present; removing system privileges for " 2043 + deletedAppName; 2044 2045 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2046 2047 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2048 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2049 } 2050 logCriticalInfo(Log.WARN, msg); 2051 } 2052 2053 /** 2054 * Make sure all system apps that we expected to appear on 2055 * the userdata partition actually showed up. If they never 2056 * appeared, crawl back and revive the system version. 2057 */ 2058 for (int i = 0; i < expectingBetter.size(); i++) { 2059 final String packageName = expectingBetter.keyAt(i); 2060 if (!mPackages.containsKey(packageName)) { 2061 final File scanFile = expectingBetter.valueAt(i); 2062 2063 logCriticalInfo(Log.WARN, "Expected better " + packageName 2064 + " but never showed up; reverting to system"); 2065 2066 final int reparseFlags; 2067 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2068 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR 2070 | PackageParser.PARSE_IS_PRIVILEGED; 2071 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2072 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR; 2074 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR; 2077 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else { 2081 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2082 continue; 2083 } 2084 2085 mSettings.enableSystemPackageLPw(packageName); 2086 2087 try { 2088 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2089 } catch (PackageManagerException e) { 2090 Slog.e(TAG, "Failed to parse original system package: " 2091 + e.getMessage()); 2092 } 2093 } 2094 } 2095 } 2096 2097 // Now that we know all of the shared libraries, update all clients to have 2098 // the correct library paths. 2099 updateAllSharedLibrariesLPw(); 2100 2101 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2102 // NOTE: We ignore potential failures here during a system scan (like 2103 // the rest of the commands above) because there's precious little we 2104 // can do about it. A settings error is reported, though. 2105 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2106 false /* force dexopt */, false /* defer dexopt */); 2107 } 2108 2109 // Now that we know all the packages we are keeping, 2110 // read and update their last usage times. 2111 mPackageUsage.readLP(); 2112 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2114 SystemClock.uptimeMillis()); 2115 Slog.i(TAG, "Time to scan packages: " 2116 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2117 + " seconds"); 2118 2119 // If the platform SDK has changed since the last time we booted, 2120 // we need to re-grant app permission to catch any new ones that 2121 // appear. This is really a hack, and means that apps can in some 2122 // cases get permissions that the user didn't initially explicitly 2123 // allow... it would be nice to have some better way to handle 2124 // this situation. 2125 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2126 != mSdkVersion; 2127 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2128 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2129 + "; regranting permissions for internal storage"); 2130 mSettings.mInternalSdkPlatform = mSdkVersion; 2131 2132 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2133 | (regrantPermissions 2134 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2135 : 0)); 2136 2137 // If this is the first boot, and it is a normal boot, then 2138 // we need to initialize the default preferred apps. 2139 if (!mRestoredSettings && !onlyCore) { 2140 mSettings.readDefaultPreferredAppsLPw(this, 0); 2141 } 2142 2143 // If this is first boot after an OTA, and a normal boot, then 2144 // we need to clear code cache directories. 2145 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2146 if (mIsUpgrade && !onlyCore) { 2147 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2148 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2149 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2150 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2151 } 2152 mSettings.mFingerprint = Build.FINGERPRINT; 2153 } 2154 2155 primeDomainVerificationsLPw(false); 2156 checkDefaultBrowser(); 2157 2158 // All the changes are done during package scanning. 2159 mSettings.updateInternalDatabaseVersion(); 2160 2161 // can downgrade to reader 2162 mSettings.writeLPr(); 2163 2164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2165 SystemClock.uptimeMillis()); 2166 2167 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2168 2169 mInstallerService = new PackageInstallerService(context, this); 2170 2171 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2172 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2173 mIntentFilterVerifierComponent); 2174 2175 } // synchronized (mPackages) 2176 } // synchronized (mInstallLock) 2177 2178 // Now after opening every single application zip, make sure they 2179 // are all flushed. Not really needed, but keeps things nice and 2180 // tidy. 2181 Runtime.getRuntime().gc(); 2182 } 2183 2184 @Override 2185 public boolean isFirstBoot() { 2186 return !mRestoredSettings; 2187 } 2188 2189 @Override 2190 public boolean isOnlyCoreApps() { 2191 return mOnlyCore; 2192 } 2193 2194 @Override 2195 public boolean isUpgrade() { 2196 return mIsUpgrade; 2197 } 2198 2199 private String getRequiredVerifierLPr() { 2200 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2201 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2202 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2203 2204 String requiredVerifier = null; 2205 2206 final int N = receivers.size(); 2207 for (int i = 0; i < N; i++) { 2208 final ResolveInfo info = receivers.get(i); 2209 2210 if (info.activityInfo == null) { 2211 continue; 2212 } 2213 2214 final String packageName = info.activityInfo.packageName; 2215 2216 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2217 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2218 continue; 2219 } 2220 2221 if (requiredVerifier != null) { 2222 throw new RuntimeException("There can be only one required verifier"); 2223 } 2224 2225 requiredVerifier = packageName; 2226 } 2227 2228 return requiredVerifier; 2229 } 2230 2231 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2232 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2233 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2234 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2235 2236 ComponentName verifierComponentName = null; 2237 2238 int priority = -1000; 2239 final int N = receivers.size(); 2240 for (int i = 0; i < N; i++) { 2241 final ResolveInfo info = receivers.get(i); 2242 2243 if (info.activityInfo == null) { 2244 continue; 2245 } 2246 2247 final String packageName = info.activityInfo.packageName; 2248 2249 final PackageSetting ps = mSettings.mPackages.get(packageName); 2250 if (ps == null) { 2251 continue; 2252 } 2253 2254 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2255 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2256 continue; 2257 } 2258 2259 // Select the IntentFilterVerifier with the highest priority 2260 if (priority < info.priority) { 2261 priority = info.priority; 2262 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2263 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2264 " with priority: " + info.priority); 2265 } 2266 } 2267 2268 return verifierComponentName; 2269 } 2270 2271 private void primeDomainVerificationsLPw(boolean logging) { 2272 Slog.d(TAG, "Start priming domain verifications"); 2273 boolean updated = false; 2274 ArraySet<String> allHostsSet = new ArraySet<>(); 2275 for (PackageParser.Package pkg : mPackages.values()) { 2276 final String packageName = pkg.packageName; 2277 if (!hasDomainURLs(pkg)) { 2278 if (logging) { 2279 Slog.d(TAG, "No priming domain verifications for " + 2280 "package with no domain URLs: " + packageName); 2281 } 2282 continue; 2283 } 2284 if (!pkg.isSystemApp()) { 2285 if (logging) { 2286 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2287 packageName); 2288 } 2289 continue; 2290 } 2291 for (PackageParser.Activity a : pkg.activities) { 2292 for (ActivityIntentInfo filter : a.intents) { 2293 if (hasValidDomains(filter, false)) { 2294 allHostsSet.addAll(filter.getHostsList()); 2295 } 2296 } 2297 } 2298 if (allHostsSet.size() == 0) { 2299 allHostsSet.add("*"); 2300 } 2301 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2302 IntentFilterVerificationInfo ivi = 2303 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2304 if (ivi != null) { 2305 // We will always log this 2306 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2307 " with hosts:" + ivi.getDomainsString()); 2308 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2309 updated = true; 2310 } 2311 else { 2312 if (logging) { 2313 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2314 } 2315 } 2316 allHostsSet.clear(); 2317 } 2318 if (updated) { 2319 if (logging) { 2320 Slog.d(TAG, "Will need to write primed domain verifications"); 2321 } 2322 } 2323 Slog.d(TAG, "End priming domain verifications"); 2324 } 2325 2326 private void checkDefaultBrowser() { 2327 final int myUserId = UserHandle.myUserId(); 2328 final String packageName = getDefaultBrowserPackageName(myUserId); 2329 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2330 if (info == null) { 2331 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2332 packageName); 2333 setDefaultBrowserPackageName(null, myUserId); 2334 } 2335 } 2336 2337 @Override 2338 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2339 throws RemoteException { 2340 try { 2341 return super.onTransact(code, data, reply, flags); 2342 } catch (RuntimeException e) { 2343 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2344 Slog.wtf(TAG, "Package Manager Crash", e); 2345 } 2346 throw e; 2347 } 2348 } 2349 2350 void cleanupInstallFailedPackage(PackageSetting ps) { 2351 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2352 2353 removeDataDirsLI(ps.volumeUuid, ps.name); 2354 if (ps.codePath != null) { 2355 if (ps.codePath.isDirectory()) { 2356 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2357 } else { 2358 ps.codePath.delete(); 2359 } 2360 } 2361 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2362 if (ps.resourcePath.isDirectory()) { 2363 FileUtils.deleteContents(ps.resourcePath); 2364 } 2365 ps.resourcePath.delete(); 2366 } 2367 mSettings.removePackageLPw(ps.name); 2368 } 2369 2370 static int[] appendInts(int[] cur, int[] add) { 2371 if (add == null) return cur; 2372 if (cur == null) return add; 2373 final int N = add.length; 2374 for (int i=0; i<N; i++) { 2375 cur = appendInt(cur, add[i]); 2376 } 2377 return cur; 2378 } 2379 2380 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2381 if (!sUserManager.exists(userId)) return null; 2382 final PackageSetting ps = (PackageSetting) p.mExtras; 2383 if (ps == null) { 2384 return null; 2385 } 2386 2387 final PermissionsState permissionsState = ps.getPermissionsState(); 2388 2389 final int[] gids = permissionsState.computeGids(userId); 2390 final Set<String> permissions = permissionsState.getPermissions(userId); 2391 final PackageUserState state = ps.readUserState(userId); 2392 2393 return PackageParser.generatePackageInfo(p, gids, flags, 2394 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2395 } 2396 2397 @Override 2398 public boolean isPackageFrozen(String packageName) { 2399 synchronized (mPackages) { 2400 final PackageSetting ps = mSettings.mPackages.get(packageName); 2401 if (ps != null) { 2402 return ps.frozen; 2403 } 2404 } 2405 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2406 return true; 2407 } 2408 2409 @Override 2410 public boolean isPackageAvailable(String packageName, int userId) { 2411 if (!sUserManager.exists(userId)) return false; 2412 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2413 synchronized (mPackages) { 2414 PackageParser.Package p = mPackages.get(packageName); 2415 if (p != null) { 2416 final PackageSetting ps = (PackageSetting) p.mExtras; 2417 if (ps != null) { 2418 final PackageUserState state = ps.readUserState(userId); 2419 if (state != null) { 2420 return PackageParser.isAvailable(state); 2421 } 2422 } 2423 } 2424 } 2425 return false; 2426 } 2427 2428 @Override 2429 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2430 if (!sUserManager.exists(userId)) return null; 2431 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2432 // reader 2433 synchronized (mPackages) { 2434 PackageParser.Package p = mPackages.get(packageName); 2435 if (DEBUG_PACKAGE_INFO) 2436 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2437 if (p != null) { 2438 return generatePackageInfo(p, flags, userId); 2439 } 2440 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2441 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2442 } 2443 } 2444 return null; 2445 } 2446 2447 @Override 2448 public String[] currentToCanonicalPackageNames(String[] names) { 2449 String[] out = new String[names.length]; 2450 // reader 2451 synchronized (mPackages) { 2452 for (int i=names.length-1; i>=0; i--) { 2453 PackageSetting ps = mSettings.mPackages.get(names[i]); 2454 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2455 } 2456 } 2457 return out; 2458 } 2459 2460 @Override 2461 public String[] canonicalToCurrentPackageNames(String[] names) { 2462 String[] out = new String[names.length]; 2463 // reader 2464 synchronized (mPackages) { 2465 for (int i=names.length-1; i>=0; i--) { 2466 String cur = mSettings.mRenamedPackages.get(names[i]); 2467 out[i] = cur != null ? cur : names[i]; 2468 } 2469 } 2470 return out; 2471 } 2472 2473 @Override 2474 public int getPackageUid(String packageName, int userId) { 2475 if (!sUserManager.exists(userId)) return -1; 2476 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2477 2478 // reader 2479 synchronized (mPackages) { 2480 PackageParser.Package p = mPackages.get(packageName); 2481 if(p != null) { 2482 return UserHandle.getUid(userId, p.applicationInfo.uid); 2483 } 2484 PackageSetting ps = mSettings.mPackages.get(packageName); 2485 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2486 return -1; 2487 } 2488 p = ps.pkg; 2489 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2490 } 2491 } 2492 2493 @Override 2494 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2495 if (!sUserManager.exists(userId)) { 2496 return null; 2497 } 2498 2499 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2500 "getPackageGids"); 2501 2502 // reader 2503 synchronized (mPackages) { 2504 PackageParser.Package p = mPackages.get(packageName); 2505 if (DEBUG_PACKAGE_INFO) { 2506 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2507 } 2508 if (p != null) { 2509 PackageSetting ps = (PackageSetting) p.mExtras; 2510 return ps.getPermissionsState().computeGids(userId); 2511 } 2512 } 2513 2514 return null; 2515 } 2516 2517 static PermissionInfo generatePermissionInfo( 2518 BasePermission bp, int flags) { 2519 if (bp.perm != null) { 2520 return PackageParser.generatePermissionInfo(bp.perm, flags); 2521 } 2522 PermissionInfo pi = new PermissionInfo(); 2523 pi.name = bp.name; 2524 pi.packageName = bp.sourcePackage; 2525 pi.nonLocalizedLabel = bp.name; 2526 pi.protectionLevel = bp.protectionLevel; 2527 return pi; 2528 } 2529 2530 @Override 2531 public PermissionInfo getPermissionInfo(String name, int flags) { 2532 // reader 2533 synchronized (mPackages) { 2534 final BasePermission p = mSettings.mPermissions.get(name); 2535 if (p != null) { 2536 return generatePermissionInfo(p, flags); 2537 } 2538 return null; 2539 } 2540 } 2541 2542 @Override 2543 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2544 // reader 2545 synchronized (mPackages) { 2546 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2547 for (BasePermission p : mSettings.mPermissions.values()) { 2548 if (group == null) { 2549 if (p.perm == null || p.perm.info.group == null) { 2550 out.add(generatePermissionInfo(p, flags)); 2551 } 2552 } else { 2553 if (p.perm != null && group.equals(p.perm.info.group)) { 2554 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2555 } 2556 } 2557 } 2558 2559 if (out.size() > 0) { 2560 return out; 2561 } 2562 return mPermissionGroups.containsKey(group) ? out : null; 2563 } 2564 } 2565 2566 @Override 2567 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2568 // reader 2569 synchronized (mPackages) { 2570 return PackageParser.generatePermissionGroupInfo( 2571 mPermissionGroups.get(name), flags); 2572 } 2573 } 2574 2575 @Override 2576 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2577 // reader 2578 synchronized (mPackages) { 2579 final int N = mPermissionGroups.size(); 2580 ArrayList<PermissionGroupInfo> out 2581 = new ArrayList<PermissionGroupInfo>(N); 2582 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2583 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2584 } 2585 return out; 2586 } 2587 } 2588 2589 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2590 int userId) { 2591 if (!sUserManager.exists(userId)) return null; 2592 PackageSetting ps = mSettings.mPackages.get(packageName); 2593 if (ps != null) { 2594 if (ps.pkg == null) { 2595 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2596 flags, userId); 2597 if (pInfo != null) { 2598 return pInfo.applicationInfo; 2599 } 2600 return null; 2601 } 2602 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2603 ps.readUserState(userId), userId); 2604 } 2605 return null; 2606 } 2607 2608 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2609 int userId) { 2610 if (!sUserManager.exists(userId)) return null; 2611 PackageSetting ps = mSettings.mPackages.get(packageName); 2612 if (ps != null) { 2613 PackageParser.Package pkg = ps.pkg; 2614 if (pkg == null) { 2615 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2616 return null; 2617 } 2618 // Only data remains, so we aren't worried about code paths 2619 pkg = new PackageParser.Package(packageName); 2620 pkg.applicationInfo.packageName = packageName; 2621 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2622 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2623 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2624 packageName, userId).getAbsolutePath(); 2625 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2626 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2627 } 2628 return generatePackageInfo(pkg, flags, userId); 2629 } 2630 return null; 2631 } 2632 2633 @Override 2634 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2635 if (!sUserManager.exists(userId)) return null; 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2637 // writer 2638 synchronized (mPackages) { 2639 PackageParser.Package p = mPackages.get(packageName); 2640 if (DEBUG_PACKAGE_INFO) Log.v( 2641 TAG, "getApplicationInfo " + packageName 2642 + ": " + p); 2643 if (p != null) { 2644 PackageSetting ps = mSettings.mPackages.get(packageName); 2645 if (ps == null) return null; 2646 // Note: isEnabledLP() does not apply here - always return info 2647 return PackageParser.generateApplicationInfo( 2648 p, flags, ps.readUserState(userId), userId); 2649 } 2650 if ("android".equals(packageName)||"system".equals(packageName)) { 2651 return mAndroidApplication; 2652 } 2653 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2654 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2655 } 2656 } 2657 return null; 2658 } 2659 2660 @Override 2661 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2662 final IPackageDataObserver observer) { 2663 mContext.enforceCallingOrSelfPermission( 2664 android.Manifest.permission.CLEAR_APP_CACHE, null); 2665 // Queue up an async operation since clearing cache may take a little while. 2666 mHandler.post(new Runnable() { 2667 public void run() { 2668 mHandler.removeCallbacks(this); 2669 int retCode = -1; 2670 synchronized (mInstallLock) { 2671 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2672 if (retCode < 0) { 2673 Slog.w(TAG, "Couldn't clear application caches"); 2674 } 2675 } 2676 if (observer != null) { 2677 try { 2678 observer.onRemoveCompleted(null, (retCode >= 0)); 2679 } catch (RemoteException e) { 2680 Slog.w(TAG, "RemoveException when invoking call back"); 2681 } 2682 } 2683 } 2684 }); 2685 } 2686 2687 @Override 2688 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2689 final IntentSender pi) { 2690 mContext.enforceCallingOrSelfPermission( 2691 android.Manifest.permission.CLEAR_APP_CACHE, null); 2692 // Queue up an async operation since clearing cache may take a little while. 2693 mHandler.post(new Runnable() { 2694 public void run() { 2695 mHandler.removeCallbacks(this); 2696 int retCode = -1; 2697 synchronized (mInstallLock) { 2698 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2699 if (retCode < 0) { 2700 Slog.w(TAG, "Couldn't clear application caches"); 2701 } 2702 } 2703 if(pi != null) { 2704 try { 2705 // Callback via pending intent 2706 int code = (retCode >= 0) ? 1 : 0; 2707 pi.sendIntent(null, code, null, 2708 null, null); 2709 } catch (SendIntentException e1) { 2710 Slog.i(TAG, "Failed to send pending intent"); 2711 } 2712 } 2713 } 2714 }); 2715 } 2716 2717 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2718 synchronized (mInstallLock) { 2719 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2720 throw new IOException("Failed to free enough space"); 2721 } 2722 } 2723 } 2724 2725 @Override 2726 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2727 if (!sUserManager.exists(userId)) return null; 2728 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2729 synchronized (mPackages) { 2730 PackageParser.Activity a = mActivities.mActivities.get(component); 2731 2732 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2733 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2734 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2735 if (ps == null) return null; 2736 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2737 userId); 2738 } 2739 if (mResolveComponentName.equals(component)) { 2740 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2741 new PackageUserState(), userId); 2742 } 2743 } 2744 return null; 2745 } 2746 2747 @Override 2748 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2749 String resolvedType) { 2750 synchronized (mPackages) { 2751 PackageParser.Activity a = mActivities.mActivities.get(component); 2752 if (a == null) { 2753 return false; 2754 } 2755 for (int i=0; i<a.intents.size(); i++) { 2756 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2757 intent.getData(), intent.getCategories(), TAG) >= 0) { 2758 return true; 2759 } 2760 } 2761 return false; 2762 } 2763 } 2764 2765 @Override 2766 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2767 if (!sUserManager.exists(userId)) return null; 2768 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2769 synchronized (mPackages) { 2770 PackageParser.Activity a = mReceivers.mActivities.get(component); 2771 if (DEBUG_PACKAGE_INFO) Log.v( 2772 TAG, "getReceiverInfo " + component + ": " + a); 2773 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2774 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2775 if (ps == null) return null; 2776 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2777 userId); 2778 } 2779 } 2780 return null; 2781 } 2782 2783 @Override 2784 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2785 if (!sUserManager.exists(userId)) return null; 2786 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2787 synchronized (mPackages) { 2788 PackageParser.Service s = mServices.mServices.get(component); 2789 if (DEBUG_PACKAGE_INFO) Log.v( 2790 TAG, "getServiceInfo " + component + ": " + s); 2791 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2792 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2793 if (ps == null) return null; 2794 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2795 userId); 2796 } 2797 } 2798 return null; 2799 } 2800 2801 @Override 2802 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2803 if (!sUserManager.exists(userId)) return null; 2804 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2805 synchronized (mPackages) { 2806 PackageParser.Provider p = mProviders.mProviders.get(component); 2807 if (DEBUG_PACKAGE_INFO) Log.v( 2808 TAG, "getProviderInfo " + component + ": " + p); 2809 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2810 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2811 if (ps == null) return null; 2812 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2813 userId); 2814 } 2815 } 2816 return null; 2817 } 2818 2819 @Override 2820 public String[] getSystemSharedLibraryNames() { 2821 Set<String> libSet; 2822 synchronized (mPackages) { 2823 libSet = mSharedLibraries.keySet(); 2824 int size = libSet.size(); 2825 if (size > 0) { 2826 String[] libs = new String[size]; 2827 libSet.toArray(libs); 2828 return libs; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 /** 2835 * @hide 2836 */ 2837 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2838 synchronized (mPackages) { 2839 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2840 if (lib != null && lib.apk != null) { 2841 return mPackages.get(lib.apk); 2842 } 2843 } 2844 return null; 2845 } 2846 2847 @Override 2848 public FeatureInfo[] getSystemAvailableFeatures() { 2849 Collection<FeatureInfo> featSet; 2850 synchronized (mPackages) { 2851 featSet = mAvailableFeatures.values(); 2852 int size = featSet.size(); 2853 if (size > 0) { 2854 FeatureInfo[] features = new FeatureInfo[size+1]; 2855 featSet.toArray(features); 2856 FeatureInfo fi = new FeatureInfo(); 2857 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2858 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2859 features[size] = fi; 2860 return features; 2861 } 2862 } 2863 return null; 2864 } 2865 2866 @Override 2867 public boolean hasSystemFeature(String name) { 2868 synchronized (mPackages) { 2869 return mAvailableFeatures.containsKey(name); 2870 } 2871 } 2872 2873 private void checkValidCaller(int uid, int userId) { 2874 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2875 return; 2876 2877 throw new SecurityException("Caller uid=" + uid 2878 + " is not privileged to communicate with user=" + userId); 2879 } 2880 2881 @Override 2882 public int checkPermission(String permName, String pkgName, int userId) { 2883 if (!sUserManager.exists(userId)) { 2884 return PackageManager.PERMISSION_DENIED; 2885 } 2886 2887 synchronized (mPackages) { 2888 final PackageParser.Package p = mPackages.get(pkgName); 2889 if (p != null && p.mExtras != null) { 2890 final PackageSetting ps = (PackageSetting) p.mExtras; 2891 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2892 return PackageManager.PERMISSION_GRANTED; 2893 } 2894 } 2895 } 2896 2897 return PackageManager.PERMISSION_DENIED; 2898 } 2899 2900 @Override 2901 public int checkUidPermission(String permName, int uid) { 2902 final int userId = UserHandle.getUserId(uid); 2903 2904 if (!sUserManager.exists(userId)) { 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 synchronized (mPackages) { 2909 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2910 if (obj != null) { 2911 final SettingBase ps = (SettingBase) obj; 2912 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2913 return PackageManager.PERMISSION_GRANTED; 2914 } 2915 } else { 2916 ArraySet<String> perms = mSystemPermissions.get(uid); 2917 if (perms != null && perms.contains(permName)) { 2918 return PackageManager.PERMISSION_GRANTED; 2919 } 2920 } 2921 } 2922 2923 return PackageManager.PERMISSION_DENIED; 2924 } 2925 2926 /** 2927 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2928 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2929 * @param checkShell TODO(yamasani): 2930 * @param message the message to log on security exception 2931 */ 2932 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2933 boolean checkShell, String message) { 2934 if (userId < 0) { 2935 throw new IllegalArgumentException("Invalid userId " + userId); 2936 } 2937 if (checkShell) { 2938 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2939 } 2940 if (userId == UserHandle.getUserId(callingUid)) return; 2941 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2942 if (requireFullPermission) { 2943 mContext.enforceCallingOrSelfPermission( 2944 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2945 } else { 2946 try { 2947 mContext.enforceCallingOrSelfPermission( 2948 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2949 } catch (SecurityException se) { 2950 mContext.enforceCallingOrSelfPermission( 2951 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2952 } 2953 } 2954 } 2955 } 2956 2957 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2958 if (callingUid == Process.SHELL_UID) { 2959 if (userHandle >= 0 2960 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2961 throw new SecurityException("Shell does not have permission to access user " 2962 + userHandle); 2963 } else if (userHandle < 0) { 2964 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2965 + Debug.getCallers(3)); 2966 } 2967 } 2968 } 2969 2970 private BasePermission findPermissionTreeLP(String permName) { 2971 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2972 if (permName.startsWith(bp.name) && 2973 permName.length() > bp.name.length() && 2974 permName.charAt(bp.name.length()) == '.') { 2975 return bp; 2976 } 2977 } 2978 return null; 2979 } 2980 2981 private BasePermission checkPermissionTreeLP(String permName) { 2982 if (permName != null) { 2983 BasePermission bp = findPermissionTreeLP(permName); 2984 if (bp != null) { 2985 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2986 return bp; 2987 } 2988 throw new SecurityException("Calling uid " 2989 + Binder.getCallingUid() 2990 + " is not allowed to add to permission tree " 2991 + bp.name + " owned by uid " + bp.uid); 2992 } 2993 } 2994 throw new SecurityException("No permission tree found for " + permName); 2995 } 2996 2997 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2998 if (s1 == null) { 2999 return s2 == null; 3000 } 3001 if (s2 == null) { 3002 return false; 3003 } 3004 if (s1.getClass() != s2.getClass()) { 3005 return false; 3006 } 3007 return s1.equals(s2); 3008 } 3009 3010 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3011 if (pi1.icon != pi2.icon) return false; 3012 if (pi1.logo != pi2.logo) return false; 3013 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3014 if (!compareStrings(pi1.name, pi2.name)) return false; 3015 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3016 // We'll take care of setting this one. 3017 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3018 // These are not currently stored in settings. 3019 //if (!compareStrings(pi1.group, pi2.group)) return false; 3020 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3021 //if (pi1.labelRes != pi2.labelRes) return false; 3022 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3023 return true; 3024 } 3025 3026 int permissionInfoFootprint(PermissionInfo info) { 3027 int size = info.name.length(); 3028 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3029 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3030 return size; 3031 } 3032 3033 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3034 int size = 0; 3035 for (BasePermission perm : mSettings.mPermissions.values()) { 3036 if (perm.uid == tree.uid) { 3037 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3038 } 3039 } 3040 return size; 3041 } 3042 3043 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3044 // We calculate the max size of permissions defined by this uid and throw 3045 // if that plus the size of 'info' would exceed our stated maximum. 3046 if (tree.uid != Process.SYSTEM_UID) { 3047 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3048 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3049 throw new SecurityException("Permission tree size cap exceeded"); 3050 } 3051 } 3052 } 3053 3054 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3055 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3056 throw new SecurityException("Label must be specified in permission"); 3057 } 3058 BasePermission tree = checkPermissionTreeLP(info.name); 3059 BasePermission bp = mSettings.mPermissions.get(info.name); 3060 boolean added = bp == null; 3061 boolean changed = true; 3062 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3063 if (added) { 3064 enforcePermissionCapLocked(info, tree); 3065 bp = new BasePermission(info.name, tree.sourcePackage, 3066 BasePermission.TYPE_DYNAMIC); 3067 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3068 throw new SecurityException( 3069 "Not allowed to modify non-dynamic permission " 3070 + info.name); 3071 } else { 3072 if (bp.protectionLevel == fixedLevel 3073 && bp.perm.owner.equals(tree.perm.owner) 3074 && bp.uid == tree.uid 3075 && comparePermissionInfos(bp.perm.info, info)) { 3076 changed = false; 3077 } 3078 } 3079 bp.protectionLevel = fixedLevel; 3080 info = new PermissionInfo(info); 3081 info.protectionLevel = fixedLevel; 3082 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3083 bp.perm.info.packageName = tree.perm.info.packageName; 3084 bp.uid = tree.uid; 3085 if (added) { 3086 mSettings.mPermissions.put(info.name, bp); 3087 } 3088 if (changed) { 3089 if (!async) { 3090 mSettings.writeLPr(); 3091 } else { 3092 scheduleWriteSettingsLocked(); 3093 } 3094 } 3095 return added; 3096 } 3097 3098 @Override 3099 public boolean addPermission(PermissionInfo info) { 3100 synchronized (mPackages) { 3101 return addPermissionLocked(info, false); 3102 } 3103 } 3104 3105 @Override 3106 public boolean addPermissionAsync(PermissionInfo info) { 3107 synchronized (mPackages) { 3108 return addPermissionLocked(info, true); 3109 } 3110 } 3111 3112 @Override 3113 public void removePermission(String name) { 3114 synchronized (mPackages) { 3115 checkPermissionTreeLP(name); 3116 BasePermission bp = mSettings.mPermissions.get(name); 3117 if (bp != null) { 3118 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3119 throw new SecurityException( 3120 "Not allowed to modify non-dynamic permission " 3121 + name); 3122 } 3123 mSettings.mPermissions.remove(name); 3124 mSettings.writeLPr(); 3125 } 3126 } 3127 } 3128 3129 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3130 BasePermission bp) { 3131 int index = pkg.requestedPermissions.indexOf(bp.name); 3132 if (index == -1) { 3133 throw new SecurityException("Package " + pkg.packageName 3134 + " has not requested permission " + bp.name); 3135 } 3136 if (!bp.isRuntime()) { 3137 throw new SecurityException("Permission " + bp.name 3138 + " is not a changeable permission type"); 3139 } 3140 } 3141 3142 @Override 3143 public void grantPermission(String packageName, String name, int userId) { 3144 if (!sUserManager.exists(userId)) { 3145 return; 3146 } 3147 3148 mContext.enforceCallingOrSelfPermission( 3149 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3150 "grantPermission"); 3151 3152 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3153 "grantPermission"); 3154 3155 boolean gidsChanged = false; 3156 final SettingBase sb; 3157 3158 synchronized (mPackages) { 3159 final PackageParser.Package pkg = mPackages.get(packageName); 3160 if (pkg == null) { 3161 throw new IllegalArgumentException("Unknown package: " + packageName); 3162 } 3163 3164 final BasePermission bp = mSettings.mPermissions.get(name); 3165 if (bp == null) { 3166 throw new IllegalArgumentException("Unknown permission: " + name); 3167 } 3168 3169 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3170 3171 sb = (SettingBase) pkg.mExtras; 3172 if (sb == null) { 3173 throw new IllegalArgumentException("Unknown package: " + packageName); 3174 } 3175 3176 final PermissionsState permissionsState = sb.getPermissionsState(); 3177 3178 final int result = permissionsState.grantRuntimePermission(bp, userId); 3179 switch (result) { 3180 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3181 return; 3182 } 3183 3184 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3185 gidsChanged = true; 3186 } 3187 break; 3188 } 3189 3190 // Not critical if that is lost - app has to request again. 3191 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3192 } 3193 3194 if (gidsChanged) { 3195 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3196 } 3197 } 3198 3199 @Override 3200 public void revokePermission(String packageName, String name, int userId) { 3201 if (!sUserManager.exists(userId)) { 3202 return; 3203 } 3204 3205 mContext.enforceCallingOrSelfPermission( 3206 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3207 "revokePermission"); 3208 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3210 "revokePermission"); 3211 3212 final SettingBase sb; 3213 3214 synchronized (mPackages) { 3215 final PackageParser.Package pkg = mPackages.get(packageName); 3216 if (pkg == null) { 3217 throw new IllegalArgumentException("Unknown package: " + packageName); 3218 } 3219 3220 final BasePermission bp = mSettings.mPermissions.get(name); 3221 if (bp == null) { 3222 throw new IllegalArgumentException("Unknown permission: " + name); 3223 } 3224 3225 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3226 3227 sb = (SettingBase) pkg.mExtras; 3228 if (sb == null) { 3229 throw new IllegalArgumentException("Unknown package: " + packageName); 3230 } 3231 3232 final PermissionsState permissionsState = sb.getPermissionsState(); 3233 3234 if (permissionsState.revokeRuntimePermission(bp, userId) == 3235 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3236 return; 3237 } 3238 3239 // Critical, after this call all should never have the permission. 3240 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3241 } 3242 3243 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3244 } 3245 3246 @Override 3247 public boolean isProtectedBroadcast(String actionName) { 3248 synchronized (mPackages) { 3249 return mProtectedBroadcasts.contains(actionName); 3250 } 3251 } 3252 3253 @Override 3254 public int checkSignatures(String pkg1, String pkg2) { 3255 synchronized (mPackages) { 3256 final PackageParser.Package p1 = mPackages.get(pkg1); 3257 final PackageParser.Package p2 = mPackages.get(pkg2); 3258 if (p1 == null || p1.mExtras == null 3259 || p2 == null || p2.mExtras == null) { 3260 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3261 } 3262 return compareSignatures(p1.mSignatures, p2.mSignatures); 3263 } 3264 } 3265 3266 @Override 3267 public int checkUidSignatures(int uid1, int uid2) { 3268 // Map to base uids. 3269 uid1 = UserHandle.getAppId(uid1); 3270 uid2 = UserHandle.getAppId(uid2); 3271 // reader 3272 synchronized (mPackages) { 3273 Signature[] s1; 3274 Signature[] s2; 3275 Object obj = mSettings.getUserIdLPr(uid1); 3276 if (obj != null) { 3277 if (obj instanceof SharedUserSetting) { 3278 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3279 } else if (obj instanceof PackageSetting) { 3280 s1 = ((PackageSetting)obj).signatures.mSignatures; 3281 } else { 3282 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3283 } 3284 } else { 3285 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3286 } 3287 obj = mSettings.getUserIdLPr(uid2); 3288 if (obj != null) { 3289 if (obj instanceof SharedUserSetting) { 3290 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3291 } else if (obj instanceof PackageSetting) { 3292 s2 = ((PackageSetting)obj).signatures.mSignatures; 3293 } else { 3294 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3295 } 3296 } else { 3297 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3298 } 3299 return compareSignatures(s1, s2); 3300 } 3301 } 3302 3303 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3304 final long identity = Binder.clearCallingIdentity(); 3305 try { 3306 if (sb instanceof SharedUserSetting) { 3307 SharedUserSetting sus = (SharedUserSetting) sb; 3308 final int packageCount = sus.packages.size(); 3309 for (int i = 0; i < packageCount; i++) { 3310 PackageSetting susPs = sus.packages.valueAt(i); 3311 if (userId == UserHandle.USER_ALL) { 3312 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3313 } else { 3314 final int uid = UserHandle.getUid(userId, susPs.appId); 3315 killUid(uid, reason); 3316 } 3317 } 3318 } else if (sb instanceof PackageSetting) { 3319 PackageSetting ps = (PackageSetting) sb; 3320 if (userId == UserHandle.USER_ALL) { 3321 killApplication(ps.pkg.packageName, ps.appId, reason); 3322 } else { 3323 final int uid = UserHandle.getUid(userId, ps.appId); 3324 killUid(uid, reason); 3325 } 3326 } 3327 } finally { 3328 Binder.restoreCallingIdentity(identity); 3329 } 3330 } 3331 3332 private static void killUid(int uid, String reason) { 3333 IActivityManager am = ActivityManagerNative.getDefault(); 3334 if (am != null) { 3335 try { 3336 am.killUid(uid, reason); 3337 } catch (RemoteException e) { 3338 /* ignore - same process */ 3339 } 3340 } 3341 } 3342 3343 /** 3344 * Compares two sets of signatures. Returns: 3345 * <br /> 3346 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3347 * <br /> 3348 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3349 * <br /> 3350 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3351 * <br /> 3352 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3353 * <br /> 3354 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3355 */ 3356 static int compareSignatures(Signature[] s1, Signature[] s2) { 3357 if (s1 == null) { 3358 return s2 == null 3359 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3360 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3361 } 3362 3363 if (s2 == null) { 3364 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3365 } 3366 3367 if (s1.length != s2.length) { 3368 return PackageManager.SIGNATURE_NO_MATCH; 3369 } 3370 3371 // Since both signature sets are of size 1, we can compare without HashSets. 3372 if (s1.length == 1) { 3373 return s1[0].equals(s2[0]) ? 3374 PackageManager.SIGNATURE_MATCH : 3375 PackageManager.SIGNATURE_NO_MATCH; 3376 } 3377 3378 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3379 for (Signature sig : s1) { 3380 set1.add(sig); 3381 } 3382 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3383 for (Signature sig : s2) { 3384 set2.add(sig); 3385 } 3386 // Make sure s2 contains all signatures in s1. 3387 if (set1.equals(set2)) { 3388 return PackageManager.SIGNATURE_MATCH; 3389 } 3390 return PackageManager.SIGNATURE_NO_MATCH; 3391 } 3392 3393 /** 3394 * If the database version for this type of package (internal storage or 3395 * external storage) is less than the version where package signatures 3396 * were updated, return true. 3397 */ 3398 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3399 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3400 DatabaseVersion.SIGNATURE_END_ENTITY)) 3401 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3402 DatabaseVersion.SIGNATURE_END_ENTITY)); 3403 } 3404 3405 /** 3406 * Used for backward compatibility to make sure any packages with 3407 * certificate chains get upgraded to the new style. {@code existingSigs} 3408 * will be in the old format (since they were stored on disk from before the 3409 * system upgrade) and {@code scannedSigs} will be in the newer format. 3410 */ 3411 private int compareSignaturesCompat(PackageSignatures existingSigs, 3412 PackageParser.Package scannedPkg) { 3413 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3414 return PackageManager.SIGNATURE_NO_MATCH; 3415 } 3416 3417 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3418 for (Signature sig : existingSigs.mSignatures) { 3419 existingSet.add(sig); 3420 } 3421 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3422 for (Signature sig : scannedPkg.mSignatures) { 3423 try { 3424 Signature[] chainSignatures = sig.getChainSignatures(); 3425 for (Signature chainSig : chainSignatures) { 3426 scannedCompatSet.add(chainSig); 3427 } 3428 } catch (CertificateEncodingException e) { 3429 scannedCompatSet.add(sig); 3430 } 3431 } 3432 /* 3433 * Make sure the expanded scanned set contains all signatures in the 3434 * existing one. 3435 */ 3436 if (scannedCompatSet.equals(existingSet)) { 3437 // Migrate the old signatures to the new scheme. 3438 existingSigs.assignSignatures(scannedPkg.mSignatures); 3439 // The new KeySets will be re-added later in the scanning process. 3440 synchronized (mPackages) { 3441 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3442 } 3443 return PackageManager.SIGNATURE_MATCH; 3444 } 3445 return PackageManager.SIGNATURE_NO_MATCH; 3446 } 3447 3448 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3449 if (isExternal(scannedPkg)) { 3450 return mSettings.isExternalDatabaseVersionOlderThan( 3451 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3452 } else { 3453 return mSettings.isInternalDatabaseVersionOlderThan( 3454 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3455 } 3456 } 3457 3458 private int compareSignaturesRecover(PackageSignatures existingSigs, 3459 PackageParser.Package scannedPkg) { 3460 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3461 return PackageManager.SIGNATURE_NO_MATCH; 3462 } 3463 3464 String msg = null; 3465 try { 3466 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3467 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3468 + scannedPkg.packageName); 3469 return PackageManager.SIGNATURE_MATCH; 3470 } 3471 } catch (CertificateException e) { 3472 msg = e.getMessage(); 3473 } 3474 3475 logCriticalInfo(Log.INFO, 3476 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3477 return PackageManager.SIGNATURE_NO_MATCH; 3478 } 3479 3480 @Override 3481 public String[] getPackagesForUid(int uid) { 3482 uid = UserHandle.getAppId(uid); 3483 // reader 3484 synchronized (mPackages) { 3485 Object obj = mSettings.getUserIdLPr(uid); 3486 if (obj instanceof SharedUserSetting) { 3487 final SharedUserSetting sus = (SharedUserSetting) obj; 3488 final int N = sus.packages.size(); 3489 final String[] res = new String[N]; 3490 final Iterator<PackageSetting> it = sus.packages.iterator(); 3491 int i = 0; 3492 while (it.hasNext()) { 3493 res[i++] = it.next().name; 3494 } 3495 return res; 3496 } else if (obj instanceof PackageSetting) { 3497 final PackageSetting ps = (PackageSetting) obj; 3498 return new String[] { ps.name }; 3499 } 3500 } 3501 return null; 3502 } 3503 3504 @Override 3505 public String getNameForUid(int uid) { 3506 // reader 3507 synchronized (mPackages) { 3508 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3509 if (obj instanceof SharedUserSetting) { 3510 final SharedUserSetting sus = (SharedUserSetting) obj; 3511 return sus.name + ":" + sus.userId; 3512 } else if (obj instanceof PackageSetting) { 3513 final PackageSetting ps = (PackageSetting) obj; 3514 return ps.name; 3515 } 3516 } 3517 return null; 3518 } 3519 3520 @Override 3521 public int getUidForSharedUser(String sharedUserName) { 3522 if(sharedUserName == null) { 3523 return -1; 3524 } 3525 // reader 3526 synchronized (mPackages) { 3527 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3528 if (suid == null) { 3529 return -1; 3530 } 3531 return suid.userId; 3532 } 3533 } 3534 3535 @Override 3536 public int getFlagsForUid(int uid) { 3537 synchronized (mPackages) { 3538 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3539 if (obj instanceof SharedUserSetting) { 3540 final SharedUserSetting sus = (SharedUserSetting) obj; 3541 return sus.pkgFlags; 3542 } else if (obj instanceof PackageSetting) { 3543 final PackageSetting ps = (PackageSetting) obj; 3544 return ps.pkgFlags; 3545 } 3546 } 3547 return 0; 3548 } 3549 3550 @Override 3551 public int getPrivateFlagsForUid(int uid) { 3552 synchronized (mPackages) { 3553 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3554 if (obj instanceof SharedUserSetting) { 3555 final SharedUserSetting sus = (SharedUserSetting) obj; 3556 return sus.pkgPrivateFlags; 3557 } else if (obj instanceof PackageSetting) { 3558 final PackageSetting ps = (PackageSetting) obj; 3559 return ps.pkgPrivateFlags; 3560 } 3561 } 3562 return 0; 3563 } 3564 3565 @Override 3566 public boolean isUidPrivileged(int uid) { 3567 uid = UserHandle.getAppId(uid); 3568 // reader 3569 synchronized (mPackages) { 3570 Object obj = mSettings.getUserIdLPr(uid); 3571 if (obj instanceof SharedUserSetting) { 3572 final SharedUserSetting sus = (SharedUserSetting) obj; 3573 final Iterator<PackageSetting> it = sus.packages.iterator(); 3574 while (it.hasNext()) { 3575 if (it.next().isPrivileged()) { 3576 return true; 3577 } 3578 } 3579 } else if (obj instanceof PackageSetting) { 3580 final PackageSetting ps = (PackageSetting) obj; 3581 return ps.isPrivileged(); 3582 } 3583 } 3584 return false; 3585 } 3586 3587 @Override 3588 public String[] getAppOpPermissionPackages(String permissionName) { 3589 synchronized (mPackages) { 3590 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3591 if (pkgs == null) { 3592 return null; 3593 } 3594 return pkgs.toArray(new String[pkgs.size()]); 3595 } 3596 } 3597 3598 @Override 3599 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3600 int flags, int userId) { 3601 if (!sUserManager.exists(userId)) return null; 3602 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3603 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3604 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3605 } 3606 3607 @Override 3608 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3609 IntentFilter filter, int match, ComponentName activity) { 3610 final int userId = UserHandle.getCallingUserId(); 3611 if (DEBUG_PREFERRED) { 3612 Log.v(TAG, "setLastChosenActivity intent=" + intent 3613 + " resolvedType=" + resolvedType 3614 + " flags=" + flags 3615 + " filter=" + filter 3616 + " match=" + match 3617 + " activity=" + activity); 3618 filter.dump(new PrintStreamPrinter(System.out), " "); 3619 } 3620 intent.setComponent(null); 3621 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3622 // Find any earlier preferred or last chosen entries and nuke them 3623 findPreferredActivity(intent, resolvedType, 3624 flags, query, 0, false, true, false, userId); 3625 // Add the new activity as the last chosen for this filter 3626 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3627 "Setting last chosen"); 3628 } 3629 3630 @Override 3631 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3632 final int userId = UserHandle.getCallingUserId(); 3633 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3634 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3635 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3636 false, false, false, userId); 3637 } 3638 3639 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3640 int flags, List<ResolveInfo> query, int userId) { 3641 if (query != null) { 3642 final int N = query.size(); 3643 if (N == 1) { 3644 return query.get(0); 3645 } else if (N > 1) { 3646 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3647 // If there is more than one activity with the same priority, 3648 // then let the user decide between them. 3649 ResolveInfo r0 = query.get(0); 3650 ResolveInfo r1 = query.get(1); 3651 if (DEBUG_INTENT_MATCHING || debug) { 3652 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3653 + r1.activityInfo.name + "=" + r1.priority); 3654 } 3655 // If the first activity has a higher priority, or a different 3656 // default, then it is always desireable to pick it. 3657 if (r0.priority != r1.priority 3658 || r0.preferredOrder != r1.preferredOrder 3659 || r0.isDefault != r1.isDefault) { 3660 return query.get(0); 3661 } 3662 // If we have saved a preference for a preferred activity for 3663 // this Intent, use that. 3664 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3665 flags, query, r0.priority, true, false, debug, userId); 3666 if (ri != null) { 3667 return ri; 3668 } 3669 if (userId != 0) { 3670 ri = new ResolveInfo(mResolveInfo); 3671 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3672 ri.activityInfo.applicationInfo = new ApplicationInfo( 3673 ri.activityInfo.applicationInfo); 3674 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3675 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3676 return ri; 3677 } 3678 return mResolveInfo; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3685 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3686 final int N = query.size(); 3687 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3688 .get(userId); 3689 // Get the list of persistent preferred activities that handle the intent 3690 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3691 List<PersistentPreferredActivity> pprefs = ppir != null 3692 ? ppir.queryIntent(intent, resolvedType, 3693 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3694 : null; 3695 if (pprefs != null && pprefs.size() > 0) { 3696 final int M = pprefs.size(); 3697 for (int i=0; i<M; i++) { 3698 final PersistentPreferredActivity ppa = pprefs.get(i); 3699 if (DEBUG_PREFERRED || debug) { 3700 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3701 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3702 + "\n component=" + ppa.mComponent); 3703 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3704 } 3705 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3706 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3707 if (DEBUG_PREFERRED || debug) { 3708 Slog.v(TAG, "Found persistent preferred activity:"); 3709 if (ai != null) { 3710 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3711 } else { 3712 Slog.v(TAG, " null"); 3713 } 3714 } 3715 if (ai == null) { 3716 // This previously registered persistent preferred activity 3717 // component is no longer known. Ignore it and do NOT remove it. 3718 continue; 3719 } 3720 for (int j=0; j<N; j++) { 3721 final ResolveInfo ri = query.get(j); 3722 if (!ri.activityInfo.applicationInfo.packageName 3723 .equals(ai.applicationInfo.packageName)) { 3724 continue; 3725 } 3726 if (!ri.activityInfo.name.equals(ai.name)) { 3727 continue; 3728 } 3729 // Found a persistent preference that can handle the intent. 3730 if (DEBUG_PREFERRED || debug) { 3731 Slog.v(TAG, "Returning persistent preferred activity: " + 3732 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3733 } 3734 return ri; 3735 } 3736 } 3737 } 3738 return null; 3739 } 3740 3741 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3742 List<ResolveInfo> query, int priority, boolean always, 3743 boolean removeMatches, boolean debug, int userId) { 3744 if (!sUserManager.exists(userId)) return null; 3745 // writer 3746 synchronized (mPackages) { 3747 if (intent.getSelector() != null) { 3748 intent = intent.getSelector(); 3749 } 3750 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3751 3752 // Try to find a matching persistent preferred activity. 3753 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3754 debug, userId); 3755 3756 // If a persistent preferred activity matched, use it. 3757 if (pri != null) { 3758 return pri; 3759 } 3760 3761 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3762 // Get the list of preferred activities that handle the intent 3763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3764 List<PreferredActivity> prefs = pir != null 3765 ? pir.queryIntent(intent, resolvedType, 3766 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3767 : null; 3768 if (prefs != null && prefs.size() > 0) { 3769 boolean changed = false; 3770 try { 3771 // First figure out how good the original match set is. 3772 // We will only allow preferred activities that came 3773 // from the same match quality. 3774 int match = 0; 3775 3776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3777 3778 final int N = query.size(); 3779 for (int j=0; j<N; j++) { 3780 final ResolveInfo ri = query.get(j); 3781 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3782 + ": 0x" + Integer.toHexString(match)); 3783 if (ri.match > match) { 3784 match = ri.match; 3785 } 3786 } 3787 3788 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3789 + Integer.toHexString(match)); 3790 3791 match &= IntentFilter.MATCH_CATEGORY_MASK; 3792 final int M = prefs.size(); 3793 for (int i=0; i<M; i++) { 3794 final PreferredActivity pa = prefs.get(i); 3795 if (DEBUG_PREFERRED || debug) { 3796 Slog.v(TAG, "Checking PreferredActivity ds=" 3797 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3798 + "\n component=" + pa.mPref.mComponent); 3799 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3800 } 3801 if (pa.mPref.mMatch != match) { 3802 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3803 + Integer.toHexString(pa.mPref.mMatch)); 3804 continue; 3805 } 3806 // If it's not an "always" type preferred activity and that's what we're 3807 // looking for, skip it. 3808 if (always && !pa.mPref.mAlways) { 3809 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3810 continue; 3811 } 3812 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3813 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3814 if (DEBUG_PREFERRED || debug) { 3815 Slog.v(TAG, "Found preferred activity:"); 3816 if (ai != null) { 3817 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3818 } else { 3819 Slog.v(TAG, " null"); 3820 } 3821 } 3822 if (ai == null) { 3823 // This previously registered preferred activity 3824 // component is no longer known. Most likely an update 3825 // to the app was installed and in the new version this 3826 // component no longer exists. Clean it up by removing 3827 // it from the preferred activities list, and skip it. 3828 Slog.w(TAG, "Removing dangling preferred activity: " 3829 + pa.mPref.mComponent); 3830 pir.removeFilter(pa); 3831 changed = true; 3832 continue; 3833 } 3834 for (int j=0; j<N; j++) { 3835 final ResolveInfo ri = query.get(j); 3836 if (!ri.activityInfo.applicationInfo.packageName 3837 .equals(ai.applicationInfo.packageName)) { 3838 continue; 3839 } 3840 if (!ri.activityInfo.name.equals(ai.name)) { 3841 continue; 3842 } 3843 3844 if (removeMatches) { 3845 pir.removeFilter(pa); 3846 changed = true; 3847 if (DEBUG_PREFERRED) { 3848 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3849 } 3850 break; 3851 } 3852 3853 // Okay we found a previously set preferred or last chosen app. 3854 // If the result set is different from when this 3855 // was created, we need to clear it and re-ask the 3856 // user their preference, if we're looking for an "always" type entry. 3857 if (always && !pa.mPref.sameSet(query)) { 3858 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3859 + intent + " type " + resolvedType); 3860 if (DEBUG_PREFERRED) { 3861 Slog.v(TAG, "Removing preferred activity since set changed " 3862 + pa.mPref.mComponent); 3863 } 3864 pir.removeFilter(pa); 3865 // Re-add the filter as a "last chosen" entry (!always) 3866 PreferredActivity lastChosen = new PreferredActivity( 3867 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3868 pir.addFilter(lastChosen); 3869 changed = true; 3870 return null; 3871 } 3872 3873 // Yay! Either the set matched or we're looking for the last chosen 3874 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3875 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3876 return ri; 3877 } 3878 } 3879 } finally { 3880 if (changed) { 3881 if (DEBUG_PREFERRED) { 3882 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3883 } 3884 scheduleWritePackageRestrictionsLocked(userId); 3885 } 3886 } 3887 } 3888 } 3889 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3890 return null; 3891 } 3892 3893 /* 3894 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3895 */ 3896 @Override 3897 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3898 int targetUserId) { 3899 mContext.enforceCallingOrSelfPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3901 List<CrossProfileIntentFilter> matches = 3902 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3903 if (matches != null) { 3904 int size = matches.size(); 3905 for (int i = 0; i < size; i++) { 3906 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3907 } 3908 } 3909 return false; 3910 } 3911 3912 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3913 String resolvedType, int userId) { 3914 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3915 if (resolver != null) { 3916 return resolver.queryIntent(intent, resolvedType, false, userId); 3917 } 3918 return null; 3919 } 3920 3921 @Override 3922 public List<ResolveInfo> queryIntentActivities(Intent intent, 3923 String resolvedType, int flags, int userId) { 3924 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3925 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3926 ComponentName comp = intent.getComponent(); 3927 if (comp == null) { 3928 if (intent.getSelector() != null) { 3929 intent = intent.getSelector(); 3930 comp = intent.getComponent(); 3931 } 3932 } 3933 3934 if (comp != null) { 3935 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3936 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3937 if (ai != null) { 3938 final ResolveInfo ri = new ResolveInfo(); 3939 ri.activityInfo = ai; 3940 list.add(ri); 3941 } 3942 return list; 3943 } 3944 3945 // reader 3946 synchronized (mPackages) { 3947 final String pkgName = intent.getPackage(); 3948 if (pkgName == null) { 3949 List<CrossProfileIntentFilter> matchingFilters = 3950 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3951 // Check for results that need to skip the current profile. 3952 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3953 resolvedType, flags, userId); 3954 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3955 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3956 result.add(resolveInfo); 3957 return filterIfNotPrimaryUser(result, userId); 3958 } 3959 3960 // Check for results in the current profile. 3961 List<ResolveInfo> result = mActivities.queryIntent( 3962 intent, resolvedType, flags, userId); 3963 3964 // Check for cross profile results. 3965 resolveInfo = queryCrossProfileIntents( 3966 matchingFilters, intent, resolvedType, flags, userId); 3967 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3968 result.add(resolveInfo); 3969 Collections.sort(result, mResolvePrioritySorter); 3970 } 3971 result = filterIfNotPrimaryUser(result, userId); 3972 if (result.size() > 1 && hasWebURI(intent)) { 3973 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3974 } 3975 return result; 3976 } 3977 final PackageParser.Package pkg = mPackages.get(pkgName); 3978 if (pkg != null) { 3979 return filterIfNotPrimaryUser( 3980 mActivities.queryIntentForPackage( 3981 intent, resolvedType, flags, pkg.activities, userId), 3982 userId); 3983 } 3984 return new ArrayList<ResolveInfo>(); 3985 } 3986 } 3987 3988 private boolean isUserEnabled(int userId) { 3989 long callingId = Binder.clearCallingIdentity(); 3990 try { 3991 UserInfo userInfo = sUserManager.getUserInfo(userId); 3992 return userInfo != null && userInfo.isEnabled(); 3993 } finally { 3994 Binder.restoreCallingIdentity(callingId); 3995 } 3996 } 3997 3998 /** 3999 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4000 * 4001 * @return filtered list 4002 */ 4003 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4004 if (userId == UserHandle.USER_OWNER) { 4005 return resolveInfos; 4006 } 4007 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4008 ResolveInfo info = resolveInfos.get(i); 4009 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4010 resolveInfos.remove(i); 4011 } 4012 } 4013 return resolveInfos; 4014 } 4015 4016 private static boolean hasWebURI(Intent intent) { 4017 if (intent.getData() == null) { 4018 return false; 4019 } 4020 final String scheme = intent.getScheme(); 4021 if (TextUtils.isEmpty(scheme)) { 4022 return false; 4023 } 4024 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4025 } 4026 4027 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4028 int flags, List<ResolveInfo> candidates) { 4029 if (DEBUG_PREFERRED) { 4030 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4031 candidates.size()); 4032 } 4033 4034 final int userId = UserHandle.getCallingUserId(); 4035 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4036 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4037 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4038 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4039 4040 synchronized (mPackages) { 4041 final int count = candidates.size(); 4042 // First, try to use the domain prefered App 4043 for (int n=0; n<count; n++) { 4044 ResolveInfo info = candidates.get(n); 4045 String packageName = info.activityInfo.packageName; 4046 PackageSetting ps = mSettings.mPackages.get(packageName); 4047 if (ps != null) { 4048 // Add to the special match all list (Browser use case) 4049 if (info.handleAllWebDataURI) { 4050 matchAllList.add(info); 4051 continue; 4052 } 4053 // Try to get the status from User settings first 4054 int status = getDomainVerificationStatusLPr(ps, userId); 4055 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4056 result.add(info); 4057 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4058 neverList.add(info); 4059 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4060 undefinedList.add(info); 4061 } 4062 } 4063 } 4064 // If there is nothing selected, add all candidates and remove the ones that the User 4065 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4066 // also remove any Browser Apps ones. 4067 // If there is still none after this pass, add all undefined one and Browser Apps and 4068 // let the User decide with the Disambiguation dialog if there are several ones. 4069 if (result.size() == 0) { 4070 result.addAll(candidates); 4071 } 4072 result.removeAll(neverList); 4073 result.removeAll(matchAllList); 4074 if (result.size() == 0) { 4075 result.addAll(undefinedList); 4076 if ((flags & MATCH_ALL) != 0) { 4077 result.addAll(matchAllList); 4078 } else { 4079 // Try to add the Default Browser if we can 4080 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4081 UserHandle.myUserId()); 4082 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4083 boolean defaultBrowserFound = false; 4084 final int browserCount = matchAllList.size(); 4085 for (int n=0; n<browserCount; n++) { 4086 ResolveInfo browser = matchAllList.get(n); 4087 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4088 result.add(browser); 4089 defaultBrowserFound = true; 4090 break; 4091 } 4092 } 4093 if (!defaultBrowserFound) { 4094 result.addAll(matchAllList); 4095 } 4096 } else { 4097 result.addAll(matchAllList); 4098 } 4099 } 4100 } 4101 } 4102 if (DEBUG_PREFERRED) { 4103 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4104 result.size()); 4105 } 4106 return result; 4107 } 4108 4109 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4110 int status = ps.getDomainVerificationStatusForUser(userId); 4111 // if none available, get the master status 4112 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4113 if (ps.getIntentFilterVerificationInfo() != null) { 4114 status = ps.getIntentFilterVerificationInfo().getStatus(); 4115 } 4116 } 4117 return status; 4118 } 4119 4120 private ResolveInfo querySkipCurrentProfileIntents( 4121 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4122 int flags, int sourceUserId) { 4123 if (matchingFilters != null) { 4124 int size = matchingFilters.size(); 4125 for (int i = 0; i < size; i ++) { 4126 CrossProfileIntentFilter filter = matchingFilters.get(i); 4127 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4128 // Checking if there are activities in the target user that can handle the 4129 // intent. 4130 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4131 flags, sourceUserId); 4132 if (resolveInfo != null) { 4133 return resolveInfo; 4134 } 4135 } 4136 } 4137 } 4138 return null; 4139 } 4140 4141 // Return matching ResolveInfo if any for skip current profile intent filters. 4142 private ResolveInfo queryCrossProfileIntents( 4143 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4144 int flags, int sourceUserId) { 4145 if (matchingFilters != null) { 4146 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4147 // match the same intent. For performance reasons, it is better not to 4148 // run queryIntent twice for the same userId 4149 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4150 int size = matchingFilters.size(); 4151 for (int i = 0; i < size; i++) { 4152 CrossProfileIntentFilter filter = matchingFilters.get(i); 4153 int targetUserId = filter.getTargetUserId(); 4154 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4155 && !alreadyTriedUserIds.get(targetUserId)) { 4156 // Checking if there are activities in the target user that can handle the 4157 // intent. 4158 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4159 flags, sourceUserId); 4160 if (resolveInfo != null) return resolveInfo; 4161 alreadyTriedUserIds.put(targetUserId, true); 4162 } 4163 } 4164 } 4165 return null; 4166 } 4167 4168 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4169 String resolvedType, int flags, int sourceUserId) { 4170 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4171 resolvedType, flags, filter.getTargetUserId()); 4172 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4173 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4174 } 4175 return null; 4176 } 4177 4178 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4179 int sourceUserId, int targetUserId) { 4180 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4181 String className; 4182 if (targetUserId == UserHandle.USER_OWNER) { 4183 className = FORWARD_INTENT_TO_USER_OWNER; 4184 } else { 4185 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4186 } 4187 ComponentName forwardingActivityComponentName = new ComponentName( 4188 mAndroidApplication.packageName, className); 4189 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4190 sourceUserId); 4191 if (targetUserId == UserHandle.USER_OWNER) { 4192 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4193 forwardingResolveInfo.noResourceId = true; 4194 } 4195 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4196 forwardingResolveInfo.priority = 0; 4197 forwardingResolveInfo.preferredOrder = 0; 4198 forwardingResolveInfo.match = 0; 4199 forwardingResolveInfo.isDefault = true; 4200 forwardingResolveInfo.filter = filter; 4201 forwardingResolveInfo.targetUserId = targetUserId; 4202 return forwardingResolveInfo; 4203 } 4204 4205 @Override 4206 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4207 Intent[] specifics, String[] specificTypes, Intent intent, 4208 String resolvedType, int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4211 false, "query intent activity options"); 4212 final String resultsAction = intent.getAction(); 4213 4214 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4215 | PackageManager.GET_RESOLVED_FILTER, userId); 4216 4217 if (DEBUG_INTENT_MATCHING) { 4218 Log.v(TAG, "Query " + intent + ": " + results); 4219 } 4220 4221 int specificsPos = 0; 4222 int N; 4223 4224 // todo: note that the algorithm used here is O(N^2). This 4225 // isn't a problem in our current environment, but if we start running 4226 // into situations where we have more than 5 or 10 matches then this 4227 // should probably be changed to something smarter... 4228 4229 // First we go through and resolve each of the specific items 4230 // that were supplied, taking care of removing any corresponding 4231 // duplicate items in the generic resolve list. 4232 if (specifics != null) { 4233 for (int i=0; i<specifics.length; i++) { 4234 final Intent sintent = specifics[i]; 4235 if (sintent == null) { 4236 continue; 4237 } 4238 4239 if (DEBUG_INTENT_MATCHING) { 4240 Log.v(TAG, "Specific #" + i + ": " + sintent); 4241 } 4242 4243 String action = sintent.getAction(); 4244 if (resultsAction != null && resultsAction.equals(action)) { 4245 // If this action was explicitly requested, then don't 4246 // remove things that have it. 4247 action = null; 4248 } 4249 4250 ResolveInfo ri = null; 4251 ActivityInfo ai = null; 4252 4253 ComponentName comp = sintent.getComponent(); 4254 if (comp == null) { 4255 ri = resolveIntent( 4256 sintent, 4257 specificTypes != null ? specificTypes[i] : null, 4258 flags, userId); 4259 if (ri == null) { 4260 continue; 4261 } 4262 if (ri == mResolveInfo) { 4263 // ACK! Must do something better with this. 4264 } 4265 ai = ri.activityInfo; 4266 comp = new ComponentName(ai.applicationInfo.packageName, 4267 ai.name); 4268 } else { 4269 ai = getActivityInfo(comp, flags, userId); 4270 if (ai == null) { 4271 continue; 4272 } 4273 } 4274 4275 // Look for any generic query activities that are duplicates 4276 // of this specific one, and remove them from the results. 4277 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4278 N = results.size(); 4279 int j; 4280 for (j=specificsPos; j<N; j++) { 4281 ResolveInfo sri = results.get(j); 4282 if ((sri.activityInfo.name.equals(comp.getClassName()) 4283 && sri.activityInfo.applicationInfo.packageName.equals( 4284 comp.getPackageName())) 4285 || (action != null && sri.filter.matchAction(action))) { 4286 results.remove(j); 4287 if (DEBUG_INTENT_MATCHING) Log.v( 4288 TAG, "Removing duplicate item from " + j 4289 + " due to specific " + specificsPos); 4290 if (ri == null) { 4291 ri = sri; 4292 } 4293 j--; 4294 N--; 4295 } 4296 } 4297 4298 // Add this specific item to its proper place. 4299 if (ri == null) { 4300 ri = new ResolveInfo(); 4301 ri.activityInfo = ai; 4302 } 4303 results.add(specificsPos, ri); 4304 ri.specificIndex = i; 4305 specificsPos++; 4306 } 4307 } 4308 4309 // Now we go through the remaining generic results and remove any 4310 // duplicate actions that are found here. 4311 N = results.size(); 4312 for (int i=specificsPos; i<N-1; i++) { 4313 final ResolveInfo rii = results.get(i); 4314 if (rii.filter == null) { 4315 continue; 4316 } 4317 4318 // Iterate over all of the actions of this result's intent 4319 // filter... typically this should be just one. 4320 final Iterator<String> it = rii.filter.actionsIterator(); 4321 if (it == null) { 4322 continue; 4323 } 4324 while (it.hasNext()) { 4325 final String action = it.next(); 4326 if (resultsAction != null && resultsAction.equals(action)) { 4327 // If this action was explicitly requested, then don't 4328 // remove things that have it. 4329 continue; 4330 } 4331 for (int j=i+1; j<N; j++) { 4332 final ResolveInfo rij = results.get(j); 4333 if (rij.filter != null && rij.filter.hasAction(action)) { 4334 results.remove(j); 4335 if (DEBUG_INTENT_MATCHING) Log.v( 4336 TAG, "Removing duplicate item from " + j 4337 + " due to action " + action + " at " + i); 4338 j--; 4339 N--; 4340 } 4341 } 4342 } 4343 4344 // If the caller didn't request filter information, drop it now 4345 // so we don't have to marshall/unmarshall it. 4346 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4347 rii.filter = null; 4348 } 4349 } 4350 4351 // Filter out the caller activity if so requested. 4352 if (caller != null) { 4353 N = results.size(); 4354 for (int i=0; i<N; i++) { 4355 ActivityInfo ainfo = results.get(i).activityInfo; 4356 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4357 && caller.getClassName().equals(ainfo.name)) { 4358 results.remove(i); 4359 break; 4360 } 4361 } 4362 } 4363 4364 // If the caller didn't request filter information, 4365 // drop them now so we don't have to 4366 // marshall/unmarshall it. 4367 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4368 N = results.size(); 4369 for (int i=0; i<N; i++) { 4370 results.get(i).filter = null; 4371 } 4372 } 4373 4374 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4375 return results; 4376 } 4377 4378 @Override 4379 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4380 int userId) { 4381 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4382 ComponentName comp = intent.getComponent(); 4383 if (comp == null) { 4384 if (intent.getSelector() != null) { 4385 intent = intent.getSelector(); 4386 comp = intent.getComponent(); 4387 } 4388 } 4389 if (comp != null) { 4390 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4391 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4392 if (ai != null) { 4393 ResolveInfo ri = new ResolveInfo(); 4394 ri.activityInfo = ai; 4395 list.add(ri); 4396 } 4397 return list; 4398 } 4399 4400 // reader 4401 synchronized (mPackages) { 4402 String pkgName = intent.getPackage(); 4403 if (pkgName == null) { 4404 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4405 } 4406 final PackageParser.Package pkg = mPackages.get(pkgName); 4407 if (pkg != null) { 4408 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4409 userId); 4410 } 4411 return null; 4412 } 4413 } 4414 4415 @Override 4416 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4417 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4418 if (!sUserManager.exists(userId)) return null; 4419 if (query != null) { 4420 if (query.size() >= 1) { 4421 // If there is more than one service with the same priority, 4422 // just arbitrarily pick the first one. 4423 return query.get(0); 4424 } 4425 } 4426 return null; 4427 } 4428 4429 @Override 4430 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4431 int userId) { 4432 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4433 ComponentName comp = intent.getComponent(); 4434 if (comp == null) { 4435 if (intent.getSelector() != null) { 4436 intent = intent.getSelector(); 4437 comp = intent.getComponent(); 4438 } 4439 } 4440 if (comp != null) { 4441 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4442 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4443 if (si != null) { 4444 final ResolveInfo ri = new ResolveInfo(); 4445 ri.serviceInfo = si; 4446 list.add(ri); 4447 } 4448 return list; 4449 } 4450 4451 // reader 4452 synchronized (mPackages) { 4453 String pkgName = intent.getPackage(); 4454 if (pkgName == null) { 4455 return mServices.queryIntent(intent, resolvedType, flags, userId); 4456 } 4457 final PackageParser.Package pkg = mPackages.get(pkgName); 4458 if (pkg != null) { 4459 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4460 userId); 4461 } 4462 return null; 4463 } 4464 } 4465 4466 @Override 4467 public List<ResolveInfo> queryIntentContentProviders( 4468 Intent intent, String resolvedType, int flags, int userId) { 4469 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4470 ComponentName comp = intent.getComponent(); 4471 if (comp == null) { 4472 if (intent.getSelector() != null) { 4473 intent = intent.getSelector(); 4474 comp = intent.getComponent(); 4475 } 4476 } 4477 if (comp != null) { 4478 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4479 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4480 if (pi != null) { 4481 final ResolveInfo ri = new ResolveInfo(); 4482 ri.providerInfo = pi; 4483 list.add(ri); 4484 } 4485 return list; 4486 } 4487 4488 // reader 4489 synchronized (mPackages) { 4490 String pkgName = intent.getPackage(); 4491 if (pkgName == null) { 4492 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4493 } 4494 final PackageParser.Package pkg = mPackages.get(pkgName); 4495 if (pkg != null) { 4496 return mProviders.queryIntentForPackage( 4497 intent, resolvedType, flags, pkg.providers, userId); 4498 } 4499 return null; 4500 } 4501 } 4502 4503 @Override 4504 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4505 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4506 4507 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4508 4509 // writer 4510 synchronized (mPackages) { 4511 ArrayList<PackageInfo> list; 4512 if (listUninstalled) { 4513 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4514 for (PackageSetting ps : mSettings.mPackages.values()) { 4515 PackageInfo pi; 4516 if (ps.pkg != null) { 4517 pi = generatePackageInfo(ps.pkg, flags, userId); 4518 } else { 4519 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4520 } 4521 if (pi != null) { 4522 list.add(pi); 4523 } 4524 } 4525 } else { 4526 list = new ArrayList<PackageInfo>(mPackages.size()); 4527 for (PackageParser.Package p : mPackages.values()) { 4528 PackageInfo pi = generatePackageInfo(p, flags, userId); 4529 if (pi != null) { 4530 list.add(pi); 4531 } 4532 } 4533 } 4534 4535 return new ParceledListSlice<PackageInfo>(list); 4536 } 4537 } 4538 4539 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4540 String[] permissions, boolean[] tmp, int flags, int userId) { 4541 int numMatch = 0; 4542 final PermissionsState permissionsState = ps.getPermissionsState(); 4543 for (int i=0; i<permissions.length; i++) { 4544 final String permission = permissions[i]; 4545 if (permissionsState.hasPermission(permission, userId)) { 4546 tmp[i] = true; 4547 numMatch++; 4548 } else { 4549 tmp[i] = false; 4550 } 4551 } 4552 if (numMatch == 0) { 4553 return; 4554 } 4555 PackageInfo pi; 4556 if (ps.pkg != null) { 4557 pi = generatePackageInfo(ps.pkg, flags, userId); 4558 } else { 4559 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4560 } 4561 // The above might return null in cases of uninstalled apps or install-state 4562 // skew across users/profiles. 4563 if (pi != null) { 4564 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4565 if (numMatch == permissions.length) { 4566 pi.requestedPermissions = permissions; 4567 } else { 4568 pi.requestedPermissions = new String[numMatch]; 4569 numMatch = 0; 4570 for (int i=0; i<permissions.length; i++) { 4571 if (tmp[i]) { 4572 pi.requestedPermissions[numMatch] = permissions[i]; 4573 numMatch++; 4574 } 4575 } 4576 } 4577 } 4578 list.add(pi); 4579 } 4580 } 4581 4582 @Override 4583 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4584 String[] permissions, int flags, int userId) { 4585 if (!sUserManager.exists(userId)) return null; 4586 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4587 4588 // writer 4589 synchronized (mPackages) { 4590 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4591 boolean[] tmpBools = new boolean[permissions.length]; 4592 if (listUninstalled) { 4593 for (PackageSetting ps : mSettings.mPackages.values()) { 4594 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4595 } 4596 } else { 4597 for (PackageParser.Package pkg : mPackages.values()) { 4598 PackageSetting ps = (PackageSetting)pkg.mExtras; 4599 if (ps != null) { 4600 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4601 userId); 4602 } 4603 } 4604 } 4605 4606 return new ParceledListSlice<PackageInfo>(list); 4607 } 4608 } 4609 4610 @Override 4611 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4612 if (!sUserManager.exists(userId)) return null; 4613 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4614 4615 // writer 4616 synchronized (mPackages) { 4617 ArrayList<ApplicationInfo> list; 4618 if (listUninstalled) { 4619 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4620 for (PackageSetting ps : mSettings.mPackages.values()) { 4621 ApplicationInfo ai; 4622 if (ps.pkg != null) { 4623 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4624 ps.readUserState(userId), userId); 4625 } else { 4626 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4627 } 4628 if (ai != null) { 4629 list.add(ai); 4630 } 4631 } 4632 } else { 4633 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4634 for (PackageParser.Package p : mPackages.values()) { 4635 if (p.mExtras != null) { 4636 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4637 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4638 if (ai != null) { 4639 list.add(ai); 4640 } 4641 } 4642 } 4643 } 4644 4645 return new ParceledListSlice<ApplicationInfo>(list); 4646 } 4647 } 4648 4649 public List<ApplicationInfo> getPersistentApplications(int flags) { 4650 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4651 4652 // reader 4653 synchronized (mPackages) { 4654 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4655 final int userId = UserHandle.getCallingUserId(); 4656 while (i.hasNext()) { 4657 final PackageParser.Package p = i.next(); 4658 if (p.applicationInfo != null 4659 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4660 && (!mSafeMode || isSystemApp(p))) { 4661 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4662 if (ps != null) { 4663 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4664 ps.readUserState(userId), userId); 4665 if (ai != null) { 4666 finalList.add(ai); 4667 } 4668 } 4669 } 4670 } 4671 } 4672 4673 return finalList; 4674 } 4675 4676 @Override 4677 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4678 if (!sUserManager.exists(userId)) return null; 4679 // reader 4680 synchronized (mPackages) { 4681 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4682 PackageSetting ps = provider != null 4683 ? mSettings.mPackages.get(provider.owner.packageName) 4684 : null; 4685 return ps != null 4686 && mSettings.isEnabledLPr(provider.info, flags, userId) 4687 && (!mSafeMode || (provider.info.applicationInfo.flags 4688 &ApplicationInfo.FLAG_SYSTEM) != 0) 4689 ? PackageParser.generateProviderInfo(provider, flags, 4690 ps.readUserState(userId), userId) 4691 : null; 4692 } 4693 } 4694 4695 /** 4696 * @deprecated 4697 */ 4698 @Deprecated 4699 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4700 // reader 4701 synchronized (mPackages) { 4702 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4703 .entrySet().iterator(); 4704 final int userId = UserHandle.getCallingUserId(); 4705 while (i.hasNext()) { 4706 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4707 PackageParser.Provider p = entry.getValue(); 4708 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4709 4710 if (ps != null && p.syncable 4711 && (!mSafeMode || (p.info.applicationInfo.flags 4712 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4713 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4714 ps.readUserState(userId), userId); 4715 if (info != null) { 4716 outNames.add(entry.getKey()); 4717 outInfo.add(info); 4718 } 4719 } 4720 } 4721 } 4722 } 4723 4724 @Override 4725 public List<ProviderInfo> queryContentProviders(String processName, 4726 int uid, int flags) { 4727 ArrayList<ProviderInfo> finalList = null; 4728 // reader 4729 synchronized (mPackages) { 4730 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4731 final int userId = processName != null ? 4732 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4733 while (i.hasNext()) { 4734 final PackageParser.Provider p = i.next(); 4735 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4736 if (ps != null && p.info.authority != null 4737 && (processName == null 4738 || (p.info.processName.equals(processName) 4739 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4740 && mSettings.isEnabledLPr(p.info, flags, userId) 4741 && (!mSafeMode 4742 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4743 if (finalList == null) { 4744 finalList = new ArrayList<ProviderInfo>(3); 4745 } 4746 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4747 ps.readUserState(userId), userId); 4748 if (info != null) { 4749 finalList.add(info); 4750 } 4751 } 4752 } 4753 } 4754 4755 if (finalList != null) { 4756 Collections.sort(finalList, mProviderInitOrderSorter); 4757 } 4758 4759 return finalList; 4760 } 4761 4762 @Override 4763 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4764 int flags) { 4765 // reader 4766 synchronized (mPackages) { 4767 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4768 return PackageParser.generateInstrumentationInfo(i, flags); 4769 } 4770 } 4771 4772 @Override 4773 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4774 int flags) { 4775 ArrayList<InstrumentationInfo> finalList = 4776 new ArrayList<InstrumentationInfo>(); 4777 4778 // reader 4779 synchronized (mPackages) { 4780 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4781 while (i.hasNext()) { 4782 final PackageParser.Instrumentation p = i.next(); 4783 if (targetPackage == null 4784 || targetPackage.equals(p.info.targetPackage)) { 4785 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4786 flags); 4787 if (ii != null) { 4788 finalList.add(ii); 4789 } 4790 } 4791 } 4792 } 4793 4794 return finalList; 4795 } 4796 4797 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4798 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4799 if (overlays == null) { 4800 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4801 return; 4802 } 4803 for (PackageParser.Package opkg : overlays.values()) { 4804 // Not much to do if idmap fails: we already logged the error 4805 // and we certainly don't want to abort installation of pkg simply 4806 // because an overlay didn't fit properly. For these reasons, 4807 // ignore the return value of createIdmapForPackagePairLI. 4808 createIdmapForPackagePairLI(pkg, opkg); 4809 } 4810 } 4811 4812 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4813 PackageParser.Package opkg) { 4814 if (!opkg.mTrustedOverlay) { 4815 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4816 opkg.baseCodePath + ": overlay not trusted"); 4817 return false; 4818 } 4819 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4820 if (overlaySet == null) { 4821 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4822 opkg.baseCodePath + " but target package has no known overlays"); 4823 return false; 4824 } 4825 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4826 // TODO: generate idmap for split APKs 4827 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4828 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4829 + opkg.baseCodePath); 4830 return false; 4831 } 4832 PackageParser.Package[] overlayArray = 4833 overlaySet.values().toArray(new PackageParser.Package[0]); 4834 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4835 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4836 return p1.mOverlayPriority - p2.mOverlayPriority; 4837 } 4838 }; 4839 Arrays.sort(overlayArray, cmp); 4840 4841 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4842 int i = 0; 4843 for (PackageParser.Package p : overlayArray) { 4844 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4845 } 4846 return true; 4847 } 4848 4849 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4850 final File[] files = dir.listFiles(); 4851 if (ArrayUtils.isEmpty(files)) { 4852 Log.d(TAG, "No files in app dir " + dir); 4853 return; 4854 } 4855 4856 if (DEBUG_PACKAGE_SCANNING) { 4857 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4858 + " flags=0x" + Integer.toHexString(parseFlags)); 4859 } 4860 4861 for (File file : files) { 4862 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4863 && !PackageInstallerService.isStageName(file.getName()); 4864 if (!isPackage) { 4865 // Ignore entries which are not packages 4866 continue; 4867 } 4868 try { 4869 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4870 scanFlags, currentTime, null); 4871 } catch (PackageManagerException e) { 4872 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4873 4874 // Delete invalid userdata apps 4875 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4876 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4877 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4878 if (file.isDirectory()) { 4879 mInstaller.rmPackageDir(file.getAbsolutePath()); 4880 } else { 4881 file.delete(); 4882 } 4883 } 4884 } 4885 } 4886 } 4887 4888 private static File getSettingsProblemFile() { 4889 File dataDir = Environment.getDataDirectory(); 4890 File systemDir = new File(dataDir, "system"); 4891 File fname = new File(systemDir, "uiderrors.txt"); 4892 return fname; 4893 } 4894 4895 static void reportSettingsProblem(int priority, String msg) { 4896 logCriticalInfo(priority, msg); 4897 } 4898 4899 static void logCriticalInfo(int priority, String msg) { 4900 Slog.println(priority, TAG, msg); 4901 EventLogTags.writePmCriticalInfo(msg); 4902 try { 4903 File fname = getSettingsProblemFile(); 4904 FileOutputStream out = new FileOutputStream(fname, true); 4905 PrintWriter pw = new FastPrintWriter(out); 4906 SimpleDateFormat formatter = new SimpleDateFormat(); 4907 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4908 pw.println(dateString + ": " + msg); 4909 pw.close(); 4910 FileUtils.setPermissions( 4911 fname.toString(), 4912 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4913 -1, -1); 4914 } catch (java.io.IOException e) { 4915 } 4916 } 4917 4918 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4919 PackageParser.Package pkg, File srcFile, int parseFlags) 4920 throws PackageManagerException { 4921 if (ps != null 4922 && ps.codePath.equals(srcFile) 4923 && ps.timeStamp == srcFile.lastModified() 4924 && !isCompatSignatureUpdateNeeded(pkg) 4925 && !isRecoverSignatureUpdateNeeded(pkg)) { 4926 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4927 if (ps.signatures.mSignatures != null 4928 && ps.signatures.mSignatures.length != 0 4929 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4930 // Optimization: reuse the existing cached certificates 4931 // if the package appears to be unchanged. 4932 pkg.mSignatures = ps.signatures.mSignatures; 4933 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4934 synchronized (mPackages) { 4935 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4936 } 4937 return; 4938 } 4939 4940 Slog.w(TAG, "PackageSetting for " + ps.name 4941 + " is missing signatures. Collecting certs again to recover them."); 4942 } else { 4943 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4944 } 4945 4946 try { 4947 pp.collectCertificates(pkg, parseFlags); 4948 pp.collectManifestDigest(pkg); 4949 } catch (PackageParserException e) { 4950 throw PackageManagerException.from(e); 4951 } 4952 } 4953 4954 /* 4955 * Scan a package and return the newly parsed package. 4956 * Returns null in case of errors and the error code is stored in mLastScanError 4957 */ 4958 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4959 long currentTime, UserHandle user) throws PackageManagerException { 4960 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4961 parseFlags |= mDefParseFlags; 4962 PackageParser pp = new PackageParser(); 4963 pp.setSeparateProcesses(mSeparateProcesses); 4964 pp.setOnlyCoreApps(mOnlyCore); 4965 pp.setDisplayMetrics(mMetrics); 4966 4967 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4968 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4969 } 4970 4971 final PackageParser.Package pkg; 4972 try { 4973 pkg = pp.parsePackage(scanFile, parseFlags); 4974 } catch (PackageParserException e) { 4975 throw PackageManagerException.from(e); 4976 } 4977 4978 PackageSetting ps = null; 4979 PackageSetting updatedPkg; 4980 // reader 4981 synchronized (mPackages) { 4982 // Look to see if we already know about this package. 4983 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4984 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4985 // This package has been renamed to its original name. Let's 4986 // use that. 4987 ps = mSettings.peekPackageLPr(oldName); 4988 } 4989 // If there was no original package, see one for the real package name. 4990 if (ps == null) { 4991 ps = mSettings.peekPackageLPr(pkg.packageName); 4992 } 4993 // Check to see if this package could be hiding/updating a system 4994 // package. Must look for it either under the original or real 4995 // package name depending on our state. 4996 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4997 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4998 } 4999 boolean updatedPkgBetter = false; 5000 // First check if this is a system package that may involve an update 5001 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5002 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5003 // it needs to drop FLAG_PRIVILEGED. 5004 if (locationIsPrivileged(scanFile)) { 5005 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5006 } else { 5007 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5008 } 5009 5010 if (ps != null && !ps.codePath.equals(scanFile)) { 5011 // The path has changed from what was last scanned... check the 5012 // version of the new path against what we have stored to determine 5013 // what to do. 5014 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5015 if (pkg.mVersionCode <= ps.versionCode) { 5016 // The system package has been updated and the code path does not match 5017 // Ignore entry. Skip it. 5018 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5019 + " ignored: updated version " + ps.versionCode 5020 + " better than this " + pkg.mVersionCode); 5021 if (!updatedPkg.codePath.equals(scanFile)) { 5022 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5023 + ps.name + " changing from " + updatedPkg.codePathString 5024 + " to " + scanFile); 5025 updatedPkg.codePath = scanFile; 5026 updatedPkg.codePathString = scanFile.toString(); 5027 updatedPkg.resourcePath = scanFile; 5028 updatedPkg.resourcePathString = scanFile.toString(); 5029 } 5030 updatedPkg.pkg = pkg; 5031 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5032 } else { 5033 // The current app on the system partition is better than 5034 // what we have updated to on the data partition; switch 5035 // back to the system partition version. 5036 // At this point, its safely assumed that package installation for 5037 // apps in system partition will go through. If not there won't be a working 5038 // version of the app 5039 // writer 5040 synchronized (mPackages) { 5041 // Just remove the loaded entries from package lists. 5042 mPackages.remove(ps.name); 5043 } 5044 5045 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5046 + " reverting from " + ps.codePathString 5047 + ": new version " + pkg.mVersionCode 5048 + " better than installed " + ps.versionCode); 5049 5050 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5051 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5052 synchronized (mInstallLock) { 5053 args.cleanUpResourcesLI(); 5054 } 5055 synchronized (mPackages) { 5056 mSettings.enableSystemPackageLPw(ps.name); 5057 } 5058 updatedPkgBetter = true; 5059 } 5060 } 5061 } 5062 5063 if (updatedPkg != null) { 5064 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5065 // initially 5066 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5067 5068 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5069 // flag set initially 5070 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5071 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5072 } 5073 } 5074 5075 // Verify certificates against what was last scanned 5076 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5077 5078 /* 5079 * A new system app appeared, but we already had a non-system one of the 5080 * same name installed earlier. 5081 */ 5082 boolean shouldHideSystemApp = false; 5083 if (updatedPkg == null && ps != null 5084 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5085 /* 5086 * Check to make sure the signatures match first. If they don't, 5087 * wipe the installed application and its data. 5088 */ 5089 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5090 != PackageManager.SIGNATURE_MATCH) { 5091 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5092 + " signatures don't match existing userdata copy; removing"); 5093 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5094 ps = null; 5095 } else { 5096 /* 5097 * If the newly-added system app is an older version than the 5098 * already installed version, hide it. It will be scanned later 5099 * and re-added like an update. 5100 */ 5101 if (pkg.mVersionCode <= ps.versionCode) { 5102 shouldHideSystemApp = true; 5103 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5104 + " but new version " + pkg.mVersionCode + " better than installed " 5105 + ps.versionCode + "; hiding system"); 5106 } else { 5107 /* 5108 * The newly found system app is a newer version that the 5109 * one previously installed. Simply remove the 5110 * already-installed application and replace it with our own 5111 * while keeping the application data. 5112 */ 5113 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5114 + " reverting from " + ps.codePathString + ": new version " 5115 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5116 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5117 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5118 synchronized (mInstallLock) { 5119 args.cleanUpResourcesLI(); 5120 } 5121 } 5122 } 5123 } 5124 5125 // The apk is forward locked (not public) if its code and resources 5126 // are kept in different files. (except for app in either system or 5127 // vendor path). 5128 // TODO grab this value from PackageSettings 5129 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5130 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5131 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5132 } 5133 } 5134 5135 // TODO: extend to support forward-locked splits 5136 String resourcePath = null; 5137 String baseResourcePath = null; 5138 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5139 if (ps != null && ps.resourcePathString != null) { 5140 resourcePath = ps.resourcePathString; 5141 baseResourcePath = ps.resourcePathString; 5142 } else { 5143 // Should not happen at all. Just log an error. 5144 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5145 } 5146 } else { 5147 resourcePath = pkg.codePath; 5148 baseResourcePath = pkg.baseCodePath; 5149 } 5150 5151 // Set application objects path explicitly. 5152 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5153 pkg.applicationInfo.setCodePath(pkg.codePath); 5154 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5155 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5156 pkg.applicationInfo.setResourcePath(resourcePath); 5157 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5158 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5159 5160 // Note that we invoke the following method only if we are about to unpack an application 5161 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5162 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5163 5164 /* 5165 * If the system app should be overridden by a previously installed 5166 * data, hide the system app now and let the /data/app scan pick it up 5167 * again. 5168 */ 5169 if (shouldHideSystemApp) { 5170 synchronized (mPackages) { 5171 /* 5172 * We have to grant systems permissions before we hide, because 5173 * grantPermissions will assume the package update is trying to 5174 * expand its permissions. 5175 */ 5176 grantPermissionsLPw(pkg, true, pkg.packageName); 5177 mSettings.disableSystemPackageLPw(pkg.packageName); 5178 } 5179 } 5180 5181 return scannedPkg; 5182 } 5183 5184 private static String fixProcessName(String defProcessName, 5185 String processName, int uid) { 5186 if (processName == null) { 5187 return defProcessName; 5188 } 5189 return processName; 5190 } 5191 5192 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5193 throws PackageManagerException { 5194 if (pkgSetting.signatures.mSignatures != null) { 5195 // Already existing package. Make sure signatures match 5196 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5197 == PackageManager.SIGNATURE_MATCH; 5198 if (!match) { 5199 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5200 == PackageManager.SIGNATURE_MATCH; 5201 } 5202 if (!match) { 5203 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5204 == PackageManager.SIGNATURE_MATCH; 5205 } 5206 if (!match) { 5207 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5208 + pkg.packageName + " signatures do not match the " 5209 + "previously installed version; ignoring!"); 5210 } 5211 } 5212 5213 // Check for shared user signatures 5214 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5215 // Already existing package. Make sure signatures match 5216 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5217 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5218 if (!match) { 5219 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5220 == PackageManager.SIGNATURE_MATCH; 5221 } 5222 if (!match) { 5223 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5224 == PackageManager.SIGNATURE_MATCH; 5225 } 5226 if (!match) { 5227 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5228 "Package " + pkg.packageName 5229 + " has no signatures that match those in shared user " 5230 + pkgSetting.sharedUser.name + "; ignoring!"); 5231 } 5232 } 5233 } 5234 5235 /** 5236 * Enforces that only the system UID or root's UID can call a method exposed 5237 * via Binder. 5238 * 5239 * @param message used as message if SecurityException is thrown 5240 * @throws SecurityException if the caller is not system or root 5241 */ 5242 private static final void enforceSystemOrRoot(String message) { 5243 final int uid = Binder.getCallingUid(); 5244 if (uid != Process.SYSTEM_UID && uid != 0) { 5245 throw new SecurityException(message); 5246 } 5247 } 5248 5249 @Override 5250 public void performBootDexOpt() { 5251 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5252 5253 // Before everything else, see whether we need to fstrim. 5254 try { 5255 IMountService ms = PackageHelper.getMountService(); 5256 if (ms != null) { 5257 final boolean isUpgrade = isUpgrade(); 5258 boolean doTrim = isUpgrade; 5259 if (doTrim) { 5260 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5261 } else { 5262 final long interval = android.provider.Settings.Global.getLong( 5263 mContext.getContentResolver(), 5264 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5265 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5266 if (interval > 0) { 5267 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5268 if (timeSinceLast > interval) { 5269 doTrim = true; 5270 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5271 + "; running immediately"); 5272 } 5273 } 5274 } 5275 if (doTrim) { 5276 if (!isFirstBoot()) { 5277 try { 5278 ActivityManagerNative.getDefault().showBootMessage( 5279 mContext.getResources().getString( 5280 R.string.android_upgrading_fstrim), true); 5281 } catch (RemoteException e) { 5282 } 5283 } 5284 ms.runMaintenance(); 5285 } 5286 } else { 5287 Slog.e(TAG, "Mount service unavailable!"); 5288 } 5289 } catch (RemoteException e) { 5290 // Can't happen; MountService is local 5291 } 5292 5293 final ArraySet<PackageParser.Package> pkgs; 5294 synchronized (mPackages) { 5295 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5296 } 5297 5298 if (pkgs != null) { 5299 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5300 // in case the device runs out of space. 5301 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5302 // Give priority to core apps. 5303 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5304 PackageParser.Package pkg = it.next(); 5305 if (pkg.coreApp) { 5306 if (DEBUG_DEXOPT) { 5307 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5308 } 5309 sortedPkgs.add(pkg); 5310 it.remove(); 5311 } 5312 } 5313 // Give priority to system apps that listen for pre boot complete. 5314 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5315 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5316 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5317 PackageParser.Package pkg = it.next(); 5318 if (pkgNames.contains(pkg.packageName)) { 5319 if (DEBUG_DEXOPT) { 5320 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5321 } 5322 sortedPkgs.add(pkg); 5323 it.remove(); 5324 } 5325 } 5326 // Give priority to system apps. 5327 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5328 PackageParser.Package pkg = it.next(); 5329 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5330 if (DEBUG_DEXOPT) { 5331 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5332 } 5333 sortedPkgs.add(pkg); 5334 it.remove(); 5335 } 5336 } 5337 // Give priority to updated system apps. 5338 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5339 PackageParser.Package pkg = it.next(); 5340 if (pkg.isUpdatedSystemApp()) { 5341 if (DEBUG_DEXOPT) { 5342 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5343 } 5344 sortedPkgs.add(pkg); 5345 it.remove(); 5346 } 5347 } 5348 // Give priority to apps that listen for boot complete. 5349 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5350 pkgNames = getPackageNamesForIntent(intent); 5351 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5352 PackageParser.Package pkg = it.next(); 5353 if (pkgNames.contains(pkg.packageName)) { 5354 if (DEBUG_DEXOPT) { 5355 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5356 } 5357 sortedPkgs.add(pkg); 5358 it.remove(); 5359 } 5360 } 5361 // Filter out packages that aren't recently used. 5362 filterRecentlyUsedApps(pkgs); 5363 // Add all remaining apps. 5364 for (PackageParser.Package pkg : pkgs) { 5365 if (DEBUG_DEXOPT) { 5366 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5367 } 5368 sortedPkgs.add(pkg); 5369 } 5370 5371 // If we want to be lazy, filter everything that wasn't recently used. 5372 if (mLazyDexOpt) { 5373 filterRecentlyUsedApps(sortedPkgs); 5374 } 5375 5376 int i = 0; 5377 int total = sortedPkgs.size(); 5378 File dataDir = Environment.getDataDirectory(); 5379 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5380 if (lowThreshold == 0) { 5381 throw new IllegalStateException("Invalid low memory threshold"); 5382 } 5383 for (PackageParser.Package pkg : sortedPkgs) { 5384 long usableSpace = dataDir.getUsableSpace(); 5385 if (usableSpace < lowThreshold) { 5386 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5387 break; 5388 } 5389 performBootDexOpt(pkg, ++i, total); 5390 } 5391 } 5392 } 5393 5394 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5395 // Filter out packages that aren't recently used. 5396 // 5397 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5398 // should do a full dexopt. 5399 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5400 int total = pkgs.size(); 5401 int skipped = 0; 5402 long now = System.currentTimeMillis(); 5403 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5404 PackageParser.Package pkg = i.next(); 5405 long then = pkg.mLastPackageUsageTimeInMills; 5406 if (then + mDexOptLRUThresholdInMills < now) { 5407 if (DEBUG_DEXOPT) { 5408 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5409 ((then == 0) ? "never" : new Date(then))); 5410 } 5411 i.remove(); 5412 skipped++; 5413 } 5414 } 5415 if (DEBUG_DEXOPT) { 5416 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5417 } 5418 } 5419 } 5420 5421 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5422 List<ResolveInfo> ris = null; 5423 try { 5424 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5425 intent, null, 0, UserHandle.USER_OWNER); 5426 } catch (RemoteException e) { 5427 } 5428 ArraySet<String> pkgNames = new ArraySet<String>(); 5429 if (ris != null) { 5430 for (ResolveInfo ri : ris) { 5431 pkgNames.add(ri.activityInfo.packageName); 5432 } 5433 } 5434 return pkgNames; 5435 } 5436 5437 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5438 if (DEBUG_DEXOPT) { 5439 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5440 } 5441 if (!isFirstBoot()) { 5442 try { 5443 ActivityManagerNative.getDefault().showBootMessage( 5444 mContext.getResources().getString(R.string.android_upgrading_apk, 5445 curr, total), true); 5446 } catch (RemoteException e) { 5447 } 5448 } 5449 PackageParser.Package p = pkg; 5450 synchronized (mInstallLock) { 5451 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5452 false /* force dex */, false /* defer */, true /* include dependencies */); 5453 } 5454 } 5455 5456 @Override 5457 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5458 return performDexOpt(packageName, instructionSet, false); 5459 } 5460 5461 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5462 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5463 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5464 if (!dexopt && !updateUsage) { 5465 // We aren't going to dexopt or update usage, so bail early. 5466 return false; 5467 } 5468 PackageParser.Package p; 5469 final String targetInstructionSet; 5470 synchronized (mPackages) { 5471 p = mPackages.get(packageName); 5472 if (p == null) { 5473 return false; 5474 } 5475 if (updateUsage) { 5476 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5477 } 5478 mPackageUsage.write(false); 5479 if (!dexopt) { 5480 // We aren't going to dexopt, so bail early. 5481 return false; 5482 } 5483 5484 targetInstructionSet = instructionSet != null ? instructionSet : 5485 getPrimaryInstructionSet(p.applicationInfo); 5486 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5487 return false; 5488 } 5489 } 5490 5491 synchronized (mInstallLock) { 5492 final String[] instructionSets = new String[] { targetInstructionSet }; 5493 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5494 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5495 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5496 } 5497 } 5498 5499 public ArraySet<String> getPackagesThatNeedDexOpt() { 5500 ArraySet<String> pkgs = null; 5501 synchronized (mPackages) { 5502 for (PackageParser.Package p : mPackages.values()) { 5503 if (DEBUG_DEXOPT) { 5504 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5505 } 5506 if (!p.mDexOptPerformed.isEmpty()) { 5507 continue; 5508 } 5509 if (pkgs == null) { 5510 pkgs = new ArraySet<String>(); 5511 } 5512 pkgs.add(p.packageName); 5513 } 5514 } 5515 return pkgs; 5516 } 5517 5518 public void shutdown() { 5519 mPackageUsage.write(true); 5520 } 5521 5522 @Override 5523 public void forceDexOpt(String packageName) { 5524 enforceSystemOrRoot("forceDexOpt"); 5525 5526 PackageParser.Package pkg; 5527 synchronized (mPackages) { 5528 pkg = mPackages.get(packageName); 5529 if (pkg == null) { 5530 throw new IllegalArgumentException("Missing package: " + packageName); 5531 } 5532 } 5533 5534 synchronized (mInstallLock) { 5535 final String[] instructionSets = new String[] { 5536 getPrimaryInstructionSet(pkg.applicationInfo) }; 5537 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5538 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5539 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5540 throw new IllegalStateException("Failed to dexopt: " + res); 5541 } 5542 } 5543 } 5544 5545 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5546 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5547 Slog.w(TAG, "Unable to update from " + oldPkg.name 5548 + " to " + newPkg.packageName 5549 + ": old package not in system partition"); 5550 return false; 5551 } else if (mPackages.get(oldPkg.name) != null) { 5552 Slog.w(TAG, "Unable to update from " + oldPkg.name 5553 + " to " + newPkg.packageName 5554 + ": old package still exists"); 5555 return false; 5556 } 5557 return true; 5558 } 5559 5560 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5561 int[] users = sUserManager.getUserIds(); 5562 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5563 if (res < 0) { 5564 return res; 5565 } 5566 for (int user : users) { 5567 if (user != 0) { 5568 res = mInstaller.createUserData(volumeUuid, packageName, 5569 UserHandle.getUid(user, uid), user, seinfo); 5570 if (res < 0) { 5571 return res; 5572 } 5573 } 5574 } 5575 return res; 5576 } 5577 5578 private int removeDataDirsLI(String volumeUuid, String packageName) { 5579 int[] users = sUserManager.getUserIds(); 5580 int res = 0; 5581 for (int user : users) { 5582 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5583 if (resInner < 0) { 5584 res = resInner; 5585 } 5586 } 5587 5588 return res; 5589 } 5590 5591 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5592 int[] users = sUserManager.getUserIds(); 5593 int res = 0; 5594 for (int user : users) { 5595 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5596 if (resInner < 0) { 5597 res = resInner; 5598 } 5599 } 5600 return res; 5601 } 5602 5603 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5604 PackageParser.Package changingLib) { 5605 if (file.path != null) { 5606 usesLibraryFiles.add(file.path); 5607 return; 5608 } 5609 PackageParser.Package p = mPackages.get(file.apk); 5610 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5611 // If we are doing this while in the middle of updating a library apk, 5612 // then we need to make sure to use that new apk for determining the 5613 // dependencies here. (We haven't yet finished committing the new apk 5614 // to the package manager state.) 5615 if (p == null || p.packageName.equals(changingLib.packageName)) { 5616 p = changingLib; 5617 } 5618 } 5619 if (p != null) { 5620 usesLibraryFiles.addAll(p.getAllCodePaths()); 5621 } 5622 } 5623 5624 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5625 PackageParser.Package changingLib) throws PackageManagerException { 5626 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5627 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5628 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5629 for (int i=0; i<N; i++) { 5630 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5631 if (file == null) { 5632 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5633 "Package " + pkg.packageName + " requires unavailable shared library " 5634 + pkg.usesLibraries.get(i) + "; failing!"); 5635 } 5636 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5637 } 5638 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5639 for (int i=0; i<N; i++) { 5640 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5641 if (file == null) { 5642 Slog.w(TAG, "Package " + pkg.packageName 5643 + " desires unavailable shared library " 5644 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5645 } else { 5646 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5647 } 5648 } 5649 N = usesLibraryFiles.size(); 5650 if (N > 0) { 5651 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5652 } else { 5653 pkg.usesLibraryFiles = null; 5654 } 5655 } 5656 } 5657 5658 private static boolean hasString(List<String> list, List<String> which) { 5659 if (list == null) { 5660 return false; 5661 } 5662 for (int i=list.size()-1; i>=0; i--) { 5663 for (int j=which.size()-1; j>=0; j--) { 5664 if (which.get(j).equals(list.get(i))) { 5665 return true; 5666 } 5667 } 5668 } 5669 return false; 5670 } 5671 5672 private void updateAllSharedLibrariesLPw() { 5673 for (PackageParser.Package pkg : mPackages.values()) { 5674 try { 5675 updateSharedLibrariesLPw(pkg, null); 5676 } catch (PackageManagerException e) { 5677 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5678 } 5679 } 5680 } 5681 5682 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5683 PackageParser.Package changingPkg) { 5684 ArrayList<PackageParser.Package> res = null; 5685 for (PackageParser.Package pkg : mPackages.values()) { 5686 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5687 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5688 if (res == null) { 5689 res = new ArrayList<PackageParser.Package>(); 5690 } 5691 res.add(pkg); 5692 try { 5693 updateSharedLibrariesLPw(pkg, changingPkg); 5694 } catch (PackageManagerException e) { 5695 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5696 } 5697 } 5698 } 5699 return res; 5700 } 5701 5702 /** 5703 * Derive the value of the {@code cpuAbiOverride} based on the provided 5704 * value and an optional stored value from the package settings. 5705 */ 5706 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5707 String cpuAbiOverride = null; 5708 5709 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5710 cpuAbiOverride = null; 5711 } else if (abiOverride != null) { 5712 cpuAbiOverride = abiOverride; 5713 } else if (settings != null) { 5714 cpuAbiOverride = settings.cpuAbiOverrideString; 5715 } 5716 5717 return cpuAbiOverride; 5718 } 5719 5720 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5721 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5722 boolean success = false; 5723 try { 5724 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5725 currentTime, user); 5726 success = true; 5727 return res; 5728 } finally { 5729 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5730 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5731 } 5732 } 5733 } 5734 5735 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5736 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5737 final File scanFile = new File(pkg.codePath); 5738 if (pkg.applicationInfo.getCodePath() == null || 5739 pkg.applicationInfo.getResourcePath() == null) { 5740 // Bail out. The resource and code paths haven't been set. 5741 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5742 "Code and resource paths haven't been set correctly"); 5743 } 5744 5745 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5746 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5747 } else { 5748 // Only allow system apps to be flagged as core apps. 5749 pkg.coreApp = false; 5750 } 5751 5752 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5753 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5754 } 5755 5756 if (mCustomResolverComponentName != null && 5757 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5758 setUpCustomResolverActivity(pkg); 5759 } 5760 5761 if (pkg.packageName.equals("android")) { 5762 synchronized (mPackages) { 5763 if (mAndroidApplication != null) { 5764 Slog.w(TAG, "*************************************************"); 5765 Slog.w(TAG, "Core android package being redefined. Skipping."); 5766 Slog.w(TAG, " file=" + scanFile); 5767 Slog.w(TAG, "*************************************************"); 5768 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5769 "Core android package being redefined. Skipping."); 5770 } 5771 5772 // Set up information for our fall-back user intent resolution activity. 5773 mPlatformPackage = pkg; 5774 pkg.mVersionCode = mSdkVersion; 5775 mAndroidApplication = pkg.applicationInfo; 5776 5777 if (!mResolverReplaced) { 5778 mResolveActivity.applicationInfo = mAndroidApplication; 5779 mResolveActivity.name = ResolverActivity.class.getName(); 5780 mResolveActivity.packageName = mAndroidApplication.packageName; 5781 mResolveActivity.processName = "system:ui"; 5782 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5783 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5784 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5785 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5786 mResolveActivity.exported = true; 5787 mResolveActivity.enabled = true; 5788 mResolveInfo.activityInfo = mResolveActivity; 5789 mResolveInfo.priority = 0; 5790 mResolveInfo.preferredOrder = 0; 5791 mResolveInfo.match = 0; 5792 mResolveComponentName = new ComponentName( 5793 mAndroidApplication.packageName, mResolveActivity.name); 5794 } 5795 } 5796 } 5797 5798 if (DEBUG_PACKAGE_SCANNING) { 5799 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5800 Log.d(TAG, "Scanning package " + pkg.packageName); 5801 } 5802 5803 if (mPackages.containsKey(pkg.packageName) 5804 || mSharedLibraries.containsKey(pkg.packageName)) { 5805 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5806 "Application package " + pkg.packageName 5807 + " already installed. Skipping duplicate."); 5808 } 5809 5810 // If we're only installing presumed-existing packages, require that the 5811 // scanned APK is both already known and at the path previously established 5812 // for it. Previously unknown packages we pick up normally, but if we have an 5813 // a priori expectation about this package's install presence, enforce it. 5814 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5815 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5816 if (known != null) { 5817 if (DEBUG_PACKAGE_SCANNING) { 5818 Log.d(TAG, "Examining " + pkg.codePath 5819 + " and requiring known paths " + known.codePathString 5820 + " & " + known.resourcePathString); 5821 } 5822 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5823 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5824 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5825 "Application package " + pkg.packageName 5826 + " found at " + pkg.applicationInfo.getCodePath() 5827 + " but expected at " + known.codePathString + "; ignoring."); 5828 } 5829 } 5830 } 5831 5832 // Initialize package source and resource directories 5833 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5834 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5835 5836 SharedUserSetting suid = null; 5837 PackageSetting pkgSetting = null; 5838 5839 if (!isSystemApp(pkg)) { 5840 // Only system apps can use these features. 5841 pkg.mOriginalPackages = null; 5842 pkg.mRealPackage = null; 5843 pkg.mAdoptPermissions = null; 5844 } 5845 5846 // writer 5847 synchronized (mPackages) { 5848 if (pkg.mSharedUserId != null) { 5849 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5850 if (suid == null) { 5851 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5852 "Creating application package " + pkg.packageName 5853 + " for shared user failed"); 5854 } 5855 if (DEBUG_PACKAGE_SCANNING) { 5856 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5857 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5858 + "): packages=" + suid.packages); 5859 } 5860 } 5861 5862 // Check if we are renaming from an original package name. 5863 PackageSetting origPackage = null; 5864 String realName = null; 5865 if (pkg.mOriginalPackages != null) { 5866 // This package may need to be renamed to a previously 5867 // installed name. Let's check on that... 5868 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5869 if (pkg.mOriginalPackages.contains(renamed)) { 5870 // This package had originally been installed as the 5871 // original name, and we have already taken care of 5872 // transitioning to the new one. Just update the new 5873 // one to continue using the old name. 5874 realName = pkg.mRealPackage; 5875 if (!pkg.packageName.equals(renamed)) { 5876 // Callers into this function may have already taken 5877 // care of renaming the package; only do it here if 5878 // it is not already done. 5879 pkg.setPackageName(renamed); 5880 } 5881 5882 } else { 5883 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5884 if ((origPackage = mSettings.peekPackageLPr( 5885 pkg.mOriginalPackages.get(i))) != null) { 5886 // We do have the package already installed under its 5887 // original name... should we use it? 5888 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5889 // New package is not compatible with original. 5890 origPackage = null; 5891 continue; 5892 } else if (origPackage.sharedUser != null) { 5893 // Make sure uid is compatible between packages. 5894 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5895 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5896 + " to " + pkg.packageName + ": old uid " 5897 + origPackage.sharedUser.name 5898 + " differs from " + pkg.mSharedUserId); 5899 origPackage = null; 5900 continue; 5901 } 5902 } else { 5903 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5904 + pkg.packageName + " to old name " + origPackage.name); 5905 } 5906 break; 5907 } 5908 } 5909 } 5910 } 5911 5912 if (mTransferedPackages.contains(pkg.packageName)) { 5913 Slog.w(TAG, "Package " + pkg.packageName 5914 + " was transferred to another, but its .apk remains"); 5915 } 5916 5917 // Just create the setting, don't add it yet. For already existing packages 5918 // the PkgSetting exists already and doesn't have to be created. 5919 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5920 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5921 pkg.applicationInfo.primaryCpuAbi, 5922 pkg.applicationInfo.secondaryCpuAbi, 5923 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5924 user, false); 5925 if (pkgSetting == null) { 5926 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5927 "Creating application package " + pkg.packageName + " failed"); 5928 } 5929 5930 if (pkgSetting.origPackage != null) { 5931 // If we are first transitioning from an original package, 5932 // fix up the new package's name now. We need to do this after 5933 // looking up the package under its new name, so getPackageLP 5934 // can take care of fiddling things correctly. 5935 pkg.setPackageName(origPackage.name); 5936 5937 // File a report about this. 5938 String msg = "New package " + pkgSetting.realName 5939 + " renamed to replace old package " + pkgSetting.name; 5940 reportSettingsProblem(Log.WARN, msg); 5941 5942 // Make a note of it. 5943 mTransferedPackages.add(origPackage.name); 5944 5945 // No longer need to retain this. 5946 pkgSetting.origPackage = null; 5947 } 5948 5949 if (realName != null) { 5950 // Make a note of it. 5951 mTransferedPackages.add(pkg.packageName); 5952 } 5953 5954 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5955 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5956 } 5957 5958 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5959 // Check all shared libraries and map to their actual file path. 5960 // We only do this here for apps not on a system dir, because those 5961 // are the only ones that can fail an install due to this. We 5962 // will take care of the system apps by updating all of their 5963 // library paths after the scan is done. 5964 updateSharedLibrariesLPw(pkg, null); 5965 } 5966 5967 if (mFoundPolicyFile) { 5968 SELinuxMMAC.assignSeinfoValue(pkg); 5969 } 5970 5971 pkg.applicationInfo.uid = pkgSetting.appId; 5972 pkg.mExtras = pkgSetting; 5973 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5974 try { 5975 verifySignaturesLP(pkgSetting, pkg); 5976 // We just determined the app is signed correctly, so bring 5977 // over the latest parsed certs. 5978 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5979 } catch (PackageManagerException e) { 5980 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5981 throw e; 5982 } 5983 // The signature has changed, but this package is in the system 5984 // image... let's recover! 5985 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5986 // However... if this package is part of a shared user, but it 5987 // doesn't match the signature of the shared user, let's fail. 5988 // What this means is that you can't change the signatures 5989 // associated with an overall shared user, which doesn't seem all 5990 // that unreasonable. 5991 if (pkgSetting.sharedUser != null) { 5992 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5993 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5994 throw new PackageManagerException( 5995 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5996 "Signature mismatch for shared user : " 5997 + pkgSetting.sharedUser); 5998 } 5999 } 6000 // File a report about this. 6001 String msg = "System package " + pkg.packageName 6002 + " signature changed; retaining data."; 6003 reportSettingsProblem(Log.WARN, msg); 6004 } 6005 } else { 6006 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6007 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6008 + pkg.packageName + " upgrade keys do not match the " 6009 + "previously installed version"); 6010 } else { 6011 // We just determined the app is signed correctly, so bring 6012 // over the latest parsed certs. 6013 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6014 } 6015 } 6016 // Verify that this new package doesn't have any content providers 6017 // that conflict with existing packages. Only do this if the 6018 // package isn't already installed, since we don't want to break 6019 // things that are installed. 6020 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6021 final int N = pkg.providers.size(); 6022 int i; 6023 for (i=0; i<N; i++) { 6024 PackageParser.Provider p = pkg.providers.get(i); 6025 if (p.info.authority != null) { 6026 String names[] = p.info.authority.split(";"); 6027 for (int j = 0; j < names.length; j++) { 6028 if (mProvidersByAuthority.containsKey(names[j])) { 6029 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6030 final String otherPackageName = 6031 ((other != null && other.getComponentName() != null) ? 6032 other.getComponentName().getPackageName() : "?"); 6033 throw new PackageManagerException( 6034 INSTALL_FAILED_CONFLICTING_PROVIDER, 6035 "Can't install because provider name " + names[j] 6036 + " (in package " + pkg.applicationInfo.packageName 6037 + ") is already used by " + otherPackageName); 6038 } 6039 } 6040 } 6041 } 6042 } 6043 6044 if (pkg.mAdoptPermissions != null) { 6045 // This package wants to adopt ownership of permissions from 6046 // another package. 6047 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6048 final String origName = pkg.mAdoptPermissions.get(i); 6049 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6050 if (orig != null) { 6051 if (verifyPackageUpdateLPr(orig, pkg)) { 6052 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6053 + pkg.packageName); 6054 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6055 } 6056 } 6057 } 6058 } 6059 } 6060 6061 final String pkgName = pkg.packageName; 6062 6063 final long scanFileTime = scanFile.lastModified(); 6064 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6065 pkg.applicationInfo.processName = fixProcessName( 6066 pkg.applicationInfo.packageName, 6067 pkg.applicationInfo.processName, 6068 pkg.applicationInfo.uid); 6069 6070 File dataPath; 6071 if (mPlatformPackage == pkg) { 6072 // The system package is special. 6073 dataPath = new File(Environment.getDataDirectory(), "system"); 6074 6075 pkg.applicationInfo.dataDir = dataPath.getPath(); 6076 6077 } else { 6078 // This is a normal package, need to make its data directory. 6079 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6080 UserHandle.USER_OWNER); 6081 6082 boolean uidError = false; 6083 if (dataPath.exists()) { 6084 int currentUid = 0; 6085 try { 6086 StructStat stat = Os.stat(dataPath.getPath()); 6087 currentUid = stat.st_uid; 6088 } catch (ErrnoException e) { 6089 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6090 } 6091 6092 // If we have mismatched owners for the data path, we have a problem. 6093 if (currentUid != pkg.applicationInfo.uid) { 6094 boolean recovered = false; 6095 if (currentUid == 0) { 6096 // The directory somehow became owned by root. Wow. 6097 // This is probably because the system was stopped while 6098 // installd was in the middle of messing with its libs 6099 // directory. Ask installd to fix that. 6100 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6101 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6102 if (ret >= 0) { 6103 recovered = true; 6104 String msg = "Package " + pkg.packageName 6105 + " unexpectedly changed to uid 0; recovered to " + 6106 + pkg.applicationInfo.uid; 6107 reportSettingsProblem(Log.WARN, msg); 6108 } 6109 } 6110 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6111 || (scanFlags&SCAN_BOOTING) != 0)) { 6112 // If this is a system app, we can at least delete its 6113 // current data so the application will still work. 6114 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6115 if (ret >= 0) { 6116 // TODO: Kill the processes first 6117 // Old data gone! 6118 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6119 ? "System package " : "Third party package "; 6120 String msg = prefix + pkg.packageName 6121 + " has changed from uid: " 6122 + currentUid + " to " 6123 + pkg.applicationInfo.uid + "; old data erased"; 6124 reportSettingsProblem(Log.WARN, msg); 6125 recovered = true; 6126 6127 // And now re-install the app. 6128 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6129 pkg.applicationInfo.seinfo); 6130 if (ret == -1) { 6131 // Ack should not happen! 6132 msg = prefix + pkg.packageName 6133 + " could not have data directory re-created after delete."; 6134 reportSettingsProblem(Log.WARN, msg); 6135 throw new PackageManagerException( 6136 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6137 } 6138 } 6139 if (!recovered) { 6140 mHasSystemUidErrors = true; 6141 } 6142 } else if (!recovered) { 6143 // If we allow this install to proceed, we will be broken. 6144 // Abort, abort! 6145 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6146 "scanPackageLI"); 6147 } 6148 if (!recovered) { 6149 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6150 + pkg.applicationInfo.uid + "/fs_" 6151 + currentUid; 6152 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6153 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6154 String msg = "Package " + pkg.packageName 6155 + " has mismatched uid: " 6156 + currentUid + " on disk, " 6157 + pkg.applicationInfo.uid + " in settings"; 6158 // writer 6159 synchronized (mPackages) { 6160 mSettings.mReadMessages.append(msg); 6161 mSettings.mReadMessages.append('\n'); 6162 uidError = true; 6163 if (!pkgSetting.uidError) { 6164 reportSettingsProblem(Log.ERROR, msg); 6165 } 6166 } 6167 } 6168 } 6169 pkg.applicationInfo.dataDir = dataPath.getPath(); 6170 if (mShouldRestoreconData) { 6171 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6172 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6173 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6174 } 6175 } else { 6176 if (DEBUG_PACKAGE_SCANNING) { 6177 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6178 Log.v(TAG, "Want this data dir: " + dataPath); 6179 } 6180 //invoke installer to do the actual installation 6181 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6182 pkg.applicationInfo.seinfo); 6183 if (ret < 0) { 6184 // Error from installer 6185 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6186 "Unable to create data dirs [errorCode=" + ret + "]"); 6187 } 6188 6189 if (dataPath.exists()) { 6190 pkg.applicationInfo.dataDir = dataPath.getPath(); 6191 } else { 6192 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6193 pkg.applicationInfo.dataDir = null; 6194 } 6195 } 6196 6197 pkgSetting.uidError = uidError; 6198 } 6199 6200 final String path = scanFile.getPath(); 6201 final String codePath = pkg.applicationInfo.getCodePath(); 6202 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6203 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6204 setBundledAppAbisAndRoots(pkg, pkgSetting); 6205 6206 // If we haven't found any native libraries for the app, check if it has 6207 // renderscript code. We'll need to force the app to 32 bit if it has 6208 // renderscript bitcode. 6209 if (pkg.applicationInfo.primaryCpuAbi == null 6210 && pkg.applicationInfo.secondaryCpuAbi == null 6211 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6212 NativeLibraryHelper.Handle handle = null; 6213 try { 6214 handle = NativeLibraryHelper.Handle.create(scanFile); 6215 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6216 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6217 } 6218 } catch (IOException ioe) { 6219 Slog.w(TAG, "Error scanning system app : " + ioe); 6220 } finally { 6221 IoUtils.closeQuietly(handle); 6222 } 6223 } 6224 6225 setNativeLibraryPaths(pkg); 6226 } else { 6227 // TODO: We can probably be smarter about this stuff. For installed apps, 6228 // we can calculate this information at install time once and for all. For 6229 // system apps, we can probably assume that this information doesn't change 6230 // after the first boot scan. As things stand, we do lots of unnecessary work. 6231 6232 // Give ourselves some initial paths; we'll come back for another 6233 // pass once we've determined ABI below. 6234 setNativeLibraryPaths(pkg); 6235 6236 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6237 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6238 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6239 6240 NativeLibraryHelper.Handle handle = null; 6241 try { 6242 handle = NativeLibraryHelper.Handle.create(scanFile); 6243 // TODO(multiArch): This can be null for apps that didn't go through the 6244 // usual installation process. We can calculate it again, like we 6245 // do during install time. 6246 // 6247 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6248 // unnecessary. 6249 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6250 6251 // Null out the abis so that they can be recalculated. 6252 pkg.applicationInfo.primaryCpuAbi = null; 6253 pkg.applicationInfo.secondaryCpuAbi = null; 6254 if (isMultiArch(pkg.applicationInfo)) { 6255 // Warn if we've set an abiOverride for multi-lib packages.. 6256 // By definition, we need to copy both 32 and 64 bit libraries for 6257 // such packages. 6258 if (pkg.cpuAbiOverride != null 6259 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6260 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6261 } 6262 6263 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6264 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6265 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6266 if (isAsec) { 6267 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6268 } else { 6269 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6270 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6271 useIsaSpecificSubdirs); 6272 } 6273 } 6274 6275 maybeThrowExceptionForMultiArchCopy( 6276 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6277 6278 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6279 if (isAsec) { 6280 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6281 } else { 6282 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6283 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6284 useIsaSpecificSubdirs); 6285 } 6286 } 6287 6288 maybeThrowExceptionForMultiArchCopy( 6289 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6290 6291 if (abi64 >= 0) { 6292 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6293 } 6294 6295 if (abi32 >= 0) { 6296 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6297 if (abi64 >= 0) { 6298 pkg.applicationInfo.secondaryCpuAbi = abi; 6299 } else { 6300 pkg.applicationInfo.primaryCpuAbi = abi; 6301 } 6302 } 6303 } else { 6304 String[] abiList = (cpuAbiOverride != null) ? 6305 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6306 6307 // Enable gross and lame hacks for apps that are built with old 6308 // SDK tools. We must scan their APKs for renderscript bitcode and 6309 // not launch them if it's present. Don't bother checking on devices 6310 // that don't have 64 bit support. 6311 boolean needsRenderScriptOverride = false; 6312 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6313 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6314 abiList = Build.SUPPORTED_32_BIT_ABIS; 6315 needsRenderScriptOverride = true; 6316 } 6317 6318 final int copyRet; 6319 if (isAsec) { 6320 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6321 } else { 6322 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6323 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6324 } 6325 6326 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6327 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6328 "Error unpackaging native libs for app, errorCode=" + copyRet); 6329 } 6330 6331 if (copyRet >= 0) { 6332 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6333 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6334 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6335 } else if (needsRenderScriptOverride) { 6336 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6337 } 6338 } 6339 } catch (IOException ioe) { 6340 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6341 } finally { 6342 IoUtils.closeQuietly(handle); 6343 } 6344 6345 // Now that we've calculated the ABIs and determined if it's an internal app, 6346 // we will go ahead and populate the nativeLibraryPath. 6347 setNativeLibraryPaths(pkg); 6348 6349 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6350 final int[] userIds = sUserManager.getUserIds(); 6351 synchronized (mInstallLock) { 6352 // Create a native library symlink only if we have native libraries 6353 // and if the native libraries are 32 bit libraries. We do not provide 6354 // this symlink for 64 bit libraries. 6355 if (pkg.applicationInfo.primaryCpuAbi != null && 6356 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6357 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6358 for (int userId : userIds) { 6359 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6360 nativeLibPath, userId) < 0) { 6361 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6362 "Failed linking native library dir (user=" + userId + ")"); 6363 } 6364 } 6365 } 6366 } 6367 } 6368 6369 // This is a special case for the "system" package, where the ABI is 6370 // dictated by the zygote configuration (and init.rc). We should keep track 6371 // of this ABI so that we can deal with "normal" applications that run under 6372 // the same UID correctly. 6373 if (mPlatformPackage == pkg) { 6374 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6375 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6376 } 6377 6378 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6379 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6380 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6381 // Copy the derived override back to the parsed package, so that we can 6382 // update the package settings accordingly. 6383 pkg.cpuAbiOverride = cpuAbiOverride; 6384 6385 if (DEBUG_ABI_SELECTION) { 6386 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6387 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6388 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6389 } 6390 6391 // Push the derived path down into PackageSettings so we know what to 6392 // clean up at uninstall time. 6393 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6394 6395 if (DEBUG_ABI_SELECTION) { 6396 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6397 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6398 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6399 } 6400 6401 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6402 // We don't do this here during boot because we can do it all 6403 // at once after scanning all existing packages. 6404 // 6405 // We also do this *before* we perform dexopt on this package, so that 6406 // we can avoid redundant dexopts, and also to make sure we've got the 6407 // code and package path correct. 6408 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6409 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6410 } 6411 6412 if ((scanFlags & SCAN_NO_DEX) == 0) { 6413 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6414 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6415 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6416 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6417 } 6418 } 6419 if (mFactoryTest && pkg.requestedPermissions.contains( 6420 android.Manifest.permission.FACTORY_TEST)) { 6421 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6422 } 6423 6424 ArrayList<PackageParser.Package> clientLibPkgs = null; 6425 6426 // writer 6427 synchronized (mPackages) { 6428 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6429 // Only system apps can add new shared libraries. 6430 if (pkg.libraryNames != null) { 6431 for (int i=0; i<pkg.libraryNames.size(); i++) { 6432 String name = pkg.libraryNames.get(i); 6433 boolean allowed = false; 6434 if (pkg.isUpdatedSystemApp()) { 6435 // New library entries can only be added through the 6436 // system image. This is important to get rid of a lot 6437 // of nasty edge cases: for example if we allowed a non- 6438 // system update of the app to add a library, then uninstalling 6439 // the update would make the library go away, and assumptions 6440 // we made such as through app install filtering would now 6441 // have allowed apps on the device which aren't compatible 6442 // with it. Better to just have the restriction here, be 6443 // conservative, and create many fewer cases that can negatively 6444 // impact the user experience. 6445 final PackageSetting sysPs = mSettings 6446 .getDisabledSystemPkgLPr(pkg.packageName); 6447 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6448 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6449 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6450 allowed = true; 6451 allowed = true; 6452 break; 6453 } 6454 } 6455 } 6456 } else { 6457 allowed = true; 6458 } 6459 if (allowed) { 6460 if (!mSharedLibraries.containsKey(name)) { 6461 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6462 } else if (!name.equals(pkg.packageName)) { 6463 Slog.w(TAG, "Package " + pkg.packageName + " library " 6464 + name + " already exists; skipping"); 6465 } 6466 } else { 6467 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6468 + name + " that is not declared on system image; skipping"); 6469 } 6470 } 6471 if ((scanFlags&SCAN_BOOTING) == 0) { 6472 // If we are not booting, we need to update any applications 6473 // that are clients of our shared library. If we are booting, 6474 // this will all be done once the scan is complete. 6475 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6476 } 6477 } 6478 } 6479 } 6480 6481 // We also need to dexopt any apps that are dependent on this library. Note that 6482 // if these fail, we should abort the install since installing the library will 6483 // result in some apps being broken. 6484 if (clientLibPkgs != null) { 6485 if ((scanFlags & SCAN_NO_DEX) == 0) { 6486 for (int i = 0; i < clientLibPkgs.size(); i++) { 6487 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6488 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6489 null /* instruction sets */, forceDex, 6490 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6491 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6492 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6493 "scanPackageLI failed to dexopt clientLibPkgs"); 6494 } 6495 } 6496 } 6497 } 6498 6499 // Also need to kill any apps that are dependent on the library. 6500 if (clientLibPkgs != null) { 6501 for (int i=0; i<clientLibPkgs.size(); i++) { 6502 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6503 killApplication(clientPkg.applicationInfo.packageName, 6504 clientPkg.applicationInfo.uid, "update lib"); 6505 } 6506 } 6507 6508 // writer 6509 synchronized (mPackages) { 6510 // We don't expect installation to fail beyond this point 6511 6512 // Add the new setting to mSettings 6513 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6514 // Add the new setting to mPackages 6515 mPackages.put(pkg.applicationInfo.packageName, pkg); 6516 // Make sure we don't accidentally delete its data. 6517 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6518 while (iter.hasNext()) { 6519 PackageCleanItem item = iter.next(); 6520 if (pkgName.equals(item.packageName)) { 6521 iter.remove(); 6522 } 6523 } 6524 6525 // Take care of first install / last update times. 6526 if (currentTime != 0) { 6527 if (pkgSetting.firstInstallTime == 0) { 6528 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6529 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6530 pkgSetting.lastUpdateTime = currentTime; 6531 } 6532 } else if (pkgSetting.firstInstallTime == 0) { 6533 // We need *something*. Take time time stamp of the file. 6534 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6535 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6536 if (scanFileTime != pkgSetting.timeStamp) { 6537 // A package on the system image has changed; consider this 6538 // to be an update. 6539 pkgSetting.lastUpdateTime = scanFileTime; 6540 } 6541 } 6542 6543 // Add the package's KeySets to the global KeySetManagerService 6544 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6545 try { 6546 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6547 if (pkg.mKeySetMapping != null) { 6548 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6549 if (pkg.mUpgradeKeySets != null) { 6550 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6551 } 6552 } 6553 } catch (NullPointerException e) { 6554 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6555 } catch (IllegalArgumentException e) { 6556 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6557 } 6558 6559 int N = pkg.providers.size(); 6560 StringBuilder r = null; 6561 int i; 6562 for (i=0; i<N; i++) { 6563 PackageParser.Provider p = pkg.providers.get(i); 6564 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6565 p.info.processName, pkg.applicationInfo.uid); 6566 mProviders.addProvider(p); 6567 p.syncable = p.info.isSyncable; 6568 if (p.info.authority != null) { 6569 String names[] = p.info.authority.split(";"); 6570 p.info.authority = null; 6571 for (int j = 0; j < names.length; j++) { 6572 if (j == 1 && p.syncable) { 6573 // We only want the first authority for a provider to possibly be 6574 // syncable, so if we already added this provider using a different 6575 // authority clear the syncable flag. We copy the provider before 6576 // changing it because the mProviders object contains a reference 6577 // to a provider that we don't want to change. 6578 // Only do this for the second authority since the resulting provider 6579 // object can be the same for all future authorities for this provider. 6580 p = new PackageParser.Provider(p); 6581 p.syncable = false; 6582 } 6583 if (!mProvidersByAuthority.containsKey(names[j])) { 6584 mProvidersByAuthority.put(names[j], p); 6585 if (p.info.authority == null) { 6586 p.info.authority = names[j]; 6587 } else { 6588 p.info.authority = p.info.authority + ";" + names[j]; 6589 } 6590 if (DEBUG_PACKAGE_SCANNING) { 6591 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6592 Log.d(TAG, "Registered content provider: " + names[j] 6593 + ", className = " + p.info.name + ", isSyncable = " 6594 + p.info.isSyncable); 6595 } 6596 } else { 6597 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6598 Slog.w(TAG, "Skipping provider name " + names[j] + 6599 " (in package " + pkg.applicationInfo.packageName + 6600 "): name already used by " 6601 + ((other != null && other.getComponentName() != null) 6602 ? other.getComponentName().getPackageName() : "?")); 6603 } 6604 } 6605 } 6606 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6607 if (r == null) { 6608 r = new StringBuilder(256); 6609 } else { 6610 r.append(' '); 6611 } 6612 r.append(p.info.name); 6613 } 6614 } 6615 if (r != null) { 6616 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6617 } 6618 6619 N = pkg.services.size(); 6620 r = null; 6621 for (i=0; i<N; i++) { 6622 PackageParser.Service s = pkg.services.get(i); 6623 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6624 s.info.processName, pkg.applicationInfo.uid); 6625 mServices.addService(s); 6626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6627 if (r == null) { 6628 r = new StringBuilder(256); 6629 } else { 6630 r.append(' '); 6631 } 6632 r.append(s.info.name); 6633 } 6634 } 6635 if (r != null) { 6636 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6637 } 6638 6639 N = pkg.receivers.size(); 6640 r = null; 6641 for (i=0; i<N; i++) { 6642 PackageParser.Activity a = pkg.receivers.get(i); 6643 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6644 a.info.processName, pkg.applicationInfo.uid); 6645 mReceivers.addActivity(a, "receiver"); 6646 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6647 if (r == null) { 6648 r = new StringBuilder(256); 6649 } else { 6650 r.append(' '); 6651 } 6652 r.append(a.info.name); 6653 } 6654 } 6655 if (r != null) { 6656 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6657 } 6658 6659 N = pkg.activities.size(); 6660 r = null; 6661 for (i=0; i<N; i++) { 6662 PackageParser.Activity a = pkg.activities.get(i); 6663 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6664 a.info.processName, pkg.applicationInfo.uid); 6665 mActivities.addActivity(a, "activity"); 6666 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6667 if (r == null) { 6668 r = new StringBuilder(256); 6669 } else { 6670 r.append(' '); 6671 } 6672 r.append(a.info.name); 6673 } 6674 } 6675 if (r != null) { 6676 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6677 } 6678 6679 N = pkg.permissionGroups.size(); 6680 r = null; 6681 for (i=0; i<N; i++) { 6682 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6683 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6684 if (cur == null) { 6685 mPermissionGroups.put(pg.info.name, pg); 6686 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6687 if (r == null) { 6688 r = new StringBuilder(256); 6689 } else { 6690 r.append(' '); 6691 } 6692 r.append(pg.info.name); 6693 } 6694 } else { 6695 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6696 + pg.info.packageName + " ignored: original from " 6697 + cur.info.packageName); 6698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6699 if (r == null) { 6700 r = new StringBuilder(256); 6701 } else { 6702 r.append(' '); 6703 } 6704 r.append("DUP:"); 6705 r.append(pg.info.name); 6706 } 6707 } 6708 } 6709 if (r != null) { 6710 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6711 } 6712 6713 N = pkg.permissions.size(); 6714 r = null; 6715 for (i=0; i<N; i++) { 6716 PackageParser.Permission p = pkg.permissions.get(i); 6717 6718 // Now that permission groups have a special meaning, we ignore permission 6719 // groups for legacy apps to prevent unexpected behavior. In particular, 6720 // permissions for one app being granted to someone just becuase they happen 6721 // to be in a group defined by another app (before this had no implications). 6722 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6723 p.group = mPermissionGroups.get(p.info.group); 6724 // Warn for a permission in an unknown group. 6725 if (p.info.group != null && p.group == null) { 6726 Slog.w(TAG, "Permission " + p.info.name + " from package " 6727 + p.info.packageName + " in an unknown group " + p.info.group); 6728 } 6729 } 6730 6731 ArrayMap<String, BasePermission> permissionMap = 6732 p.tree ? mSettings.mPermissionTrees 6733 : mSettings.mPermissions; 6734 BasePermission bp = permissionMap.get(p.info.name); 6735 6736 // Allow system apps to redefine non-system permissions 6737 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6738 final boolean currentOwnerIsSystem = (bp.perm != null 6739 && isSystemApp(bp.perm.owner)); 6740 if (isSystemApp(p.owner)) { 6741 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6742 // It's a built-in permission and no owner, take ownership now 6743 bp.packageSetting = pkgSetting; 6744 bp.perm = p; 6745 bp.uid = pkg.applicationInfo.uid; 6746 bp.sourcePackage = p.info.packageName; 6747 } else if (!currentOwnerIsSystem) { 6748 String msg = "New decl " + p.owner + " of permission " 6749 + p.info.name + " is system; overriding " + bp.sourcePackage; 6750 reportSettingsProblem(Log.WARN, msg); 6751 bp = null; 6752 } 6753 } 6754 } 6755 6756 if (bp == null) { 6757 bp = new BasePermission(p.info.name, p.info.packageName, 6758 BasePermission.TYPE_NORMAL); 6759 permissionMap.put(p.info.name, bp); 6760 } 6761 6762 if (bp.perm == null) { 6763 if (bp.sourcePackage == null 6764 || bp.sourcePackage.equals(p.info.packageName)) { 6765 BasePermission tree = findPermissionTreeLP(p.info.name); 6766 if (tree == null 6767 || tree.sourcePackage.equals(p.info.packageName)) { 6768 bp.packageSetting = pkgSetting; 6769 bp.perm = p; 6770 bp.uid = pkg.applicationInfo.uid; 6771 bp.sourcePackage = p.info.packageName; 6772 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6773 if (r == null) { 6774 r = new StringBuilder(256); 6775 } else { 6776 r.append(' '); 6777 } 6778 r.append(p.info.name); 6779 } 6780 } else { 6781 Slog.w(TAG, "Permission " + p.info.name + " from package " 6782 + p.info.packageName + " ignored: base tree " 6783 + tree.name + " is from package " 6784 + tree.sourcePackage); 6785 } 6786 } else { 6787 Slog.w(TAG, "Permission " + p.info.name + " from package " 6788 + p.info.packageName + " ignored: original from " 6789 + bp.sourcePackage); 6790 } 6791 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6792 if (r == null) { 6793 r = new StringBuilder(256); 6794 } else { 6795 r.append(' '); 6796 } 6797 r.append("DUP:"); 6798 r.append(p.info.name); 6799 } 6800 if (bp.perm == p) { 6801 bp.protectionLevel = p.info.protectionLevel; 6802 } 6803 } 6804 6805 if (r != null) { 6806 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6807 } 6808 6809 N = pkg.instrumentation.size(); 6810 r = null; 6811 for (i=0; i<N; i++) { 6812 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6813 a.info.packageName = pkg.applicationInfo.packageName; 6814 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6815 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6816 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6817 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6818 a.info.dataDir = pkg.applicationInfo.dataDir; 6819 6820 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6821 // need other information about the application, like the ABI and what not ? 6822 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6823 mInstrumentation.put(a.getComponentName(), a); 6824 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6825 if (r == null) { 6826 r = new StringBuilder(256); 6827 } else { 6828 r.append(' '); 6829 } 6830 r.append(a.info.name); 6831 } 6832 } 6833 if (r != null) { 6834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6835 } 6836 6837 if (pkg.protectedBroadcasts != null) { 6838 N = pkg.protectedBroadcasts.size(); 6839 for (i=0; i<N; i++) { 6840 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6841 } 6842 } 6843 6844 pkgSetting.setTimeStamp(scanFileTime); 6845 6846 // Create idmap files for pairs of (packages, overlay packages). 6847 // Note: "android", ie framework-res.apk, is handled by native layers. 6848 if (pkg.mOverlayTarget != null) { 6849 // This is an overlay package. 6850 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6851 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6852 mOverlays.put(pkg.mOverlayTarget, 6853 new ArrayMap<String, PackageParser.Package>()); 6854 } 6855 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6856 map.put(pkg.packageName, pkg); 6857 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6858 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6859 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6860 "scanPackageLI failed to createIdmap"); 6861 } 6862 } 6863 } else if (mOverlays.containsKey(pkg.packageName) && 6864 !pkg.packageName.equals("android")) { 6865 // This is a regular package, with one or more known overlay packages. 6866 createIdmapsForPackageLI(pkg); 6867 } 6868 } 6869 6870 return pkg; 6871 } 6872 6873 /** 6874 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6875 * i.e, so that all packages can be run inside a single process if required. 6876 * 6877 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6878 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6879 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6880 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6881 * updating a package that belongs to a shared user. 6882 * 6883 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6884 * adds unnecessary complexity. 6885 */ 6886 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6887 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6888 String requiredInstructionSet = null; 6889 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6890 requiredInstructionSet = VMRuntime.getInstructionSet( 6891 scannedPackage.applicationInfo.primaryCpuAbi); 6892 } 6893 6894 PackageSetting requirer = null; 6895 for (PackageSetting ps : packagesForUser) { 6896 // If packagesForUser contains scannedPackage, we skip it. This will happen 6897 // when scannedPackage is an update of an existing package. Without this check, 6898 // we will never be able to change the ABI of any package belonging to a shared 6899 // user, even if it's compatible with other packages. 6900 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6901 if (ps.primaryCpuAbiString == null) { 6902 continue; 6903 } 6904 6905 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6906 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6907 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6908 // this but there's not much we can do. 6909 String errorMessage = "Instruction set mismatch, " 6910 + ((requirer == null) ? "[caller]" : requirer) 6911 + " requires " + requiredInstructionSet + " whereas " + ps 6912 + " requires " + instructionSet; 6913 Slog.w(TAG, errorMessage); 6914 } 6915 6916 if (requiredInstructionSet == null) { 6917 requiredInstructionSet = instructionSet; 6918 requirer = ps; 6919 } 6920 } 6921 } 6922 6923 if (requiredInstructionSet != null) { 6924 String adjustedAbi; 6925 if (requirer != null) { 6926 // requirer != null implies that either scannedPackage was null or that scannedPackage 6927 // did not require an ABI, in which case we have to adjust scannedPackage to match 6928 // the ABI of the set (which is the same as requirer's ABI) 6929 adjustedAbi = requirer.primaryCpuAbiString; 6930 if (scannedPackage != null) { 6931 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6932 } 6933 } else { 6934 // requirer == null implies that we're updating all ABIs in the set to 6935 // match scannedPackage. 6936 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6937 } 6938 6939 for (PackageSetting ps : packagesForUser) { 6940 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6941 if (ps.primaryCpuAbiString != null) { 6942 continue; 6943 } 6944 6945 ps.primaryCpuAbiString = adjustedAbi; 6946 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6947 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6948 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6949 6950 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6951 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6952 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6953 ps.primaryCpuAbiString = null; 6954 ps.pkg.applicationInfo.primaryCpuAbi = null; 6955 return; 6956 } else { 6957 mInstaller.rmdex(ps.codePathString, 6958 getDexCodeInstructionSet(getPreferredInstructionSet())); 6959 } 6960 } 6961 } 6962 } 6963 } 6964 } 6965 6966 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6967 synchronized (mPackages) { 6968 mResolverReplaced = true; 6969 // Set up information for custom user intent resolution activity. 6970 mResolveActivity.applicationInfo = pkg.applicationInfo; 6971 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6972 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6973 mResolveActivity.processName = pkg.applicationInfo.packageName; 6974 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6975 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6976 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6977 mResolveActivity.theme = 0; 6978 mResolveActivity.exported = true; 6979 mResolveActivity.enabled = true; 6980 mResolveInfo.activityInfo = mResolveActivity; 6981 mResolveInfo.priority = 0; 6982 mResolveInfo.preferredOrder = 0; 6983 mResolveInfo.match = 0; 6984 mResolveComponentName = mCustomResolverComponentName; 6985 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6986 mResolveComponentName); 6987 } 6988 } 6989 6990 private static String calculateBundledApkRoot(final String codePathString) { 6991 final File codePath = new File(codePathString); 6992 final File codeRoot; 6993 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6994 codeRoot = Environment.getRootDirectory(); 6995 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6996 codeRoot = Environment.getOemDirectory(); 6997 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6998 codeRoot = Environment.getVendorDirectory(); 6999 } else { 7000 // Unrecognized code path; take its top real segment as the apk root: 7001 // e.g. /something/app/blah.apk => /something 7002 try { 7003 File f = codePath.getCanonicalFile(); 7004 File parent = f.getParentFile(); // non-null because codePath is a file 7005 File tmp; 7006 while ((tmp = parent.getParentFile()) != null) { 7007 f = parent; 7008 parent = tmp; 7009 } 7010 codeRoot = f; 7011 Slog.w(TAG, "Unrecognized code path " 7012 + codePath + " - using " + codeRoot); 7013 } catch (IOException e) { 7014 // Can't canonicalize the code path -- shenanigans? 7015 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7016 return Environment.getRootDirectory().getPath(); 7017 } 7018 } 7019 return codeRoot.getPath(); 7020 } 7021 7022 /** 7023 * Derive and set the location of native libraries for the given package, 7024 * which varies depending on where and how the package was installed. 7025 */ 7026 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7027 final ApplicationInfo info = pkg.applicationInfo; 7028 final String codePath = pkg.codePath; 7029 final File codeFile = new File(codePath); 7030 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7031 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7032 7033 info.nativeLibraryRootDir = null; 7034 info.nativeLibraryRootRequiresIsa = false; 7035 info.nativeLibraryDir = null; 7036 info.secondaryNativeLibraryDir = null; 7037 7038 if (isApkFile(codeFile)) { 7039 // Monolithic install 7040 if (bundledApp) { 7041 // If "/system/lib64/apkname" exists, assume that is the per-package 7042 // native library directory to use; otherwise use "/system/lib/apkname". 7043 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7044 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7045 getPrimaryInstructionSet(info)); 7046 7047 // This is a bundled system app so choose the path based on the ABI. 7048 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7049 // is just the default path. 7050 final String apkName = deriveCodePathName(codePath); 7051 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7052 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7053 apkName).getAbsolutePath(); 7054 7055 if (info.secondaryCpuAbi != null) { 7056 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7057 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7058 secondaryLibDir, apkName).getAbsolutePath(); 7059 } 7060 } else if (asecApp) { 7061 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7062 .getAbsolutePath(); 7063 } else { 7064 final String apkName = deriveCodePathName(codePath); 7065 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7066 .getAbsolutePath(); 7067 } 7068 7069 info.nativeLibraryRootRequiresIsa = false; 7070 info.nativeLibraryDir = info.nativeLibraryRootDir; 7071 } else { 7072 // Cluster install 7073 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7074 info.nativeLibraryRootRequiresIsa = true; 7075 7076 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7077 getPrimaryInstructionSet(info)).getAbsolutePath(); 7078 7079 if (info.secondaryCpuAbi != null) { 7080 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7081 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7082 } 7083 } 7084 } 7085 7086 /** 7087 * Calculate the abis and roots for a bundled app. These can uniquely 7088 * be determined from the contents of the system partition, i.e whether 7089 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7090 * of this information, and instead assume that the system was built 7091 * sensibly. 7092 */ 7093 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7094 PackageSetting pkgSetting) { 7095 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7096 7097 // If "/system/lib64/apkname" exists, assume that is the per-package 7098 // native library directory to use; otherwise use "/system/lib/apkname". 7099 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7100 setBundledAppAbi(pkg, apkRoot, apkName); 7101 // pkgSetting might be null during rescan following uninstall of updates 7102 // to a bundled app, so accommodate that possibility. The settings in 7103 // that case will be established later from the parsed package. 7104 // 7105 // If the settings aren't null, sync them up with what we've just derived. 7106 // note that apkRoot isn't stored in the package settings. 7107 if (pkgSetting != null) { 7108 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7109 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7110 } 7111 } 7112 7113 /** 7114 * Deduces the ABI of a bundled app and sets the relevant fields on the 7115 * parsed pkg object. 7116 * 7117 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7118 * under which system libraries are installed. 7119 * @param apkName the name of the installed package. 7120 */ 7121 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7122 final File codeFile = new File(pkg.codePath); 7123 7124 final boolean has64BitLibs; 7125 final boolean has32BitLibs; 7126 if (isApkFile(codeFile)) { 7127 // Monolithic install 7128 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7129 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7130 } else { 7131 // Cluster install 7132 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7133 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7134 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7135 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7136 has64BitLibs = (new File(rootDir, isa)).exists(); 7137 } else { 7138 has64BitLibs = false; 7139 } 7140 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7141 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7142 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7143 has32BitLibs = (new File(rootDir, isa)).exists(); 7144 } else { 7145 has32BitLibs = false; 7146 } 7147 } 7148 7149 if (has64BitLibs && !has32BitLibs) { 7150 // The package has 64 bit libs, but not 32 bit libs. Its primary 7151 // ABI should be 64 bit. We can safely assume here that the bundled 7152 // native libraries correspond to the most preferred ABI in the list. 7153 7154 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7155 pkg.applicationInfo.secondaryCpuAbi = null; 7156 } else if (has32BitLibs && !has64BitLibs) { 7157 // The package has 32 bit libs but not 64 bit libs. Its primary 7158 // ABI should be 32 bit. 7159 7160 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7161 pkg.applicationInfo.secondaryCpuAbi = null; 7162 } else if (has32BitLibs && has64BitLibs) { 7163 // The application has both 64 and 32 bit bundled libraries. We check 7164 // here that the app declares multiArch support, and warn if it doesn't. 7165 // 7166 // We will be lenient here and record both ABIs. The primary will be the 7167 // ABI that's higher on the list, i.e, a device that's configured to prefer 7168 // 64 bit apps will see a 64 bit primary ABI, 7169 7170 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7171 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7172 } 7173 7174 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7175 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7176 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7177 } else { 7178 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7179 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7180 } 7181 } else { 7182 pkg.applicationInfo.primaryCpuAbi = null; 7183 pkg.applicationInfo.secondaryCpuAbi = null; 7184 } 7185 } 7186 7187 private void killApplication(String pkgName, int appId, String reason) { 7188 // Request the ActivityManager to kill the process(only for existing packages) 7189 // so that we do not end up in a confused state while the user is still using the older 7190 // version of the application while the new one gets installed. 7191 IActivityManager am = ActivityManagerNative.getDefault(); 7192 if (am != null) { 7193 try { 7194 am.killApplicationWithAppId(pkgName, appId, reason); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 } 7199 7200 void removePackageLI(PackageSetting ps, boolean chatty) { 7201 if (DEBUG_INSTALL) { 7202 if (chatty) 7203 Log.d(TAG, "Removing package " + ps.name); 7204 } 7205 7206 // writer 7207 synchronized (mPackages) { 7208 mPackages.remove(ps.name); 7209 final PackageParser.Package pkg = ps.pkg; 7210 if (pkg != null) { 7211 cleanPackageDataStructuresLILPw(pkg, chatty); 7212 } 7213 } 7214 } 7215 7216 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7217 if (DEBUG_INSTALL) { 7218 if (chatty) 7219 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7220 } 7221 7222 // writer 7223 synchronized (mPackages) { 7224 mPackages.remove(pkg.applicationInfo.packageName); 7225 cleanPackageDataStructuresLILPw(pkg, chatty); 7226 } 7227 } 7228 7229 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7230 int N = pkg.providers.size(); 7231 StringBuilder r = null; 7232 int i; 7233 for (i=0; i<N; i++) { 7234 PackageParser.Provider p = pkg.providers.get(i); 7235 mProviders.removeProvider(p); 7236 if (p.info.authority == null) { 7237 7238 /* There was another ContentProvider with this authority when 7239 * this app was installed so this authority is null, 7240 * Ignore it as we don't have to unregister the provider. 7241 */ 7242 continue; 7243 } 7244 String names[] = p.info.authority.split(";"); 7245 for (int j = 0; j < names.length; j++) { 7246 if (mProvidersByAuthority.get(names[j]) == p) { 7247 mProvidersByAuthority.remove(names[j]); 7248 if (DEBUG_REMOVE) { 7249 if (chatty) 7250 Log.d(TAG, "Unregistered content provider: " + names[j] 7251 + ", className = " + p.info.name + ", isSyncable = " 7252 + p.info.isSyncable); 7253 } 7254 } 7255 } 7256 if (DEBUG_REMOVE && chatty) { 7257 if (r == null) { 7258 r = new StringBuilder(256); 7259 } else { 7260 r.append(' '); 7261 } 7262 r.append(p.info.name); 7263 } 7264 } 7265 if (r != null) { 7266 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7267 } 7268 7269 N = pkg.services.size(); 7270 r = null; 7271 for (i=0; i<N; i++) { 7272 PackageParser.Service s = pkg.services.get(i); 7273 mServices.removeService(s); 7274 if (chatty) { 7275 if (r == null) { 7276 r = new StringBuilder(256); 7277 } else { 7278 r.append(' '); 7279 } 7280 r.append(s.info.name); 7281 } 7282 } 7283 if (r != null) { 7284 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7285 } 7286 7287 N = pkg.receivers.size(); 7288 r = null; 7289 for (i=0; i<N; i++) { 7290 PackageParser.Activity a = pkg.receivers.get(i); 7291 mReceivers.removeActivity(a, "receiver"); 7292 if (DEBUG_REMOVE && chatty) { 7293 if (r == null) { 7294 r = new StringBuilder(256); 7295 } else { 7296 r.append(' '); 7297 } 7298 r.append(a.info.name); 7299 } 7300 } 7301 if (r != null) { 7302 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7303 } 7304 7305 N = pkg.activities.size(); 7306 r = null; 7307 for (i=0; i<N; i++) { 7308 PackageParser.Activity a = pkg.activities.get(i); 7309 mActivities.removeActivity(a, "activity"); 7310 if (DEBUG_REMOVE && chatty) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append(a.info.name); 7317 } 7318 } 7319 if (r != null) { 7320 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7321 } 7322 7323 N = pkg.permissions.size(); 7324 r = null; 7325 for (i=0; i<N; i++) { 7326 PackageParser.Permission p = pkg.permissions.get(i); 7327 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7328 if (bp == null) { 7329 bp = mSettings.mPermissionTrees.get(p.info.name); 7330 } 7331 if (bp != null && bp.perm == p) { 7332 bp.perm = null; 7333 if (DEBUG_REMOVE && chatty) { 7334 if (r == null) { 7335 r = new StringBuilder(256); 7336 } else { 7337 r.append(' '); 7338 } 7339 r.append(p.info.name); 7340 } 7341 } 7342 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7343 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7344 if (appOpPerms != null) { 7345 appOpPerms.remove(pkg.packageName); 7346 } 7347 } 7348 } 7349 if (r != null) { 7350 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7351 } 7352 7353 N = pkg.requestedPermissions.size(); 7354 r = null; 7355 for (i=0; i<N; i++) { 7356 String perm = pkg.requestedPermissions.get(i); 7357 BasePermission bp = mSettings.mPermissions.get(perm); 7358 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7359 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7360 if (appOpPerms != null) { 7361 appOpPerms.remove(pkg.packageName); 7362 if (appOpPerms.isEmpty()) { 7363 mAppOpPermissionPackages.remove(perm); 7364 } 7365 } 7366 } 7367 } 7368 if (r != null) { 7369 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7370 } 7371 7372 N = pkg.instrumentation.size(); 7373 r = null; 7374 for (i=0; i<N; i++) { 7375 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7376 mInstrumentation.remove(a.getComponentName()); 7377 if (DEBUG_REMOVE && chatty) { 7378 if (r == null) { 7379 r = new StringBuilder(256); 7380 } else { 7381 r.append(' '); 7382 } 7383 r.append(a.info.name); 7384 } 7385 } 7386 if (r != null) { 7387 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7388 } 7389 7390 r = null; 7391 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7392 // Only system apps can hold shared libraries. 7393 if (pkg.libraryNames != null) { 7394 for (i=0; i<pkg.libraryNames.size(); i++) { 7395 String name = pkg.libraryNames.get(i); 7396 SharedLibraryEntry cur = mSharedLibraries.get(name); 7397 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7398 mSharedLibraries.remove(name); 7399 if (DEBUG_REMOVE && chatty) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append(name); 7406 } 7407 } 7408 } 7409 } 7410 } 7411 if (r != null) { 7412 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7413 } 7414 } 7415 7416 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7417 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7418 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7419 return true; 7420 } 7421 } 7422 return false; 7423 } 7424 7425 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7426 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7427 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7428 7429 private void updatePermissionsLPw(String changingPkg, 7430 PackageParser.Package pkgInfo, int flags) { 7431 // Make sure there are no dangling permission trees. 7432 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7433 while (it.hasNext()) { 7434 final BasePermission bp = it.next(); 7435 if (bp.packageSetting == null) { 7436 // We may not yet have parsed the package, so just see if 7437 // we still know about its settings. 7438 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7439 } 7440 if (bp.packageSetting == null) { 7441 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7442 + " from package " + bp.sourcePackage); 7443 it.remove(); 7444 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7445 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7446 Slog.i(TAG, "Removing old permission tree: " + bp.name 7447 + " from package " + bp.sourcePackage); 7448 flags |= UPDATE_PERMISSIONS_ALL; 7449 it.remove(); 7450 } 7451 } 7452 } 7453 7454 // Make sure all dynamic permissions have been assigned to a package, 7455 // and make sure there are no dangling permissions. 7456 it = mSettings.mPermissions.values().iterator(); 7457 while (it.hasNext()) { 7458 final BasePermission bp = it.next(); 7459 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7460 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7461 + bp.name + " pkg=" + bp.sourcePackage 7462 + " info=" + bp.pendingInfo); 7463 if (bp.packageSetting == null && bp.pendingInfo != null) { 7464 final BasePermission tree = findPermissionTreeLP(bp.name); 7465 if (tree != null && tree.perm != null) { 7466 bp.packageSetting = tree.packageSetting; 7467 bp.perm = new PackageParser.Permission(tree.perm.owner, 7468 new PermissionInfo(bp.pendingInfo)); 7469 bp.perm.info.packageName = tree.perm.info.packageName; 7470 bp.perm.info.name = bp.name; 7471 bp.uid = tree.uid; 7472 } 7473 } 7474 } 7475 if (bp.packageSetting == null) { 7476 // We may not yet have parsed the package, so just see if 7477 // we still know about its settings. 7478 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7479 } 7480 if (bp.packageSetting == null) { 7481 Slog.w(TAG, "Removing dangling permission: " + bp.name 7482 + " from package " + bp.sourcePackage); 7483 it.remove(); 7484 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7485 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7486 Slog.i(TAG, "Removing old permission: " + bp.name 7487 + " from package " + bp.sourcePackage); 7488 flags |= UPDATE_PERMISSIONS_ALL; 7489 it.remove(); 7490 } 7491 } 7492 } 7493 7494 // Now update the permissions for all packages, in particular 7495 // replace the granted permissions of the system packages. 7496 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7497 for (PackageParser.Package pkg : mPackages.values()) { 7498 if (pkg != pkgInfo) { 7499 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7500 changingPkg); 7501 } 7502 } 7503 } 7504 7505 if (pkgInfo != null) { 7506 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7507 } 7508 } 7509 7510 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7511 String packageOfInterest) { 7512 // IMPORTANT: There are two types of permissions: install and runtime. 7513 // Install time permissions are granted when the app is installed to 7514 // all device users and users added in the future. Runtime permissions 7515 // are granted at runtime explicitly to specific users. Normal and signature 7516 // protected permissions are install time permissions. Dangerous permissions 7517 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7518 // otherwise they are runtime permissions. This function does not manage 7519 // runtime permissions except for the case an app targeting Lollipop MR1 7520 // being upgraded to target a newer SDK, in which case dangerous permissions 7521 // are transformed from install time to runtime ones. 7522 7523 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7524 if (ps == null) { 7525 return; 7526 } 7527 7528 PermissionsState permissionsState = ps.getPermissionsState(); 7529 PermissionsState origPermissions = permissionsState; 7530 7531 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7532 7533 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7534 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7535 7536 boolean changedInstallPermission = false; 7537 7538 if (replace) { 7539 ps.installPermissionsFixed = false; 7540 if (!ps.isSharedUser()) { 7541 origPermissions = new PermissionsState(permissionsState); 7542 permissionsState.reset(); 7543 } 7544 } 7545 7546 permissionsState.setGlobalGids(mGlobalGids); 7547 7548 final int N = pkg.requestedPermissions.size(); 7549 for (int i=0; i<N; i++) { 7550 final String name = pkg.requestedPermissions.get(i); 7551 final BasePermission bp = mSettings.mPermissions.get(name); 7552 7553 if (DEBUG_INSTALL) { 7554 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7555 } 7556 7557 if (bp == null || bp.packageSetting == null) { 7558 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7559 Slog.w(TAG, "Unknown permission " + name 7560 + " in package " + pkg.packageName); 7561 } 7562 continue; 7563 } 7564 7565 final String perm = bp.name; 7566 boolean allowedSig = false; 7567 int grant = GRANT_DENIED; 7568 7569 // Keep track of app op permissions. 7570 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7571 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7572 if (pkgs == null) { 7573 pkgs = new ArraySet<>(); 7574 mAppOpPermissionPackages.put(bp.name, pkgs); 7575 } 7576 pkgs.add(pkg.packageName); 7577 } 7578 7579 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7580 switch (level) { 7581 case PermissionInfo.PROTECTION_NORMAL: { 7582 // For all apps normal permissions are install time ones. 7583 grant = GRANT_INSTALL; 7584 } break; 7585 7586 case PermissionInfo.PROTECTION_DANGEROUS: { 7587 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7588 // For legacy apps dangerous permissions are install time ones. 7589 grant = GRANT_INSTALL; 7590 } else if (ps.isSystem()) { 7591 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7592 if (origPermissions.hasInstallPermission(bp.name)) { 7593 // If a system app had an install permission, then the app was 7594 // upgraded and we grant the permissions as runtime to all users. 7595 grant = GRANT_UPGRADE; 7596 upgradeUserIds = currentUserIds; 7597 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7598 // If users changed since the last permissions update for a 7599 // system app, we grant the permission as runtime to the new users. 7600 grant = GRANT_UPGRADE; 7601 upgradeUserIds = currentUserIds; 7602 for (int userId : updatedUserIds) { 7603 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7604 } 7605 } else { 7606 // Otherwise, we grant the permission as runtime if the app 7607 // already had it, i.e. we preserve runtime permissions. 7608 grant = GRANT_RUNTIME; 7609 } 7610 } else if (origPermissions.hasInstallPermission(bp.name)) { 7611 // For legacy apps that became modern, install becomes runtime. 7612 grant = GRANT_UPGRADE; 7613 upgradeUserIds = currentUserIds; 7614 } else if (replace) { 7615 // For upgraded modern apps keep runtime permissions unchanged. 7616 grant = GRANT_RUNTIME; 7617 } 7618 } break; 7619 7620 case PermissionInfo.PROTECTION_SIGNATURE: { 7621 // For all apps signature permissions are install time ones. 7622 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7623 if (allowedSig) { 7624 grant = GRANT_INSTALL; 7625 } 7626 } break; 7627 } 7628 7629 if (DEBUG_INSTALL) { 7630 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7631 } 7632 7633 if (grant != GRANT_DENIED) { 7634 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7635 // If this is an existing, non-system package, then 7636 // we can't add any new permissions to it. 7637 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7638 // Except... if this is a permission that was added 7639 // to the platform (note: need to only do this when 7640 // updating the platform). 7641 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7642 grant = GRANT_DENIED; 7643 } 7644 } 7645 } 7646 7647 switch (grant) { 7648 case GRANT_INSTALL: { 7649 // Grant an install permission. 7650 if (permissionsState.grantInstallPermission(bp) != 7651 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7652 changedInstallPermission = true; 7653 } 7654 } break; 7655 7656 case GRANT_RUNTIME: { 7657 // Grant previously granted runtime permissions. 7658 for (int userId : UserManagerService.getInstance().getUserIds()) { 7659 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7660 if (permissionsState.grantRuntimePermission(bp, userId) == 7661 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7662 // If we cannot put the permission as it was, we have to write. 7663 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7664 changedRuntimePermissionUserIds, userId); 7665 } 7666 } 7667 } 7668 } break; 7669 7670 case GRANT_UPGRADE: { 7671 // Grant runtime permissions for a previously held install permission. 7672 permissionsState.revokeInstallPermission(bp); 7673 for (int userId : upgradeUserIds) { 7674 if (permissionsState.grantRuntimePermission(bp, userId) != 7675 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7676 // If we granted the permission, we have to write. 7677 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7678 changedRuntimePermissionUserIds, userId); 7679 } 7680 } 7681 } break; 7682 7683 default: { 7684 if (packageOfInterest == null 7685 || packageOfInterest.equals(pkg.packageName)) { 7686 Slog.w(TAG, "Not granting permission " + perm 7687 + " to package " + pkg.packageName 7688 + " because it was previously installed without"); 7689 } 7690 } break; 7691 } 7692 } else { 7693 if (permissionsState.revokeInstallPermission(bp) != 7694 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7695 changedInstallPermission = true; 7696 Slog.i(TAG, "Un-granting permission " + perm 7697 + " from package " + pkg.packageName 7698 + " (protectionLevel=" + bp.protectionLevel 7699 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7700 + ")"); 7701 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7702 // Don't print warning for app op permissions, since it is fine for them 7703 // not to be granted, there is a UI for the user to decide. 7704 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7705 Slog.w(TAG, "Not granting permission " + perm 7706 + " to package " + pkg.packageName 7707 + " (protectionLevel=" + bp.protectionLevel 7708 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7709 + ")"); 7710 } 7711 } 7712 } 7713 } 7714 7715 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7716 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7717 // This is the first that we have heard about this package, so the 7718 // permissions we have now selected are fixed until explicitly 7719 // changed. 7720 ps.installPermissionsFixed = true; 7721 } 7722 7723 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7724 7725 // Persist the runtime permissions state for users with changes. 7726 for (int userId : changedRuntimePermissionUserIds) { 7727 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7728 } 7729 } 7730 7731 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7732 boolean allowed = false; 7733 final int NP = PackageParser.NEW_PERMISSIONS.length; 7734 for (int ip=0; ip<NP; ip++) { 7735 final PackageParser.NewPermissionInfo npi 7736 = PackageParser.NEW_PERMISSIONS[ip]; 7737 if (npi.name.equals(perm) 7738 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7739 allowed = true; 7740 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7741 + pkg.packageName); 7742 break; 7743 } 7744 } 7745 return allowed; 7746 } 7747 7748 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7749 BasePermission bp, PermissionsState origPermissions) { 7750 boolean allowed; 7751 allowed = (compareSignatures( 7752 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7753 == PackageManager.SIGNATURE_MATCH) 7754 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7755 == PackageManager.SIGNATURE_MATCH); 7756 if (!allowed && (bp.protectionLevel 7757 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7758 if (isSystemApp(pkg)) { 7759 // For updated system applications, a system permission 7760 // is granted only if it had been defined by the original application. 7761 if (pkg.isUpdatedSystemApp()) { 7762 final PackageSetting sysPs = mSettings 7763 .getDisabledSystemPkgLPr(pkg.packageName); 7764 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7765 // If the original was granted this permission, we take 7766 // that grant decision as read and propagate it to the 7767 // update. 7768 if (sysPs.isPrivileged()) { 7769 allowed = true; 7770 } 7771 } else { 7772 // The system apk may have been updated with an older 7773 // version of the one on the data partition, but which 7774 // granted a new system permission that it didn't have 7775 // before. In this case we do want to allow the app to 7776 // now get the new permission if the ancestral apk is 7777 // privileged to get it. 7778 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7779 for (int j=0; 7780 j<sysPs.pkg.requestedPermissions.size(); j++) { 7781 if (perm.equals( 7782 sysPs.pkg.requestedPermissions.get(j))) { 7783 allowed = true; 7784 break; 7785 } 7786 } 7787 } 7788 } 7789 } else { 7790 allowed = isPrivilegedApp(pkg); 7791 } 7792 } 7793 } 7794 if (!allowed && (bp.protectionLevel 7795 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7796 // For development permissions, a development permission 7797 // is granted only if it was already granted. 7798 allowed = origPermissions.hasInstallPermission(perm); 7799 } 7800 return allowed; 7801 } 7802 7803 final class ActivityIntentResolver 7804 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7806 boolean defaultOnly, int userId) { 7807 if (!sUserManager.exists(userId)) return null; 7808 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7809 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7810 } 7811 7812 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7813 int userId) { 7814 if (!sUserManager.exists(userId)) return null; 7815 mFlags = flags; 7816 return super.queryIntent(intent, resolvedType, 7817 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7818 } 7819 7820 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7821 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7822 if (!sUserManager.exists(userId)) return null; 7823 if (packageActivities == null) { 7824 return null; 7825 } 7826 mFlags = flags; 7827 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7828 final int N = packageActivities.size(); 7829 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7830 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7831 7832 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7833 for (int i = 0; i < N; ++i) { 7834 intentFilters = packageActivities.get(i).intents; 7835 if (intentFilters != null && intentFilters.size() > 0) { 7836 PackageParser.ActivityIntentInfo[] array = 7837 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7838 intentFilters.toArray(array); 7839 listCut.add(array); 7840 } 7841 } 7842 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7843 } 7844 7845 public final void addActivity(PackageParser.Activity a, String type) { 7846 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7847 mActivities.put(a.getComponentName(), a); 7848 if (DEBUG_SHOW_INFO) 7849 Log.v( 7850 TAG, " " + type + " " + 7851 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7852 if (DEBUG_SHOW_INFO) 7853 Log.v(TAG, " Class=" + a.info.name); 7854 final int NI = a.intents.size(); 7855 for (int j=0; j<NI; j++) { 7856 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7857 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7858 intent.setPriority(0); 7859 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7860 + a.className + " with priority > 0, forcing to 0"); 7861 } 7862 if (DEBUG_SHOW_INFO) { 7863 Log.v(TAG, " IntentFilter:"); 7864 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7865 } 7866 if (!intent.debugCheck()) { 7867 Log.w(TAG, "==> For Activity " + a.info.name); 7868 } 7869 addFilter(intent); 7870 } 7871 } 7872 7873 public final void removeActivity(PackageParser.Activity a, String type) { 7874 mActivities.remove(a.getComponentName()); 7875 if (DEBUG_SHOW_INFO) { 7876 Log.v(TAG, " " + type + " " 7877 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7878 : a.info.name) + ":"); 7879 Log.v(TAG, " Class=" + a.info.name); 7880 } 7881 final int NI = a.intents.size(); 7882 for (int j=0; j<NI; j++) { 7883 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7884 if (DEBUG_SHOW_INFO) { 7885 Log.v(TAG, " IntentFilter:"); 7886 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7887 } 7888 removeFilter(intent); 7889 } 7890 } 7891 7892 @Override 7893 protected boolean allowFilterResult( 7894 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7895 ActivityInfo filterAi = filter.activity.info; 7896 for (int i=dest.size()-1; i>=0; i--) { 7897 ActivityInfo destAi = dest.get(i).activityInfo; 7898 if (destAi.name == filterAi.name 7899 && destAi.packageName == filterAi.packageName) { 7900 return false; 7901 } 7902 } 7903 return true; 7904 } 7905 7906 @Override 7907 protected ActivityIntentInfo[] newArray(int size) { 7908 return new ActivityIntentInfo[size]; 7909 } 7910 7911 @Override 7912 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7913 if (!sUserManager.exists(userId)) return true; 7914 PackageParser.Package p = filter.activity.owner; 7915 if (p != null) { 7916 PackageSetting ps = (PackageSetting)p.mExtras; 7917 if (ps != null) { 7918 // System apps are never considered stopped for purposes of 7919 // filtering, because there may be no way for the user to 7920 // actually re-launch them. 7921 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7922 && ps.getStopped(userId); 7923 } 7924 } 7925 return false; 7926 } 7927 7928 @Override 7929 protected boolean isPackageForFilter(String packageName, 7930 PackageParser.ActivityIntentInfo info) { 7931 return packageName.equals(info.activity.owner.packageName); 7932 } 7933 7934 @Override 7935 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7936 int match, int userId) { 7937 if (!sUserManager.exists(userId)) return null; 7938 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7939 return null; 7940 } 7941 final PackageParser.Activity activity = info.activity; 7942 if (mSafeMode && (activity.info.applicationInfo.flags 7943 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7944 return null; 7945 } 7946 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7947 if (ps == null) { 7948 return null; 7949 } 7950 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7951 ps.readUserState(userId), userId); 7952 if (ai == null) { 7953 return null; 7954 } 7955 final ResolveInfo res = new ResolveInfo(); 7956 res.activityInfo = ai; 7957 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7958 res.filter = info; 7959 } 7960 if (info != null) { 7961 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7962 } 7963 res.priority = info.getPriority(); 7964 res.preferredOrder = activity.owner.mPreferredOrder; 7965 //System.out.println("Result: " + res.activityInfo.className + 7966 // " = " + res.priority); 7967 res.match = match; 7968 res.isDefault = info.hasDefault; 7969 res.labelRes = info.labelRes; 7970 res.nonLocalizedLabel = info.nonLocalizedLabel; 7971 if (userNeedsBadging(userId)) { 7972 res.noResourceId = true; 7973 } else { 7974 res.icon = info.icon; 7975 } 7976 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7977 return res; 7978 } 7979 7980 @Override 7981 protected void sortResults(List<ResolveInfo> results) { 7982 Collections.sort(results, mResolvePrioritySorter); 7983 } 7984 7985 @Override 7986 protected void dumpFilter(PrintWriter out, String prefix, 7987 PackageParser.ActivityIntentInfo filter) { 7988 out.print(prefix); out.print( 7989 Integer.toHexString(System.identityHashCode(filter.activity))); 7990 out.print(' '); 7991 filter.activity.printComponentShortName(out); 7992 out.print(" filter "); 7993 out.println(Integer.toHexString(System.identityHashCode(filter))); 7994 } 7995 7996 @Override 7997 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7998 return filter.activity; 7999 } 8000 8001 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8002 PackageParser.Activity activity = (PackageParser.Activity)label; 8003 out.print(prefix); out.print( 8004 Integer.toHexString(System.identityHashCode(activity))); 8005 out.print(' '); 8006 activity.printComponentShortName(out); 8007 if (count > 1) { 8008 out.print(" ("); out.print(count); out.print(" filters)"); 8009 } 8010 out.println(); 8011 } 8012 8013// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8014// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8015// final List<ResolveInfo> retList = Lists.newArrayList(); 8016// while (i.hasNext()) { 8017// final ResolveInfo resolveInfo = i.next(); 8018// if (isEnabledLP(resolveInfo.activityInfo)) { 8019// retList.add(resolveInfo); 8020// } 8021// } 8022// return retList; 8023// } 8024 8025 // Keys are String (activity class name), values are Activity. 8026 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8027 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8028 private int mFlags; 8029 } 8030 8031 private final class ServiceIntentResolver 8032 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8033 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8034 boolean defaultOnly, int userId) { 8035 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8036 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8037 } 8038 8039 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8040 int userId) { 8041 if (!sUserManager.exists(userId)) return null; 8042 mFlags = flags; 8043 return super.queryIntent(intent, resolvedType, 8044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8045 } 8046 8047 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8048 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8049 if (!sUserManager.exists(userId)) return null; 8050 if (packageServices == null) { 8051 return null; 8052 } 8053 mFlags = flags; 8054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8055 final int N = packageServices.size(); 8056 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8057 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8058 8059 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8060 for (int i = 0; i < N; ++i) { 8061 intentFilters = packageServices.get(i).intents; 8062 if (intentFilters != null && intentFilters.size() > 0) { 8063 PackageParser.ServiceIntentInfo[] array = 8064 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8065 intentFilters.toArray(array); 8066 listCut.add(array); 8067 } 8068 } 8069 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8070 } 8071 8072 public final void addService(PackageParser.Service s) { 8073 mServices.put(s.getComponentName(), s); 8074 if (DEBUG_SHOW_INFO) { 8075 Log.v(TAG, " " 8076 + (s.info.nonLocalizedLabel != null 8077 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8078 Log.v(TAG, " Class=" + s.info.name); 8079 } 8080 final int NI = s.intents.size(); 8081 int j; 8082 for (j=0; j<NI; j++) { 8083 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8084 if (DEBUG_SHOW_INFO) { 8085 Log.v(TAG, " IntentFilter:"); 8086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8087 } 8088 if (!intent.debugCheck()) { 8089 Log.w(TAG, "==> For Service " + s.info.name); 8090 } 8091 addFilter(intent); 8092 } 8093 } 8094 8095 public final void removeService(PackageParser.Service s) { 8096 mServices.remove(s.getComponentName()); 8097 if (DEBUG_SHOW_INFO) { 8098 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8099 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8100 Log.v(TAG, " Class=" + s.info.name); 8101 } 8102 final int NI = s.intents.size(); 8103 int j; 8104 for (j=0; j<NI; j++) { 8105 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8106 if (DEBUG_SHOW_INFO) { 8107 Log.v(TAG, " IntentFilter:"); 8108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8109 } 8110 removeFilter(intent); 8111 } 8112 } 8113 8114 @Override 8115 protected boolean allowFilterResult( 8116 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8117 ServiceInfo filterSi = filter.service.info; 8118 for (int i=dest.size()-1; i>=0; i--) { 8119 ServiceInfo destAi = dest.get(i).serviceInfo; 8120 if (destAi.name == filterSi.name 8121 && destAi.packageName == filterSi.packageName) { 8122 return false; 8123 } 8124 } 8125 return true; 8126 } 8127 8128 @Override 8129 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8130 return new PackageParser.ServiceIntentInfo[size]; 8131 } 8132 8133 @Override 8134 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8135 if (!sUserManager.exists(userId)) return true; 8136 PackageParser.Package p = filter.service.owner; 8137 if (p != null) { 8138 PackageSetting ps = (PackageSetting)p.mExtras; 8139 if (ps != null) { 8140 // System apps are never considered stopped for purposes of 8141 // filtering, because there may be no way for the user to 8142 // actually re-launch them. 8143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8144 && ps.getStopped(userId); 8145 } 8146 } 8147 return false; 8148 } 8149 8150 @Override 8151 protected boolean isPackageForFilter(String packageName, 8152 PackageParser.ServiceIntentInfo info) { 8153 return packageName.equals(info.service.owner.packageName); 8154 } 8155 8156 @Override 8157 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8158 int match, int userId) { 8159 if (!sUserManager.exists(userId)) return null; 8160 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8161 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8162 return null; 8163 } 8164 final PackageParser.Service service = info.service; 8165 if (mSafeMode && (service.info.applicationInfo.flags 8166 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8167 return null; 8168 } 8169 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8170 if (ps == null) { 8171 return null; 8172 } 8173 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8174 ps.readUserState(userId), userId); 8175 if (si == null) { 8176 return null; 8177 } 8178 final ResolveInfo res = new ResolveInfo(); 8179 res.serviceInfo = si; 8180 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8181 res.filter = filter; 8182 } 8183 res.priority = info.getPriority(); 8184 res.preferredOrder = service.owner.mPreferredOrder; 8185 res.match = match; 8186 res.isDefault = info.hasDefault; 8187 res.labelRes = info.labelRes; 8188 res.nonLocalizedLabel = info.nonLocalizedLabel; 8189 res.icon = info.icon; 8190 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8191 return res; 8192 } 8193 8194 @Override 8195 protected void sortResults(List<ResolveInfo> results) { 8196 Collections.sort(results, mResolvePrioritySorter); 8197 } 8198 8199 @Override 8200 protected void dumpFilter(PrintWriter out, String prefix, 8201 PackageParser.ServiceIntentInfo filter) { 8202 out.print(prefix); out.print( 8203 Integer.toHexString(System.identityHashCode(filter.service))); 8204 out.print(' '); 8205 filter.service.printComponentShortName(out); 8206 out.print(" filter "); 8207 out.println(Integer.toHexString(System.identityHashCode(filter))); 8208 } 8209 8210 @Override 8211 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8212 return filter.service; 8213 } 8214 8215 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8216 PackageParser.Service service = (PackageParser.Service)label; 8217 out.print(prefix); out.print( 8218 Integer.toHexString(System.identityHashCode(service))); 8219 out.print(' '); 8220 service.printComponentShortName(out); 8221 if (count > 1) { 8222 out.print(" ("); out.print(count); out.print(" filters)"); 8223 } 8224 out.println(); 8225 } 8226 8227// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8228// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8229// final List<ResolveInfo> retList = Lists.newArrayList(); 8230// while (i.hasNext()) { 8231// final ResolveInfo resolveInfo = (ResolveInfo) i; 8232// if (isEnabledLP(resolveInfo.serviceInfo)) { 8233// retList.add(resolveInfo); 8234// } 8235// } 8236// return retList; 8237// } 8238 8239 // Keys are String (activity class name), values are Activity. 8240 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8241 = new ArrayMap<ComponentName, PackageParser.Service>(); 8242 private int mFlags; 8243 }; 8244 8245 private final class ProviderIntentResolver 8246 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8247 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8248 boolean defaultOnly, int userId) { 8249 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8250 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8251 } 8252 8253 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8254 int userId) { 8255 if (!sUserManager.exists(userId)) 8256 return null; 8257 mFlags = flags; 8258 return super.queryIntent(intent, resolvedType, 8259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8260 } 8261 8262 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8263 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8264 if (!sUserManager.exists(userId)) 8265 return null; 8266 if (packageProviders == null) { 8267 return null; 8268 } 8269 mFlags = flags; 8270 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8271 final int N = packageProviders.size(); 8272 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8273 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8274 8275 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8276 for (int i = 0; i < N; ++i) { 8277 intentFilters = packageProviders.get(i).intents; 8278 if (intentFilters != null && intentFilters.size() > 0) { 8279 PackageParser.ProviderIntentInfo[] array = 8280 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8281 intentFilters.toArray(array); 8282 listCut.add(array); 8283 } 8284 } 8285 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8286 } 8287 8288 public final void addProvider(PackageParser.Provider p) { 8289 if (mProviders.containsKey(p.getComponentName())) { 8290 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8291 return; 8292 } 8293 8294 mProviders.put(p.getComponentName(), p); 8295 if (DEBUG_SHOW_INFO) { 8296 Log.v(TAG, " " 8297 + (p.info.nonLocalizedLabel != null 8298 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8299 Log.v(TAG, " Class=" + p.info.name); 8300 } 8301 final int NI = p.intents.size(); 8302 int j; 8303 for (j = 0; j < NI; j++) { 8304 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8305 if (DEBUG_SHOW_INFO) { 8306 Log.v(TAG, " IntentFilter:"); 8307 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8308 } 8309 if (!intent.debugCheck()) { 8310 Log.w(TAG, "==> For Provider " + p.info.name); 8311 } 8312 addFilter(intent); 8313 } 8314 } 8315 8316 public final void removeProvider(PackageParser.Provider p) { 8317 mProviders.remove(p.getComponentName()); 8318 if (DEBUG_SHOW_INFO) { 8319 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8320 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8321 Log.v(TAG, " Class=" + p.info.name); 8322 } 8323 final int NI = p.intents.size(); 8324 int j; 8325 for (j = 0; j < NI; j++) { 8326 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8327 if (DEBUG_SHOW_INFO) { 8328 Log.v(TAG, " IntentFilter:"); 8329 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8330 } 8331 removeFilter(intent); 8332 } 8333 } 8334 8335 @Override 8336 protected boolean allowFilterResult( 8337 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8338 ProviderInfo filterPi = filter.provider.info; 8339 for (int i = dest.size() - 1; i >= 0; i--) { 8340 ProviderInfo destPi = dest.get(i).providerInfo; 8341 if (destPi.name == filterPi.name 8342 && destPi.packageName == filterPi.packageName) { 8343 return false; 8344 } 8345 } 8346 return true; 8347 } 8348 8349 @Override 8350 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8351 return new PackageParser.ProviderIntentInfo[size]; 8352 } 8353 8354 @Override 8355 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8356 if (!sUserManager.exists(userId)) 8357 return true; 8358 PackageParser.Package p = filter.provider.owner; 8359 if (p != null) { 8360 PackageSetting ps = (PackageSetting) p.mExtras; 8361 if (ps != null) { 8362 // System apps are never considered stopped for purposes of 8363 // filtering, because there may be no way for the user to 8364 // actually re-launch them. 8365 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8366 && ps.getStopped(userId); 8367 } 8368 } 8369 return false; 8370 } 8371 8372 @Override 8373 protected boolean isPackageForFilter(String packageName, 8374 PackageParser.ProviderIntentInfo info) { 8375 return packageName.equals(info.provider.owner.packageName); 8376 } 8377 8378 @Override 8379 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8380 int match, int userId) { 8381 if (!sUserManager.exists(userId)) 8382 return null; 8383 final PackageParser.ProviderIntentInfo info = filter; 8384 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8385 return null; 8386 } 8387 final PackageParser.Provider provider = info.provider; 8388 if (mSafeMode && (provider.info.applicationInfo.flags 8389 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8390 return null; 8391 } 8392 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8393 if (ps == null) { 8394 return null; 8395 } 8396 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8397 ps.readUserState(userId), userId); 8398 if (pi == null) { 8399 return null; 8400 } 8401 final ResolveInfo res = new ResolveInfo(); 8402 res.providerInfo = pi; 8403 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8404 res.filter = filter; 8405 } 8406 res.priority = info.getPriority(); 8407 res.preferredOrder = provider.owner.mPreferredOrder; 8408 res.match = match; 8409 res.isDefault = info.hasDefault; 8410 res.labelRes = info.labelRes; 8411 res.nonLocalizedLabel = info.nonLocalizedLabel; 8412 res.icon = info.icon; 8413 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8414 return res; 8415 } 8416 8417 @Override 8418 protected void sortResults(List<ResolveInfo> results) { 8419 Collections.sort(results, mResolvePrioritySorter); 8420 } 8421 8422 @Override 8423 protected void dumpFilter(PrintWriter out, String prefix, 8424 PackageParser.ProviderIntentInfo filter) { 8425 out.print(prefix); 8426 out.print( 8427 Integer.toHexString(System.identityHashCode(filter.provider))); 8428 out.print(' '); 8429 filter.provider.printComponentShortName(out); 8430 out.print(" filter "); 8431 out.println(Integer.toHexString(System.identityHashCode(filter))); 8432 } 8433 8434 @Override 8435 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8436 return filter.provider; 8437 } 8438 8439 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8440 PackageParser.Provider provider = (PackageParser.Provider)label; 8441 out.print(prefix); out.print( 8442 Integer.toHexString(System.identityHashCode(provider))); 8443 out.print(' '); 8444 provider.printComponentShortName(out); 8445 if (count > 1) { 8446 out.print(" ("); out.print(count); out.print(" filters)"); 8447 } 8448 out.println(); 8449 } 8450 8451 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8452 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8453 private int mFlags; 8454 }; 8455 8456 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8457 new Comparator<ResolveInfo>() { 8458 public int compare(ResolveInfo r1, ResolveInfo r2) { 8459 int v1 = r1.priority; 8460 int v2 = r2.priority; 8461 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8462 if (v1 != v2) { 8463 return (v1 > v2) ? -1 : 1; 8464 } 8465 v1 = r1.preferredOrder; 8466 v2 = r2.preferredOrder; 8467 if (v1 != v2) { 8468 return (v1 > v2) ? -1 : 1; 8469 } 8470 if (r1.isDefault != r2.isDefault) { 8471 return r1.isDefault ? -1 : 1; 8472 } 8473 v1 = r1.match; 8474 v2 = r2.match; 8475 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8476 if (v1 != v2) { 8477 return (v1 > v2) ? -1 : 1; 8478 } 8479 if (r1.system != r2.system) { 8480 return r1.system ? -1 : 1; 8481 } 8482 return 0; 8483 } 8484 }; 8485 8486 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8487 new Comparator<ProviderInfo>() { 8488 public int compare(ProviderInfo p1, ProviderInfo p2) { 8489 final int v1 = p1.initOrder; 8490 final int v2 = p2.initOrder; 8491 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8492 } 8493 }; 8494 8495 final void sendPackageBroadcast(final String action, final String pkg, 8496 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8497 final int[] userIds) { 8498 mHandler.post(new Runnable() { 8499 @Override 8500 public void run() { 8501 try { 8502 final IActivityManager am = ActivityManagerNative.getDefault(); 8503 if (am == null) return; 8504 final int[] resolvedUserIds; 8505 if (userIds == null) { 8506 resolvedUserIds = am.getRunningUserIds(); 8507 } else { 8508 resolvedUserIds = userIds; 8509 } 8510 for (int id : resolvedUserIds) { 8511 final Intent intent = new Intent(action, 8512 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8513 if (extras != null) { 8514 intent.putExtras(extras); 8515 } 8516 if (targetPkg != null) { 8517 intent.setPackage(targetPkg); 8518 } 8519 // Modify the UID when posting to other users 8520 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8521 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8522 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8523 intent.putExtra(Intent.EXTRA_UID, uid); 8524 } 8525 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8526 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8527 if (DEBUG_BROADCASTS) { 8528 RuntimeException here = new RuntimeException("here"); 8529 here.fillInStackTrace(); 8530 Slog.d(TAG, "Sending to user " + id + ": " 8531 + intent.toShortString(false, true, false, false) 8532 + " " + intent.getExtras(), here); 8533 } 8534 am.broadcastIntent(null, intent, null, finishedReceiver, 8535 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8536 finishedReceiver != null, false, id); 8537 } 8538 } catch (RemoteException ex) { 8539 } 8540 } 8541 }); 8542 } 8543 8544 /** 8545 * Check if the external storage media is available. This is true if there 8546 * is a mounted external storage medium or if the external storage is 8547 * emulated. 8548 */ 8549 private boolean isExternalMediaAvailable() { 8550 return mMediaMounted || Environment.isExternalStorageEmulated(); 8551 } 8552 8553 @Override 8554 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8555 // writer 8556 synchronized (mPackages) { 8557 if (!isExternalMediaAvailable()) { 8558 // If the external storage is no longer mounted at this point, 8559 // the caller may not have been able to delete all of this 8560 // packages files and can not delete any more. Bail. 8561 return null; 8562 } 8563 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8564 if (lastPackage != null) { 8565 pkgs.remove(lastPackage); 8566 } 8567 if (pkgs.size() > 0) { 8568 return pkgs.get(0); 8569 } 8570 } 8571 return null; 8572 } 8573 8574 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8575 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8576 userId, andCode ? 1 : 0, packageName); 8577 if (mSystemReady) { 8578 msg.sendToTarget(); 8579 } else { 8580 if (mPostSystemReadyMessages == null) { 8581 mPostSystemReadyMessages = new ArrayList<>(); 8582 } 8583 mPostSystemReadyMessages.add(msg); 8584 } 8585 } 8586 8587 void startCleaningPackages() { 8588 // reader 8589 synchronized (mPackages) { 8590 if (!isExternalMediaAvailable()) { 8591 return; 8592 } 8593 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8594 return; 8595 } 8596 } 8597 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8598 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8599 IActivityManager am = ActivityManagerNative.getDefault(); 8600 if (am != null) { 8601 try { 8602 am.startService(null, intent, null, UserHandle.USER_OWNER); 8603 } catch (RemoteException e) { 8604 } 8605 } 8606 } 8607 8608 @Override 8609 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8610 int installFlags, String installerPackageName, VerificationParams verificationParams, 8611 String packageAbiOverride) { 8612 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8613 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8614 } 8615 8616 @Override 8617 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8618 int installFlags, String installerPackageName, VerificationParams verificationParams, 8619 String packageAbiOverride, int userId) { 8620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8621 8622 final int callingUid = Binder.getCallingUid(); 8623 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8624 8625 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8626 try { 8627 if (observer != null) { 8628 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8629 } 8630 } catch (RemoteException re) { 8631 } 8632 return; 8633 } 8634 8635 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8636 installFlags |= PackageManager.INSTALL_FROM_ADB; 8637 8638 } else { 8639 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8640 // about installerPackageName. 8641 8642 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8643 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8644 } 8645 8646 UserHandle user; 8647 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8648 user = UserHandle.ALL; 8649 } else { 8650 user = new UserHandle(userId); 8651 } 8652 8653 // Only system components can circumvent runtime permissions when installing. 8654 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8655 && mContext.checkCallingOrSelfPermission(Manifest.permission 8656 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8657 throw new SecurityException("You need the " 8658 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8659 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8660 } 8661 8662 verificationParams.setInstallerUid(callingUid); 8663 8664 final File originFile = new File(originPath); 8665 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8666 8667 final Message msg = mHandler.obtainMessage(INIT_COPY); 8668 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8669 null, verificationParams, user, packageAbiOverride); 8670 mHandler.sendMessage(msg); 8671 } 8672 8673 void installStage(String packageName, File stagedDir, String stagedCid, 8674 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8675 String installerPackageName, int installerUid, UserHandle user) { 8676 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8677 params.referrerUri, installerUid, null); 8678 8679 final OriginInfo origin; 8680 if (stagedDir != null) { 8681 origin = OriginInfo.fromStagedFile(stagedDir); 8682 } else { 8683 origin = OriginInfo.fromStagedContainer(stagedCid); 8684 } 8685 8686 final Message msg = mHandler.obtainMessage(INIT_COPY); 8687 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8688 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8689 mHandler.sendMessage(msg); 8690 } 8691 8692 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8693 Bundle extras = new Bundle(1); 8694 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8695 8696 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8697 packageName, extras, null, null, new int[] {userId}); 8698 try { 8699 IActivityManager am = ActivityManagerNative.getDefault(); 8700 final boolean isSystem = 8701 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8702 if (isSystem && am.isUserRunning(userId, false)) { 8703 // The just-installed/enabled app is bundled on the system, so presumed 8704 // to be able to run automatically without needing an explicit launch. 8705 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8706 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8707 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8708 .setPackage(packageName); 8709 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8710 android.app.AppOpsManager.OP_NONE, false, false, userId); 8711 } 8712 } catch (RemoteException e) { 8713 // shouldn't happen 8714 Slog.w(TAG, "Unable to bootstrap installed package", e); 8715 } 8716 } 8717 8718 @Override 8719 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8720 int userId) { 8721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8722 PackageSetting pkgSetting; 8723 final int uid = Binder.getCallingUid(); 8724 enforceCrossUserPermission(uid, userId, true, true, 8725 "setApplicationHiddenSetting for user " + userId); 8726 8727 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8728 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8729 return false; 8730 } 8731 8732 long callingId = Binder.clearCallingIdentity(); 8733 try { 8734 boolean sendAdded = false; 8735 boolean sendRemoved = false; 8736 // writer 8737 synchronized (mPackages) { 8738 pkgSetting = mSettings.mPackages.get(packageName); 8739 if (pkgSetting == null) { 8740 return false; 8741 } 8742 if (pkgSetting.getHidden(userId) != hidden) { 8743 pkgSetting.setHidden(hidden, userId); 8744 mSettings.writePackageRestrictionsLPr(userId); 8745 if (hidden) { 8746 sendRemoved = true; 8747 } else { 8748 sendAdded = true; 8749 } 8750 } 8751 } 8752 if (sendAdded) { 8753 sendPackageAddedForUser(packageName, pkgSetting, userId); 8754 return true; 8755 } 8756 if (sendRemoved) { 8757 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8758 "hiding pkg"); 8759 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8760 } 8761 } finally { 8762 Binder.restoreCallingIdentity(callingId); 8763 } 8764 return false; 8765 } 8766 8767 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8768 int userId) { 8769 final PackageRemovedInfo info = new PackageRemovedInfo(); 8770 info.removedPackage = packageName; 8771 info.removedUsers = new int[] {userId}; 8772 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8773 info.sendBroadcast(false, false, false); 8774 } 8775 8776 /** 8777 * Returns true if application is not found or there was an error. Otherwise it returns 8778 * the hidden state of the package for the given user. 8779 */ 8780 @Override 8781 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8783 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8784 false, "getApplicationHidden for user " + userId); 8785 PackageSetting pkgSetting; 8786 long callingId = Binder.clearCallingIdentity(); 8787 try { 8788 // writer 8789 synchronized (mPackages) { 8790 pkgSetting = mSettings.mPackages.get(packageName); 8791 if (pkgSetting == null) { 8792 return true; 8793 } 8794 return pkgSetting.getHidden(userId); 8795 } 8796 } finally { 8797 Binder.restoreCallingIdentity(callingId); 8798 } 8799 } 8800 8801 /** 8802 * @hide 8803 */ 8804 @Override 8805 public int installExistingPackageAsUser(String packageName, int userId) { 8806 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8807 null); 8808 PackageSetting pkgSetting; 8809 final int uid = Binder.getCallingUid(); 8810 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8811 + userId); 8812 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8813 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8814 } 8815 8816 long callingId = Binder.clearCallingIdentity(); 8817 try { 8818 boolean sendAdded = false; 8819 8820 // writer 8821 synchronized (mPackages) { 8822 pkgSetting = mSettings.mPackages.get(packageName); 8823 if (pkgSetting == null) { 8824 return PackageManager.INSTALL_FAILED_INVALID_URI; 8825 } 8826 if (!pkgSetting.getInstalled(userId)) { 8827 pkgSetting.setInstalled(true, userId); 8828 pkgSetting.setHidden(false, userId); 8829 mSettings.writePackageRestrictionsLPr(userId); 8830 sendAdded = true; 8831 } 8832 } 8833 8834 if (sendAdded) { 8835 sendPackageAddedForUser(packageName, pkgSetting, userId); 8836 } 8837 } finally { 8838 Binder.restoreCallingIdentity(callingId); 8839 } 8840 8841 return PackageManager.INSTALL_SUCCEEDED; 8842 } 8843 8844 boolean isUserRestricted(int userId, String restrictionKey) { 8845 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8846 if (restrictions.getBoolean(restrictionKey, false)) { 8847 Log.w(TAG, "User is restricted: " + restrictionKey); 8848 return true; 8849 } 8850 return false; 8851 } 8852 8853 @Override 8854 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8855 mContext.enforceCallingOrSelfPermission( 8856 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8857 "Only package verification agents can verify applications"); 8858 8859 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8860 final PackageVerificationResponse response = new PackageVerificationResponse( 8861 verificationCode, Binder.getCallingUid()); 8862 msg.arg1 = id; 8863 msg.obj = response; 8864 mHandler.sendMessage(msg); 8865 } 8866 8867 @Override 8868 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8869 long millisecondsToDelay) { 8870 mContext.enforceCallingOrSelfPermission( 8871 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8872 "Only package verification agents can extend verification timeouts"); 8873 8874 final PackageVerificationState state = mPendingVerification.get(id); 8875 final PackageVerificationResponse response = new PackageVerificationResponse( 8876 verificationCodeAtTimeout, Binder.getCallingUid()); 8877 8878 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8879 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8880 } 8881 if (millisecondsToDelay < 0) { 8882 millisecondsToDelay = 0; 8883 } 8884 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8885 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8886 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8887 } 8888 8889 if ((state != null) && !state.timeoutExtended()) { 8890 state.extendTimeout(); 8891 8892 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8893 msg.arg1 = id; 8894 msg.obj = response; 8895 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8896 } 8897 } 8898 8899 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8900 int verificationCode, UserHandle user) { 8901 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8902 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8903 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8904 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8905 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8906 8907 mContext.sendBroadcastAsUser(intent, user, 8908 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8909 } 8910 8911 private ComponentName matchComponentForVerifier(String packageName, 8912 List<ResolveInfo> receivers) { 8913 ActivityInfo targetReceiver = null; 8914 8915 final int NR = receivers.size(); 8916 for (int i = 0; i < NR; i++) { 8917 final ResolveInfo info = receivers.get(i); 8918 if (info.activityInfo == null) { 8919 continue; 8920 } 8921 8922 if (packageName.equals(info.activityInfo.packageName)) { 8923 targetReceiver = info.activityInfo; 8924 break; 8925 } 8926 } 8927 8928 if (targetReceiver == null) { 8929 return null; 8930 } 8931 8932 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8933 } 8934 8935 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8936 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8937 if (pkgInfo.verifiers.length == 0) { 8938 return null; 8939 } 8940 8941 final int N = pkgInfo.verifiers.length; 8942 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8943 for (int i = 0; i < N; i++) { 8944 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8945 8946 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8947 receivers); 8948 if (comp == null) { 8949 continue; 8950 } 8951 8952 final int verifierUid = getUidForVerifier(verifierInfo); 8953 if (verifierUid == -1) { 8954 continue; 8955 } 8956 8957 if (DEBUG_VERIFY) { 8958 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8959 + " with the correct signature"); 8960 } 8961 sufficientVerifiers.add(comp); 8962 verificationState.addSufficientVerifier(verifierUid); 8963 } 8964 8965 return sufficientVerifiers; 8966 } 8967 8968 private int getUidForVerifier(VerifierInfo verifierInfo) { 8969 synchronized (mPackages) { 8970 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8971 if (pkg == null) { 8972 return -1; 8973 } else if (pkg.mSignatures.length != 1) { 8974 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8975 + " has more than one signature; ignoring"); 8976 return -1; 8977 } 8978 8979 /* 8980 * If the public key of the package's signature does not match 8981 * our expected public key, then this is a different package and 8982 * we should skip. 8983 */ 8984 8985 final byte[] expectedPublicKey; 8986 try { 8987 final Signature verifierSig = pkg.mSignatures[0]; 8988 final PublicKey publicKey = verifierSig.getPublicKey(); 8989 expectedPublicKey = publicKey.getEncoded(); 8990 } catch (CertificateException e) { 8991 return -1; 8992 } 8993 8994 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8995 8996 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8997 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8998 + " does not have the expected public key; ignoring"); 8999 return -1; 9000 } 9001 9002 return pkg.applicationInfo.uid; 9003 } 9004 } 9005 9006 @Override 9007 public void finishPackageInstall(int token) { 9008 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9009 9010 if (DEBUG_INSTALL) { 9011 Slog.v(TAG, "BM finishing package install for " + token); 9012 } 9013 9014 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9015 mHandler.sendMessage(msg); 9016 } 9017 9018 /** 9019 * Get the verification agent timeout. 9020 * 9021 * @return verification timeout in milliseconds 9022 */ 9023 private long getVerificationTimeout() { 9024 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9025 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9026 DEFAULT_VERIFICATION_TIMEOUT); 9027 } 9028 9029 /** 9030 * Get the default verification agent response code. 9031 * 9032 * @return default verification response code 9033 */ 9034 private int getDefaultVerificationResponse() { 9035 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9036 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9037 DEFAULT_VERIFICATION_RESPONSE); 9038 } 9039 9040 /** 9041 * Check whether or not package verification has been enabled. 9042 * 9043 * @return true if verification should be performed 9044 */ 9045 private boolean isVerificationEnabled(int userId, int installFlags) { 9046 if (!DEFAULT_VERIFY_ENABLE) { 9047 return false; 9048 } 9049 9050 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9051 9052 // Check if installing from ADB 9053 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9054 // Do not run verification in a test harness environment 9055 if (ActivityManager.isRunningInTestHarness()) { 9056 return false; 9057 } 9058 if (ensureVerifyAppsEnabled) { 9059 return true; 9060 } 9061 // Check if the developer does not want package verification for ADB installs 9062 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9063 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9064 return false; 9065 } 9066 } 9067 9068 if (ensureVerifyAppsEnabled) { 9069 return true; 9070 } 9071 9072 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9073 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9074 } 9075 9076 @Override 9077 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9078 throws RemoteException { 9079 mContext.enforceCallingOrSelfPermission( 9080 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9081 "Only intentfilter verification agents can verify applications"); 9082 9083 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9084 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9085 Binder.getCallingUid(), verificationCode, failedDomains); 9086 msg.arg1 = id; 9087 msg.obj = response; 9088 mHandler.sendMessage(msg); 9089 } 9090 9091 @Override 9092 public int getIntentVerificationStatus(String packageName, int userId) { 9093 synchronized (mPackages) { 9094 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9095 } 9096 } 9097 9098 @Override 9099 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9100 boolean result = false; 9101 synchronized (mPackages) { 9102 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9103 } 9104 if (result) { 9105 scheduleWritePackageRestrictionsLocked(userId); 9106 } 9107 return result; 9108 } 9109 9110 @Override 9111 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9112 synchronized (mPackages) { 9113 return mSettings.getIntentFilterVerificationsLPr(packageName); 9114 } 9115 } 9116 9117 @Override 9118 public List<IntentFilter> getAllIntentFilters(String packageName) { 9119 if (TextUtils.isEmpty(packageName)) { 9120 return Collections.<IntentFilter>emptyList(); 9121 } 9122 synchronized (mPackages) { 9123 PackageParser.Package pkg = mPackages.get(packageName); 9124 if (pkg == null || pkg.activities == null) { 9125 return Collections.<IntentFilter>emptyList(); 9126 } 9127 final int count = pkg.activities.size(); 9128 ArrayList<IntentFilter> result = new ArrayList<>(); 9129 for (int n=0; n<count; n++) { 9130 PackageParser.Activity activity = pkg.activities.get(n); 9131 if (activity.intents != null || activity.intents.size() > 0) { 9132 result.addAll(activity.intents); 9133 } 9134 } 9135 return result; 9136 } 9137 } 9138 9139 @Override 9140 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9141 synchronized (mPackages) { 9142 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9143 if (packageName != null) { 9144 result |= updateIntentVerificationStatus(packageName, 9145 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9146 UserHandle.myUserId()); 9147 } 9148 return result; 9149 } 9150 } 9151 9152 @Override 9153 public String getDefaultBrowserPackageName(int userId) { 9154 synchronized (mPackages) { 9155 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9156 } 9157 } 9158 9159 /** 9160 * Get the "allow unknown sources" setting. 9161 * 9162 * @return the current "allow unknown sources" setting 9163 */ 9164 private int getUnknownSourcesSettings() { 9165 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9166 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9167 -1); 9168 } 9169 9170 @Override 9171 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9172 final int uid = Binder.getCallingUid(); 9173 // writer 9174 synchronized (mPackages) { 9175 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9176 if (targetPackageSetting == null) { 9177 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9178 } 9179 9180 PackageSetting installerPackageSetting; 9181 if (installerPackageName != null) { 9182 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9183 if (installerPackageSetting == null) { 9184 throw new IllegalArgumentException("Unknown installer package: " 9185 + installerPackageName); 9186 } 9187 } else { 9188 installerPackageSetting = null; 9189 } 9190 9191 Signature[] callerSignature; 9192 Object obj = mSettings.getUserIdLPr(uid); 9193 if (obj != null) { 9194 if (obj instanceof SharedUserSetting) { 9195 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9196 } else if (obj instanceof PackageSetting) { 9197 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9198 } else { 9199 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9200 } 9201 } else { 9202 throw new SecurityException("Unknown calling uid " + uid); 9203 } 9204 9205 // Verify: can't set installerPackageName to a package that is 9206 // not signed with the same cert as the caller. 9207 if (installerPackageSetting != null) { 9208 if (compareSignatures(callerSignature, 9209 installerPackageSetting.signatures.mSignatures) 9210 != PackageManager.SIGNATURE_MATCH) { 9211 throw new SecurityException( 9212 "Caller does not have same cert as new installer package " 9213 + installerPackageName); 9214 } 9215 } 9216 9217 // Verify: if target already has an installer package, it must 9218 // be signed with the same cert as the caller. 9219 if (targetPackageSetting.installerPackageName != null) { 9220 PackageSetting setting = mSettings.mPackages.get( 9221 targetPackageSetting.installerPackageName); 9222 // If the currently set package isn't valid, then it's always 9223 // okay to change it. 9224 if (setting != null) { 9225 if (compareSignatures(callerSignature, 9226 setting.signatures.mSignatures) 9227 != PackageManager.SIGNATURE_MATCH) { 9228 throw new SecurityException( 9229 "Caller does not have same cert as old installer package " 9230 + targetPackageSetting.installerPackageName); 9231 } 9232 } 9233 } 9234 9235 // Okay! 9236 targetPackageSetting.installerPackageName = installerPackageName; 9237 scheduleWriteSettingsLocked(); 9238 } 9239 } 9240 9241 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9242 // Queue up an async operation since the package installation may take a little while. 9243 mHandler.post(new Runnable() { 9244 public void run() { 9245 mHandler.removeCallbacks(this); 9246 // Result object to be returned 9247 PackageInstalledInfo res = new PackageInstalledInfo(); 9248 res.returnCode = currentStatus; 9249 res.uid = -1; 9250 res.pkg = null; 9251 res.removedInfo = new PackageRemovedInfo(); 9252 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9253 args.doPreInstall(res.returnCode); 9254 synchronized (mInstallLock) { 9255 installPackageLI(args, res); 9256 } 9257 args.doPostInstall(res.returnCode, res.uid); 9258 } 9259 9260 // A restore should be performed at this point if (a) the install 9261 // succeeded, (b) the operation is not an update, and (c) the new 9262 // package has not opted out of backup participation. 9263 final boolean update = res.removedInfo.removedPackage != null; 9264 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9265 boolean doRestore = !update 9266 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9267 9268 // Set up the post-install work request bookkeeping. This will be used 9269 // and cleaned up by the post-install event handling regardless of whether 9270 // there's a restore pass performed. Token values are >= 1. 9271 int token; 9272 if (mNextInstallToken < 0) mNextInstallToken = 1; 9273 token = mNextInstallToken++; 9274 9275 PostInstallData data = new PostInstallData(args, res); 9276 mRunningInstalls.put(token, data); 9277 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9278 9279 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9280 // Pass responsibility to the Backup Manager. It will perform a 9281 // restore if appropriate, then pass responsibility back to the 9282 // Package Manager to run the post-install observer callbacks 9283 // and broadcasts. 9284 IBackupManager bm = IBackupManager.Stub.asInterface( 9285 ServiceManager.getService(Context.BACKUP_SERVICE)); 9286 if (bm != null) { 9287 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9288 + " to BM for possible restore"); 9289 try { 9290 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9291 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9292 } else { 9293 doRestore = false; 9294 } 9295 } catch (RemoteException e) { 9296 // can't happen; the backup manager is local 9297 } catch (Exception e) { 9298 Slog.e(TAG, "Exception trying to enqueue restore", e); 9299 doRestore = false; 9300 } 9301 } else { 9302 Slog.e(TAG, "Backup Manager not found!"); 9303 doRestore = false; 9304 } 9305 } 9306 9307 if (!doRestore) { 9308 // No restore possible, or the Backup Manager was mysteriously not 9309 // available -- just fire the post-install work request directly. 9310 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9311 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9312 mHandler.sendMessage(msg); 9313 } 9314 } 9315 }); 9316 } 9317 9318 private abstract class HandlerParams { 9319 private static final int MAX_RETRIES = 4; 9320 9321 /** 9322 * Number of times startCopy() has been attempted and had a non-fatal 9323 * error. 9324 */ 9325 private int mRetries = 0; 9326 9327 /** User handle for the user requesting the information or installation. */ 9328 private final UserHandle mUser; 9329 9330 HandlerParams(UserHandle user) { 9331 mUser = user; 9332 } 9333 9334 UserHandle getUser() { 9335 return mUser; 9336 } 9337 9338 final boolean startCopy() { 9339 boolean res; 9340 try { 9341 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9342 9343 if (++mRetries > MAX_RETRIES) { 9344 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9345 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9346 handleServiceError(); 9347 return false; 9348 } else { 9349 handleStartCopy(); 9350 res = true; 9351 } 9352 } catch (RemoteException e) { 9353 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9354 mHandler.sendEmptyMessage(MCS_RECONNECT); 9355 res = false; 9356 } 9357 handleReturnCode(); 9358 return res; 9359 } 9360 9361 final void serviceError() { 9362 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9363 handleServiceError(); 9364 handleReturnCode(); 9365 } 9366 9367 abstract void handleStartCopy() throws RemoteException; 9368 abstract void handleServiceError(); 9369 abstract void handleReturnCode(); 9370 } 9371 9372 class MeasureParams extends HandlerParams { 9373 private final PackageStats mStats; 9374 private boolean mSuccess; 9375 9376 private final IPackageStatsObserver mObserver; 9377 9378 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9379 super(new UserHandle(stats.userHandle)); 9380 mObserver = observer; 9381 mStats = stats; 9382 } 9383 9384 @Override 9385 public String toString() { 9386 return "MeasureParams{" 9387 + Integer.toHexString(System.identityHashCode(this)) 9388 + " " + mStats.packageName + "}"; 9389 } 9390 9391 @Override 9392 void handleStartCopy() throws RemoteException { 9393 synchronized (mInstallLock) { 9394 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9395 } 9396 9397 if (mSuccess) { 9398 final boolean mounted; 9399 if (Environment.isExternalStorageEmulated()) { 9400 mounted = true; 9401 } else { 9402 final String status = Environment.getExternalStorageState(); 9403 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9404 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9405 } 9406 9407 if (mounted) { 9408 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9409 9410 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9411 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9412 9413 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9414 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9415 9416 // Always subtract cache size, since it's a subdirectory 9417 mStats.externalDataSize -= mStats.externalCacheSize; 9418 9419 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9420 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9421 9422 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9423 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9424 } 9425 } 9426 } 9427 9428 @Override 9429 void handleReturnCode() { 9430 if (mObserver != null) { 9431 try { 9432 mObserver.onGetStatsCompleted(mStats, mSuccess); 9433 } catch (RemoteException e) { 9434 Slog.i(TAG, "Observer no longer exists."); 9435 } 9436 } 9437 } 9438 9439 @Override 9440 void handleServiceError() { 9441 Slog.e(TAG, "Could not measure application " + mStats.packageName 9442 + " external storage"); 9443 } 9444 } 9445 9446 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9447 throws RemoteException { 9448 long result = 0; 9449 for (File path : paths) { 9450 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9451 } 9452 return result; 9453 } 9454 9455 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9456 for (File path : paths) { 9457 try { 9458 mcs.clearDirectory(path.getAbsolutePath()); 9459 } catch (RemoteException e) { 9460 } 9461 } 9462 } 9463 9464 static class OriginInfo { 9465 /** 9466 * Location where install is coming from, before it has been 9467 * copied/renamed into place. This could be a single monolithic APK 9468 * file, or a cluster directory. This location may be untrusted. 9469 */ 9470 final File file; 9471 final String cid; 9472 9473 /** 9474 * Flag indicating that {@link #file} or {@link #cid} has already been 9475 * staged, meaning downstream users don't need to defensively copy the 9476 * contents. 9477 */ 9478 final boolean staged; 9479 9480 /** 9481 * Flag indicating that {@link #file} or {@link #cid} is an already 9482 * installed app that is being moved. 9483 */ 9484 final boolean existing; 9485 9486 final String resolvedPath; 9487 final File resolvedFile; 9488 9489 static OriginInfo fromNothing() { 9490 return new OriginInfo(null, null, false, false); 9491 } 9492 9493 static OriginInfo fromUntrustedFile(File file) { 9494 return new OriginInfo(file, null, false, false); 9495 } 9496 9497 static OriginInfo fromExistingFile(File file) { 9498 return new OriginInfo(file, null, false, true); 9499 } 9500 9501 static OriginInfo fromStagedFile(File file) { 9502 return new OriginInfo(file, null, true, false); 9503 } 9504 9505 static OriginInfo fromStagedContainer(String cid) { 9506 return new OriginInfo(null, cid, true, false); 9507 } 9508 9509 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9510 this.file = file; 9511 this.cid = cid; 9512 this.staged = staged; 9513 this.existing = existing; 9514 9515 if (cid != null) { 9516 resolvedPath = PackageHelper.getSdDir(cid); 9517 resolvedFile = new File(resolvedPath); 9518 } else if (file != null) { 9519 resolvedPath = file.getAbsolutePath(); 9520 resolvedFile = file; 9521 } else { 9522 resolvedPath = null; 9523 resolvedFile = null; 9524 } 9525 } 9526 } 9527 9528 class MoveInfo { 9529 final int moveId; 9530 final String fromUuid; 9531 final String toUuid; 9532 final String packageName; 9533 final String dataAppName; 9534 final int appId; 9535 final String seinfo; 9536 9537 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9538 String dataAppName, int appId, String seinfo) { 9539 this.moveId = moveId; 9540 this.fromUuid = fromUuid; 9541 this.toUuid = toUuid; 9542 this.packageName = packageName; 9543 this.dataAppName = dataAppName; 9544 this.appId = appId; 9545 this.seinfo = seinfo; 9546 } 9547 } 9548 9549 class InstallParams extends HandlerParams { 9550 final OriginInfo origin; 9551 final MoveInfo move; 9552 final IPackageInstallObserver2 observer; 9553 int installFlags; 9554 final String installerPackageName; 9555 final String volumeUuid; 9556 final VerificationParams verificationParams; 9557 private InstallArgs mArgs; 9558 private int mRet; 9559 final String packageAbiOverride; 9560 9561 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9562 int installFlags, String installerPackageName, String volumeUuid, 9563 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9564 super(user); 9565 this.origin = origin; 9566 this.move = move; 9567 this.observer = observer; 9568 this.installFlags = installFlags; 9569 this.installerPackageName = installerPackageName; 9570 this.volumeUuid = volumeUuid; 9571 this.verificationParams = verificationParams; 9572 this.packageAbiOverride = packageAbiOverride; 9573 } 9574 9575 @Override 9576 public String toString() { 9577 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9578 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9579 } 9580 9581 public ManifestDigest getManifestDigest() { 9582 if (verificationParams == null) { 9583 return null; 9584 } 9585 return verificationParams.getManifestDigest(); 9586 } 9587 9588 private int installLocationPolicy(PackageInfoLite pkgLite) { 9589 String packageName = pkgLite.packageName; 9590 int installLocation = pkgLite.installLocation; 9591 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9592 // reader 9593 synchronized (mPackages) { 9594 PackageParser.Package pkg = mPackages.get(packageName); 9595 if (pkg != null) { 9596 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9597 // Check for downgrading. 9598 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9599 try { 9600 checkDowngrade(pkg, pkgLite); 9601 } catch (PackageManagerException e) { 9602 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9603 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9604 } 9605 } 9606 // Check for updated system application. 9607 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9608 if (onSd) { 9609 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9610 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9611 } 9612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9613 } else { 9614 if (onSd) { 9615 // Install flag overrides everything. 9616 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9617 } 9618 // If current upgrade specifies particular preference 9619 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9620 // Application explicitly specified internal. 9621 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9622 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9623 // App explictly prefers external. Let policy decide 9624 } else { 9625 // Prefer previous location 9626 if (isExternal(pkg)) { 9627 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9628 } 9629 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9630 } 9631 } 9632 } else { 9633 // Invalid install. Return error code 9634 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9635 } 9636 } 9637 } 9638 // All the special cases have been taken care of. 9639 // Return result based on recommended install location. 9640 if (onSd) { 9641 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9642 } 9643 return pkgLite.recommendedInstallLocation; 9644 } 9645 9646 /* 9647 * Invoke remote method to get package information and install 9648 * location values. Override install location based on default 9649 * policy if needed and then create install arguments based 9650 * on the install location. 9651 */ 9652 public void handleStartCopy() throws RemoteException { 9653 int ret = PackageManager.INSTALL_SUCCEEDED; 9654 9655 // If we're already staged, we've firmly committed to an install location 9656 if (origin.staged) { 9657 if (origin.file != null) { 9658 installFlags |= PackageManager.INSTALL_INTERNAL; 9659 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9660 } else if (origin.cid != null) { 9661 installFlags |= PackageManager.INSTALL_EXTERNAL; 9662 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9663 } else { 9664 throw new IllegalStateException("Invalid stage location"); 9665 } 9666 } 9667 9668 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9669 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9670 9671 PackageInfoLite pkgLite = null; 9672 9673 if (onInt && onSd) { 9674 // Check if both bits are set. 9675 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9676 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9677 } else { 9678 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9679 packageAbiOverride); 9680 9681 /* 9682 * If we have too little free space, try to free cache 9683 * before giving up. 9684 */ 9685 if (!origin.staged && pkgLite.recommendedInstallLocation 9686 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9687 // TODO: focus freeing disk space on the target device 9688 final StorageManager storage = StorageManager.from(mContext); 9689 final long lowThreshold = storage.getStorageLowBytes( 9690 Environment.getDataDirectory()); 9691 9692 final long sizeBytes = mContainerService.calculateInstalledSize( 9693 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9694 9695 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9696 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9697 installFlags, packageAbiOverride); 9698 } 9699 9700 /* 9701 * The cache free must have deleted the file we 9702 * downloaded to install. 9703 * 9704 * TODO: fix the "freeCache" call to not delete 9705 * the file we care about. 9706 */ 9707 if (pkgLite.recommendedInstallLocation 9708 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9709 pkgLite.recommendedInstallLocation 9710 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9711 } 9712 } 9713 } 9714 9715 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9716 int loc = pkgLite.recommendedInstallLocation; 9717 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9718 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9719 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9720 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9721 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9722 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9723 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9724 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9725 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9726 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9727 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9728 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9729 } else { 9730 // Override with defaults if needed. 9731 loc = installLocationPolicy(pkgLite); 9732 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9733 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9734 } else if (!onSd && !onInt) { 9735 // Override install location with flags 9736 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9737 // Set the flag to install on external media. 9738 installFlags |= PackageManager.INSTALL_EXTERNAL; 9739 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9740 } else { 9741 // Make sure the flag for installing on external 9742 // media is unset 9743 installFlags |= PackageManager.INSTALL_INTERNAL; 9744 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9745 } 9746 } 9747 } 9748 } 9749 9750 final InstallArgs args = createInstallArgs(this); 9751 mArgs = args; 9752 9753 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9754 /* 9755 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9756 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9757 */ 9758 int userIdentifier = getUser().getIdentifier(); 9759 if (userIdentifier == UserHandle.USER_ALL 9760 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9761 userIdentifier = UserHandle.USER_OWNER; 9762 } 9763 9764 /* 9765 * Determine if we have any installed package verifiers. If we 9766 * do, then we'll defer to them to verify the packages. 9767 */ 9768 final int requiredUid = mRequiredVerifierPackage == null ? -1 9769 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9770 if (!origin.existing && requiredUid != -1 9771 && isVerificationEnabled(userIdentifier, installFlags)) { 9772 final Intent verification = new Intent( 9773 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9774 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9775 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9776 PACKAGE_MIME_TYPE); 9777 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9778 9779 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9780 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9781 0 /* TODO: Which userId? */); 9782 9783 if (DEBUG_VERIFY) { 9784 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9785 + verification.toString() + " with " + pkgLite.verifiers.length 9786 + " optional verifiers"); 9787 } 9788 9789 final int verificationId = mPendingVerificationToken++; 9790 9791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9792 9793 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9794 installerPackageName); 9795 9796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9797 installFlags); 9798 9799 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9800 pkgLite.packageName); 9801 9802 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9803 pkgLite.versionCode); 9804 9805 if (verificationParams != null) { 9806 if (verificationParams.getVerificationURI() != null) { 9807 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9808 verificationParams.getVerificationURI()); 9809 } 9810 if (verificationParams.getOriginatingURI() != null) { 9811 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9812 verificationParams.getOriginatingURI()); 9813 } 9814 if (verificationParams.getReferrer() != null) { 9815 verification.putExtra(Intent.EXTRA_REFERRER, 9816 verificationParams.getReferrer()); 9817 } 9818 if (verificationParams.getOriginatingUid() >= 0) { 9819 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9820 verificationParams.getOriginatingUid()); 9821 } 9822 if (verificationParams.getInstallerUid() >= 0) { 9823 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9824 verificationParams.getInstallerUid()); 9825 } 9826 } 9827 9828 final PackageVerificationState verificationState = new PackageVerificationState( 9829 requiredUid, args); 9830 9831 mPendingVerification.append(verificationId, verificationState); 9832 9833 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9834 receivers, verificationState); 9835 9836 /* 9837 * If any sufficient verifiers were listed in the package 9838 * manifest, attempt to ask them. 9839 */ 9840 if (sufficientVerifiers != null) { 9841 final int N = sufficientVerifiers.size(); 9842 if (N == 0) { 9843 Slog.i(TAG, "Additional verifiers required, but none installed."); 9844 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9845 } else { 9846 for (int i = 0; i < N; i++) { 9847 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9848 9849 final Intent sufficientIntent = new Intent(verification); 9850 sufficientIntent.setComponent(verifierComponent); 9851 9852 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9853 } 9854 } 9855 } 9856 9857 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9858 mRequiredVerifierPackage, receivers); 9859 if (ret == PackageManager.INSTALL_SUCCEEDED 9860 && mRequiredVerifierPackage != null) { 9861 /* 9862 * Send the intent to the required verification agent, 9863 * but only start the verification timeout after the 9864 * target BroadcastReceivers have run. 9865 */ 9866 verification.setComponent(requiredVerifierComponent); 9867 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9868 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9869 new BroadcastReceiver() { 9870 @Override 9871 public void onReceive(Context context, Intent intent) { 9872 final Message msg = mHandler 9873 .obtainMessage(CHECK_PENDING_VERIFICATION); 9874 msg.arg1 = verificationId; 9875 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9876 } 9877 }, null, 0, null, null); 9878 9879 /* 9880 * We don't want the copy to proceed until verification 9881 * succeeds, so null out this field. 9882 */ 9883 mArgs = null; 9884 } 9885 } else { 9886 /* 9887 * No package verification is enabled, so immediately start 9888 * the remote call to initiate copy using temporary file. 9889 */ 9890 ret = args.copyApk(mContainerService, true); 9891 } 9892 } 9893 9894 mRet = ret; 9895 } 9896 9897 @Override 9898 void handleReturnCode() { 9899 // If mArgs is null, then MCS couldn't be reached. When it 9900 // reconnects, it will try again to install. At that point, this 9901 // will succeed. 9902 if (mArgs != null) { 9903 processPendingInstall(mArgs, mRet); 9904 } 9905 } 9906 9907 @Override 9908 void handleServiceError() { 9909 mArgs = createInstallArgs(this); 9910 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9911 } 9912 9913 public boolean isForwardLocked() { 9914 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9915 } 9916 } 9917 9918 /** 9919 * Used during creation of InstallArgs 9920 * 9921 * @param installFlags package installation flags 9922 * @return true if should be installed on external storage 9923 */ 9924 private static boolean installOnExternalAsec(int installFlags) { 9925 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9926 return false; 9927 } 9928 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9929 return true; 9930 } 9931 return false; 9932 } 9933 9934 /** 9935 * Used during creation of InstallArgs 9936 * 9937 * @param installFlags package installation flags 9938 * @return true if should be installed as forward locked 9939 */ 9940 private static boolean installForwardLocked(int installFlags) { 9941 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9942 } 9943 9944 private InstallArgs createInstallArgs(InstallParams params) { 9945 if (params.move != null) { 9946 return new MoveInstallArgs(params); 9947 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9948 return new AsecInstallArgs(params); 9949 } else { 9950 return new FileInstallArgs(params); 9951 } 9952 } 9953 9954 /** 9955 * Create args that describe an existing installed package. Typically used 9956 * when cleaning up old installs, or used as a move source. 9957 */ 9958 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9959 String resourcePath, String[] instructionSets) { 9960 final boolean isInAsec; 9961 if (installOnExternalAsec(installFlags)) { 9962 /* Apps on SD card are always in ASEC containers. */ 9963 isInAsec = true; 9964 } else if (installForwardLocked(installFlags) 9965 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9966 /* 9967 * Forward-locked apps are only in ASEC containers if they're the 9968 * new style 9969 */ 9970 isInAsec = true; 9971 } else { 9972 isInAsec = false; 9973 } 9974 9975 if (isInAsec) { 9976 return new AsecInstallArgs(codePath, instructionSets, 9977 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9978 } else { 9979 return new FileInstallArgs(codePath, resourcePath, instructionSets); 9980 } 9981 } 9982 9983 static abstract class InstallArgs { 9984 /** @see InstallParams#origin */ 9985 final OriginInfo origin; 9986 /** @see InstallParams#move */ 9987 final MoveInfo move; 9988 9989 final IPackageInstallObserver2 observer; 9990 // Always refers to PackageManager flags only 9991 final int installFlags; 9992 final String installerPackageName; 9993 final String volumeUuid; 9994 final ManifestDigest manifestDigest; 9995 final UserHandle user; 9996 final String abiOverride; 9997 9998 // The list of instruction sets supported by this app. This is currently 9999 // only used during the rmdex() phase to clean up resources. We can get rid of this 10000 // if we move dex files under the common app path. 10001 /* nullable */ String[] instructionSets; 10002 10003 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10004 int installFlags, String installerPackageName, String volumeUuid, 10005 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10006 String abiOverride) { 10007 this.origin = origin; 10008 this.move = move; 10009 this.installFlags = installFlags; 10010 this.observer = observer; 10011 this.installerPackageName = installerPackageName; 10012 this.volumeUuid = volumeUuid; 10013 this.manifestDigest = manifestDigest; 10014 this.user = user; 10015 this.instructionSets = instructionSets; 10016 this.abiOverride = abiOverride; 10017 } 10018 10019 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10020 abstract int doPreInstall(int status); 10021 10022 /** 10023 * Rename package into final resting place. All paths on the given 10024 * scanned package should be updated to reflect the rename. 10025 */ 10026 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10027 abstract int doPostInstall(int status, int uid); 10028 10029 /** @see PackageSettingBase#codePathString */ 10030 abstract String getCodePath(); 10031 /** @see PackageSettingBase#resourcePathString */ 10032 abstract String getResourcePath(); 10033 10034 // Need installer lock especially for dex file removal. 10035 abstract void cleanUpResourcesLI(); 10036 abstract boolean doPostDeleteLI(boolean delete); 10037 10038 /** 10039 * Called before the source arguments are copied. This is used mostly 10040 * for MoveParams when it needs to read the source file to put it in the 10041 * destination. 10042 */ 10043 int doPreCopy() { 10044 return PackageManager.INSTALL_SUCCEEDED; 10045 } 10046 10047 /** 10048 * Called after the source arguments are copied. This is used mostly for 10049 * MoveParams when it needs to read the source file to put it in the 10050 * destination. 10051 * 10052 * @return 10053 */ 10054 int doPostCopy(int uid) { 10055 return PackageManager.INSTALL_SUCCEEDED; 10056 } 10057 10058 protected boolean isFwdLocked() { 10059 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10060 } 10061 10062 protected boolean isExternalAsec() { 10063 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10064 } 10065 10066 UserHandle getUser() { 10067 return user; 10068 } 10069 } 10070 10071 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10072 if (!allCodePaths.isEmpty()) { 10073 if (instructionSets == null) { 10074 throw new IllegalStateException("instructionSet == null"); 10075 } 10076 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10077 for (String codePath : allCodePaths) { 10078 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10079 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10080 if (retCode < 0) { 10081 Slog.w(TAG, "Couldn't remove dex file for package: " 10082 + " at location " + codePath + ", retcode=" + retCode); 10083 // we don't consider this to be a failure of the core package deletion 10084 } 10085 } 10086 } 10087 } 10088 } 10089 10090 /** 10091 * Logic to handle installation of non-ASEC applications, including copying 10092 * and renaming logic. 10093 */ 10094 class FileInstallArgs extends InstallArgs { 10095 private File codeFile; 10096 private File resourceFile; 10097 10098 // Example topology: 10099 // /data/app/com.example/base.apk 10100 // /data/app/com.example/split_foo.apk 10101 // /data/app/com.example/lib/arm/libfoo.so 10102 // /data/app/com.example/lib/arm64/libfoo.so 10103 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10104 10105 /** New install */ 10106 FileInstallArgs(InstallParams params) { 10107 super(params.origin, params.move, params.observer, params.installFlags, 10108 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10109 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10110 if (isFwdLocked()) { 10111 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10112 } 10113 } 10114 10115 /** Existing install */ 10116 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10117 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10118 null); 10119 this.codeFile = (codePath != null) ? new File(codePath) : null; 10120 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10121 } 10122 10123 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10124 if (origin.staged) { 10125 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10126 codeFile = origin.file; 10127 resourceFile = origin.file; 10128 return PackageManager.INSTALL_SUCCEEDED; 10129 } 10130 10131 try { 10132 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10133 codeFile = tempDir; 10134 resourceFile = tempDir; 10135 } catch (IOException e) { 10136 Slog.w(TAG, "Failed to create copy file: " + e); 10137 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10138 } 10139 10140 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10141 @Override 10142 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10143 if (!FileUtils.isValidExtFilename(name)) { 10144 throw new IllegalArgumentException("Invalid filename: " + name); 10145 } 10146 try { 10147 final File file = new File(codeFile, name); 10148 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10149 O_RDWR | O_CREAT, 0644); 10150 Os.chmod(file.getAbsolutePath(), 0644); 10151 return new ParcelFileDescriptor(fd); 10152 } catch (ErrnoException e) { 10153 throw new RemoteException("Failed to open: " + e.getMessage()); 10154 } 10155 } 10156 }; 10157 10158 int ret = PackageManager.INSTALL_SUCCEEDED; 10159 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10160 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10161 Slog.e(TAG, "Failed to copy package"); 10162 return ret; 10163 } 10164 10165 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10166 NativeLibraryHelper.Handle handle = null; 10167 try { 10168 handle = NativeLibraryHelper.Handle.create(codeFile); 10169 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10170 abiOverride); 10171 } catch (IOException e) { 10172 Slog.e(TAG, "Copying native libraries failed", e); 10173 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10174 } finally { 10175 IoUtils.closeQuietly(handle); 10176 } 10177 10178 return ret; 10179 } 10180 10181 int doPreInstall(int status) { 10182 if (status != PackageManager.INSTALL_SUCCEEDED) { 10183 cleanUp(); 10184 } 10185 return status; 10186 } 10187 10188 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10189 if (status != PackageManager.INSTALL_SUCCEEDED) { 10190 cleanUp(); 10191 return false; 10192 } 10193 10194 final File targetDir = codeFile.getParentFile(); 10195 final File beforeCodeFile = codeFile; 10196 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10197 10198 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10199 try { 10200 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10201 } catch (ErrnoException e) { 10202 Slog.d(TAG, "Failed to rename", e); 10203 return false; 10204 } 10205 10206 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10207 Slog.d(TAG, "Failed to restorecon"); 10208 return false; 10209 } 10210 10211 // Reflect the rename internally 10212 codeFile = afterCodeFile; 10213 resourceFile = afterCodeFile; 10214 10215 // Reflect the rename in scanned details 10216 pkg.codePath = afterCodeFile.getAbsolutePath(); 10217 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10218 pkg.baseCodePath); 10219 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10220 pkg.splitCodePaths); 10221 10222 // Reflect the rename in app info 10223 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10224 pkg.applicationInfo.setCodePath(pkg.codePath); 10225 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10226 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10227 pkg.applicationInfo.setResourcePath(pkg.codePath); 10228 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10229 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10230 10231 return true; 10232 } 10233 10234 int doPostInstall(int status, int uid) { 10235 if (status != PackageManager.INSTALL_SUCCEEDED) { 10236 cleanUp(); 10237 } 10238 return status; 10239 } 10240 10241 @Override 10242 String getCodePath() { 10243 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10244 } 10245 10246 @Override 10247 String getResourcePath() { 10248 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10249 } 10250 10251 private boolean cleanUp() { 10252 if (codeFile == null || !codeFile.exists()) { 10253 return false; 10254 } 10255 10256 if (codeFile.isDirectory()) { 10257 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10258 } else { 10259 codeFile.delete(); 10260 } 10261 10262 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10263 resourceFile.delete(); 10264 } 10265 10266 return true; 10267 } 10268 10269 void cleanUpResourcesLI() { 10270 // Try enumerating all code paths before deleting 10271 List<String> allCodePaths = Collections.EMPTY_LIST; 10272 if (codeFile != null && codeFile.exists()) { 10273 try { 10274 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10275 allCodePaths = pkg.getAllCodePaths(); 10276 } catch (PackageParserException e) { 10277 // Ignored; we tried our best 10278 } 10279 } 10280 10281 cleanUp(); 10282 removeDexFiles(allCodePaths, instructionSets); 10283 } 10284 10285 boolean doPostDeleteLI(boolean delete) { 10286 // XXX err, shouldn't we respect the delete flag? 10287 cleanUpResourcesLI(); 10288 return true; 10289 } 10290 } 10291 10292 private boolean isAsecExternal(String cid) { 10293 final String asecPath = PackageHelper.getSdFilesystem(cid); 10294 return !asecPath.startsWith(mAsecInternalPath); 10295 } 10296 10297 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10298 PackageManagerException { 10299 if (copyRet < 0) { 10300 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10301 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10302 throw new PackageManagerException(copyRet, message); 10303 } 10304 } 10305 } 10306 10307 /** 10308 * Extract the MountService "container ID" from the full code path of an 10309 * .apk. 10310 */ 10311 static String cidFromCodePath(String fullCodePath) { 10312 int eidx = fullCodePath.lastIndexOf("/"); 10313 String subStr1 = fullCodePath.substring(0, eidx); 10314 int sidx = subStr1.lastIndexOf("/"); 10315 return subStr1.substring(sidx+1, eidx); 10316 } 10317 10318 /** 10319 * Logic to handle installation of ASEC applications, including copying and 10320 * renaming logic. 10321 */ 10322 class AsecInstallArgs extends InstallArgs { 10323 static final String RES_FILE_NAME = "pkg.apk"; 10324 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10325 10326 String cid; 10327 String packagePath; 10328 String resourcePath; 10329 10330 /** New install */ 10331 AsecInstallArgs(InstallParams params) { 10332 super(params.origin, params.move, params.observer, params.installFlags, 10333 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10334 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10335 } 10336 10337 /** Existing install */ 10338 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10339 boolean isExternal, boolean isForwardLocked) { 10340 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10341 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10342 instructionSets, null); 10343 // Hackily pretend we're still looking at a full code path 10344 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10345 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10346 } 10347 10348 // Extract cid from fullCodePath 10349 int eidx = fullCodePath.lastIndexOf("/"); 10350 String subStr1 = fullCodePath.substring(0, eidx); 10351 int sidx = subStr1.lastIndexOf("/"); 10352 cid = subStr1.substring(sidx+1, eidx); 10353 setMountPath(subStr1); 10354 } 10355 10356 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10357 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10358 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10359 instructionSets, null); 10360 this.cid = cid; 10361 setMountPath(PackageHelper.getSdDir(cid)); 10362 } 10363 10364 void createCopyFile() { 10365 cid = mInstallerService.allocateExternalStageCidLegacy(); 10366 } 10367 10368 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10369 if (origin.staged) { 10370 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10371 cid = origin.cid; 10372 setMountPath(PackageHelper.getSdDir(cid)); 10373 return PackageManager.INSTALL_SUCCEEDED; 10374 } 10375 10376 if (temp) { 10377 createCopyFile(); 10378 } else { 10379 /* 10380 * Pre-emptively destroy the container since it's destroyed if 10381 * copying fails due to it existing anyway. 10382 */ 10383 PackageHelper.destroySdDir(cid); 10384 } 10385 10386 final String newMountPath = imcs.copyPackageToContainer( 10387 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10388 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10389 10390 if (newMountPath != null) { 10391 setMountPath(newMountPath); 10392 return PackageManager.INSTALL_SUCCEEDED; 10393 } else { 10394 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10395 } 10396 } 10397 10398 @Override 10399 String getCodePath() { 10400 return packagePath; 10401 } 10402 10403 @Override 10404 String getResourcePath() { 10405 return resourcePath; 10406 } 10407 10408 int doPreInstall(int status) { 10409 if (status != PackageManager.INSTALL_SUCCEEDED) { 10410 // Destroy container 10411 PackageHelper.destroySdDir(cid); 10412 } else { 10413 boolean mounted = PackageHelper.isContainerMounted(cid); 10414 if (!mounted) { 10415 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10416 Process.SYSTEM_UID); 10417 if (newMountPath != null) { 10418 setMountPath(newMountPath); 10419 } else { 10420 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10421 } 10422 } 10423 } 10424 return status; 10425 } 10426 10427 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10428 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10429 String newMountPath = null; 10430 if (PackageHelper.isContainerMounted(cid)) { 10431 // Unmount the container 10432 if (!PackageHelper.unMountSdDir(cid)) { 10433 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10434 return false; 10435 } 10436 } 10437 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10438 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10439 " which might be stale. Will try to clean up."); 10440 // Clean up the stale container and proceed to recreate. 10441 if (!PackageHelper.destroySdDir(newCacheId)) { 10442 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10443 return false; 10444 } 10445 // Successfully cleaned up stale container. Try to rename again. 10446 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10447 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10448 + " inspite of cleaning it up."); 10449 return false; 10450 } 10451 } 10452 if (!PackageHelper.isContainerMounted(newCacheId)) { 10453 Slog.w(TAG, "Mounting container " + newCacheId); 10454 newMountPath = PackageHelper.mountSdDir(newCacheId, 10455 getEncryptKey(), Process.SYSTEM_UID); 10456 } else { 10457 newMountPath = PackageHelper.getSdDir(newCacheId); 10458 } 10459 if (newMountPath == null) { 10460 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10461 return false; 10462 } 10463 Log.i(TAG, "Succesfully renamed " + cid + 10464 " to " + newCacheId + 10465 " at new path: " + newMountPath); 10466 cid = newCacheId; 10467 10468 final File beforeCodeFile = new File(packagePath); 10469 setMountPath(newMountPath); 10470 final File afterCodeFile = new File(packagePath); 10471 10472 // Reflect the rename in scanned details 10473 pkg.codePath = afterCodeFile.getAbsolutePath(); 10474 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10475 pkg.baseCodePath); 10476 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10477 pkg.splitCodePaths); 10478 10479 // Reflect the rename in app info 10480 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10481 pkg.applicationInfo.setCodePath(pkg.codePath); 10482 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10483 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10484 pkg.applicationInfo.setResourcePath(pkg.codePath); 10485 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10486 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10487 10488 return true; 10489 } 10490 10491 private void setMountPath(String mountPath) { 10492 final File mountFile = new File(mountPath); 10493 10494 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10495 if (monolithicFile.exists()) { 10496 packagePath = monolithicFile.getAbsolutePath(); 10497 if (isFwdLocked()) { 10498 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10499 } else { 10500 resourcePath = packagePath; 10501 } 10502 } else { 10503 packagePath = mountFile.getAbsolutePath(); 10504 resourcePath = packagePath; 10505 } 10506 } 10507 10508 int doPostInstall(int status, int uid) { 10509 if (status != PackageManager.INSTALL_SUCCEEDED) { 10510 cleanUp(); 10511 } else { 10512 final int groupOwner; 10513 final String protectedFile; 10514 if (isFwdLocked()) { 10515 groupOwner = UserHandle.getSharedAppGid(uid); 10516 protectedFile = RES_FILE_NAME; 10517 } else { 10518 groupOwner = -1; 10519 protectedFile = null; 10520 } 10521 10522 if (uid < Process.FIRST_APPLICATION_UID 10523 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10524 Slog.e(TAG, "Failed to finalize " + cid); 10525 PackageHelper.destroySdDir(cid); 10526 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10527 } 10528 10529 boolean mounted = PackageHelper.isContainerMounted(cid); 10530 if (!mounted) { 10531 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10532 } 10533 } 10534 return status; 10535 } 10536 10537 private void cleanUp() { 10538 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10539 10540 // Destroy secure container 10541 PackageHelper.destroySdDir(cid); 10542 } 10543 10544 private List<String> getAllCodePaths() { 10545 final File codeFile = new File(getCodePath()); 10546 if (codeFile != null && codeFile.exists()) { 10547 try { 10548 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10549 return pkg.getAllCodePaths(); 10550 } catch (PackageParserException e) { 10551 // Ignored; we tried our best 10552 } 10553 } 10554 return Collections.EMPTY_LIST; 10555 } 10556 10557 void cleanUpResourcesLI() { 10558 // Enumerate all code paths before deleting 10559 cleanUpResourcesLI(getAllCodePaths()); 10560 } 10561 10562 private void cleanUpResourcesLI(List<String> allCodePaths) { 10563 cleanUp(); 10564 removeDexFiles(allCodePaths, instructionSets); 10565 } 10566 10567 String getPackageName() { 10568 return getAsecPackageName(cid); 10569 } 10570 10571 boolean doPostDeleteLI(boolean delete) { 10572 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10573 final List<String> allCodePaths = getAllCodePaths(); 10574 boolean mounted = PackageHelper.isContainerMounted(cid); 10575 if (mounted) { 10576 // Unmount first 10577 if (PackageHelper.unMountSdDir(cid)) { 10578 mounted = false; 10579 } 10580 } 10581 if (!mounted && delete) { 10582 cleanUpResourcesLI(allCodePaths); 10583 } 10584 return !mounted; 10585 } 10586 10587 @Override 10588 int doPreCopy() { 10589 if (isFwdLocked()) { 10590 if (!PackageHelper.fixSdPermissions(cid, 10591 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10592 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10593 } 10594 } 10595 10596 return PackageManager.INSTALL_SUCCEEDED; 10597 } 10598 10599 @Override 10600 int doPostCopy(int uid) { 10601 if (isFwdLocked()) { 10602 if (uid < Process.FIRST_APPLICATION_UID 10603 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10604 RES_FILE_NAME)) { 10605 Slog.e(TAG, "Failed to finalize " + cid); 10606 PackageHelper.destroySdDir(cid); 10607 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10608 } 10609 } 10610 10611 return PackageManager.INSTALL_SUCCEEDED; 10612 } 10613 } 10614 10615 /** 10616 * Logic to handle movement of existing installed applications. 10617 */ 10618 class MoveInstallArgs extends InstallArgs { 10619 private File codeFile; 10620 private File resourceFile; 10621 10622 /** New install */ 10623 MoveInstallArgs(InstallParams params) { 10624 super(params.origin, params.move, params.observer, params.installFlags, 10625 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10626 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10627 } 10628 10629 int copyApk(IMediaContainerService imcs, boolean temp) { 10630 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10631 + move.toUuid); 10632 synchronized (mInstaller) { 10633 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10634 move.dataAppName, move.appId, move.seinfo) != 0) { 10635 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10636 } 10637 } 10638 10639 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10640 resourceFile = codeFile; 10641 Slog.d(TAG, "codeFile after move is " + codeFile); 10642 10643 return PackageManager.INSTALL_SUCCEEDED; 10644 } 10645 10646 int doPreInstall(int status) { 10647 if (status != PackageManager.INSTALL_SUCCEEDED) { 10648 cleanUp(); 10649 } 10650 return status; 10651 } 10652 10653 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10654 if (status != PackageManager.INSTALL_SUCCEEDED) { 10655 cleanUp(); 10656 return false; 10657 } 10658 10659 // Reflect the move in app info 10660 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10661 pkg.applicationInfo.setCodePath(pkg.codePath); 10662 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10663 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10664 pkg.applicationInfo.setResourcePath(pkg.codePath); 10665 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10666 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10667 10668 return true; 10669 } 10670 10671 int doPostInstall(int status, int uid) { 10672 if (status != PackageManager.INSTALL_SUCCEEDED) { 10673 cleanUp(); 10674 } 10675 return status; 10676 } 10677 10678 @Override 10679 String getCodePath() { 10680 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10681 } 10682 10683 @Override 10684 String getResourcePath() { 10685 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10686 } 10687 10688 private boolean cleanUp() { 10689 if (codeFile == null || !codeFile.exists()) { 10690 return false; 10691 } 10692 10693 if (codeFile.isDirectory()) { 10694 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10695 } else { 10696 codeFile.delete(); 10697 } 10698 10699 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10700 resourceFile.delete(); 10701 } 10702 10703 return true; 10704 } 10705 10706 void cleanUpResourcesLI() { 10707 cleanUp(); 10708 } 10709 10710 boolean doPostDeleteLI(boolean delete) { 10711 // XXX err, shouldn't we respect the delete flag? 10712 cleanUpResourcesLI(); 10713 return true; 10714 } 10715 } 10716 10717 static String getAsecPackageName(String packageCid) { 10718 int idx = packageCid.lastIndexOf("-"); 10719 if (idx == -1) { 10720 return packageCid; 10721 } 10722 return packageCid.substring(0, idx); 10723 } 10724 10725 // Utility method used to create code paths based on package name and available index. 10726 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10727 String idxStr = ""; 10728 int idx = 1; 10729 // Fall back to default value of idx=1 if prefix is not 10730 // part of oldCodePath 10731 if (oldCodePath != null) { 10732 String subStr = oldCodePath; 10733 // Drop the suffix right away 10734 if (suffix != null && subStr.endsWith(suffix)) { 10735 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10736 } 10737 // If oldCodePath already contains prefix find out the 10738 // ending index to either increment or decrement. 10739 int sidx = subStr.lastIndexOf(prefix); 10740 if (sidx != -1) { 10741 subStr = subStr.substring(sidx + prefix.length()); 10742 if (subStr != null) { 10743 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10744 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10745 } 10746 try { 10747 idx = Integer.parseInt(subStr); 10748 if (idx <= 1) { 10749 idx++; 10750 } else { 10751 idx--; 10752 } 10753 } catch(NumberFormatException e) { 10754 } 10755 } 10756 } 10757 } 10758 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10759 return prefix + idxStr; 10760 } 10761 10762 private File getNextCodePath(File targetDir, String packageName) { 10763 int suffix = 1; 10764 File result; 10765 do { 10766 result = new File(targetDir, packageName + "-" + suffix); 10767 suffix++; 10768 } while (result.exists()); 10769 return result; 10770 } 10771 10772 // Utility method that returns the relative package path with respect 10773 // to the installation directory. Like say for /data/data/com.test-1.apk 10774 // string com.test-1 is returned. 10775 static String deriveCodePathName(String codePath) { 10776 if (codePath == null) { 10777 return null; 10778 } 10779 final File codeFile = new File(codePath); 10780 final String name = codeFile.getName(); 10781 if (codeFile.isDirectory()) { 10782 return name; 10783 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10784 final int lastDot = name.lastIndexOf('.'); 10785 return name.substring(0, lastDot); 10786 } else { 10787 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10788 return null; 10789 } 10790 } 10791 10792 class PackageInstalledInfo { 10793 String name; 10794 int uid; 10795 // The set of users that originally had this package installed. 10796 int[] origUsers; 10797 // The set of users that now have this package installed. 10798 int[] newUsers; 10799 PackageParser.Package pkg; 10800 int returnCode; 10801 String returnMsg; 10802 PackageRemovedInfo removedInfo; 10803 10804 public void setError(int code, String msg) { 10805 returnCode = code; 10806 returnMsg = msg; 10807 Slog.w(TAG, msg); 10808 } 10809 10810 public void setError(String msg, PackageParserException e) { 10811 returnCode = e.error; 10812 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10813 Slog.w(TAG, msg, e); 10814 } 10815 10816 public void setError(String msg, PackageManagerException e) { 10817 returnCode = e.error; 10818 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10819 Slog.w(TAG, msg, e); 10820 } 10821 10822 // In some error cases we want to convey more info back to the observer 10823 String origPackage; 10824 String origPermission; 10825 } 10826 10827 /* 10828 * Install a non-existing package. 10829 */ 10830 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10831 UserHandle user, String installerPackageName, String volumeUuid, 10832 PackageInstalledInfo res) { 10833 // Remember this for later, in case we need to rollback this install 10834 String pkgName = pkg.packageName; 10835 10836 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10837 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10838 UserHandle.USER_OWNER).exists(); 10839 synchronized(mPackages) { 10840 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10841 // A package with the same name is already installed, though 10842 // it has been renamed to an older name. The package we 10843 // are trying to install should be installed as an update to 10844 // the existing one, but that has not been requested, so bail. 10845 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10846 + " without first uninstalling package running as " 10847 + mSettings.mRenamedPackages.get(pkgName)); 10848 return; 10849 } 10850 if (mPackages.containsKey(pkgName)) { 10851 // Don't allow installation over an existing package with the same name. 10852 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10853 + " without first uninstalling."); 10854 return; 10855 } 10856 } 10857 10858 try { 10859 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10860 System.currentTimeMillis(), user); 10861 10862 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10863 // delete the partially installed application. the data directory will have to be 10864 // restored if it was already existing 10865 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10866 // remove package from internal structures. Note that we want deletePackageX to 10867 // delete the package data and cache directories that it created in 10868 // scanPackageLocked, unless those directories existed before we even tried to 10869 // install. 10870 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10871 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10872 res.removedInfo, true); 10873 } 10874 10875 } catch (PackageManagerException e) { 10876 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10877 } 10878 } 10879 10880 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10881 // Upgrade keysets are being used. Determine if new package has a superset of the 10882 // required keys. 10883 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10884 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10885 for (int i = 0; i < upgradeKeySets.length; i++) { 10886 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10887 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10888 return true; 10889 } 10890 } 10891 return false; 10892 } 10893 10894 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10895 UserHandle user, String installerPackageName, String volumeUuid, 10896 PackageInstalledInfo res) { 10897 final PackageParser.Package oldPackage; 10898 final String pkgName = pkg.packageName; 10899 final int[] allUsers; 10900 final boolean[] perUserInstalled; 10901 final boolean weFroze; 10902 10903 // First find the old package info and check signatures 10904 synchronized(mPackages) { 10905 oldPackage = mPackages.get(pkgName); 10906 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10907 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10908 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10909 // default to original signature matching 10910 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10911 != PackageManager.SIGNATURE_MATCH) { 10912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10913 "New package has a different signature: " + pkgName); 10914 return; 10915 } 10916 } else { 10917 if(!checkUpgradeKeySetLP(ps, pkg)) { 10918 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10919 "New package not signed by keys specified by upgrade-keysets: " 10920 + pkgName); 10921 return; 10922 } 10923 } 10924 10925 // In case of rollback, remember per-user/profile install state 10926 allUsers = sUserManager.getUserIds(); 10927 perUserInstalled = new boolean[allUsers.length]; 10928 for (int i = 0; i < allUsers.length; i++) { 10929 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10930 } 10931 10932 // Mark the app as frozen to prevent launching during the upgrade 10933 // process, and then kill all running instances 10934 if (!ps.frozen) { 10935 ps.frozen = true; 10936 weFroze = true; 10937 } else { 10938 weFroze = false; 10939 } 10940 } 10941 10942 // Now that we're guarded by frozen state, kill app during upgrade 10943 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 10944 10945 try { 10946 boolean sysPkg = (isSystemApp(oldPackage)); 10947 if (sysPkg) { 10948 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10949 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10950 } else { 10951 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10952 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10953 } 10954 } finally { 10955 // Regardless of success or failure of upgrade steps above, always 10956 // unfreeze the package if we froze it 10957 if (weFroze) { 10958 unfreezePackage(pkgName); 10959 } 10960 } 10961 } 10962 10963 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10964 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10965 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10966 String volumeUuid, PackageInstalledInfo res) { 10967 String pkgName = deletedPackage.packageName; 10968 boolean deletedPkg = true; 10969 boolean updatedSettings = false; 10970 10971 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10972 + deletedPackage); 10973 long origUpdateTime; 10974 if (pkg.mExtras != null) { 10975 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10976 } else { 10977 origUpdateTime = 0; 10978 } 10979 10980 // First delete the existing package while retaining the data directory 10981 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10982 res.removedInfo, true)) { 10983 // If the existing package wasn't successfully deleted 10984 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10985 deletedPkg = false; 10986 } else { 10987 // Successfully deleted the old package; proceed with replace. 10988 10989 // If deleted package lived in a container, give users a chance to 10990 // relinquish resources before killing. 10991 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10992 if (DEBUG_INSTALL) { 10993 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10994 } 10995 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10996 final ArrayList<String> pkgList = new ArrayList<String>(1); 10997 pkgList.add(deletedPackage.applicationInfo.packageName); 10998 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10999 } 11000 11001 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11002 try { 11003 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11004 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11005 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11006 perUserInstalled, res, user); 11007 updatedSettings = true; 11008 } catch (PackageManagerException e) { 11009 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11010 } 11011 } 11012 11013 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11014 // remove package from internal structures. Note that we want deletePackageX to 11015 // delete the package data and cache directories that it created in 11016 // scanPackageLocked, unless those directories existed before we even tried to 11017 // install. 11018 if(updatedSettings) { 11019 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11020 deletePackageLI( 11021 pkgName, null, true, allUsers, perUserInstalled, 11022 PackageManager.DELETE_KEEP_DATA, 11023 res.removedInfo, true); 11024 } 11025 // Since we failed to install the new package we need to restore the old 11026 // package that we deleted. 11027 if (deletedPkg) { 11028 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11029 File restoreFile = new File(deletedPackage.codePath); 11030 // Parse old package 11031 boolean oldExternal = isExternal(deletedPackage); 11032 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11033 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11034 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11035 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11036 try { 11037 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11038 } catch (PackageManagerException e) { 11039 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11040 + e.getMessage()); 11041 return; 11042 } 11043 // Restore of old package succeeded. Update permissions. 11044 // writer 11045 synchronized (mPackages) { 11046 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11047 UPDATE_PERMISSIONS_ALL); 11048 // can downgrade to reader 11049 mSettings.writeLPr(); 11050 } 11051 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11052 } 11053 } 11054 } 11055 11056 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11057 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11058 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11059 String volumeUuid, PackageInstalledInfo res) { 11060 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11061 + ", old=" + deletedPackage); 11062 boolean disabledSystem = false; 11063 boolean updatedSettings = false; 11064 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11065 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11066 != 0) { 11067 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11068 } 11069 String packageName = deletedPackage.packageName; 11070 if (packageName == null) { 11071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11072 "Attempt to delete null packageName."); 11073 return; 11074 } 11075 PackageParser.Package oldPkg; 11076 PackageSetting oldPkgSetting; 11077 // reader 11078 synchronized (mPackages) { 11079 oldPkg = mPackages.get(packageName); 11080 oldPkgSetting = mSettings.mPackages.get(packageName); 11081 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11082 (oldPkgSetting == null)) { 11083 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11084 "Couldn't find package:" + packageName + " information"); 11085 return; 11086 } 11087 } 11088 11089 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11090 res.removedInfo.removedPackage = packageName; 11091 // Remove existing system package 11092 removePackageLI(oldPkgSetting, true); 11093 // writer 11094 synchronized (mPackages) { 11095 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11096 if (!disabledSystem && deletedPackage != null) { 11097 // We didn't need to disable the .apk as a current system package, 11098 // which means we are replacing another update that is already 11099 // installed. We need to make sure to delete the older one's .apk. 11100 res.removedInfo.args = createInstallArgsForExisting(0, 11101 deletedPackage.applicationInfo.getCodePath(), 11102 deletedPackage.applicationInfo.getResourcePath(), 11103 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11104 } else { 11105 res.removedInfo.args = null; 11106 } 11107 } 11108 11109 // Successfully disabled the old package. Now proceed with re-installation 11110 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11111 11112 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11113 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11114 11115 PackageParser.Package newPackage = null; 11116 try { 11117 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11118 if (newPackage.mExtras != null) { 11119 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11120 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11121 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11122 11123 // is the update attempting to change shared user? that isn't going to work... 11124 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11125 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11126 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11127 + " to " + newPkgSetting.sharedUser); 11128 updatedSettings = true; 11129 } 11130 } 11131 11132 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11133 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11134 perUserInstalled, res, user); 11135 updatedSettings = true; 11136 } 11137 11138 } catch (PackageManagerException e) { 11139 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11140 } 11141 11142 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11143 // Re installation failed. Restore old information 11144 // Remove new pkg information 11145 if (newPackage != null) { 11146 removeInstalledPackageLI(newPackage, true); 11147 } 11148 // Add back the old system package 11149 try { 11150 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11151 } catch (PackageManagerException e) { 11152 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11153 } 11154 // Restore the old system information in Settings 11155 synchronized (mPackages) { 11156 if (disabledSystem) { 11157 mSettings.enableSystemPackageLPw(packageName); 11158 } 11159 if (updatedSettings) { 11160 mSettings.setInstallerPackageName(packageName, 11161 oldPkgSetting.installerPackageName); 11162 } 11163 mSettings.writeLPr(); 11164 } 11165 } 11166 } 11167 11168 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11169 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11170 UserHandle user) { 11171 String pkgName = newPackage.packageName; 11172 synchronized (mPackages) { 11173 //write settings. the installStatus will be incomplete at this stage. 11174 //note that the new package setting would have already been 11175 //added to mPackages. It hasn't been persisted yet. 11176 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11177 mSettings.writeLPr(); 11178 } 11179 11180 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11181 11182 synchronized (mPackages) { 11183 updatePermissionsLPw(newPackage.packageName, newPackage, 11184 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11185 ? UPDATE_PERMISSIONS_ALL : 0)); 11186 // For system-bundled packages, we assume that installing an upgraded version 11187 // of the package implies that the user actually wants to run that new code, 11188 // so we enable the package. 11189 PackageSetting ps = mSettings.mPackages.get(pkgName); 11190 if (ps != null) { 11191 if (isSystemApp(newPackage)) { 11192 // NB: implicit assumption that system package upgrades apply to all users 11193 if (DEBUG_INSTALL) { 11194 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11195 } 11196 if (res.origUsers != null) { 11197 for (int userHandle : res.origUsers) { 11198 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11199 userHandle, installerPackageName); 11200 } 11201 } 11202 // Also convey the prior install/uninstall state 11203 if (allUsers != null && perUserInstalled != null) { 11204 for (int i = 0; i < allUsers.length; i++) { 11205 if (DEBUG_INSTALL) { 11206 Slog.d(TAG, " user " + allUsers[i] 11207 + " => " + perUserInstalled[i]); 11208 } 11209 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11210 } 11211 // these install state changes will be persisted in the 11212 // upcoming call to mSettings.writeLPr(). 11213 } 11214 } 11215 // It's implied that when a user requests installation, they want the app to be 11216 // installed and enabled. 11217 int userId = user.getIdentifier(); 11218 if (userId != UserHandle.USER_ALL) { 11219 ps.setInstalled(true, userId); 11220 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11221 } 11222 } 11223 res.name = pkgName; 11224 res.uid = newPackage.applicationInfo.uid; 11225 res.pkg = newPackage; 11226 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11227 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11228 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11229 //to update install status 11230 mSettings.writeLPr(); 11231 } 11232 } 11233 11234 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11235 final int installFlags = args.installFlags; 11236 final String installerPackageName = args.installerPackageName; 11237 final String volumeUuid = args.volumeUuid; 11238 final File tmpPackageFile = new File(args.getCodePath()); 11239 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11240 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11241 || (args.volumeUuid != null)); 11242 boolean replace = false; 11243 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11244 // Result object to be returned 11245 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11246 11247 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11248 // Retrieve PackageSettings and parse package 11249 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11250 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11251 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11252 PackageParser pp = new PackageParser(); 11253 pp.setSeparateProcesses(mSeparateProcesses); 11254 pp.setDisplayMetrics(mMetrics); 11255 11256 final PackageParser.Package pkg; 11257 try { 11258 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11259 } catch (PackageParserException e) { 11260 res.setError("Failed parse during installPackageLI", e); 11261 return; 11262 } 11263 11264 // Mark that we have an install time CPU ABI override. 11265 pkg.cpuAbiOverride = args.abiOverride; 11266 11267 String pkgName = res.name = pkg.packageName; 11268 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11269 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11270 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11271 return; 11272 } 11273 } 11274 11275 try { 11276 pp.collectCertificates(pkg, parseFlags); 11277 pp.collectManifestDigest(pkg); 11278 } catch (PackageParserException e) { 11279 res.setError("Failed collect during installPackageLI", e); 11280 return; 11281 } 11282 11283 /* If the installer passed in a manifest digest, compare it now. */ 11284 if (args.manifestDigest != null) { 11285 if (DEBUG_INSTALL) { 11286 final String parsedManifest = pkg.manifestDigest == null ? "null" 11287 : pkg.manifestDigest.toString(); 11288 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11289 + parsedManifest); 11290 } 11291 11292 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11293 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11294 return; 11295 } 11296 } else if (DEBUG_INSTALL) { 11297 final String parsedManifest = pkg.manifestDigest == null 11298 ? "null" : pkg.manifestDigest.toString(); 11299 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11300 } 11301 11302 // Get rid of all references to package scan path via parser. 11303 pp = null; 11304 String oldCodePath = null; 11305 boolean systemApp = false; 11306 synchronized (mPackages) { 11307 // Check if installing already existing package 11308 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11309 String oldName = mSettings.mRenamedPackages.get(pkgName); 11310 if (pkg.mOriginalPackages != null 11311 && pkg.mOriginalPackages.contains(oldName) 11312 && mPackages.containsKey(oldName)) { 11313 // This package is derived from an original package, 11314 // and this device has been updating from that original 11315 // name. We must continue using the original name, so 11316 // rename the new package here. 11317 pkg.setPackageName(oldName); 11318 pkgName = pkg.packageName; 11319 replace = true; 11320 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11321 + oldName + " pkgName=" + pkgName); 11322 } else if (mPackages.containsKey(pkgName)) { 11323 // This package, under its official name, already exists 11324 // on the device; we should replace it. 11325 replace = true; 11326 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11327 } 11328 } 11329 11330 PackageSetting ps = mSettings.mPackages.get(pkgName); 11331 if (ps != null) { 11332 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11333 11334 // Quick sanity check that we're signed correctly if updating; 11335 // we'll check this again later when scanning, but we want to 11336 // bail early here before tripping over redefined permissions. 11337 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11338 try { 11339 verifySignaturesLP(ps, pkg); 11340 } catch (PackageManagerException e) { 11341 res.setError(e.error, e.getMessage()); 11342 return; 11343 } 11344 } else { 11345 if (!checkUpgradeKeySetLP(ps, pkg)) { 11346 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11347 + pkg.packageName + " upgrade keys do not match the " 11348 + "previously installed version"); 11349 return; 11350 } 11351 } 11352 11353 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11354 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11355 systemApp = (ps.pkg.applicationInfo.flags & 11356 ApplicationInfo.FLAG_SYSTEM) != 0; 11357 } 11358 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11359 } 11360 11361 // Check whether the newly-scanned package wants to define an already-defined perm 11362 int N = pkg.permissions.size(); 11363 for (int i = N-1; i >= 0; i--) { 11364 PackageParser.Permission perm = pkg.permissions.get(i); 11365 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11366 if (bp != null) { 11367 // If the defining package is signed with our cert, it's okay. This 11368 // also includes the "updating the same package" case, of course. 11369 // "updating same package" could also involve key-rotation. 11370 final boolean sigsOk; 11371 if (!bp.sourcePackage.equals(pkg.packageName) 11372 || !(bp.packageSetting instanceof PackageSetting) 11373 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11374 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11375 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11376 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11377 } else { 11378 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11379 } 11380 if (!sigsOk) { 11381 // If the owning package is the system itself, we log but allow 11382 // install to proceed; we fail the install on all other permission 11383 // redefinitions. 11384 if (!bp.sourcePackage.equals("android")) { 11385 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11386 + pkg.packageName + " attempting to redeclare permission " 11387 + perm.info.name + " already owned by " + bp.sourcePackage); 11388 res.origPermission = perm.info.name; 11389 res.origPackage = bp.sourcePackage; 11390 return; 11391 } else { 11392 Slog.w(TAG, "Package " + pkg.packageName 11393 + " attempting to redeclare system permission " 11394 + perm.info.name + "; ignoring new declaration"); 11395 pkg.permissions.remove(i); 11396 } 11397 } 11398 } 11399 } 11400 11401 } 11402 11403 if (systemApp && onExternal) { 11404 // Disable updates to system apps on sdcard 11405 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11406 "Cannot install updates to system apps on sdcard"); 11407 return; 11408 } 11409 11410 if (args.move != null) { 11411 // We did an in-place move, so dex is ready to roll 11412 scanFlags |= SCAN_NO_DEX; 11413 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11414 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11415 scanFlags |= SCAN_NO_DEX; 11416 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11417 int result = mPackageDexOptimizer 11418 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11419 false /* defer */, false /* inclDependencies */); 11420 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11421 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11422 return; 11423 } 11424 } 11425 11426 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11427 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11428 return; 11429 } 11430 11431 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11432 11433 if (replace) { 11434 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11435 installerPackageName, volumeUuid, res); 11436 } else { 11437 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11438 args.user, installerPackageName, volumeUuid, res); 11439 } 11440 synchronized (mPackages) { 11441 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11442 if (ps != null) { 11443 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11444 } 11445 } 11446 } 11447 11448 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11449 if (mIntentFilterVerifierComponent == null) { 11450 Slog.d(TAG, "No IntentFilter verification will not be done as " 11451 + "there is no IntentFilterVerifier available!"); 11452 return; 11453 } 11454 11455 final int verifierUid = getPackageUid( 11456 mIntentFilterVerifierComponent.getPackageName(), 11457 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11458 11459 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11460 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11461 msg.obj = pkg; 11462 msg.arg1 = userId; 11463 msg.arg2 = verifierUid; 11464 11465 mHandler.sendMessage(msg); 11466 } 11467 11468 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11469 PackageParser.Package pkg) { 11470 int size = pkg.activities.size(); 11471 if (size == 0) { 11472 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11473 return; 11474 } 11475 11476 final boolean hasDomainURLs = hasDomainURLs(pkg); 11477 if (!hasDomainURLs) { 11478 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11479 return; 11480 } 11481 11482 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11483 + " Activities needs verification ..."); 11484 11485 final int verificationId = mIntentFilterVerificationToken++; 11486 int count = 0; 11487 final String packageName = pkg.packageName; 11488 ArrayList<String> allHosts = new ArrayList<>(); 11489 11490 synchronized (mPackages) { 11491 for (PackageParser.Activity a : pkg.activities) { 11492 for (ActivityIntentInfo filter : a.intents) { 11493 boolean needsFilterVerification = filter.needsVerification(); 11494 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11495 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11496 mIntentFilterVerifier.addOneIntentFilterVerification( 11497 verifierUid, userId, verificationId, filter, packageName); 11498 count++; 11499 } else if (!needsFilterVerification) { 11500 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11501 if (hasValidDomains(filter)) { 11502 ArrayList<String> hosts = filter.getHostsList(); 11503 if (hosts.size() > 0) { 11504 allHosts.addAll(hosts); 11505 } else { 11506 if (allHosts.isEmpty()) { 11507 allHosts.add("*"); 11508 } 11509 } 11510 } 11511 } else { 11512 Slog.d(TAG, "Verification already done for IntentFilter:" 11513 + filter.toString()); 11514 } 11515 } 11516 } 11517 } 11518 11519 if (count > 0) { 11520 mIntentFilterVerifier.startVerifications(userId); 11521 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11522 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11523 } else { 11524 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11525 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11526 packageName, allHosts) != null) { 11527 scheduleWriteSettingsLocked(); 11528 } 11529 } 11530 } 11531 11532 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11533 final ComponentName cn = filter.activity.getComponentName(); 11534 final String packageName = cn.getPackageName(); 11535 11536 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11537 packageName); 11538 if (ivi == null) { 11539 return true; 11540 } 11541 int status = ivi.getStatus(); 11542 switch (status) { 11543 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11544 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11545 return true; 11546 11547 default: 11548 // Nothing to do 11549 return false; 11550 } 11551 } 11552 11553 private static boolean isMultiArch(PackageSetting ps) { 11554 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11555 } 11556 11557 private static boolean isMultiArch(ApplicationInfo info) { 11558 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11559 } 11560 11561 private static boolean isExternal(PackageParser.Package pkg) { 11562 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11563 } 11564 11565 private static boolean isExternal(PackageSetting ps) { 11566 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11567 } 11568 11569 private static boolean isExternal(ApplicationInfo info) { 11570 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11571 } 11572 11573 private static boolean isSystemApp(PackageParser.Package pkg) { 11574 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11575 } 11576 11577 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11578 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11579 } 11580 11581 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11582 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11583 } 11584 11585 private static boolean isSystemApp(PackageSetting ps) { 11586 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11587 } 11588 11589 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11590 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11591 } 11592 11593 private int packageFlagsToInstallFlags(PackageSetting ps) { 11594 int installFlags = 0; 11595 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11596 // This existing package was an external ASEC install when we have 11597 // the external flag without a UUID 11598 installFlags |= PackageManager.INSTALL_EXTERNAL; 11599 } 11600 if (ps.isForwardLocked()) { 11601 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11602 } 11603 return installFlags; 11604 } 11605 11606 private void deleteTempPackageFiles() { 11607 final FilenameFilter filter = new FilenameFilter() { 11608 public boolean accept(File dir, String name) { 11609 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11610 } 11611 }; 11612 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11613 file.delete(); 11614 } 11615 } 11616 11617 @Override 11618 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11619 int flags) { 11620 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11621 flags); 11622 } 11623 11624 @Override 11625 public void deletePackage(final String packageName, 11626 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11627 mContext.enforceCallingOrSelfPermission( 11628 android.Manifest.permission.DELETE_PACKAGES, null); 11629 final int uid = Binder.getCallingUid(); 11630 if (UserHandle.getUserId(uid) != userId) { 11631 mContext.enforceCallingPermission( 11632 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11633 "deletePackage for user " + userId); 11634 } 11635 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11636 try { 11637 observer.onPackageDeleted(packageName, 11638 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11639 } catch (RemoteException re) { 11640 } 11641 return; 11642 } 11643 11644 boolean uninstallBlocked = false; 11645 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11646 int[] users = sUserManager.getUserIds(); 11647 for (int i = 0; i < users.length; ++i) { 11648 if (getBlockUninstallForUser(packageName, users[i])) { 11649 uninstallBlocked = true; 11650 break; 11651 } 11652 } 11653 } else { 11654 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11655 } 11656 if (uninstallBlocked) { 11657 try { 11658 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11659 null); 11660 } catch (RemoteException re) { 11661 } 11662 return; 11663 } 11664 11665 if (DEBUG_REMOVE) { 11666 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11667 } 11668 // Queue up an async operation since the package deletion may take a little while. 11669 mHandler.post(new Runnable() { 11670 public void run() { 11671 mHandler.removeCallbacks(this); 11672 final int returnCode = deletePackageX(packageName, userId, flags); 11673 if (observer != null) { 11674 try { 11675 observer.onPackageDeleted(packageName, returnCode, null); 11676 } catch (RemoteException e) { 11677 Log.i(TAG, "Observer no longer exists."); 11678 } //end catch 11679 } //end if 11680 } //end run 11681 }); 11682 } 11683 11684 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11685 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11686 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11687 try { 11688 if (dpm != null) { 11689 if (dpm.isDeviceOwner(packageName)) { 11690 return true; 11691 } 11692 int[] users; 11693 if (userId == UserHandle.USER_ALL) { 11694 users = sUserManager.getUserIds(); 11695 } else { 11696 users = new int[]{userId}; 11697 } 11698 for (int i = 0; i < users.length; ++i) { 11699 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11700 return true; 11701 } 11702 } 11703 } 11704 } catch (RemoteException e) { 11705 } 11706 return false; 11707 } 11708 11709 /** 11710 * This method is an internal method that could be get invoked either 11711 * to delete an installed package or to clean up a failed installation. 11712 * After deleting an installed package, a broadcast is sent to notify any 11713 * listeners that the package has been installed. For cleaning up a failed 11714 * installation, the broadcast is not necessary since the package's 11715 * installation wouldn't have sent the initial broadcast either 11716 * The key steps in deleting a package are 11717 * deleting the package information in internal structures like mPackages, 11718 * deleting the packages base directories through installd 11719 * updating mSettings to reflect current status 11720 * persisting settings for later use 11721 * sending a broadcast if necessary 11722 */ 11723 private int deletePackageX(String packageName, int userId, int flags) { 11724 final PackageRemovedInfo info = new PackageRemovedInfo(); 11725 final boolean res; 11726 11727 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11728 ? UserHandle.ALL : new UserHandle(userId); 11729 11730 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11731 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11732 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11733 } 11734 11735 boolean removedForAllUsers = false; 11736 boolean systemUpdate = false; 11737 11738 // for the uninstall-updates case and restricted profiles, remember the per- 11739 // userhandle installed state 11740 int[] allUsers; 11741 boolean[] perUserInstalled; 11742 synchronized (mPackages) { 11743 PackageSetting ps = mSettings.mPackages.get(packageName); 11744 allUsers = sUserManager.getUserIds(); 11745 perUserInstalled = new boolean[allUsers.length]; 11746 for (int i = 0; i < allUsers.length; i++) { 11747 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11748 } 11749 } 11750 11751 synchronized (mInstallLock) { 11752 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11753 res = deletePackageLI(packageName, removeForUser, 11754 true, allUsers, perUserInstalled, 11755 flags | REMOVE_CHATTY, info, true); 11756 systemUpdate = info.isRemovedPackageSystemUpdate; 11757 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11758 removedForAllUsers = true; 11759 } 11760 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11761 + " removedForAllUsers=" + removedForAllUsers); 11762 } 11763 11764 if (res) { 11765 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11766 11767 // If the removed package was a system update, the old system package 11768 // was re-enabled; we need to broadcast this information 11769 if (systemUpdate) { 11770 Bundle extras = new Bundle(1); 11771 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11772 ? info.removedAppId : info.uid); 11773 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11774 11775 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11776 extras, null, null, null); 11777 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11778 extras, null, null, null); 11779 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11780 null, packageName, null, null); 11781 } 11782 } 11783 // Force a gc here. 11784 Runtime.getRuntime().gc(); 11785 // Delete the resources here after sending the broadcast to let 11786 // other processes clean up before deleting resources. 11787 if (info.args != null) { 11788 synchronized (mInstallLock) { 11789 info.args.doPostDeleteLI(true); 11790 } 11791 } 11792 11793 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11794 } 11795 11796 class PackageRemovedInfo { 11797 String removedPackage; 11798 int uid = -1; 11799 int removedAppId = -1; 11800 int[] removedUsers = null; 11801 boolean isRemovedPackageSystemUpdate = false; 11802 // Clean up resources deleted packages. 11803 InstallArgs args = null; 11804 11805 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11806 Bundle extras = new Bundle(1); 11807 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11808 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11809 if (replacing) { 11810 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11811 } 11812 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11813 if (removedPackage != null) { 11814 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11815 extras, null, null, removedUsers); 11816 if (fullRemove && !replacing) { 11817 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11818 extras, null, null, removedUsers); 11819 } 11820 } 11821 if (removedAppId >= 0) { 11822 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11823 removedUsers); 11824 } 11825 } 11826 } 11827 11828 /* 11829 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11830 * flag is not set, the data directory is removed as well. 11831 * make sure this flag is set for partially installed apps. If not its meaningless to 11832 * delete a partially installed application. 11833 */ 11834 private void removePackageDataLI(PackageSetting ps, 11835 int[] allUserHandles, boolean[] perUserInstalled, 11836 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11837 String packageName = ps.name; 11838 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11839 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11840 // Retrieve object to delete permissions for shared user later on 11841 final PackageSetting deletedPs; 11842 // reader 11843 synchronized (mPackages) { 11844 deletedPs = mSettings.mPackages.get(packageName); 11845 if (outInfo != null) { 11846 outInfo.removedPackage = packageName; 11847 outInfo.removedUsers = deletedPs != null 11848 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11849 : null; 11850 } 11851 } 11852 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11853 removeDataDirsLI(ps.volumeUuid, packageName); 11854 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11855 } 11856 // writer 11857 synchronized (mPackages) { 11858 if (deletedPs != null) { 11859 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11860 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11861 clearDefaultBrowserIfNeeded(packageName); 11862 if (outInfo != null) { 11863 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11864 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11865 } 11866 updatePermissionsLPw(deletedPs.name, null, 0); 11867 if (deletedPs.sharedUser != null) { 11868 // Remove permissions associated with package. Since runtime 11869 // permissions are per user we have to kill the removed package 11870 // or packages running under the shared user of the removed 11871 // package if revoking the permissions requested only by the removed 11872 // package is successful and this causes a change in gids. 11873 for (int userId : UserManagerService.getInstance().getUserIds()) { 11874 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11875 userId); 11876 if (userIdToKill == UserHandle.USER_ALL 11877 || userIdToKill >= UserHandle.USER_OWNER) { 11878 // If gids changed for this user, kill all affected packages. 11879 mHandler.post(new Runnable() { 11880 @Override 11881 public void run() { 11882 // This has to happen with no lock held. 11883 killSettingPackagesForUser(deletedPs, userIdToKill, 11884 KILL_APP_REASON_GIDS_CHANGED); 11885 } 11886 }); 11887 break; 11888 } 11889 } 11890 } 11891 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11892 } 11893 // make sure to preserve per-user disabled state if this removal was just 11894 // a downgrade of a system app to the factory package 11895 if (allUserHandles != null && perUserInstalled != null) { 11896 if (DEBUG_REMOVE) { 11897 Slog.d(TAG, "Propagating install state across downgrade"); 11898 } 11899 for (int i = 0; i < allUserHandles.length; i++) { 11900 if (DEBUG_REMOVE) { 11901 Slog.d(TAG, " user " + allUserHandles[i] 11902 + " => " + perUserInstalled[i]); 11903 } 11904 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11905 } 11906 } 11907 } 11908 // can downgrade to reader 11909 if (writeSettings) { 11910 // Save settings now 11911 mSettings.writeLPr(); 11912 } 11913 } 11914 if (outInfo != null) { 11915 // A user ID was deleted here. Go through all users and remove it 11916 // from KeyStore. 11917 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11918 } 11919 } 11920 11921 static boolean locationIsPrivileged(File path) { 11922 try { 11923 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11924 .getCanonicalPath(); 11925 return path.getCanonicalPath().startsWith(privilegedAppDir); 11926 } catch (IOException e) { 11927 Slog.e(TAG, "Unable to access code path " + path); 11928 } 11929 return false; 11930 } 11931 11932 /* 11933 * Tries to delete system package. 11934 */ 11935 private boolean deleteSystemPackageLI(PackageSetting newPs, 11936 int[] allUserHandles, boolean[] perUserInstalled, 11937 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11938 final boolean applyUserRestrictions 11939 = (allUserHandles != null) && (perUserInstalled != null); 11940 PackageSetting disabledPs = null; 11941 // Confirm if the system package has been updated 11942 // An updated system app can be deleted. This will also have to restore 11943 // the system pkg from system partition 11944 // reader 11945 synchronized (mPackages) { 11946 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11947 } 11948 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11949 + " disabledPs=" + disabledPs); 11950 if (disabledPs == null) { 11951 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11952 return false; 11953 } else if (DEBUG_REMOVE) { 11954 Slog.d(TAG, "Deleting system pkg from data partition"); 11955 } 11956 if (DEBUG_REMOVE) { 11957 if (applyUserRestrictions) { 11958 Slog.d(TAG, "Remembering install states:"); 11959 for (int i = 0; i < allUserHandles.length; i++) { 11960 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11961 } 11962 } 11963 } 11964 // Delete the updated package 11965 outInfo.isRemovedPackageSystemUpdate = true; 11966 if (disabledPs.versionCode < newPs.versionCode) { 11967 // Delete data for downgrades 11968 flags &= ~PackageManager.DELETE_KEEP_DATA; 11969 } else { 11970 // Preserve data by setting flag 11971 flags |= PackageManager.DELETE_KEEP_DATA; 11972 } 11973 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11974 allUserHandles, perUserInstalled, outInfo, writeSettings); 11975 if (!ret) { 11976 return false; 11977 } 11978 // writer 11979 synchronized (mPackages) { 11980 // Reinstate the old system package 11981 mSettings.enableSystemPackageLPw(newPs.name); 11982 // Remove any native libraries from the upgraded package. 11983 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11984 } 11985 // Install the system package 11986 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11987 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11988 if (locationIsPrivileged(disabledPs.codePath)) { 11989 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11990 } 11991 11992 final PackageParser.Package newPkg; 11993 try { 11994 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11995 } catch (PackageManagerException e) { 11996 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11997 return false; 11998 } 11999 12000 // writer 12001 synchronized (mPackages) { 12002 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12003 updatePermissionsLPw(newPkg.packageName, newPkg, 12004 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12005 if (applyUserRestrictions) { 12006 if (DEBUG_REMOVE) { 12007 Slog.d(TAG, "Propagating install state across reinstall"); 12008 } 12009 for (int i = 0; i < allUserHandles.length; i++) { 12010 if (DEBUG_REMOVE) { 12011 Slog.d(TAG, " user " + allUserHandles[i] 12012 + " => " + perUserInstalled[i]); 12013 } 12014 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12015 } 12016 // Regardless of writeSettings we need to ensure that this restriction 12017 // state propagation is persisted 12018 mSettings.writeAllUsersPackageRestrictionsLPr(); 12019 } 12020 // can downgrade to reader here 12021 if (writeSettings) { 12022 mSettings.writeLPr(); 12023 } 12024 } 12025 return true; 12026 } 12027 12028 private boolean deleteInstalledPackageLI(PackageSetting ps, 12029 boolean deleteCodeAndResources, int flags, 12030 int[] allUserHandles, boolean[] perUserInstalled, 12031 PackageRemovedInfo outInfo, boolean writeSettings) { 12032 if (outInfo != null) { 12033 outInfo.uid = ps.appId; 12034 } 12035 12036 // Delete package data from internal structures and also remove data if flag is set 12037 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12038 12039 // Delete application code and resources 12040 if (deleteCodeAndResources && (outInfo != null)) { 12041 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12042 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12043 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12044 } 12045 return true; 12046 } 12047 12048 @Override 12049 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12050 int userId) { 12051 mContext.enforceCallingOrSelfPermission( 12052 android.Manifest.permission.DELETE_PACKAGES, null); 12053 synchronized (mPackages) { 12054 PackageSetting ps = mSettings.mPackages.get(packageName); 12055 if (ps == null) { 12056 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12057 return false; 12058 } 12059 if (!ps.getInstalled(userId)) { 12060 // Can't block uninstall for an app that is not installed or enabled. 12061 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12062 return false; 12063 } 12064 ps.setBlockUninstall(blockUninstall, userId); 12065 mSettings.writePackageRestrictionsLPr(userId); 12066 } 12067 return true; 12068 } 12069 12070 @Override 12071 public boolean getBlockUninstallForUser(String packageName, int userId) { 12072 synchronized (mPackages) { 12073 PackageSetting ps = mSettings.mPackages.get(packageName); 12074 if (ps == null) { 12075 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12076 return false; 12077 } 12078 return ps.getBlockUninstall(userId); 12079 } 12080 } 12081 12082 /* 12083 * This method handles package deletion in general 12084 */ 12085 private boolean deletePackageLI(String packageName, UserHandle user, 12086 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12087 int flags, PackageRemovedInfo outInfo, 12088 boolean writeSettings) { 12089 if (packageName == null) { 12090 Slog.w(TAG, "Attempt to delete null packageName."); 12091 return false; 12092 } 12093 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12094 PackageSetting ps; 12095 boolean dataOnly = false; 12096 int removeUser = -1; 12097 int appId = -1; 12098 synchronized (mPackages) { 12099 ps = mSettings.mPackages.get(packageName); 12100 if (ps == null) { 12101 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12102 return false; 12103 } 12104 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12105 && user.getIdentifier() != UserHandle.USER_ALL) { 12106 // The caller is asking that the package only be deleted for a single 12107 // user. To do this, we just mark its uninstalled state and delete 12108 // its data. If this is a system app, we only allow this to happen if 12109 // they have set the special DELETE_SYSTEM_APP which requests different 12110 // semantics than normal for uninstalling system apps. 12111 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12112 ps.setUserState(user.getIdentifier(), 12113 COMPONENT_ENABLED_STATE_DEFAULT, 12114 false, //installed 12115 true, //stopped 12116 true, //notLaunched 12117 false, //hidden 12118 null, null, null, 12119 false, // blockUninstall 12120 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12121 if (!isSystemApp(ps)) { 12122 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12123 // Other user still have this package installed, so all 12124 // we need to do is clear this user's data and save that 12125 // it is uninstalled. 12126 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12127 removeUser = user.getIdentifier(); 12128 appId = ps.appId; 12129 scheduleWritePackageRestrictionsLocked(removeUser); 12130 } else { 12131 // We need to set it back to 'installed' so the uninstall 12132 // broadcasts will be sent correctly. 12133 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12134 ps.setInstalled(true, user.getIdentifier()); 12135 } 12136 } else { 12137 // This is a system app, so we assume that the 12138 // other users still have this package installed, so all 12139 // we need to do is clear this user's data and save that 12140 // it is uninstalled. 12141 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12142 removeUser = user.getIdentifier(); 12143 appId = ps.appId; 12144 scheduleWritePackageRestrictionsLocked(removeUser); 12145 } 12146 } 12147 } 12148 12149 if (removeUser >= 0) { 12150 // From above, we determined that we are deleting this only 12151 // for a single user. Continue the work here. 12152 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12153 if (outInfo != null) { 12154 outInfo.removedPackage = packageName; 12155 outInfo.removedAppId = appId; 12156 outInfo.removedUsers = new int[] {removeUser}; 12157 } 12158 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12159 removeKeystoreDataIfNeeded(removeUser, appId); 12160 schedulePackageCleaning(packageName, removeUser, false); 12161 synchronized (mPackages) { 12162 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12163 scheduleWritePackageRestrictionsLocked(removeUser); 12164 } 12165 } 12166 return true; 12167 } 12168 12169 if (dataOnly) { 12170 // Delete application data first 12171 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12172 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12173 return true; 12174 } 12175 12176 boolean ret = false; 12177 if (isSystemApp(ps)) { 12178 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12179 // When an updated system application is deleted we delete the existing resources as well and 12180 // fall back to existing code in system partition 12181 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12182 flags, outInfo, writeSettings); 12183 } else { 12184 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12185 // Kill application pre-emptively especially for apps on sd. 12186 killApplication(packageName, ps.appId, "uninstall pkg"); 12187 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12188 allUserHandles, perUserInstalled, 12189 outInfo, writeSettings); 12190 } 12191 12192 return ret; 12193 } 12194 12195 private final class ClearStorageConnection implements ServiceConnection { 12196 IMediaContainerService mContainerService; 12197 12198 @Override 12199 public void onServiceConnected(ComponentName name, IBinder service) { 12200 synchronized (this) { 12201 mContainerService = IMediaContainerService.Stub.asInterface(service); 12202 notifyAll(); 12203 } 12204 } 12205 12206 @Override 12207 public void onServiceDisconnected(ComponentName name) { 12208 } 12209 } 12210 12211 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12212 final boolean mounted; 12213 if (Environment.isExternalStorageEmulated()) { 12214 mounted = true; 12215 } else { 12216 final String status = Environment.getExternalStorageState(); 12217 12218 mounted = status.equals(Environment.MEDIA_MOUNTED) 12219 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12220 } 12221 12222 if (!mounted) { 12223 return; 12224 } 12225 12226 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12227 int[] users; 12228 if (userId == UserHandle.USER_ALL) { 12229 users = sUserManager.getUserIds(); 12230 } else { 12231 users = new int[] { userId }; 12232 } 12233 final ClearStorageConnection conn = new ClearStorageConnection(); 12234 if (mContext.bindServiceAsUser( 12235 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12236 try { 12237 for (int curUser : users) { 12238 long timeout = SystemClock.uptimeMillis() + 5000; 12239 synchronized (conn) { 12240 long now = SystemClock.uptimeMillis(); 12241 while (conn.mContainerService == null && now < timeout) { 12242 try { 12243 conn.wait(timeout - now); 12244 } catch (InterruptedException e) { 12245 } 12246 } 12247 } 12248 if (conn.mContainerService == null) { 12249 return; 12250 } 12251 12252 final UserEnvironment userEnv = new UserEnvironment(curUser); 12253 clearDirectory(conn.mContainerService, 12254 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12255 if (allData) { 12256 clearDirectory(conn.mContainerService, 12257 userEnv.buildExternalStorageAppDataDirs(packageName)); 12258 clearDirectory(conn.mContainerService, 12259 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12260 } 12261 } 12262 } finally { 12263 mContext.unbindService(conn); 12264 } 12265 } 12266 } 12267 12268 @Override 12269 public void clearApplicationUserData(final String packageName, 12270 final IPackageDataObserver observer, final int userId) { 12271 mContext.enforceCallingOrSelfPermission( 12272 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12273 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12274 // Queue up an async operation since the package deletion may take a little while. 12275 mHandler.post(new Runnable() { 12276 public void run() { 12277 mHandler.removeCallbacks(this); 12278 final boolean succeeded; 12279 synchronized (mInstallLock) { 12280 succeeded = clearApplicationUserDataLI(packageName, userId); 12281 } 12282 clearExternalStorageDataSync(packageName, userId, true); 12283 if (succeeded) { 12284 // invoke DeviceStorageMonitor's update method to clear any notifications 12285 DeviceStorageMonitorInternal 12286 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12287 if (dsm != null) { 12288 dsm.checkMemory(); 12289 } 12290 } 12291 if(observer != null) { 12292 try { 12293 observer.onRemoveCompleted(packageName, succeeded); 12294 } catch (RemoteException e) { 12295 Log.i(TAG, "Observer no longer exists."); 12296 } 12297 } //end if observer 12298 } //end run 12299 }); 12300 } 12301 12302 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12303 if (packageName == null) { 12304 Slog.w(TAG, "Attempt to delete null packageName."); 12305 return false; 12306 } 12307 12308 // Try finding details about the requested package 12309 PackageParser.Package pkg; 12310 synchronized (mPackages) { 12311 pkg = mPackages.get(packageName); 12312 if (pkg == null) { 12313 final PackageSetting ps = mSettings.mPackages.get(packageName); 12314 if (ps != null) { 12315 pkg = ps.pkg; 12316 } 12317 } 12318 } 12319 12320 if (pkg == null) { 12321 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12322 } 12323 12324 // Always delete data directories for package, even if we found no other 12325 // record of app. This helps users recover from UID mismatches without 12326 // resorting to a full data wipe. 12327 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12328 if (retCode < 0) { 12329 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12330 return false; 12331 } 12332 12333 if (pkg == null) { 12334 return false; 12335 } 12336 12337 if (pkg != null && pkg.applicationInfo != null) { 12338 final int appId = pkg.applicationInfo.uid; 12339 removeKeystoreDataIfNeeded(userId, appId); 12340 } 12341 12342 // Create a native library symlink only if we have native libraries 12343 // and if the native libraries are 32 bit libraries. We do not provide 12344 // this symlink for 64 bit libraries. 12345 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12346 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12347 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12348 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12349 nativeLibPath, userId) < 0) { 12350 Slog.w(TAG, "Failed linking native library dir"); 12351 return false; 12352 } 12353 } 12354 12355 return true; 12356 } 12357 12358 /** 12359 * Remove entries from the keystore daemon. Will only remove it if the 12360 * {@code appId} is valid. 12361 */ 12362 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12363 if (appId < 0) { 12364 return; 12365 } 12366 12367 final KeyStore keyStore = KeyStore.getInstance(); 12368 if (keyStore != null) { 12369 if (userId == UserHandle.USER_ALL) { 12370 for (final int individual : sUserManager.getUserIds()) { 12371 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12372 } 12373 } else { 12374 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12375 } 12376 } else { 12377 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12378 } 12379 } 12380 12381 @Override 12382 public void deleteApplicationCacheFiles(final String packageName, 12383 final IPackageDataObserver observer) { 12384 mContext.enforceCallingOrSelfPermission( 12385 android.Manifest.permission.DELETE_CACHE_FILES, null); 12386 // Queue up an async operation since the package deletion may take a little while. 12387 final int userId = UserHandle.getCallingUserId(); 12388 mHandler.post(new Runnable() { 12389 public void run() { 12390 mHandler.removeCallbacks(this); 12391 final boolean succeded; 12392 synchronized (mInstallLock) { 12393 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12394 } 12395 clearExternalStorageDataSync(packageName, userId, false); 12396 if (observer != null) { 12397 try { 12398 observer.onRemoveCompleted(packageName, succeded); 12399 } catch (RemoteException e) { 12400 Log.i(TAG, "Observer no longer exists."); 12401 } 12402 } //end if observer 12403 } //end run 12404 }); 12405 } 12406 12407 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12408 if (packageName == null) { 12409 Slog.w(TAG, "Attempt to delete null packageName."); 12410 return false; 12411 } 12412 PackageParser.Package p; 12413 synchronized (mPackages) { 12414 p = mPackages.get(packageName); 12415 } 12416 if (p == null) { 12417 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12418 return false; 12419 } 12420 final ApplicationInfo applicationInfo = p.applicationInfo; 12421 if (applicationInfo == null) { 12422 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12423 return false; 12424 } 12425 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12426 if (retCode < 0) { 12427 Slog.w(TAG, "Couldn't remove cache files for package: " 12428 + packageName + " u" + userId); 12429 return false; 12430 } 12431 return true; 12432 } 12433 12434 @Override 12435 public void getPackageSizeInfo(final String packageName, int userHandle, 12436 final IPackageStatsObserver observer) { 12437 mContext.enforceCallingOrSelfPermission( 12438 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12439 if (packageName == null) { 12440 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12441 } 12442 12443 PackageStats stats = new PackageStats(packageName, userHandle); 12444 12445 /* 12446 * Queue up an async operation since the package measurement may take a 12447 * little while. 12448 */ 12449 Message msg = mHandler.obtainMessage(INIT_COPY); 12450 msg.obj = new MeasureParams(stats, observer); 12451 mHandler.sendMessage(msg); 12452 } 12453 12454 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12455 PackageStats pStats) { 12456 if (packageName == null) { 12457 Slog.w(TAG, "Attempt to get size of null packageName."); 12458 return false; 12459 } 12460 PackageParser.Package p; 12461 boolean dataOnly = false; 12462 String libDirRoot = null; 12463 String asecPath = null; 12464 PackageSetting ps = null; 12465 synchronized (mPackages) { 12466 p = mPackages.get(packageName); 12467 ps = mSettings.mPackages.get(packageName); 12468 if(p == null) { 12469 dataOnly = true; 12470 if((ps == null) || (ps.pkg == null)) { 12471 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12472 return false; 12473 } 12474 p = ps.pkg; 12475 } 12476 if (ps != null) { 12477 libDirRoot = ps.legacyNativeLibraryPathString; 12478 } 12479 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12480 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12481 if (secureContainerId != null) { 12482 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12483 } 12484 } 12485 } 12486 String publicSrcDir = null; 12487 if(!dataOnly) { 12488 final ApplicationInfo applicationInfo = p.applicationInfo; 12489 if (applicationInfo == null) { 12490 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12491 return false; 12492 } 12493 if (p.isForwardLocked()) { 12494 publicSrcDir = applicationInfo.getBaseResourcePath(); 12495 } 12496 } 12497 // TODO: extend to measure size of split APKs 12498 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12499 // not just the first level. 12500 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12501 // just the primary. 12502 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12503 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12504 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12505 if (res < 0) { 12506 return false; 12507 } 12508 12509 // Fix-up for forward-locked applications in ASEC containers. 12510 if (!isExternal(p)) { 12511 pStats.codeSize += pStats.externalCodeSize; 12512 pStats.externalCodeSize = 0L; 12513 } 12514 12515 return true; 12516 } 12517 12518 12519 @Override 12520 public void addPackageToPreferred(String packageName) { 12521 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12522 } 12523 12524 @Override 12525 public void removePackageFromPreferred(String packageName) { 12526 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12527 } 12528 12529 @Override 12530 public List<PackageInfo> getPreferredPackages(int flags) { 12531 return new ArrayList<PackageInfo>(); 12532 } 12533 12534 private int getUidTargetSdkVersionLockedLPr(int uid) { 12535 Object obj = mSettings.getUserIdLPr(uid); 12536 if (obj instanceof SharedUserSetting) { 12537 final SharedUserSetting sus = (SharedUserSetting) obj; 12538 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12539 final Iterator<PackageSetting> it = sus.packages.iterator(); 12540 while (it.hasNext()) { 12541 final PackageSetting ps = it.next(); 12542 if (ps.pkg != null) { 12543 int v = ps.pkg.applicationInfo.targetSdkVersion; 12544 if (v < vers) vers = v; 12545 } 12546 } 12547 return vers; 12548 } else if (obj instanceof PackageSetting) { 12549 final PackageSetting ps = (PackageSetting) obj; 12550 if (ps.pkg != null) { 12551 return ps.pkg.applicationInfo.targetSdkVersion; 12552 } 12553 } 12554 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12555 } 12556 12557 @Override 12558 public void addPreferredActivity(IntentFilter filter, int match, 12559 ComponentName[] set, ComponentName activity, int userId) { 12560 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12561 "Adding preferred"); 12562 } 12563 12564 private void addPreferredActivityInternal(IntentFilter filter, int match, 12565 ComponentName[] set, ComponentName activity, boolean always, int userId, 12566 String opname) { 12567 // writer 12568 int callingUid = Binder.getCallingUid(); 12569 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12570 if (filter.countActions() == 0) { 12571 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12572 return; 12573 } 12574 synchronized (mPackages) { 12575 if (mContext.checkCallingOrSelfPermission( 12576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12577 != PackageManager.PERMISSION_GRANTED) { 12578 if (getUidTargetSdkVersionLockedLPr(callingUid) 12579 < Build.VERSION_CODES.FROYO) { 12580 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12581 + callingUid); 12582 return; 12583 } 12584 mContext.enforceCallingOrSelfPermission( 12585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12586 } 12587 12588 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12589 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12590 + userId + ":"); 12591 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12592 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12593 scheduleWritePackageRestrictionsLocked(userId); 12594 } 12595 } 12596 12597 @Override 12598 public void replacePreferredActivity(IntentFilter filter, int match, 12599 ComponentName[] set, ComponentName activity, int userId) { 12600 if (filter.countActions() != 1) { 12601 throw new IllegalArgumentException( 12602 "replacePreferredActivity expects filter to have only 1 action."); 12603 } 12604 if (filter.countDataAuthorities() != 0 12605 || filter.countDataPaths() != 0 12606 || filter.countDataSchemes() > 1 12607 || filter.countDataTypes() != 0) { 12608 throw new IllegalArgumentException( 12609 "replacePreferredActivity expects filter to have no data authorities, " + 12610 "paths, or types; and at most one scheme."); 12611 } 12612 12613 final int callingUid = Binder.getCallingUid(); 12614 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12615 synchronized (mPackages) { 12616 if (mContext.checkCallingOrSelfPermission( 12617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12618 != PackageManager.PERMISSION_GRANTED) { 12619 if (getUidTargetSdkVersionLockedLPr(callingUid) 12620 < Build.VERSION_CODES.FROYO) { 12621 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12622 + Binder.getCallingUid()); 12623 return; 12624 } 12625 mContext.enforceCallingOrSelfPermission( 12626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12627 } 12628 12629 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12630 if (pir != null) { 12631 // Get all of the existing entries that exactly match this filter. 12632 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12633 if (existing != null && existing.size() == 1) { 12634 PreferredActivity cur = existing.get(0); 12635 if (DEBUG_PREFERRED) { 12636 Slog.i(TAG, "Checking replace of preferred:"); 12637 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12638 if (!cur.mPref.mAlways) { 12639 Slog.i(TAG, " -- CUR; not mAlways!"); 12640 } else { 12641 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12642 Slog.i(TAG, " -- CUR: mSet=" 12643 + Arrays.toString(cur.mPref.mSetComponents)); 12644 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12645 Slog.i(TAG, " -- NEW: mMatch=" 12646 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12647 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12648 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12649 } 12650 } 12651 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12652 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12653 && cur.mPref.sameSet(set)) { 12654 // Setting the preferred activity to what it happens to be already 12655 if (DEBUG_PREFERRED) { 12656 Slog.i(TAG, "Replacing with same preferred activity " 12657 + cur.mPref.mShortComponent + " for user " 12658 + userId + ":"); 12659 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12660 } 12661 return; 12662 } 12663 } 12664 12665 if (existing != null) { 12666 if (DEBUG_PREFERRED) { 12667 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12668 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12669 } 12670 for (int i = 0; i < existing.size(); i++) { 12671 PreferredActivity pa = existing.get(i); 12672 if (DEBUG_PREFERRED) { 12673 Slog.i(TAG, "Removing existing preferred activity " 12674 + pa.mPref.mComponent + ":"); 12675 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12676 } 12677 pir.removeFilter(pa); 12678 } 12679 } 12680 } 12681 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12682 "Replacing preferred"); 12683 } 12684 } 12685 12686 @Override 12687 public void clearPackagePreferredActivities(String packageName) { 12688 final int uid = Binder.getCallingUid(); 12689 // writer 12690 synchronized (mPackages) { 12691 PackageParser.Package pkg = mPackages.get(packageName); 12692 if (pkg == null || pkg.applicationInfo.uid != uid) { 12693 if (mContext.checkCallingOrSelfPermission( 12694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12695 != PackageManager.PERMISSION_GRANTED) { 12696 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12697 < Build.VERSION_CODES.FROYO) { 12698 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12699 + Binder.getCallingUid()); 12700 return; 12701 } 12702 mContext.enforceCallingOrSelfPermission( 12703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12704 } 12705 } 12706 12707 int user = UserHandle.getCallingUserId(); 12708 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12709 scheduleWritePackageRestrictionsLocked(user); 12710 } 12711 } 12712 } 12713 12714 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12715 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12716 ArrayList<PreferredActivity> removed = null; 12717 boolean changed = false; 12718 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12719 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12720 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12721 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12722 continue; 12723 } 12724 Iterator<PreferredActivity> it = pir.filterIterator(); 12725 while (it.hasNext()) { 12726 PreferredActivity pa = it.next(); 12727 // Mark entry for removal only if it matches the package name 12728 // and the entry is of type "always". 12729 if (packageName == null || 12730 (pa.mPref.mComponent.getPackageName().equals(packageName) 12731 && pa.mPref.mAlways)) { 12732 if (removed == null) { 12733 removed = new ArrayList<PreferredActivity>(); 12734 } 12735 removed.add(pa); 12736 } 12737 } 12738 if (removed != null) { 12739 for (int j=0; j<removed.size(); j++) { 12740 PreferredActivity pa = removed.get(j); 12741 pir.removeFilter(pa); 12742 } 12743 changed = true; 12744 } 12745 } 12746 return changed; 12747 } 12748 12749 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12750 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12751 if (userId == UserHandle.USER_ALL) { 12752 if (mSettings.removeIntentFilterVerificationLPw(packageName, 12753 sUserManager.getUserIds())) { 12754 for (int oneUserId : sUserManager.getUserIds()) { 12755 scheduleWritePackageRestrictionsLocked(oneUserId); 12756 } 12757 } 12758 } else { 12759 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 12760 scheduleWritePackageRestrictionsLocked(userId); 12761 } 12762 } 12763 } 12764 12765 12766 void clearDefaultBrowserIfNeeded(String packageName) { 12767 for (int oneUserId : sUserManager.getUserIds()) { 12768 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 12769 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 12770 if (packageName.equals(defaultBrowserPackageName)) { 12771 setDefaultBrowserPackageName(null, oneUserId); 12772 } 12773 } 12774 } 12775 12776 @Override 12777 public void resetPreferredActivities(int userId) { 12778 /* TODO: Actually use userId. Why is it being passed in? */ 12779 mContext.enforceCallingOrSelfPermission( 12780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12781 // writer 12782 synchronized (mPackages) { 12783 int user = UserHandle.getCallingUserId(); 12784 clearPackagePreferredActivitiesLPw(null, user); 12785 mSettings.readDefaultPreferredAppsLPw(this, user); 12786 scheduleWritePackageRestrictionsLocked(user); 12787 } 12788 } 12789 12790 @Override 12791 public int getPreferredActivities(List<IntentFilter> outFilters, 12792 List<ComponentName> outActivities, String packageName) { 12793 12794 int num = 0; 12795 final int userId = UserHandle.getCallingUserId(); 12796 // reader 12797 synchronized (mPackages) { 12798 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12799 if (pir != null) { 12800 final Iterator<PreferredActivity> it = pir.filterIterator(); 12801 while (it.hasNext()) { 12802 final PreferredActivity pa = it.next(); 12803 if (packageName == null 12804 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12805 && pa.mPref.mAlways)) { 12806 if (outFilters != null) { 12807 outFilters.add(new IntentFilter(pa)); 12808 } 12809 if (outActivities != null) { 12810 outActivities.add(pa.mPref.mComponent); 12811 } 12812 } 12813 } 12814 } 12815 } 12816 12817 return num; 12818 } 12819 12820 @Override 12821 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12822 int userId) { 12823 int callingUid = Binder.getCallingUid(); 12824 if (callingUid != Process.SYSTEM_UID) { 12825 throw new SecurityException( 12826 "addPersistentPreferredActivity can only be run by the system"); 12827 } 12828 if (filter.countActions() == 0) { 12829 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12830 return; 12831 } 12832 synchronized (mPackages) { 12833 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12834 " :"); 12835 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12836 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12837 new PersistentPreferredActivity(filter, activity)); 12838 scheduleWritePackageRestrictionsLocked(userId); 12839 } 12840 } 12841 12842 @Override 12843 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12844 int callingUid = Binder.getCallingUid(); 12845 if (callingUid != Process.SYSTEM_UID) { 12846 throw new SecurityException( 12847 "clearPackagePersistentPreferredActivities can only be run by the system"); 12848 } 12849 ArrayList<PersistentPreferredActivity> removed = null; 12850 boolean changed = false; 12851 synchronized (mPackages) { 12852 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12853 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12854 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12855 .valueAt(i); 12856 if (userId != thisUserId) { 12857 continue; 12858 } 12859 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12860 while (it.hasNext()) { 12861 PersistentPreferredActivity ppa = it.next(); 12862 // Mark entry for removal only if it matches the package name. 12863 if (ppa.mComponent.getPackageName().equals(packageName)) { 12864 if (removed == null) { 12865 removed = new ArrayList<PersistentPreferredActivity>(); 12866 } 12867 removed.add(ppa); 12868 } 12869 } 12870 if (removed != null) { 12871 for (int j=0; j<removed.size(); j++) { 12872 PersistentPreferredActivity ppa = removed.get(j); 12873 ppir.removeFilter(ppa); 12874 } 12875 changed = true; 12876 } 12877 } 12878 12879 if (changed) { 12880 scheduleWritePackageRestrictionsLocked(userId); 12881 } 12882 } 12883 } 12884 12885 /** 12886 * Non-Binder method, support for the backup/restore mechanism: write the 12887 * full set of preferred activities in its canonical XML format. Returns true 12888 * on success; false otherwise. 12889 */ 12890 @Override 12891 public byte[] getPreferredActivityBackup(int userId) { 12892 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12893 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12894 } 12895 12896 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12897 try { 12898 final XmlSerializer serializer = new FastXmlSerializer(); 12899 serializer.setOutput(dataStream, "utf-8"); 12900 serializer.startDocument(null, true); 12901 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12902 12903 synchronized (mPackages) { 12904 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12905 } 12906 12907 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12908 serializer.endDocument(); 12909 serializer.flush(); 12910 } catch (Exception e) { 12911 if (DEBUG_BACKUP) { 12912 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12913 } 12914 return null; 12915 } 12916 12917 return dataStream.toByteArray(); 12918 } 12919 12920 @Override 12921 public void restorePreferredActivities(byte[] backup, int userId) { 12922 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12923 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12924 } 12925 12926 try { 12927 final XmlPullParser parser = Xml.newPullParser(); 12928 parser.setInput(new ByteArrayInputStream(backup), null); 12929 12930 int type; 12931 while ((type = parser.next()) != XmlPullParser.START_TAG 12932 && type != XmlPullParser.END_DOCUMENT) { 12933 } 12934 if (type != XmlPullParser.START_TAG) { 12935 // oops didn't find a start tag?! 12936 if (DEBUG_BACKUP) { 12937 Slog.e(TAG, "Didn't find start tag during restore"); 12938 } 12939 return; 12940 } 12941 12942 // this is supposed to be TAG_PREFERRED_BACKUP 12943 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12944 if (DEBUG_BACKUP) { 12945 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12946 } 12947 return; 12948 } 12949 12950 // skip interfering stuff, then we're aligned with the backing implementation 12951 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12952 synchronized (mPackages) { 12953 mSettings.readPreferredActivitiesLPw(parser, userId); 12954 } 12955 } catch (Exception e) { 12956 if (DEBUG_BACKUP) { 12957 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12958 } 12959 } 12960 } 12961 12962 @Override 12963 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12964 int sourceUserId, int targetUserId, int flags) { 12965 mContext.enforceCallingOrSelfPermission( 12966 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12967 int callingUid = Binder.getCallingUid(); 12968 enforceOwnerRights(ownerPackage, callingUid); 12969 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12970 if (intentFilter.countActions() == 0) { 12971 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12972 return; 12973 } 12974 synchronized (mPackages) { 12975 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12976 ownerPackage, targetUserId, flags); 12977 CrossProfileIntentResolver resolver = 12978 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12979 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12980 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12981 if (existing != null) { 12982 int size = existing.size(); 12983 for (int i = 0; i < size; i++) { 12984 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12985 return; 12986 } 12987 } 12988 } 12989 resolver.addFilter(newFilter); 12990 scheduleWritePackageRestrictionsLocked(sourceUserId); 12991 } 12992 } 12993 12994 @Override 12995 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12996 mContext.enforceCallingOrSelfPermission( 12997 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12998 int callingUid = Binder.getCallingUid(); 12999 enforceOwnerRights(ownerPackage, callingUid); 13000 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13001 synchronized (mPackages) { 13002 CrossProfileIntentResolver resolver = 13003 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13004 ArraySet<CrossProfileIntentFilter> set = 13005 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13006 for (CrossProfileIntentFilter filter : set) { 13007 if (filter.getOwnerPackage().equals(ownerPackage)) { 13008 resolver.removeFilter(filter); 13009 } 13010 } 13011 scheduleWritePackageRestrictionsLocked(sourceUserId); 13012 } 13013 } 13014 13015 // Enforcing that callingUid is owning pkg on userId 13016 private void enforceOwnerRights(String pkg, int callingUid) { 13017 // The system owns everything. 13018 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13019 return; 13020 } 13021 int callingUserId = UserHandle.getUserId(callingUid); 13022 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13023 if (pi == null) { 13024 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13025 + callingUserId); 13026 } 13027 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13028 throw new SecurityException("Calling uid " + callingUid 13029 + " does not own package " + pkg); 13030 } 13031 } 13032 13033 @Override 13034 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13035 Intent intent = new Intent(Intent.ACTION_MAIN); 13036 intent.addCategory(Intent.CATEGORY_HOME); 13037 13038 final int callingUserId = UserHandle.getCallingUserId(); 13039 List<ResolveInfo> list = queryIntentActivities(intent, null, 13040 PackageManager.GET_META_DATA, callingUserId); 13041 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13042 true, false, false, callingUserId); 13043 13044 allHomeCandidates.clear(); 13045 if (list != null) { 13046 for (ResolveInfo ri : list) { 13047 allHomeCandidates.add(ri); 13048 } 13049 } 13050 return (preferred == null || preferred.activityInfo == null) 13051 ? null 13052 : new ComponentName(preferred.activityInfo.packageName, 13053 preferred.activityInfo.name); 13054 } 13055 13056 @Override 13057 public void setApplicationEnabledSetting(String appPackageName, 13058 int newState, int flags, int userId, String callingPackage) { 13059 if (!sUserManager.exists(userId)) return; 13060 if (callingPackage == null) { 13061 callingPackage = Integer.toString(Binder.getCallingUid()); 13062 } 13063 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13064 } 13065 13066 @Override 13067 public void setComponentEnabledSetting(ComponentName componentName, 13068 int newState, int flags, int userId) { 13069 if (!sUserManager.exists(userId)) return; 13070 setEnabledSetting(componentName.getPackageName(), 13071 componentName.getClassName(), newState, flags, userId, null); 13072 } 13073 13074 private void setEnabledSetting(final String packageName, String className, int newState, 13075 final int flags, int userId, String callingPackage) { 13076 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13077 || newState == COMPONENT_ENABLED_STATE_ENABLED 13078 || newState == COMPONENT_ENABLED_STATE_DISABLED 13079 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13080 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13081 throw new IllegalArgumentException("Invalid new component state: " 13082 + newState); 13083 } 13084 PackageSetting pkgSetting; 13085 final int uid = Binder.getCallingUid(); 13086 final int permission = mContext.checkCallingOrSelfPermission( 13087 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13088 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13089 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13090 boolean sendNow = false; 13091 boolean isApp = (className == null); 13092 String componentName = isApp ? packageName : className; 13093 int packageUid = -1; 13094 ArrayList<String> components; 13095 13096 // writer 13097 synchronized (mPackages) { 13098 pkgSetting = mSettings.mPackages.get(packageName); 13099 if (pkgSetting == null) { 13100 if (className == null) { 13101 throw new IllegalArgumentException( 13102 "Unknown package: " + packageName); 13103 } 13104 throw new IllegalArgumentException( 13105 "Unknown component: " + packageName 13106 + "/" + className); 13107 } 13108 // Allow root and verify that userId is not being specified by a different user 13109 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13110 throw new SecurityException( 13111 "Permission Denial: attempt to change component state from pid=" 13112 + Binder.getCallingPid() 13113 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13114 } 13115 if (className == null) { 13116 // We're dealing with an application/package level state change 13117 if (pkgSetting.getEnabled(userId) == newState) { 13118 // Nothing to do 13119 return; 13120 } 13121 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13122 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13123 // Don't care about who enables an app. 13124 callingPackage = null; 13125 } 13126 pkgSetting.setEnabled(newState, userId, callingPackage); 13127 // pkgSetting.pkg.mSetEnabled = newState; 13128 } else { 13129 // We're dealing with a component level state change 13130 // First, verify that this is a valid class name. 13131 PackageParser.Package pkg = pkgSetting.pkg; 13132 if (pkg == null || !pkg.hasComponentClassName(className)) { 13133 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13134 throw new IllegalArgumentException("Component class " + className 13135 + " does not exist in " + packageName); 13136 } else { 13137 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13138 + className + " does not exist in " + packageName); 13139 } 13140 } 13141 switch (newState) { 13142 case COMPONENT_ENABLED_STATE_ENABLED: 13143 if (!pkgSetting.enableComponentLPw(className, userId)) { 13144 return; 13145 } 13146 break; 13147 case COMPONENT_ENABLED_STATE_DISABLED: 13148 if (!pkgSetting.disableComponentLPw(className, userId)) { 13149 return; 13150 } 13151 break; 13152 case COMPONENT_ENABLED_STATE_DEFAULT: 13153 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13154 return; 13155 } 13156 break; 13157 default: 13158 Slog.e(TAG, "Invalid new component state: " + newState); 13159 return; 13160 } 13161 } 13162 scheduleWritePackageRestrictionsLocked(userId); 13163 components = mPendingBroadcasts.get(userId, packageName); 13164 final boolean newPackage = components == null; 13165 if (newPackage) { 13166 components = new ArrayList<String>(); 13167 } 13168 if (!components.contains(componentName)) { 13169 components.add(componentName); 13170 } 13171 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13172 sendNow = true; 13173 // Purge entry from pending broadcast list if another one exists already 13174 // since we are sending one right away. 13175 mPendingBroadcasts.remove(userId, packageName); 13176 } else { 13177 if (newPackage) { 13178 mPendingBroadcasts.put(userId, packageName, components); 13179 } 13180 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13181 // Schedule a message 13182 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13183 } 13184 } 13185 } 13186 13187 long callingId = Binder.clearCallingIdentity(); 13188 try { 13189 if (sendNow) { 13190 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13191 sendPackageChangedBroadcast(packageName, 13192 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13193 } 13194 } finally { 13195 Binder.restoreCallingIdentity(callingId); 13196 } 13197 } 13198 13199 private void sendPackageChangedBroadcast(String packageName, 13200 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13201 if (DEBUG_INSTALL) 13202 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13203 + componentNames); 13204 Bundle extras = new Bundle(4); 13205 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13206 String nameList[] = new String[componentNames.size()]; 13207 componentNames.toArray(nameList); 13208 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13209 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13210 extras.putInt(Intent.EXTRA_UID, packageUid); 13211 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13212 new int[] {UserHandle.getUserId(packageUid)}); 13213 } 13214 13215 @Override 13216 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13217 if (!sUserManager.exists(userId)) return; 13218 final int uid = Binder.getCallingUid(); 13219 final int permission = mContext.checkCallingOrSelfPermission( 13220 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13221 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13222 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13223 // writer 13224 synchronized (mPackages) { 13225 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13226 allowedByPermission, uid, userId)) { 13227 scheduleWritePackageRestrictionsLocked(userId); 13228 } 13229 } 13230 } 13231 13232 @Override 13233 public String getInstallerPackageName(String packageName) { 13234 // reader 13235 synchronized (mPackages) { 13236 return mSettings.getInstallerPackageNameLPr(packageName); 13237 } 13238 } 13239 13240 @Override 13241 public int getApplicationEnabledSetting(String packageName, int userId) { 13242 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13243 int uid = Binder.getCallingUid(); 13244 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13245 // reader 13246 synchronized (mPackages) { 13247 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13248 } 13249 } 13250 13251 @Override 13252 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13253 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13254 int uid = Binder.getCallingUid(); 13255 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13256 // reader 13257 synchronized (mPackages) { 13258 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13259 } 13260 } 13261 13262 @Override 13263 public void enterSafeMode() { 13264 enforceSystemOrRoot("Only the system can request entering safe mode"); 13265 13266 if (!mSystemReady) { 13267 mSafeMode = true; 13268 } 13269 } 13270 13271 @Override 13272 public void systemReady() { 13273 mSystemReady = true; 13274 13275 // Read the compatibilty setting when the system is ready. 13276 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13277 mContext.getContentResolver(), 13278 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13279 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13280 if (DEBUG_SETTINGS) { 13281 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13282 } 13283 13284 synchronized (mPackages) { 13285 // Verify that all of the preferred activity components actually 13286 // exist. It is possible for applications to be updated and at 13287 // that point remove a previously declared activity component that 13288 // had been set as a preferred activity. We try to clean this up 13289 // the next time we encounter that preferred activity, but it is 13290 // possible for the user flow to never be able to return to that 13291 // situation so here we do a sanity check to make sure we haven't 13292 // left any junk around. 13293 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13294 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13295 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13296 removed.clear(); 13297 for (PreferredActivity pa : pir.filterSet()) { 13298 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13299 removed.add(pa); 13300 } 13301 } 13302 if (removed.size() > 0) { 13303 for (int r=0; r<removed.size(); r++) { 13304 PreferredActivity pa = removed.get(r); 13305 Slog.w(TAG, "Removing dangling preferred activity: " 13306 + pa.mPref.mComponent); 13307 pir.removeFilter(pa); 13308 } 13309 mSettings.writePackageRestrictionsLPr( 13310 mSettings.mPreferredActivities.keyAt(i)); 13311 } 13312 } 13313 } 13314 sUserManager.systemReady(); 13315 13316 // Kick off any messages waiting for system ready 13317 if (mPostSystemReadyMessages != null) { 13318 for (Message msg : mPostSystemReadyMessages) { 13319 msg.sendToTarget(); 13320 } 13321 mPostSystemReadyMessages = null; 13322 } 13323 13324 // Watch for external volumes that come and go over time 13325 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13326 storage.registerListener(mStorageListener); 13327 13328 mInstallerService.systemReady(); 13329 } 13330 13331 @Override 13332 public boolean isSafeMode() { 13333 return mSafeMode; 13334 } 13335 13336 @Override 13337 public boolean hasSystemUidErrors() { 13338 return mHasSystemUidErrors; 13339 } 13340 13341 static String arrayToString(int[] array) { 13342 StringBuffer buf = new StringBuffer(128); 13343 buf.append('['); 13344 if (array != null) { 13345 for (int i=0; i<array.length; i++) { 13346 if (i > 0) buf.append(", "); 13347 buf.append(array[i]); 13348 } 13349 } 13350 buf.append(']'); 13351 return buf.toString(); 13352 } 13353 13354 static class DumpState { 13355 public static final int DUMP_LIBS = 1 << 0; 13356 public static final int DUMP_FEATURES = 1 << 1; 13357 public static final int DUMP_RESOLVERS = 1 << 2; 13358 public static final int DUMP_PERMISSIONS = 1 << 3; 13359 public static final int DUMP_PACKAGES = 1 << 4; 13360 public static final int DUMP_SHARED_USERS = 1 << 5; 13361 public static final int DUMP_MESSAGES = 1 << 6; 13362 public static final int DUMP_PROVIDERS = 1 << 7; 13363 public static final int DUMP_VERIFIERS = 1 << 8; 13364 public static final int DUMP_PREFERRED = 1 << 9; 13365 public static final int DUMP_PREFERRED_XML = 1 << 10; 13366 public static final int DUMP_KEYSETS = 1 << 11; 13367 public static final int DUMP_VERSION = 1 << 12; 13368 public static final int DUMP_INSTALLS = 1 << 13; 13369 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13370 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13371 13372 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13373 13374 private int mTypes; 13375 13376 private int mOptions; 13377 13378 private boolean mTitlePrinted; 13379 13380 private SharedUserSetting mSharedUser; 13381 13382 public boolean isDumping(int type) { 13383 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13384 return true; 13385 } 13386 13387 return (mTypes & type) != 0; 13388 } 13389 13390 public void setDump(int type) { 13391 mTypes |= type; 13392 } 13393 13394 public boolean isOptionEnabled(int option) { 13395 return (mOptions & option) != 0; 13396 } 13397 13398 public void setOptionEnabled(int option) { 13399 mOptions |= option; 13400 } 13401 13402 public boolean onTitlePrinted() { 13403 final boolean printed = mTitlePrinted; 13404 mTitlePrinted = true; 13405 return printed; 13406 } 13407 13408 public boolean getTitlePrinted() { 13409 return mTitlePrinted; 13410 } 13411 13412 public void setTitlePrinted(boolean enabled) { 13413 mTitlePrinted = enabled; 13414 } 13415 13416 public SharedUserSetting getSharedUser() { 13417 return mSharedUser; 13418 } 13419 13420 public void setSharedUser(SharedUserSetting user) { 13421 mSharedUser = user; 13422 } 13423 } 13424 13425 @Override 13426 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13427 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13428 != PackageManager.PERMISSION_GRANTED) { 13429 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13430 + Binder.getCallingPid() 13431 + ", uid=" + Binder.getCallingUid() 13432 + " without permission " 13433 + android.Manifest.permission.DUMP); 13434 return; 13435 } 13436 13437 DumpState dumpState = new DumpState(); 13438 boolean fullPreferred = false; 13439 boolean checkin = false; 13440 13441 String packageName = null; 13442 13443 int opti = 0; 13444 while (opti < args.length) { 13445 String opt = args[opti]; 13446 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13447 break; 13448 } 13449 opti++; 13450 13451 if ("-a".equals(opt)) { 13452 // Right now we only know how to print all. 13453 } else if ("-h".equals(opt)) { 13454 pw.println("Package manager dump options:"); 13455 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13456 pw.println(" --checkin: dump for a checkin"); 13457 pw.println(" -f: print details of intent filters"); 13458 pw.println(" -h: print this help"); 13459 pw.println(" cmd may be one of:"); 13460 pw.println(" l[ibraries]: list known shared libraries"); 13461 pw.println(" f[ibraries]: list device features"); 13462 pw.println(" k[eysets]: print known keysets"); 13463 pw.println(" r[esolvers]: dump intent resolvers"); 13464 pw.println(" perm[issions]: dump permissions"); 13465 pw.println(" pref[erred]: print preferred package settings"); 13466 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13467 pw.println(" prov[iders]: dump content providers"); 13468 pw.println(" p[ackages]: dump installed packages"); 13469 pw.println(" s[hared-users]: dump shared user IDs"); 13470 pw.println(" m[essages]: print collected runtime messages"); 13471 pw.println(" v[erifiers]: print package verifier info"); 13472 pw.println(" version: print database version info"); 13473 pw.println(" write: write current settings now"); 13474 pw.println(" <package.name>: info about given package"); 13475 pw.println(" installs: details about install sessions"); 13476 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13477 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13478 return; 13479 } else if ("--checkin".equals(opt)) { 13480 checkin = true; 13481 } else if ("-f".equals(opt)) { 13482 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13483 } else { 13484 pw.println("Unknown argument: " + opt + "; use -h for help"); 13485 } 13486 } 13487 13488 // Is the caller requesting to dump a particular piece of data? 13489 if (opti < args.length) { 13490 String cmd = args[opti]; 13491 opti++; 13492 // Is this a package name? 13493 if ("android".equals(cmd) || cmd.contains(".")) { 13494 packageName = cmd; 13495 // When dumping a single package, we always dump all of its 13496 // filter information since the amount of data will be reasonable. 13497 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13498 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13499 dumpState.setDump(DumpState.DUMP_LIBS); 13500 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13501 dumpState.setDump(DumpState.DUMP_FEATURES); 13502 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13503 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13504 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13505 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13506 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13507 dumpState.setDump(DumpState.DUMP_PREFERRED); 13508 } else if ("preferred-xml".equals(cmd)) { 13509 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13510 if (opti < args.length && "--full".equals(args[opti])) { 13511 fullPreferred = true; 13512 opti++; 13513 } 13514 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13515 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13516 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13517 dumpState.setDump(DumpState.DUMP_PACKAGES); 13518 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13519 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13520 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13521 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13522 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13523 dumpState.setDump(DumpState.DUMP_MESSAGES); 13524 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13525 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13526 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13527 || "intent-filter-verifiers".equals(cmd)) { 13528 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13529 } else if ("version".equals(cmd)) { 13530 dumpState.setDump(DumpState.DUMP_VERSION); 13531 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13532 dumpState.setDump(DumpState.DUMP_KEYSETS); 13533 } else if ("installs".equals(cmd)) { 13534 dumpState.setDump(DumpState.DUMP_INSTALLS); 13535 } else if ("write".equals(cmd)) { 13536 synchronized (mPackages) { 13537 mSettings.writeLPr(); 13538 pw.println("Settings written."); 13539 return; 13540 } 13541 } 13542 } 13543 13544 if (checkin) { 13545 pw.println("vers,1"); 13546 } 13547 13548 // reader 13549 synchronized (mPackages) { 13550 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13551 if (!checkin) { 13552 if (dumpState.onTitlePrinted()) 13553 pw.println(); 13554 pw.println("Database versions:"); 13555 pw.print(" SDK Version:"); 13556 pw.print(" internal="); 13557 pw.print(mSettings.mInternalSdkPlatform); 13558 pw.print(" external="); 13559 pw.println(mSettings.mExternalSdkPlatform); 13560 pw.print(" DB Version:"); 13561 pw.print(" internal="); 13562 pw.print(mSettings.mInternalDatabaseVersion); 13563 pw.print(" external="); 13564 pw.println(mSettings.mExternalDatabaseVersion); 13565 } 13566 } 13567 13568 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13569 if (!checkin) { 13570 if (dumpState.onTitlePrinted()) 13571 pw.println(); 13572 pw.println("Verifiers:"); 13573 pw.print(" Required: "); 13574 pw.print(mRequiredVerifierPackage); 13575 pw.print(" (uid="); 13576 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13577 pw.println(")"); 13578 } else if (mRequiredVerifierPackage != null) { 13579 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13580 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13581 } 13582 } 13583 13584 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13585 packageName == null) { 13586 if (mIntentFilterVerifierComponent != null) { 13587 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13588 if (!checkin) { 13589 if (dumpState.onTitlePrinted()) 13590 pw.println(); 13591 pw.println("Intent Filter Verifier:"); 13592 pw.print(" Using: "); 13593 pw.print(verifierPackageName); 13594 pw.print(" (uid="); 13595 pw.print(getPackageUid(verifierPackageName, 0)); 13596 pw.println(")"); 13597 } else if (verifierPackageName != null) { 13598 pw.print("ifv,"); pw.print(verifierPackageName); 13599 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13600 } 13601 } else { 13602 pw.println(); 13603 pw.println("No Intent Filter Verifier available!"); 13604 } 13605 } 13606 13607 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13608 boolean printedHeader = false; 13609 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13610 while (it.hasNext()) { 13611 String name = it.next(); 13612 SharedLibraryEntry ent = mSharedLibraries.get(name); 13613 if (!checkin) { 13614 if (!printedHeader) { 13615 if (dumpState.onTitlePrinted()) 13616 pw.println(); 13617 pw.println("Libraries:"); 13618 printedHeader = true; 13619 } 13620 pw.print(" "); 13621 } else { 13622 pw.print("lib,"); 13623 } 13624 pw.print(name); 13625 if (!checkin) { 13626 pw.print(" -> "); 13627 } 13628 if (ent.path != null) { 13629 if (!checkin) { 13630 pw.print("(jar) "); 13631 pw.print(ent.path); 13632 } else { 13633 pw.print(",jar,"); 13634 pw.print(ent.path); 13635 } 13636 } else { 13637 if (!checkin) { 13638 pw.print("(apk) "); 13639 pw.print(ent.apk); 13640 } else { 13641 pw.print(",apk,"); 13642 pw.print(ent.apk); 13643 } 13644 } 13645 pw.println(); 13646 } 13647 } 13648 13649 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13650 if (dumpState.onTitlePrinted()) 13651 pw.println(); 13652 if (!checkin) { 13653 pw.println("Features:"); 13654 } 13655 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13656 while (it.hasNext()) { 13657 String name = it.next(); 13658 if (!checkin) { 13659 pw.print(" "); 13660 } else { 13661 pw.print("feat,"); 13662 } 13663 pw.println(name); 13664 } 13665 } 13666 13667 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13668 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13669 : "Activity Resolver Table:", " ", packageName, 13670 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13671 dumpState.setTitlePrinted(true); 13672 } 13673 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13674 : "Receiver Resolver Table:", " ", packageName, 13675 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13676 dumpState.setTitlePrinted(true); 13677 } 13678 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13679 : "Service Resolver Table:", " ", packageName, 13680 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13681 dumpState.setTitlePrinted(true); 13682 } 13683 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13684 : "Provider Resolver Table:", " ", packageName, 13685 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13686 dumpState.setTitlePrinted(true); 13687 } 13688 } 13689 13690 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13691 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13692 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13693 int user = mSettings.mPreferredActivities.keyAt(i); 13694 if (pir.dump(pw, 13695 dumpState.getTitlePrinted() 13696 ? "\nPreferred Activities User " + user + ":" 13697 : "Preferred Activities User " + user + ":", " ", 13698 packageName, true, false)) { 13699 dumpState.setTitlePrinted(true); 13700 } 13701 } 13702 } 13703 13704 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13705 pw.flush(); 13706 FileOutputStream fout = new FileOutputStream(fd); 13707 BufferedOutputStream str = new BufferedOutputStream(fout); 13708 XmlSerializer serializer = new FastXmlSerializer(); 13709 try { 13710 serializer.setOutput(str, "utf-8"); 13711 serializer.startDocument(null, true); 13712 serializer.setFeature( 13713 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13714 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13715 serializer.endDocument(); 13716 serializer.flush(); 13717 } catch (IllegalArgumentException e) { 13718 pw.println("Failed writing: " + e); 13719 } catch (IllegalStateException e) { 13720 pw.println("Failed writing: " + e); 13721 } catch (IOException e) { 13722 pw.println("Failed writing: " + e); 13723 } 13724 } 13725 13726 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13727 pw.println(); 13728 int count = mSettings.mPackages.size(); 13729 if (count == 0) { 13730 pw.println("No domain preferred apps!"); 13731 pw.println(); 13732 } else { 13733 final String prefix = " "; 13734 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13735 if (allPackageSettings.size() == 0) { 13736 pw.println("No domain preferred apps!"); 13737 pw.println(); 13738 } else { 13739 pw.println("Domain preferred apps status:"); 13740 pw.println(); 13741 count = 0; 13742 for (PackageSetting ps : allPackageSettings) { 13743 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13744 if (ivi == null || ivi.getPackageName() == null) continue; 13745 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13746 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13747 pw.println(prefix + "Status: " + ivi.getStatusString()); 13748 pw.println(); 13749 count++; 13750 } 13751 if (count == 0) { 13752 pw.println(prefix + "No domain preferred app status!"); 13753 pw.println(); 13754 } 13755 for (int userId : sUserManager.getUserIds()) { 13756 pw.println("Domain preferred apps for User " + userId + ":"); 13757 pw.println(); 13758 count = 0; 13759 for (PackageSetting ps : allPackageSettings) { 13760 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13761 if (ivi == null || ivi.getPackageName() == null) { 13762 continue; 13763 } 13764 final int status = ps.getDomainVerificationStatusForUser(userId); 13765 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13766 continue; 13767 } 13768 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13769 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13770 String statusStr = IntentFilterVerificationInfo. 13771 getStatusStringFromValue(status); 13772 pw.println(prefix + "Status: " + statusStr); 13773 pw.println(); 13774 count++; 13775 } 13776 if (count == 0) { 13777 pw.println(prefix + "No domain preferred apps!"); 13778 pw.println(); 13779 } 13780 } 13781 } 13782 } 13783 } 13784 13785 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13786 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13787 if (packageName == null) { 13788 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13789 if (iperm == 0) { 13790 if (dumpState.onTitlePrinted()) 13791 pw.println(); 13792 pw.println("AppOp Permissions:"); 13793 } 13794 pw.print(" AppOp Permission "); 13795 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13796 pw.println(":"); 13797 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13798 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13799 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13800 } 13801 } 13802 } 13803 } 13804 13805 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13806 boolean printedSomething = false; 13807 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13808 if (packageName != null && !packageName.equals(p.info.packageName)) { 13809 continue; 13810 } 13811 if (!printedSomething) { 13812 if (dumpState.onTitlePrinted()) 13813 pw.println(); 13814 pw.println("Registered ContentProviders:"); 13815 printedSomething = true; 13816 } 13817 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13818 pw.print(" "); pw.println(p.toString()); 13819 } 13820 printedSomething = false; 13821 for (Map.Entry<String, PackageParser.Provider> entry : 13822 mProvidersByAuthority.entrySet()) { 13823 PackageParser.Provider p = entry.getValue(); 13824 if (packageName != null && !packageName.equals(p.info.packageName)) { 13825 continue; 13826 } 13827 if (!printedSomething) { 13828 if (dumpState.onTitlePrinted()) 13829 pw.println(); 13830 pw.println("ContentProvider Authorities:"); 13831 printedSomething = true; 13832 } 13833 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13834 pw.print(" "); pw.println(p.toString()); 13835 if (p.info != null && p.info.applicationInfo != null) { 13836 final String appInfo = p.info.applicationInfo.toString(); 13837 pw.print(" applicationInfo="); pw.println(appInfo); 13838 } 13839 } 13840 } 13841 13842 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13843 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13844 } 13845 13846 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13847 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13848 } 13849 13850 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13851 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13852 } 13853 13854 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13855 // XXX should handle packageName != null by dumping only install data that 13856 // the given package is involved with. 13857 if (dumpState.onTitlePrinted()) pw.println(); 13858 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13859 } 13860 13861 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13862 if (dumpState.onTitlePrinted()) pw.println(); 13863 mSettings.dumpReadMessagesLPr(pw, dumpState); 13864 13865 pw.println(); 13866 pw.println("Package warning messages:"); 13867 BufferedReader in = null; 13868 String line = null; 13869 try { 13870 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13871 while ((line = in.readLine()) != null) { 13872 if (line.contains("ignored: updated version")) continue; 13873 pw.println(line); 13874 } 13875 } catch (IOException ignored) { 13876 } finally { 13877 IoUtils.closeQuietly(in); 13878 } 13879 } 13880 13881 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13882 BufferedReader in = null; 13883 String line = null; 13884 try { 13885 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13886 while ((line = in.readLine()) != null) { 13887 if (line.contains("ignored: updated version")) continue; 13888 pw.print("msg,"); 13889 pw.println(line); 13890 } 13891 } catch (IOException ignored) { 13892 } finally { 13893 IoUtils.closeQuietly(in); 13894 } 13895 } 13896 } 13897 } 13898 13899 // ------- apps on sdcard specific code ------- 13900 static final boolean DEBUG_SD_INSTALL = false; 13901 13902 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13903 13904 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13905 13906 private boolean mMediaMounted = false; 13907 13908 static String getEncryptKey() { 13909 try { 13910 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13911 SD_ENCRYPTION_KEYSTORE_NAME); 13912 if (sdEncKey == null) { 13913 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13914 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13915 if (sdEncKey == null) { 13916 Slog.e(TAG, "Failed to create encryption keys"); 13917 return null; 13918 } 13919 } 13920 return sdEncKey; 13921 } catch (NoSuchAlgorithmException nsae) { 13922 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13923 return null; 13924 } catch (IOException ioe) { 13925 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13926 return null; 13927 } 13928 } 13929 13930 /* 13931 * Update media status on PackageManager. 13932 */ 13933 @Override 13934 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13935 int callingUid = Binder.getCallingUid(); 13936 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13937 throw new SecurityException("Media status can only be updated by the system"); 13938 } 13939 // reader; this apparently protects mMediaMounted, but should probably 13940 // be a different lock in that case. 13941 synchronized (mPackages) { 13942 Log.i(TAG, "Updating external media status from " 13943 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13944 + (mediaStatus ? "mounted" : "unmounted")); 13945 if (DEBUG_SD_INSTALL) 13946 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13947 + ", mMediaMounted=" + mMediaMounted); 13948 if (mediaStatus == mMediaMounted) { 13949 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13950 : 0, -1); 13951 mHandler.sendMessage(msg); 13952 return; 13953 } 13954 mMediaMounted = mediaStatus; 13955 } 13956 // Queue up an async operation since the package installation may take a 13957 // little while. 13958 mHandler.post(new Runnable() { 13959 public void run() { 13960 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13961 } 13962 }); 13963 } 13964 13965 /** 13966 * Called by MountService when the initial ASECs to scan are available. 13967 * Should block until all the ASEC containers are finished being scanned. 13968 */ 13969 public void scanAvailableAsecs() { 13970 updateExternalMediaStatusInner(true, false, false); 13971 if (mShouldRestoreconData) { 13972 SELinuxMMAC.setRestoreconDone(); 13973 mShouldRestoreconData = false; 13974 } 13975 } 13976 13977 /* 13978 * Collect information of applications on external media, map them against 13979 * existing containers and update information based on current mount status. 13980 * Please note that we always have to report status if reportStatus has been 13981 * set to true especially when unloading packages. 13982 */ 13983 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13984 boolean externalStorage) { 13985 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13986 int[] uidArr = EmptyArray.INT; 13987 13988 final String[] list = PackageHelper.getSecureContainerList(); 13989 if (ArrayUtils.isEmpty(list)) { 13990 Log.i(TAG, "No secure containers found"); 13991 } else { 13992 // Process list of secure containers and categorize them 13993 // as active or stale based on their package internal state. 13994 13995 // reader 13996 synchronized (mPackages) { 13997 for (String cid : list) { 13998 // Leave stages untouched for now; installer service owns them 13999 if (PackageInstallerService.isStageName(cid)) continue; 14000 14001 if (DEBUG_SD_INSTALL) 14002 Log.i(TAG, "Processing container " + cid); 14003 String pkgName = getAsecPackageName(cid); 14004 if (pkgName == null) { 14005 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14006 continue; 14007 } 14008 if (DEBUG_SD_INSTALL) 14009 Log.i(TAG, "Looking for pkg : " + pkgName); 14010 14011 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14012 if (ps == null) { 14013 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14014 continue; 14015 } 14016 14017 /* 14018 * Skip packages that are not external if we're unmounting 14019 * external storage. 14020 */ 14021 if (externalStorage && !isMounted && !isExternal(ps)) { 14022 continue; 14023 } 14024 14025 final AsecInstallArgs args = new AsecInstallArgs(cid, 14026 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14027 // The package status is changed only if the code path 14028 // matches between settings and the container id. 14029 if (ps.codePathString != null 14030 && ps.codePathString.startsWith(args.getCodePath())) { 14031 if (DEBUG_SD_INSTALL) { 14032 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14033 + " at code path: " + ps.codePathString); 14034 } 14035 14036 // We do have a valid package installed on sdcard 14037 processCids.put(args, ps.codePathString); 14038 final int uid = ps.appId; 14039 if (uid != -1) { 14040 uidArr = ArrayUtils.appendInt(uidArr, uid); 14041 } 14042 } else { 14043 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14044 + ps.codePathString); 14045 } 14046 } 14047 } 14048 14049 Arrays.sort(uidArr); 14050 } 14051 14052 // Process packages with valid entries. 14053 if (isMounted) { 14054 if (DEBUG_SD_INSTALL) 14055 Log.i(TAG, "Loading packages"); 14056 loadMediaPackages(processCids, uidArr); 14057 startCleaningPackages(); 14058 mInstallerService.onSecureContainersAvailable(); 14059 } else { 14060 if (DEBUG_SD_INSTALL) 14061 Log.i(TAG, "Unloading packages"); 14062 unloadMediaPackages(processCids, uidArr, reportStatus); 14063 } 14064 } 14065 14066 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14067 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14068 final int size = infos.size(); 14069 final String[] packageNames = new String[size]; 14070 final int[] packageUids = new int[size]; 14071 for (int i = 0; i < size; i++) { 14072 final ApplicationInfo info = infos.get(i); 14073 packageNames[i] = info.packageName; 14074 packageUids[i] = info.uid; 14075 } 14076 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14077 finishedReceiver); 14078 } 14079 14080 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14081 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14082 sendResourcesChangedBroadcast(mediaStatus, replacing, 14083 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14084 } 14085 14086 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14087 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14088 int size = pkgList.length; 14089 if (size > 0) { 14090 // Send broadcasts here 14091 Bundle extras = new Bundle(); 14092 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14093 if (uidArr != null) { 14094 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14095 } 14096 if (replacing) { 14097 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14098 } 14099 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14100 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14101 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14102 } 14103 } 14104 14105 /* 14106 * Look at potentially valid container ids from processCids If package 14107 * information doesn't match the one on record or package scanning fails, 14108 * the cid is added to list of removeCids. We currently don't delete stale 14109 * containers. 14110 */ 14111 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14112 ArrayList<String> pkgList = new ArrayList<String>(); 14113 Set<AsecInstallArgs> keys = processCids.keySet(); 14114 14115 for (AsecInstallArgs args : keys) { 14116 String codePath = processCids.get(args); 14117 if (DEBUG_SD_INSTALL) 14118 Log.i(TAG, "Loading container : " + args.cid); 14119 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14120 try { 14121 // Make sure there are no container errors first. 14122 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14123 Slog.e(TAG, "Failed to mount cid : " + args.cid 14124 + " when installing from sdcard"); 14125 continue; 14126 } 14127 // Check code path here. 14128 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14129 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14130 + " does not match one in settings " + codePath); 14131 continue; 14132 } 14133 // Parse package 14134 int parseFlags = mDefParseFlags; 14135 if (args.isExternalAsec()) { 14136 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14137 } 14138 if (args.isFwdLocked()) { 14139 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14140 } 14141 14142 synchronized (mInstallLock) { 14143 PackageParser.Package pkg = null; 14144 try { 14145 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14146 } catch (PackageManagerException e) { 14147 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14148 } 14149 // Scan the package 14150 if (pkg != null) { 14151 /* 14152 * TODO why is the lock being held? doPostInstall is 14153 * called in other places without the lock. This needs 14154 * to be straightened out. 14155 */ 14156 // writer 14157 synchronized (mPackages) { 14158 retCode = PackageManager.INSTALL_SUCCEEDED; 14159 pkgList.add(pkg.packageName); 14160 // Post process args 14161 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14162 pkg.applicationInfo.uid); 14163 } 14164 } else { 14165 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14166 } 14167 } 14168 14169 } finally { 14170 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14171 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14172 } 14173 } 14174 } 14175 // writer 14176 synchronized (mPackages) { 14177 // If the platform SDK has changed since the last time we booted, 14178 // we need to re-grant app permission to catch any new ones that 14179 // appear. This is really a hack, and means that apps can in some 14180 // cases get permissions that the user didn't initially explicitly 14181 // allow... it would be nice to have some better way to handle 14182 // this situation. 14183 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14184 if (regrantPermissions) 14185 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14186 + mSdkVersion + "; regranting permissions for external storage"); 14187 mSettings.mExternalSdkPlatform = mSdkVersion; 14188 14189 // Make sure group IDs have been assigned, and any permission 14190 // changes in other apps are accounted for 14191 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14192 | (regrantPermissions 14193 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14194 : 0)); 14195 14196 mSettings.updateExternalDatabaseVersion(); 14197 14198 // can downgrade to reader 14199 // Persist settings 14200 mSettings.writeLPr(); 14201 } 14202 // Send a broadcast to let everyone know we are done processing 14203 if (pkgList.size() > 0) { 14204 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14205 } 14206 } 14207 14208 /* 14209 * Utility method to unload a list of specified containers 14210 */ 14211 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14212 // Just unmount all valid containers. 14213 for (AsecInstallArgs arg : cidArgs) { 14214 synchronized (mInstallLock) { 14215 arg.doPostDeleteLI(false); 14216 } 14217 } 14218 } 14219 14220 /* 14221 * Unload packages mounted on external media. This involves deleting package 14222 * data from internal structures, sending broadcasts about diabled packages, 14223 * gc'ing to free up references, unmounting all secure containers 14224 * corresponding to packages on external media, and posting a 14225 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14226 * that we always have to post this message if status has been requested no 14227 * matter what. 14228 */ 14229 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14230 final boolean reportStatus) { 14231 if (DEBUG_SD_INSTALL) 14232 Log.i(TAG, "unloading media packages"); 14233 ArrayList<String> pkgList = new ArrayList<String>(); 14234 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14235 final Set<AsecInstallArgs> keys = processCids.keySet(); 14236 for (AsecInstallArgs args : keys) { 14237 String pkgName = args.getPackageName(); 14238 if (DEBUG_SD_INSTALL) 14239 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14240 // Delete package internally 14241 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14242 synchronized (mInstallLock) { 14243 boolean res = deletePackageLI(pkgName, null, false, null, null, 14244 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14245 if (res) { 14246 pkgList.add(pkgName); 14247 } else { 14248 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14249 failedList.add(args); 14250 } 14251 } 14252 } 14253 14254 // reader 14255 synchronized (mPackages) { 14256 // We didn't update the settings after removing each package; 14257 // write them now for all packages. 14258 mSettings.writeLPr(); 14259 } 14260 14261 // We have to absolutely send UPDATED_MEDIA_STATUS only 14262 // after confirming that all the receivers processed the ordered 14263 // broadcast when packages get disabled, force a gc to clean things up. 14264 // and unload all the containers. 14265 if (pkgList.size() > 0) { 14266 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14267 new IIntentReceiver.Stub() { 14268 public void performReceive(Intent intent, int resultCode, String data, 14269 Bundle extras, boolean ordered, boolean sticky, 14270 int sendingUser) throws RemoteException { 14271 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14272 reportStatus ? 1 : 0, 1, keys); 14273 mHandler.sendMessage(msg); 14274 } 14275 }); 14276 } else { 14277 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14278 keys); 14279 mHandler.sendMessage(msg); 14280 } 14281 } 14282 14283 private void loadPrivatePackages(VolumeInfo vol) { 14284 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14285 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14286 synchronized (mInstallLock) { 14287 synchronized (mPackages) { 14288 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14289 for (PackageSetting ps : packages) { 14290 final PackageParser.Package pkg; 14291 try { 14292 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14293 loaded.add(pkg.applicationInfo); 14294 } catch (PackageManagerException e) { 14295 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14296 } 14297 } 14298 14299 // TODO: regrant any permissions that changed based since original install 14300 14301 mSettings.writeLPr(); 14302 } 14303 } 14304 14305 Slog.d(TAG, "Loaded packages " + loaded); 14306 sendResourcesChangedBroadcast(true, false, loaded, null); 14307 } 14308 14309 private void unloadPrivatePackages(VolumeInfo vol) { 14310 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14311 synchronized (mInstallLock) { 14312 synchronized (mPackages) { 14313 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14314 for (PackageSetting ps : packages) { 14315 if (ps.pkg == null) continue; 14316 14317 final ApplicationInfo info = ps.pkg.applicationInfo; 14318 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14319 if (deletePackageLI(ps.name, null, false, null, null, 14320 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14321 unloaded.add(info); 14322 } else { 14323 Slog.w(TAG, "Failed to unload " + ps.codePath); 14324 } 14325 } 14326 14327 mSettings.writeLPr(); 14328 } 14329 } 14330 14331 Slog.d(TAG, "Unloaded packages " + unloaded); 14332 sendResourcesChangedBroadcast(false, false, unloaded, null); 14333 } 14334 14335 private void unfreezePackage(String packageName) { 14336 synchronized (mPackages) { 14337 final PackageSetting ps = mSettings.mPackages.get(packageName); 14338 if (ps != null) { 14339 ps.frozen = false; 14340 } 14341 } 14342 } 14343 14344 @Override 14345 public int movePackage(final String packageName, final String volumeUuid) { 14346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14347 14348 final int moveId = mNextMoveId.getAndIncrement(); 14349 try { 14350 movePackageInternal(packageName, volumeUuid, moveId); 14351 } catch (PackageManagerException e) { 14352 Slog.d(TAG, "Failed to move " + packageName, e); 14353 mMoveCallbacks.notifyStatusChanged(moveId, 14354 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14355 } 14356 return moveId; 14357 } 14358 14359 private void movePackageInternal(final String packageName, final String volumeUuid, 14360 final int moveId) throws PackageManagerException { 14361 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14362 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14363 final PackageManager pm = mContext.getPackageManager(); 14364 14365 final boolean currentAsec; 14366 final String currentVolumeUuid; 14367 final File codeFile; 14368 final String installerPackageName; 14369 final String packageAbiOverride; 14370 final int appId; 14371 final String seinfo; 14372 final String label; 14373 14374 // reader 14375 synchronized (mPackages) { 14376 final PackageParser.Package pkg = mPackages.get(packageName); 14377 final PackageSetting ps = mSettings.mPackages.get(packageName); 14378 if (pkg == null || ps == null) { 14379 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14380 } 14381 14382 if (pkg.applicationInfo.isSystemApp()) { 14383 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14384 "Cannot move system application"); 14385 } 14386 14387 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14388 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14389 "Package already moved to " + volumeUuid); 14390 } 14391 14392 final File probe = new File(pkg.codePath); 14393 final File probeOat = new File(probe, "oat"); 14394 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14395 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14396 "Move only supported for modern cluster style installs"); 14397 } 14398 14399 if (ps.frozen) { 14400 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14401 "Failed to move already frozen package"); 14402 } 14403 ps.frozen = true; 14404 14405 currentAsec = pkg.applicationInfo.isForwardLocked() 14406 || pkg.applicationInfo.isExternalAsec(); 14407 currentVolumeUuid = ps.volumeUuid; 14408 codeFile = new File(pkg.codePath); 14409 installerPackageName = ps.installerPackageName; 14410 packageAbiOverride = ps.cpuAbiOverrideString; 14411 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14412 seinfo = pkg.applicationInfo.seinfo; 14413 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14414 } 14415 14416 // Now that we're guarded by frozen state, kill app during move 14417 killApplication(packageName, appId, "move pkg"); 14418 14419 final Bundle extras = new Bundle(); 14420 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14421 extras.putString(Intent.EXTRA_TITLE, label); 14422 mMoveCallbacks.notifyCreated(moveId, extras); 14423 14424 int installFlags; 14425 final boolean moveCompleteApp; 14426 final File measurePath; 14427 14428 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14429 installFlags = INSTALL_INTERNAL; 14430 moveCompleteApp = !currentAsec; 14431 measurePath = Environment.getDataAppDirectory(volumeUuid); 14432 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14433 installFlags = INSTALL_EXTERNAL; 14434 moveCompleteApp = false; 14435 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14436 } else { 14437 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14438 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14439 || !volume.isMountedWritable()) { 14440 unfreezePackage(packageName); 14441 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14442 "Move location not mounted private volume"); 14443 } 14444 14445 Preconditions.checkState(!currentAsec); 14446 14447 installFlags = INSTALL_INTERNAL; 14448 moveCompleteApp = true; 14449 measurePath = Environment.getDataAppDirectory(volumeUuid); 14450 } 14451 14452 final PackageStats stats = new PackageStats(null, -1); 14453 synchronized (mInstaller) { 14454 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14455 unfreezePackage(packageName); 14456 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14457 "Failed to measure package size"); 14458 } 14459 } 14460 14461 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14462 14463 final long startFreeBytes = measurePath.getFreeSpace(); 14464 final long sizeBytes; 14465 if (moveCompleteApp) { 14466 sizeBytes = stats.codeSize + stats.dataSize; 14467 } else { 14468 sizeBytes = stats.codeSize; 14469 } 14470 14471 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14472 unfreezePackage(packageName); 14473 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14474 "Not enough free space to move"); 14475 } 14476 14477 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14478 14479 final CountDownLatch installedLatch = new CountDownLatch(1); 14480 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14481 @Override 14482 public void onUserActionRequired(Intent intent) throws RemoteException { 14483 throw new IllegalStateException(); 14484 } 14485 14486 @Override 14487 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14488 Bundle extras) throws RemoteException { 14489 Slog.d(TAG, "Install result for move: " 14490 + PackageManager.installStatusToString(returnCode, msg)); 14491 14492 installedLatch.countDown(); 14493 14494 // Regardless of success or failure of the move operation, 14495 // always unfreeze the package 14496 unfreezePackage(packageName); 14497 14498 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14499 switch (status) { 14500 case PackageInstaller.STATUS_SUCCESS: 14501 mMoveCallbacks.notifyStatusChanged(moveId, 14502 PackageManager.MOVE_SUCCEEDED); 14503 break; 14504 case PackageInstaller.STATUS_FAILURE_STORAGE: 14505 mMoveCallbacks.notifyStatusChanged(moveId, 14506 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14507 break; 14508 default: 14509 mMoveCallbacks.notifyStatusChanged(moveId, 14510 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14511 break; 14512 } 14513 } 14514 }; 14515 14516 final MoveInfo move; 14517 if (moveCompleteApp) { 14518 // Kick off a thread to report progress estimates 14519 new Thread() { 14520 @Override 14521 public void run() { 14522 while (true) { 14523 try { 14524 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14525 break; 14526 } 14527 } catch (InterruptedException ignored) { 14528 } 14529 14530 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14531 final int progress = 10 + (int) MathUtils.constrain( 14532 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14533 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14534 } 14535 } 14536 }.start(); 14537 14538 final String dataAppName = codeFile.getName(); 14539 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14540 dataAppName, appId, seinfo); 14541 } else { 14542 move = null; 14543 } 14544 14545 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14546 14547 final Message msg = mHandler.obtainMessage(INIT_COPY); 14548 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14549 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14550 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14551 mHandler.sendMessage(msg); 14552 } 14553 14554 @Override 14555 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14557 14558 final int realMoveId = mNextMoveId.getAndIncrement(); 14559 final Bundle extras = new Bundle(); 14560 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14561 mMoveCallbacks.notifyCreated(realMoveId, extras); 14562 14563 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14564 @Override 14565 public void onCreated(int moveId, Bundle extras) { 14566 // Ignored 14567 } 14568 14569 @Override 14570 public void onStatusChanged(int moveId, int status, long estMillis) { 14571 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14572 } 14573 }; 14574 14575 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14576 storage.setPrimaryStorageUuid(volumeUuid, callback); 14577 return realMoveId; 14578 } 14579 14580 @Override 14581 public int getMoveStatus(int moveId) { 14582 mContext.enforceCallingOrSelfPermission( 14583 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14584 return mMoveCallbacks.mLastStatus.get(moveId); 14585 } 14586 14587 @Override 14588 public void registerMoveCallback(IPackageMoveObserver callback) { 14589 mContext.enforceCallingOrSelfPermission( 14590 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14591 mMoveCallbacks.register(callback); 14592 } 14593 14594 @Override 14595 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14596 mContext.enforceCallingOrSelfPermission( 14597 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14598 mMoveCallbacks.unregister(callback); 14599 } 14600 14601 @Override 14602 public boolean setInstallLocation(int loc) { 14603 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14604 null); 14605 if (getInstallLocation() == loc) { 14606 return true; 14607 } 14608 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14609 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14610 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14611 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14612 return true; 14613 } 14614 return false; 14615 } 14616 14617 @Override 14618 public int getInstallLocation() { 14619 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14620 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14621 PackageHelper.APP_INSTALL_AUTO); 14622 } 14623 14624 /** Called by UserManagerService */ 14625 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14626 mDirtyUsers.remove(userHandle); 14627 mSettings.removeUserLPw(userHandle); 14628 mPendingBroadcasts.remove(userHandle); 14629 if (mInstaller != null) { 14630 // Technically, we shouldn't be doing this with the package lock 14631 // held. However, this is very rare, and there is already so much 14632 // other disk I/O going on, that we'll let it slide for now. 14633 final StorageManager storage = StorageManager.from(mContext); 14634 final List<VolumeInfo> vols = storage.getVolumes(); 14635 for (VolumeInfo vol : vols) { 14636 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14637 final String volumeUuid = vol.getFsUuid(); 14638 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14639 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14640 } 14641 } 14642 } 14643 mUserNeedsBadging.delete(userHandle); 14644 removeUnusedPackagesLILPw(userManager, userHandle); 14645 } 14646 14647 /** 14648 * We're removing userHandle and would like to remove any downloaded packages 14649 * that are no longer in use by any other user. 14650 * @param userHandle the user being removed 14651 */ 14652 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14653 final boolean DEBUG_CLEAN_APKS = false; 14654 int [] users = userManager.getUserIdsLPr(); 14655 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14656 while (psit.hasNext()) { 14657 PackageSetting ps = psit.next(); 14658 if (ps.pkg == null) { 14659 continue; 14660 } 14661 final String packageName = ps.pkg.packageName; 14662 // Skip over if system app 14663 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14664 continue; 14665 } 14666 if (DEBUG_CLEAN_APKS) { 14667 Slog.i(TAG, "Checking package " + packageName); 14668 } 14669 boolean keep = false; 14670 for (int i = 0; i < users.length; i++) { 14671 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14672 keep = true; 14673 if (DEBUG_CLEAN_APKS) { 14674 Slog.i(TAG, " Keeping package " + packageName + " for user " 14675 + users[i]); 14676 } 14677 break; 14678 } 14679 } 14680 if (!keep) { 14681 if (DEBUG_CLEAN_APKS) { 14682 Slog.i(TAG, " Removing package " + packageName); 14683 } 14684 mHandler.post(new Runnable() { 14685 public void run() { 14686 deletePackageX(packageName, userHandle, 0); 14687 } //end run 14688 }); 14689 } 14690 } 14691 } 14692 14693 /** Called by UserManagerService */ 14694 void createNewUserLILPw(int userHandle, File path) { 14695 if (mInstaller != null) { 14696 mInstaller.createUserConfig(userHandle); 14697 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14698 } 14699 } 14700 14701 void newUserCreatedLILPw(int userHandle) { 14702 // Adding a user requires updating runtime permissions for system apps. 14703 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14704 } 14705 14706 @Override 14707 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14708 mContext.enforceCallingOrSelfPermission( 14709 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14710 "Only package verification agents can read the verifier device identity"); 14711 14712 synchronized (mPackages) { 14713 return mSettings.getVerifierDeviceIdentityLPw(); 14714 } 14715 } 14716 14717 @Override 14718 public void setPermissionEnforced(String permission, boolean enforced) { 14719 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14720 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14721 synchronized (mPackages) { 14722 if (mSettings.mReadExternalStorageEnforced == null 14723 || mSettings.mReadExternalStorageEnforced != enforced) { 14724 mSettings.mReadExternalStorageEnforced = enforced; 14725 mSettings.writeLPr(); 14726 } 14727 } 14728 // kill any non-foreground processes so we restart them and 14729 // grant/revoke the GID. 14730 final IActivityManager am = ActivityManagerNative.getDefault(); 14731 if (am != null) { 14732 final long token = Binder.clearCallingIdentity(); 14733 try { 14734 am.killProcessesBelowForeground("setPermissionEnforcement"); 14735 } catch (RemoteException e) { 14736 } finally { 14737 Binder.restoreCallingIdentity(token); 14738 } 14739 } 14740 } else { 14741 throw new IllegalArgumentException("No selective enforcement for " + permission); 14742 } 14743 } 14744 14745 @Override 14746 @Deprecated 14747 public boolean isPermissionEnforced(String permission) { 14748 return true; 14749 } 14750 14751 @Override 14752 public boolean isStorageLow() { 14753 final long token = Binder.clearCallingIdentity(); 14754 try { 14755 final DeviceStorageMonitorInternal 14756 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14757 if (dsm != null) { 14758 return dsm.isMemoryLow(); 14759 } else { 14760 return false; 14761 } 14762 } finally { 14763 Binder.restoreCallingIdentity(token); 14764 } 14765 } 14766 14767 @Override 14768 public IPackageInstaller getPackageInstaller() { 14769 return mInstallerService; 14770 } 14771 14772 private boolean userNeedsBadging(int userId) { 14773 int index = mUserNeedsBadging.indexOfKey(userId); 14774 if (index < 0) { 14775 final UserInfo userInfo; 14776 final long token = Binder.clearCallingIdentity(); 14777 try { 14778 userInfo = sUserManager.getUserInfo(userId); 14779 } finally { 14780 Binder.restoreCallingIdentity(token); 14781 } 14782 final boolean b; 14783 if (userInfo != null && userInfo.isManagedProfile()) { 14784 b = true; 14785 } else { 14786 b = false; 14787 } 14788 mUserNeedsBadging.put(userId, b); 14789 return b; 14790 } 14791 return mUserNeedsBadging.valueAt(index); 14792 } 14793 14794 @Override 14795 public KeySet getKeySetByAlias(String packageName, String alias) { 14796 if (packageName == null || alias == null) { 14797 return null; 14798 } 14799 synchronized(mPackages) { 14800 final PackageParser.Package pkg = mPackages.get(packageName); 14801 if (pkg == null) { 14802 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14803 throw new IllegalArgumentException("Unknown package: " + packageName); 14804 } 14805 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14806 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14807 } 14808 } 14809 14810 @Override 14811 public KeySet getSigningKeySet(String packageName) { 14812 if (packageName == null) { 14813 return null; 14814 } 14815 synchronized(mPackages) { 14816 final PackageParser.Package pkg = mPackages.get(packageName); 14817 if (pkg == null) { 14818 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14819 throw new IllegalArgumentException("Unknown package: " + packageName); 14820 } 14821 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14822 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14823 throw new SecurityException("May not access signing KeySet of other apps."); 14824 } 14825 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14826 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14827 } 14828 } 14829 14830 @Override 14831 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14832 if (packageName == null || ks == null) { 14833 return false; 14834 } 14835 synchronized(mPackages) { 14836 final PackageParser.Package pkg = mPackages.get(packageName); 14837 if (pkg == null) { 14838 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14839 throw new IllegalArgumentException("Unknown package: " + packageName); 14840 } 14841 IBinder ksh = ks.getToken(); 14842 if (ksh instanceof KeySetHandle) { 14843 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14844 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14845 } 14846 return false; 14847 } 14848 } 14849 14850 @Override 14851 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14852 if (packageName == null || ks == null) { 14853 return false; 14854 } 14855 synchronized(mPackages) { 14856 final PackageParser.Package pkg = mPackages.get(packageName); 14857 if (pkg == null) { 14858 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14859 throw new IllegalArgumentException("Unknown package: " + packageName); 14860 } 14861 IBinder ksh = ks.getToken(); 14862 if (ksh instanceof KeySetHandle) { 14863 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14864 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14865 } 14866 return false; 14867 } 14868 } 14869 14870 public void getUsageStatsIfNoPackageUsageInfo() { 14871 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14872 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14873 if (usm == null) { 14874 throw new IllegalStateException("UsageStatsManager must be initialized"); 14875 } 14876 long now = System.currentTimeMillis(); 14877 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14878 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14879 String packageName = entry.getKey(); 14880 PackageParser.Package pkg = mPackages.get(packageName); 14881 if (pkg == null) { 14882 continue; 14883 } 14884 UsageStats usage = entry.getValue(); 14885 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14886 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14887 } 14888 } 14889 } 14890 14891 /** 14892 * Check and throw if the given before/after packages would be considered a 14893 * downgrade. 14894 */ 14895 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14896 throws PackageManagerException { 14897 if (after.versionCode < before.mVersionCode) { 14898 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14899 "Update version code " + after.versionCode + " is older than current " 14900 + before.mVersionCode); 14901 } else if (after.versionCode == before.mVersionCode) { 14902 if (after.baseRevisionCode < before.baseRevisionCode) { 14903 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14904 "Update base revision code " + after.baseRevisionCode 14905 + " is older than current " + before.baseRevisionCode); 14906 } 14907 14908 if (!ArrayUtils.isEmpty(after.splitNames)) { 14909 for (int i = 0; i < after.splitNames.length; i++) { 14910 final String splitName = after.splitNames[i]; 14911 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14912 if (j != -1) { 14913 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14914 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14915 "Update split " + splitName + " revision code " 14916 + after.splitRevisionCodes[i] + " is older than current " 14917 + before.splitRevisionCodes[j]); 14918 } 14919 } 14920 } 14921 } 14922 } 14923 } 14924 14925 private static class MoveCallbacks extends Handler { 14926 private static final int MSG_CREATED = 1; 14927 private static final int MSG_STATUS_CHANGED = 2; 14928 14929 private final RemoteCallbackList<IPackageMoveObserver> 14930 mCallbacks = new RemoteCallbackList<>(); 14931 14932 private final SparseIntArray mLastStatus = new SparseIntArray(); 14933 14934 public MoveCallbacks(Looper looper) { 14935 super(looper); 14936 } 14937 14938 public void register(IPackageMoveObserver callback) { 14939 mCallbacks.register(callback); 14940 } 14941 14942 public void unregister(IPackageMoveObserver callback) { 14943 mCallbacks.unregister(callback); 14944 } 14945 14946 @Override 14947 public void handleMessage(Message msg) { 14948 final SomeArgs args = (SomeArgs) msg.obj; 14949 final int n = mCallbacks.beginBroadcast(); 14950 for (int i = 0; i < n; i++) { 14951 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14952 try { 14953 invokeCallback(callback, msg.what, args); 14954 } catch (RemoteException ignored) { 14955 } 14956 } 14957 mCallbacks.finishBroadcast(); 14958 args.recycle(); 14959 } 14960 14961 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14962 throws RemoteException { 14963 switch (what) { 14964 case MSG_CREATED: { 14965 callback.onCreated(args.argi1, (Bundle) args.arg2); 14966 break; 14967 } 14968 case MSG_STATUS_CHANGED: { 14969 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14970 break; 14971 } 14972 } 14973 } 14974 14975 private void notifyCreated(int moveId, Bundle extras) { 14976 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 14977 14978 final SomeArgs args = SomeArgs.obtain(); 14979 args.argi1 = moveId; 14980 args.arg2 = extras; 14981 obtainMessage(MSG_CREATED, args).sendToTarget(); 14982 } 14983 14984 private void notifyStatusChanged(int moveId, int status) { 14985 notifyStatusChanged(moveId, status, -1); 14986 } 14987 14988 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14989 Slog.v(TAG, "Move " + moveId + " status " + status); 14990 14991 final SomeArgs args = SomeArgs.obtain(); 14992 args.argi1 = moveId; 14993 args.argi2 = status; 14994 args.arg3 = estMillis; 14995 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14996 14997 synchronized (mLastStatus) { 14998 mLastStatus.put(moveId, status); 14999 } 15000 } 15001 } 15002} 15003