PackageManagerService.java revision bd0e9e4958acdc6ab5f607bc252fddba877d20f9
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 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 281 282 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 307 static final int REMOVE_CHATTY = 1<<16; 308 309 /** 310 * Timeout (in milliseconds) after which the watchdog should declare that 311 * our handler thread is wedged. The usual default for such things is one 312 * minute but we sometimes do very lengthy I/O operations on this thread, 313 * such as installing multi-gigabyte applications, so ours needs to be longer. 314 */ 315 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 316 317 /** 318 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 319 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 320 * settings entry if available, otherwise we use the hardcoded default. If it's been 321 * more than this long since the last fstrim, we force one during the boot sequence. 322 * 323 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 324 * one gets run at the next available charging+idle time. This final mandatory 325 * no-fstrim check kicks in only of the other scheduling criteria is never met. 326 */ 327 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 328 329 /** 330 * Whether verification is enabled by default. 331 */ 332 private static final boolean DEFAULT_VERIFY_ENABLE = true; 333 334 /** 335 * The default maximum time to wait for the verification agent to return in 336 * milliseconds. 337 */ 338 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 339 340 /** 341 * The default response for package verification timeout. 342 * 343 * This can be either PackageManager.VERIFICATION_ALLOW or 344 * PackageManager.VERIFICATION_REJECT. 345 */ 346 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 347 348 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 349 350 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 351 DEFAULT_CONTAINER_PACKAGE, 352 "com.android.defcontainer.DefaultContainerService"); 353 354 private static final String KILL_APP_REASON_GIDS_CHANGED = 355 "permission grant or revoke changed gids"; 356 357 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 358 "permissions revoked"; 359 360 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 361 362 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 363 364 /** Permission grant: not grant the permission. */ 365 private static final int GRANT_DENIED = 1; 366 367 /** Permission grant: grant the permission as an install permission. */ 368 private static final int GRANT_INSTALL = 2; 369 370 /** Permission grant: grant the permission as a runtime one. */ 371 private static final int GRANT_RUNTIME = 3; 372 373 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 374 private static final int GRANT_UPGRADE = 4; 375 376 final ServiceThread mHandlerThread; 377 378 final PackageHandler mHandler; 379 380 /** 381 * Messages for {@link #mHandler} that need to wait for system ready before 382 * being dispatched. 383 */ 384 private ArrayList<Message> mPostSystemReadyMessages; 385 386 final int mSdkVersion = Build.VERSION.SDK_INT; 387 388 final Context mContext; 389 final boolean mFactoryTest; 390 final boolean mOnlyCore; 391 final boolean mLazyDexOpt; 392 final long mDexOptLRUThresholdInMills; 393 final DisplayMetrics mMetrics; 394 final int mDefParseFlags; 395 final String[] mSeparateProcesses; 396 final boolean mIsUpgrade; 397 398 // This is where all application persistent data goes. 399 final File mAppDataDir; 400 401 // This is where all application persistent data goes for secondary users. 402 final File mUserAppDataDir; 403 404 /** The location for ASEC container files on internal storage. */ 405 final String mAsecInternalPath; 406 407 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 408 // LOCK HELD. Can be called with mInstallLock held. 409 final Installer mInstaller; 410 411 /** Directory where installed third-party apps stored */ 412 final File mAppInstallDir; 413 414 /** 415 * Directory to which applications installed internally have their 416 * 32 bit native libraries copied. 417 */ 418 private File mAppLib32InstallDir; 419 420 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 421 // apps. 422 final File mDrmAppPrivateInstallDir; 423 424 // ---------------------------------------------------------------- 425 426 // Lock for state used when installing and doing other long running 427 // operations. Methods that must be called with this lock held have 428 // the suffix "LI". 429 final Object mInstallLock = new Object(); 430 431 // ---------------------------------------------------------------- 432 433 // Keys are String (package name), values are Package. This also serves 434 // as the lock for the global state. Methods that must be called with 435 // this lock held have the prefix "LP". 436 final ArrayMap<String, PackageParser.Package> mPackages = 437 new ArrayMap<String, PackageParser.Package>(); 438 439 // Tracks available target package names -> overlay package paths. 440 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 441 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 442 443 final Settings mSettings; 444 boolean mRestoredSettings; 445 446 // System configuration read by SystemConfig. 447 final int[] mGlobalGids; 448 final SparseArray<ArraySet<String>> mSystemPermissions; 449 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 450 451 // If mac_permissions.xml was found for seinfo labeling. 452 boolean mFoundPolicyFile; 453 454 // If a recursive restorecon of /data/data/<pkg> is needed. 455 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 456 457 public static final class SharedLibraryEntry { 458 public final String path; 459 public final String apk; 460 461 SharedLibraryEntry(String _path, String _apk) { 462 path = _path; 463 apk = _apk; 464 } 465 } 466 467 // Currently known shared libraries. 468 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 469 new ArrayMap<String, SharedLibraryEntry>(); 470 471 // All available activities, for your resolving pleasure. 472 final ActivityIntentResolver mActivities = 473 new ActivityIntentResolver(); 474 475 // All available receivers, for your resolving pleasure. 476 final ActivityIntentResolver mReceivers = 477 new ActivityIntentResolver(); 478 479 // All available services, for your resolving pleasure. 480 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 481 482 // All available providers, for your resolving pleasure. 483 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 484 485 // Mapping from provider base names (first directory in content URI codePath) 486 // to the provider information. 487 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 488 new ArrayMap<String, PackageParser.Provider>(); 489 490 // Mapping from instrumentation class names to info about them. 491 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 492 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 493 494 // Mapping from permission names to info about them. 495 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 496 new ArrayMap<String, PackageParser.PermissionGroup>(); 497 498 // Packages whose data we have transfered into another package, thus 499 // should no longer exist. 500 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 501 502 // Broadcast actions that are only available to the system. 503 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 504 505 /** List of packages waiting for verification. */ 506 final SparseArray<PackageVerificationState> mPendingVerification 507 = new SparseArray<PackageVerificationState>(); 508 509 /** Set of packages associated with each app op permission. */ 510 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 511 512 final PackageInstallerService mInstallerService; 513 514 private final PackageDexOptimizer mPackageDexOptimizer; 515 516 private AtomicInteger mNextMoveId = new AtomicInteger(); 517 private final MoveCallbacks mMoveCallbacks; 518 519 // Cache of users who need badging. 520 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 521 522 /** Token for keys in mPendingVerification. */ 523 private int mPendingVerificationToken = 0; 524 525 volatile boolean mSystemReady; 526 volatile boolean mSafeMode; 527 volatile boolean mHasSystemUidErrors; 528 529 ApplicationInfo mAndroidApplication; 530 final ActivityInfo mResolveActivity = new ActivityInfo(); 531 final ResolveInfo mResolveInfo = new ResolveInfo(); 532 ComponentName mResolveComponentName; 533 PackageParser.Package mPlatformPackage; 534 ComponentName mCustomResolverComponentName; 535 536 boolean mResolverReplaced = false; 537 538 private final ComponentName mIntentFilterVerifierComponent; 539 private int mIntentFilterVerificationToken = 0; 540 541 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 542 = new SparseArray<IntentFilterVerificationState>(); 543 544 private interface IntentFilterVerifier<T extends IntentFilter> { 545 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 546 T filter, String packageName); 547 void startVerifications(int userId); 548 void receiveVerificationResponse(int verificationId); 549 } 550 551 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 552 private Context mContext; 553 private ComponentName mIntentFilterVerifierComponent; 554 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 555 556 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 557 mContext = context; 558 mIntentFilterVerifierComponent = verifierComponent; 559 } 560 561 private String getDefaultScheme() { 562 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 563 return IntentFilter.SCHEME_HTTP; 564 } 565 566 @Override 567 public void startVerifications(int userId) { 568 // Launch verifications requests 569 int count = mCurrentIntentFilterVerifications.size(); 570 for (int n=0; n<count; n++) { 571 int verificationId = mCurrentIntentFilterVerifications.get(n); 572 final IntentFilterVerificationState ivs = 573 mIntentFilterVerificationStates.get(verificationId); 574 575 String packageName = ivs.getPackageName(); 576 577 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 578 final int filterCount = filters.size(); 579 ArraySet<String> domainsSet = new ArraySet<>(); 580 for (int m=0; m<filterCount; m++) { 581 PackageParser.ActivityIntentInfo filter = filters.get(m); 582 domainsSet.addAll(filter.getHostsList()); 583 } 584 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 585 synchronized (mPackages) { 586 if (mSettings.createIntentFilterVerificationIfNeededLPw( 587 packageName, domainsList) != null) { 588 scheduleWriteSettingsLocked(); 589 } 590 } 591 sendVerificationRequest(userId, verificationId, ivs); 592 } 593 mCurrentIntentFilterVerifications.clear(); 594 } 595 596 private void sendVerificationRequest(int userId, int verificationId, 597 IntentFilterVerificationState ivs) { 598 599 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 602 verificationId); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 605 getDefaultScheme()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 608 ivs.getHostsString()); 609 verificationIntent.putExtra( 610 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 611 ivs.getPackageName()); 612 verificationIntent.setComponent(mIntentFilterVerifierComponent); 613 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 614 615 UserHandle user = new UserHandle(userId); 616 mContext.sendBroadcastAsUser(verificationIntent, user); 617 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 618 } 619 620 public void receiveVerificationResponse(int verificationId) { 621 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 622 623 final boolean verified = ivs.isVerified(); 624 625 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 626 final int count = filters.size(); 627 for (int n=0; n<count; n++) { 628 PackageParser.ActivityIntentInfo filter = filters.get(n); 629 filter.setVerified(verified); 630 631 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 632 + verified + " and hosts:" + ivs.getHostsString()); 633 } 634 635 mIntentFilterVerificationStates.remove(verificationId); 636 637 final String packageName = ivs.getPackageName(); 638 IntentFilterVerificationInfo ivi = null; 639 640 synchronized (mPackages) { 641 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 642 } 643 if (ivi == null) { 644 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 645 + verificationId + " packageName:" + packageName); 646 return; 647 } 648 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 649 + verificationId); 650 651 synchronized (mPackages) { 652 if (verified) { 653 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 654 } else { 655 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 656 } 657 scheduleWriteSettingsLocked(); 658 659 final int userId = ivs.getUserId(); 660 if (userId != UserHandle.USER_ALL) { 661 final int userStatus = 662 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 663 664 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 665 boolean needUpdate = false; 666 667 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 668 // already been set by the User thru the Disambiguation dialog 669 switch (userStatus) { 670 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 671 if (verified) { 672 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 673 } else { 674 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 675 } 676 needUpdate = true; 677 break; 678 679 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 680 if (verified) { 681 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 682 needUpdate = true; 683 } 684 break; 685 686 default: 687 // Nothing to do 688 } 689 690 if (needUpdate) { 691 mSettings.updateIntentFilterVerificationStatusLPw( 692 packageName, updatedStatus, userId); 693 scheduleWritePackageRestrictionsLocked(userId); 694 } 695 } 696 } 697 } 698 699 @Override 700 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 701 ActivityIntentInfo filter, String packageName) { 702 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 703 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 704 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 705 return false; 706 } 707 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 708 if (ivs == null) { 709 ivs = createDomainVerificationState(verifierId, userId, verificationId, 710 packageName); 711 } 712 if (!hasValidDomains(filter)) { 713 return false; 714 } 715 ivs.addFilter(filter); 716 return true; 717 } 718 719 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 720 int userId, int verificationId, String packageName) { 721 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 722 verifierId, userId, packageName); 723 ivs.setPendingState(); 724 synchronized (mPackages) { 725 mIntentFilterVerificationStates.append(verificationId, ivs); 726 mCurrentIntentFilterVerifications.add(verificationId); 727 } 728 return ivs; 729 } 730 } 731 732 private static boolean hasValidDomains(ActivityIntentInfo filter) { 733 return hasValidDomains(filter, true); 734 } 735 736 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 737 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 738 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 739 if (!hasHTTPorHTTPS) { 740 if (logging) { 741 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 742 } 743 return false; 744 } 745 return true; 746 } 747 748 private IntentFilterVerifier mIntentFilterVerifier; 749 750 // Set of pending broadcasts for aggregating enable/disable of components. 751 static class PendingPackageBroadcasts { 752 // for each user id, a map of <package name -> components within that package> 753 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 754 755 public PendingPackageBroadcasts() { 756 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 757 } 758 759 public ArrayList<String> get(int userId, String packageName) { 760 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 761 return packages.get(packageName); 762 } 763 764 public void put(int userId, String packageName, ArrayList<String> components) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 packages.put(packageName, components); 767 } 768 769 public void remove(int userId, String packageName) { 770 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 771 if (packages != null) { 772 packages.remove(packageName); 773 } 774 } 775 776 public void remove(int userId) { 777 mUidMap.remove(userId); 778 } 779 780 public int userIdCount() { 781 return mUidMap.size(); 782 } 783 784 public int userIdAt(int n) { 785 return mUidMap.keyAt(n); 786 } 787 788 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 789 return mUidMap.get(userId); 790 } 791 792 public int size() { 793 // total number of pending broadcast entries across all userIds 794 int num = 0; 795 for (int i = 0; i< mUidMap.size(); i++) { 796 num += mUidMap.valueAt(i).size(); 797 } 798 return num; 799 } 800 801 public void clear() { 802 mUidMap.clear(); 803 } 804 805 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 806 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 807 if (map == null) { 808 map = new ArrayMap<String, ArrayList<String>>(); 809 mUidMap.put(userId, map); 810 } 811 return map; 812 } 813 } 814 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 815 816 // Service Connection to remote media container service to copy 817 // package uri's from external media onto secure containers 818 // or internal storage. 819 private IMediaContainerService mContainerService = null; 820 821 static final int SEND_PENDING_BROADCAST = 1; 822 static final int MCS_BOUND = 3; 823 static final int END_COPY = 4; 824 static final int INIT_COPY = 5; 825 static final int MCS_UNBIND = 6; 826 static final int START_CLEANING_PACKAGE = 7; 827 static final int FIND_INSTALL_LOC = 8; 828 static final int POST_INSTALL = 9; 829 static final int MCS_RECONNECT = 10; 830 static final int MCS_GIVE_UP = 11; 831 static final int UPDATED_MEDIA_STATUS = 12; 832 static final int WRITE_SETTINGS = 13; 833 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 834 static final int PACKAGE_VERIFIED = 15; 835 static final int CHECK_PENDING_VERIFICATION = 16; 836 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 837 static final int INTENT_FILTER_VERIFIED = 18; 838 839 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 840 841 // Delay time in millisecs 842 static final int BROADCAST_DELAY = 10 * 1000; 843 844 static UserManagerService sUserManager; 845 846 // Stores a list of users whose package restrictions file needs to be updated 847 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 848 849 final private DefaultContainerConnection mDefContainerConn = 850 new DefaultContainerConnection(); 851 class DefaultContainerConnection implements ServiceConnection { 852 public void onServiceConnected(ComponentName name, IBinder service) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 854 IMediaContainerService imcs = 855 IMediaContainerService.Stub.asInterface(service); 856 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 857 } 858 859 public void onServiceDisconnected(ComponentName name) { 860 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 861 } 862 }; 863 864 // Recordkeeping of restore-after-install operations that are currently in flight 865 // between the Package Manager and the Backup Manager 866 class PostInstallData { 867 public InstallArgs args; 868 public PackageInstalledInfo res; 869 870 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 871 args = _a; 872 res = _r; 873 } 874 }; 875 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 876 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 877 878 // backup/restore of preferred activity state 879 private static final String TAG_PREFERRED_BACKUP = "pa"; 880 881 private final String mRequiredVerifierPackage; 882 883 private final PackageUsage mPackageUsage = new PackageUsage(); 884 885 private class PackageUsage { 886 private static final int WRITE_INTERVAL 887 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 888 889 private final Object mFileLock = new Object(); 890 private final AtomicLong mLastWritten = new AtomicLong(0); 891 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 892 893 private boolean mIsHistoricalPackageUsageAvailable = true; 894 895 boolean isHistoricalPackageUsageAvailable() { 896 return mIsHistoricalPackageUsageAvailable; 897 } 898 899 void write(boolean force) { 900 if (force) { 901 writeInternal(); 902 return; 903 } 904 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 905 && !DEBUG_DEXOPT) { 906 return; 907 } 908 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 909 new Thread("PackageUsage_DiskWriter") { 910 @Override 911 public void run() { 912 try { 913 writeInternal(); 914 } finally { 915 mBackgroundWriteRunning.set(false); 916 } 917 } 918 }.start(); 919 } 920 } 921 922 private void writeInternal() { 923 synchronized (mPackages) { 924 synchronized (mFileLock) { 925 AtomicFile file = getFile(); 926 FileOutputStream f = null; 927 try { 928 f = file.startWrite(); 929 BufferedOutputStream out = new BufferedOutputStream(f); 930 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 931 StringBuilder sb = new StringBuilder(); 932 for (PackageParser.Package pkg : mPackages.values()) { 933 if (pkg.mLastPackageUsageTimeInMills == 0) { 934 continue; 935 } 936 sb.setLength(0); 937 sb.append(pkg.packageName); 938 sb.append(' '); 939 sb.append((long)pkg.mLastPackageUsageTimeInMills); 940 sb.append('\n'); 941 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 942 } 943 out.flush(); 944 file.finishWrite(f); 945 } catch (IOException e) { 946 if (f != null) { 947 file.failWrite(f); 948 } 949 Log.e(TAG, "Failed to write package usage times", e); 950 } 951 } 952 } 953 mLastWritten.set(SystemClock.elapsedRealtime()); 954 } 955 956 void readLP() { 957 synchronized (mFileLock) { 958 AtomicFile file = getFile(); 959 BufferedInputStream in = null; 960 try { 961 in = new BufferedInputStream(file.openRead()); 962 StringBuffer sb = new StringBuffer(); 963 while (true) { 964 String packageName = readToken(in, sb, ' '); 965 if (packageName == null) { 966 break; 967 } 968 String timeInMillisString = readToken(in, sb, '\n'); 969 if (timeInMillisString == null) { 970 throw new IOException("Failed to find last usage time for package " 971 + packageName); 972 } 973 PackageParser.Package pkg = mPackages.get(packageName); 974 if (pkg == null) { 975 continue; 976 } 977 long timeInMillis; 978 try { 979 timeInMillis = Long.parseLong(timeInMillisString.toString()); 980 } catch (NumberFormatException e) { 981 throw new IOException("Failed to parse " + timeInMillisString 982 + " as a long.", e); 983 } 984 pkg.mLastPackageUsageTimeInMills = timeInMillis; 985 } 986 } catch (FileNotFoundException expected) { 987 mIsHistoricalPackageUsageAvailable = false; 988 } catch (IOException e) { 989 Log.w(TAG, "Failed to read package usage times", e); 990 } finally { 991 IoUtils.closeQuietly(in); 992 } 993 } 994 mLastWritten.set(SystemClock.elapsedRealtime()); 995 } 996 997 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 998 throws IOException { 999 sb.setLength(0); 1000 while (true) { 1001 int ch = in.read(); 1002 if (ch == -1) { 1003 if (sb.length() == 0) { 1004 return null; 1005 } 1006 throw new IOException("Unexpected EOF"); 1007 } 1008 if (ch == endOfToken) { 1009 return sb.toString(); 1010 } 1011 sb.append((char)ch); 1012 } 1013 } 1014 1015 private AtomicFile getFile() { 1016 File dataDir = Environment.getDataDirectory(); 1017 File systemDir = new File(dataDir, "system"); 1018 File fname = new File(systemDir, "package-usage.list"); 1019 return new AtomicFile(fname); 1020 } 1021 } 1022 1023 class PackageHandler extends Handler { 1024 private boolean mBound = false; 1025 final ArrayList<HandlerParams> mPendingInstalls = 1026 new ArrayList<HandlerParams>(); 1027 1028 private boolean connectToService() { 1029 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1030 " DefaultContainerService"); 1031 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1033 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1034 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1035 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1036 mBound = true; 1037 return true; 1038 } 1039 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1040 return false; 1041 } 1042 1043 private void disconnectService() { 1044 mContainerService = null; 1045 mBound = false; 1046 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1047 mContext.unbindService(mDefContainerConn); 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 } 1050 1051 PackageHandler(Looper looper) { 1052 super(looper); 1053 } 1054 1055 public void handleMessage(Message msg) { 1056 try { 1057 doHandleMessage(msg); 1058 } finally { 1059 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1060 } 1061 } 1062 1063 void doHandleMessage(Message msg) { 1064 switch (msg.what) { 1065 case INIT_COPY: { 1066 HandlerParams params = (HandlerParams) msg.obj; 1067 int idx = mPendingInstalls.size(); 1068 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1069 // If a bind was already initiated we dont really 1070 // need to do anything. The pending install 1071 // will be processed later on. 1072 if (!mBound) { 1073 // If this is the only one pending we might 1074 // have to bind to the service again. 1075 if (!connectToService()) { 1076 Slog.e(TAG, "Failed to bind to media container service"); 1077 params.serviceError(); 1078 return; 1079 } else { 1080 // Once we bind to the service, the first 1081 // pending request will be processed. 1082 mPendingInstalls.add(idx, params); 1083 } 1084 } else { 1085 mPendingInstalls.add(idx, params); 1086 // Already bound to the service. Just make 1087 // sure we trigger off processing the first request. 1088 if (idx == 0) { 1089 mHandler.sendEmptyMessage(MCS_BOUND); 1090 } 1091 } 1092 break; 1093 } 1094 case MCS_BOUND: { 1095 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1096 if (msg.obj != null) { 1097 mContainerService = (IMediaContainerService) msg.obj; 1098 } 1099 if (mContainerService == null) { 1100 // Something seriously wrong. Bail out 1101 Slog.e(TAG, "Cannot bind to media container service"); 1102 for (HandlerParams params : mPendingInstalls) { 1103 // Indicate service bind error 1104 params.serviceError(); 1105 } 1106 mPendingInstalls.clear(); 1107 } else if (mPendingInstalls.size() > 0) { 1108 HandlerParams params = mPendingInstalls.get(0); 1109 if (params != null) { 1110 if (params.startCopy()) { 1111 // We are done... look for more work or to 1112 // go idle. 1113 if (DEBUG_SD_INSTALL) Log.i(TAG, 1114 "Checking for more work or unbind..."); 1115 // Delete pending install 1116 if (mPendingInstalls.size() > 0) { 1117 mPendingInstalls.remove(0); 1118 } 1119 if (mPendingInstalls.size() == 0) { 1120 if (mBound) { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Posting delayed MCS_UNBIND"); 1123 removeMessages(MCS_UNBIND); 1124 Message ubmsg = obtainMessage(MCS_UNBIND); 1125 // Unbind after a little delay, to avoid 1126 // continual thrashing. 1127 sendMessageDelayed(ubmsg, 10000); 1128 } 1129 } else { 1130 // There are more pending requests in queue. 1131 // Just post MCS_BOUND message to trigger processing 1132 // of next pending install. 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, 1134 "Posting MCS_BOUND for next work"); 1135 mHandler.sendEmptyMessage(MCS_BOUND); 1136 } 1137 } 1138 } 1139 } else { 1140 // Should never happen ideally. 1141 Slog.w(TAG, "Empty queue"); 1142 } 1143 break; 1144 } 1145 case MCS_RECONNECT: { 1146 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1147 if (mPendingInstalls.size() > 0) { 1148 if (mBound) { 1149 disconnectService(); 1150 } 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 for (HandlerParams params : mPendingInstalls) { 1154 // Indicate service bind error 1155 params.serviceError(); 1156 } 1157 mPendingInstalls.clear(); 1158 } 1159 } 1160 break; 1161 } 1162 case MCS_UNBIND: { 1163 // If there is no actual work left, then time to unbind. 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1165 1166 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1167 if (mBound) { 1168 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1169 1170 disconnectService(); 1171 } 1172 } else if (mPendingInstalls.size() > 0) { 1173 // There are more pending requests in queue. 1174 // Just post MCS_BOUND message to trigger processing 1175 // of next pending install. 1176 mHandler.sendEmptyMessage(MCS_BOUND); 1177 } 1178 1179 break; 1180 } 1181 case MCS_GIVE_UP: { 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1183 mPendingInstalls.remove(0); 1184 break; 1185 } 1186 case SEND_PENDING_BROADCAST: { 1187 String packages[]; 1188 ArrayList<String> components[]; 1189 int size = 0; 1190 int uids[]; 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1192 synchronized (mPackages) { 1193 if (mPendingBroadcasts == null) { 1194 return; 1195 } 1196 size = mPendingBroadcasts.size(); 1197 if (size <= 0) { 1198 // Nothing to be done. Just return 1199 return; 1200 } 1201 packages = new String[size]; 1202 components = new ArrayList[size]; 1203 uids = new int[size]; 1204 int i = 0; // filling out the above arrays 1205 1206 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1207 int packageUserId = mPendingBroadcasts.userIdAt(n); 1208 Iterator<Map.Entry<String, ArrayList<String>>> it 1209 = mPendingBroadcasts.packagesForUserId(packageUserId) 1210 .entrySet().iterator(); 1211 while (it.hasNext() && i < size) { 1212 Map.Entry<String, ArrayList<String>> ent = it.next(); 1213 packages[i] = ent.getKey(); 1214 components[i] = ent.getValue(); 1215 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1216 uids[i] = (ps != null) 1217 ? UserHandle.getUid(packageUserId, ps.appId) 1218 : -1; 1219 i++; 1220 } 1221 } 1222 size = i; 1223 mPendingBroadcasts.clear(); 1224 } 1225 // Send broadcasts 1226 for (int i = 0; i < size; i++) { 1227 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1228 } 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1230 break; 1231 } 1232 case START_CLEANING_PACKAGE: { 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 final String packageName = (String)msg.obj; 1235 final int userId = msg.arg1; 1236 final boolean andCode = msg.arg2 != 0; 1237 synchronized (mPackages) { 1238 if (userId == UserHandle.USER_ALL) { 1239 int[] users = sUserManager.getUserIds(); 1240 for (int user : users) { 1241 mSettings.addPackageToCleanLPw( 1242 new PackageCleanItem(user, packageName, andCode)); 1243 } 1244 } else { 1245 mSettings.addPackageToCleanLPw( 1246 new PackageCleanItem(userId, packageName, andCode)); 1247 } 1248 } 1249 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1250 startCleaningPackages(); 1251 } break; 1252 case POST_INSTALL: { 1253 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1254 PostInstallData data = mRunningInstalls.get(msg.arg1); 1255 mRunningInstalls.delete(msg.arg1); 1256 boolean deleteOld = false; 1257 1258 if (data != null) { 1259 InstallArgs args = data.args; 1260 PackageInstalledInfo res = data.res; 1261 1262 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1263 res.removedInfo.sendBroadcast(false, true, false); 1264 Bundle extras = new Bundle(1); 1265 extras.putInt(Intent.EXTRA_UID, res.uid); 1266 1267 // Now that we successfully installed the package, grant runtime 1268 // permissions if requested before broadcasting the install. 1269 if ((args.installFlags 1270 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1271 grantRequestedRuntimePermissions(res.pkg, 1272 args.user.getIdentifier()); 1273 } 1274 1275 // Determine the set of users who are adding this 1276 // package for the first time vs. those who are seeing 1277 // an update. 1278 int[] firstUsers; 1279 int[] updateUsers = new int[0]; 1280 if (res.origUsers == null || res.origUsers.length == 0) { 1281 firstUsers = res.newUsers; 1282 } else { 1283 firstUsers = new int[0]; 1284 for (int i=0; i<res.newUsers.length; i++) { 1285 int user = res.newUsers[i]; 1286 boolean isNew = true; 1287 for (int j=0; j<res.origUsers.length; j++) { 1288 if (res.origUsers[j] == user) { 1289 isNew = false; 1290 break; 1291 } 1292 } 1293 if (isNew) { 1294 int[] newFirst = new int[firstUsers.length+1]; 1295 System.arraycopy(firstUsers, 0, newFirst, 0, 1296 firstUsers.length); 1297 newFirst[firstUsers.length] = user; 1298 firstUsers = newFirst; 1299 } else { 1300 int[] newUpdate = new int[updateUsers.length+1]; 1301 System.arraycopy(updateUsers, 0, newUpdate, 0, 1302 updateUsers.length); 1303 newUpdate[updateUsers.length] = user; 1304 updateUsers = newUpdate; 1305 } 1306 } 1307 } 1308 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1309 res.pkg.applicationInfo.packageName, 1310 extras, null, null, firstUsers); 1311 final boolean update = res.removedInfo.removedPackage != null; 1312 if (update) { 1313 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1314 } 1315 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1316 res.pkg.applicationInfo.packageName, 1317 extras, null, null, updateUsers); 1318 if (update) { 1319 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1320 res.pkg.applicationInfo.packageName, 1321 extras, null, null, updateUsers); 1322 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1323 null, null, 1324 res.pkg.applicationInfo.packageName, null, updateUsers); 1325 1326 // treat asec-hosted packages like removable media on upgrade 1327 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1328 if (DEBUG_INSTALL) { 1329 Slog.i(TAG, "upgrading pkg " + res.pkg 1330 + " is ASEC-hosted -> AVAILABLE"); 1331 } 1332 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1333 ArrayList<String> pkgList = new ArrayList<String>(1); 1334 pkgList.add(res.pkg.applicationInfo.packageName); 1335 sendResourcesChangedBroadcast(true, true, 1336 pkgList,uidArray, null); 1337 } 1338 } 1339 if (res.removedInfo.args != null) { 1340 // Remove the replaced package's older resources safely now 1341 deleteOld = true; 1342 } 1343 1344 // Log current value of "unknown sources" setting 1345 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1346 getUnknownSourcesSettings()); 1347 } 1348 // Force a gc to clear up things 1349 Runtime.getRuntime().gc(); 1350 // We delete after a gc for applications on sdcard. 1351 if (deleteOld) { 1352 synchronized (mInstallLock) { 1353 res.removedInfo.args.doPostDeleteLI(true); 1354 } 1355 } 1356 if (args.observer != null) { 1357 try { 1358 Bundle extras = extrasForInstallResult(res); 1359 args.observer.onPackageInstalled(res.name, res.returnCode, 1360 res.returnMsg, extras); 1361 } catch (RemoteException e) { 1362 Slog.i(TAG, "Observer no longer exists."); 1363 } 1364 } 1365 } else { 1366 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1367 } 1368 } break; 1369 case UPDATED_MEDIA_STATUS: { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1371 boolean reportStatus = msg.arg1 == 1; 1372 boolean doGc = msg.arg2 == 1; 1373 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1374 if (doGc) { 1375 // Force a gc to clear up stale containers. 1376 Runtime.getRuntime().gc(); 1377 } 1378 if (msg.obj != null) { 1379 @SuppressWarnings("unchecked") 1380 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1382 // Unload containers 1383 unloadAllContainers(args); 1384 } 1385 if (reportStatus) { 1386 try { 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1388 PackageHelper.getMountService().finishMediaUpdate(); 1389 } catch (RemoteException e) { 1390 Log.e(TAG, "MountService not running?"); 1391 } 1392 } 1393 } break; 1394 case WRITE_SETTINGS: { 1395 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1396 synchronized (mPackages) { 1397 removeMessages(WRITE_SETTINGS); 1398 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1399 mSettings.writeLPr(); 1400 mDirtyUsers.clear(); 1401 } 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 } break; 1404 case WRITE_PACKAGE_RESTRICTIONS: { 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 synchronized (mPackages) { 1407 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1408 for (int userId : mDirtyUsers) { 1409 mSettings.writePackageRestrictionsLPr(userId); 1410 } 1411 mDirtyUsers.clear(); 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 } break; 1415 case CHECK_PENDING_VERIFICATION: { 1416 final int verificationId = msg.arg1; 1417 final PackageVerificationState state = mPendingVerification.get(verificationId); 1418 1419 if ((state != null) && !state.timeoutExtended()) { 1420 final InstallArgs args = state.getInstallArgs(); 1421 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1422 1423 Slog.i(TAG, "Verification timed out for " + originUri); 1424 mPendingVerification.remove(verificationId); 1425 1426 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1427 1428 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1429 Slog.i(TAG, "Continuing with installation of " + originUri); 1430 state.setVerifierResponse(Binder.getCallingUid(), 1431 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1432 broadcastPackageVerified(verificationId, originUri, 1433 PackageManager.VERIFICATION_ALLOW, 1434 state.getInstallArgs().getUser()); 1435 try { 1436 ret = args.copyApk(mContainerService, true); 1437 } catch (RemoteException e) { 1438 Slog.e(TAG, "Could not contact the ContainerService"); 1439 } 1440 } else { 1441 broadcastPackageVerified(verificationId, originUri, 1442 PackageManager.VERIFICATION_REJECT, 1443 state.getInstallArgs().getUser()); 1444 } 1445 1446 processPendingInstall(args, ret); 1447 mHandler.sendEmptyMessage(MCS_UNBIND); 1448 } 1449 break; 1450 } 1451 case PACKAGE_VERIFIED: { 1452 final int verificationId = msg.arg1; 1453 1454 final PackageVerificationState state = mPendingVerification.get(verificationId); 1455 if (state == null) { 1456 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1457 break; 1458 } 1459 1460 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1461 1462 state.setVerifierResponse(response.callerUid, response.code); 1463 1464 if (state.isVerificationComplete()) { 1465 mPendingVerification.remove(verificationId); 1466 1467 final InstallArgs args = state.getInstallArgs(); 1468 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1469 1470 int ret; 1471 if (state.isInstallAllowed()) { 1472 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1473 broadcastPackageVerified(verificationId, originUri, 1474 response.code, state.getInstallArgs().getUser()); 1475 try { 1476 ret = args.copyApk(mContainerService, true); 1477 } catch (RemoteException e) { 1478 Slog.e(TAG, "Could not contact the ContainerService"); 1479 } 1480 } else { 1481 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1482 } 1483 1484 processPendingInstall(args, ret); 1485 1486 mHandler.sendEmptyMessage(MCS_UNBIND); 1487 } 1488 1489 break; 1490 } 1491 case START_INTENT_FILTER_VERIFICATIONS: { 1492 int userId = msg.arg1; 1493 int verifierUid = msg.arg2; 1494 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1495 1496 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1497 break; 1498 } 1499 case INTENT_FILTER_VERIFIED: { 1500 final int verificationId = msg.arg1; 1501 1502 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1503 verificationId); 1504 if (state == null) { 1505 Slog.w(TAG, "Invalid IntentFilter verification token " 1506 + verificationId + " received"); 1507 break; 1508 } 1509 1510 final int userId = state.getUserId(); 1511 1512 Slog.d(TAG, "Processing IntentFilter verification with token:" 1513 + verificationId + " and userId:" + userId); 1514 1515 final IntentFilterVerificationResponse response = 1516 (IntentFilterVerificationResponse) msg.obj; 1517 1518 state.setVerifierResponse(response.callerUid, response.code); 1519 1520 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1521 + " and userId:" + userId 1522 + " is settings verifier response with response code:" 1523 + response.code); 1524 1525 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1526 Slog.d(TAG, "Domains failing verification: " 1527 + response.getFailedDomainsString()); 1528 } 1529 1530 if (state.isVerificationComplete()) { 1531 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1532 } else { 1533 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1534 + " was not said to be complete"); 1535 } 1536 1537 break; 1538 } 1539 } 1540 } 1541 } 1542 1543 private StorageEventListener mStorageListener = new StorageEventListener() { 1544 @Override 1545 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1546 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1547 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1548 // TODO: ensure that private directories exist for all active users 1549 // TODO: remove user data whose serial number doesn't match 1550 loadPrivatePackages(vol); 1551 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1552 unloadPrivatePackages(vol); 1553 } 1554 } 1555 1556 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1557 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1558 updateExternalMediaStatus(true, false); 1559 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1560 updateExternalMediaStatus(false, false); 1561 } 1562 } 1563 } 1564 1565 @Override 1566 public void onVolumeForgotten(String fsUuid) { 1567 // TODO: remove all packages hosted on this uuid 1568 } 1569 }; 1570 1571 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1572 if (userId >= UserHandle.USER_OWNER) { 1573 grantRequestedRuntimePermissionsForUser(pkg, userId); 1574 } else if (userId == UserHandle.USER_ALL) { 1575 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1576 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1577 } 1578 } 1579 } 1580 1581 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1582 SettingBase sb = (SettingBase) pkg.mExtras; 1583 if (sb == null) { 1584 return; 1585 } 1586 1587 PermissionsState permissionsState = sb.getPermissionsState(); 1588 1589 for (String permission : pkg.requestedPermissions) { 1590 BasePermission bp = mSettings.mPermissions.get(permission); 1591 if (bp != null && bp.isRuntime()) { 1592 permissionsState.grantRuntimePermission(bp, userId); 1593 } 1594 } 1595 } 1596 1597 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1598 Bundle extras = null; 1599 switch (res.returnCode) { 1600 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1601 extras = new Bundle(); 1602 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1603 res.origPermission); 1604 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1605 res.origPackage); 1606 break; 1607 } 1608 } 1609 return extras; 1610 } 1611 1612 void scheduleWriteSettingsLocked() { 1613 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1614 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1615 } 1616 } 1617 1618 void scheduleWritePackageRestrictionsLocked(int userId) { 1619 if (!sUserManager.exists(userId)) return; 1620 mDirtyUsers.add(userId); 1621 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1622 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1623 } 1624 } 1625 1626 public static PackageManagerService main(Context context, Installer installer, 1627 boolean factoryTest, boolean onlyCore) { 1628 PackageManagerService m = new PackageManagerService(context, installer, 1629 factoryTest, onlyCore); 1630 ServiceManager.addService("package", m); 1631 return m; 1632 } 1633 1634 static String[] splitString(String str, char sep) { 1635 int count = 1; 1636 int i = 0; 1637 while ((i=str.indexOf(sep, i)) >= 0) { 1638 count++; 1639 i++; 1640 } 1641 1642 String[] res = new String[count]; 1643 i=0; 1644 count = 0; 1645 int lastI=0; 1646 while ((i=str.indexOf(sep, i)) >= 0) { 1647 res[count] = str.substring(lastI, i); 1648 count++; 1649 i++; 1650 lastI = i; 1651 } 1652 res[count] = str.substring(lastI, str.length()); 1653 return res; 1654 } 1655 1656 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1657 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1658 Context.DISPLAY_SERVICE); 1659 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1660 } 1661 1662 public PackageManagerService(Context context, Installer installer, 1663 boolean factoryTest, boolean onlyCore) { 1664 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1665 SystemClock.uptimeMillis()); 1666 1667 if (mSdkVersion <= 0) { 1668 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1669 } 1670 1671 mContext = context; 1672 mFactoryTest = factoryTest; 1673 mOnlyCore = onlyCore; 1674 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1675 mMetrics = new DisplayMetrics(); 1676 mSettings = new Settings(mPackages); 1677 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1682 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1683 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1684 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1685 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1686 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1687 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1688 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1689 1690 // TODO: add a property to control this? 1691 long dexOptLRUThresholdInMinutes; 1692 if (mLazyDexOpt) { 1693 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1694 } else { 1695 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1696 } 1697 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1698 1699 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1700 if (separateProcesses != null && separateProcesses.length() > 0) { 1701 if ("*".equals(separateProcesses)) { 1702 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1703 mSeparateProcesses = null; 1704 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1705 } else { 1706 mDefParseFlags = 0; 1707 mSeparateProcesses = separateProcesses.split(","); 1708 Slog.w(TAG, "Running with debug.separate_processes: " 1709 + separateProcesses); 1710 } 1711 } else { 1712 mDefParseFlags = 0; 1713 mSeparateProcesses = null; 1714 } 1715 1716 mInstaller = installer; 1717 mPackageDexOptimizer = new PackageDexOptimizer(this); 1718 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1719 1720 getDefaultDisplayMetrics(context, mMetrics); 1721 1722 SystemConfig systemConfig = SystemConfig.getInstance(); 1723 mGlobalGids = systemConfig.getGlobalGids(); 1724 mSystemPermissions = systemConfig.getSystemPermissions(); 1725 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1726 1727 synchronized (mInstallLock) { 1728 // writer 1729 synchronized (mPackages) { 1730 mHandlerThread = new ServiceThread(TAG, 1731 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1732 mHandlerThread.start(); 1733 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1734 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1735 1736 File dataDir = Environment.getDataDirectory(); 1737 mAppDataDir = new File(dataDir, "data"); 1738 mAppInstallDir = new File(dataDir, "app"); 1739 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1740 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1741 mUserAppDataDir = new File(dataDir, "user"); 1742 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1743 1744 sUserManager = new UserManagerService(context, this, 1745 mInstallLock, mPackages); 1746 1747 // Propagate permission configuration in to package manager. 1748 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1749 = systemConfig.getPermissions(); 1750 for (int i=0; i<permConfig.size(); i++) { 1751 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1752 BasePermission bp = mSettings.mPermissions.get(perm.name); 1753 if (bp == null) { 1754 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1755 mSettings.mPermissions.put(perm.name, bp); 1756 } 1757 if (perm.gids != null) { 1758 bp.setGids(perm.gids, perm.perUser); 1759 } 1760 } 1761 1762 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1763 for (int i=0; i<libConfig.size(); i++) { 1764 mSharedLibraries.put(libConfig.keyAt(i), 1765 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1766 } 1767 1768 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1769 1770 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1771 mSdkVersion, mOnlyCore); 1772 1773 String customResolverActivity = Resources.getSystem().getString( 1774 R.string.config_customResolverActivity); 1775 if (TextUtils.isEmpty(customResolverActivity)) { 1776 customResolverActivity = null; 1777 } else { 1778 mCustomResolverComponentName = ComponentName.unflattenFromString( 1779 customResolverActivity); 1780 } 1781 1782 long startTime = SystemClock.uptimeMillis(); 1783 1784 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1785 startTime); 1786 1787 // Set flag to monitor and not change apk file paths when 1788 // scanning install directories. 1789 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1790 1791 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1792 1793 /** 1794 * Add everything in the in the boot class path to the 1795 * list of process files because dexopt will have been run 1796 * if necessary during zygote startup. 1797 */ 1798 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1799 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1800 1801 if (bootClassPath != null) { 1802 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1803 for (String element : bootClassPathElements) { 1804 alreadyDexOpted.add(element); 1805 } 1806 } else { 1807 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1808 } 1809 1810 if (systemServerClassPath != null) { 1811 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1812 for (String element : systemServerClassPathElements) { 1813 alreadyDexOpted.add(element); 1814 } 1815 } else { 1816 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1817 } 1818 1819 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1820 final String[] dexCodeInstructionSets = 1821 getDexCodeInstructionSets( 1822 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1823 1824 /** 1825 * Ensure all external libraries have had dexopt run on them. 1826 */ 1827 if (mSharedLibraries.size() > 0) { 1828 // NOTE: For now, we're compiling these system "shared libraries" 1829 // (and framework jars) into all available architectures. It's possible 1830 // to compile them only when we come across an app that uses them (there's 1831 // already logic for that in scanPackageLI) but that adds some complexity. 1832 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1833 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1834 final String lib = libEntry.path; 1835 if (lib == null) { 1836 continue; 1837 } 1838 1839 try { 1840 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1841 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1842 alreadyDexOpted.add(lib); 1843 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1844 } 1845 } catch (FileNotFoundException e) { 1846 Slog.w(TAG, "Library not found: " + lib); 1847 } catch (IOException e) { 1848 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1849 + e.getMessage()); 1850 } 1851 } 1852 } 1853 } 1854 1855 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1856 1857 // Gross hack for now: we know this file doesn't contain any 1858 // code, so don't dexopt it to avoid the resulting log spew. 1859 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1860 1861 // Gross hack for now: we know this file is only part of 1862 // the boot class path for art, so don't dexopt it to 1863 // avoid the resulting log spew. 1864 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1865 1866 /** 1867 * And there are a number of commands implemented in Java, which 1868 * we currently need to do the dexopt on so that they can be 1869 * run from a non-root shell. 1870 */ 1871 String[] frameworkFiles = frameworkDir.list(); 1872 if (frameworkFiles != null) { 1873 // TODO: We could compile these only for the most preferred ABI. We should 1874 // first double check that the dex files for these commands are not referenced 1875 // by other system apps. 1876 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1877 for (int i=0; i<frameworkFiles.length; i++) { 1878 File libPath = new File(frameworkDir, frameworkFiles[i]); 1879 String path = libPath.getPath(); 1880 // Skip the file if we already did it. 1881 if (alreadyDexOpted.contains(path)) { 1882 continue; 1883 } 1884 // Skip the file if it is not a type we want to dexopt. 1885 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1886 continue; 1887 } 1888 try { 1889 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1890 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1891 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1892 } 1893 } catch (FileNotFoundException e) { 1894 Slog.w(TAG, "Jar not found: " + path); 1895 } catch (IOException e) { 1896 Slog.w(TAG, "Exception reading jar: " + path, e); 1897 } 1898 } 1899 } 1900 } 1901 1902 // Collect vendor overlay packages. 1903 // (Do this before scanning any apps.) 1904 // For security and version matching reason, only consider 1905 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1906 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1907 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1908 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1909 1910 // Find base frameworks (resource packages without code). 1911 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1912 | PackageParser.PARSE_IS_SYSTEM_DIR 1913 | PackageParser.PARSE_IS_PRIVILEGED, 1914 scanFlags | SCAN_NO_DEX, 0); 1915 1916 // Collected privileged system packages. 1917 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1918 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1919 | PackageParser.PARSE_IS_SYSTEM_DIR 1920 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1921 1922 // Collect ordinary system packages. 1923 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1924 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1925 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1926 1927 // Collect all vendor packages. 1928 File vendorAppDir = new File("/vendor/app"); 1929 try { 1930 vendorAppDir = vendorAppDir.getCanonicalFile(); 1931 } catch (IOException e) { 1932 // failed to look up canonical path, continue with original one 1933 } 1934 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1935 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1936 1937 // Collect all OEM packages. 1938 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1939 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1941 1942 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1943 mInstaller.moveFiles(); 1944 1945 // Prune any system packages that no longer exist. 1946 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1947 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1948 if (!mOnlyCore) { 1949 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1950 while (psit.hasNext()) { 1951 PackageSetting ps = psit.next(); 1952 1953 /* 1954 * If this is not a system app, it can't be a 1955 * disable system app. 1956 */ 1957 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1958 continue; 1959 } 1960 1961 /* 1962 * If the package is scanned, it's not erased. 1963 */ 1964 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1965 if (scannedPkg != null) { 1966 /* 1967 * If the system app is both scanned and in the 1968 * disabled packages list, then it must have been 1969 * added via OTA. Remove it from the currently 1970 * scanned package so the previously user-installed 1971 * application can be scanned. 1972 */ 1973 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1974 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1975 + ps.name + "; removing system app. Last known codePath=" 1976 + ps.codePathString + ", installStatus=" + ps.installStatus 1977 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1978 + scannedPkg.mVersionCode); 1979 removePackageLI(ps, true); 1980 expectingBetter.put(ps.name, ps.codePath); 1981 } 1982 1983 continue; 1984 } 1985 1986 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1987 psit.remove(); 1988 logCriticalInfo(Log.WARN, "System package " + ps.name 1989 + " no longer exists; wiping its data"); 1990 removeDataDirsLI(null, ps.name); 1991 } else { 1992 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1993 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1994 possiblyDeletedUpdatedSystemApps.add(ps.name); 1995 } 1996 } 1997 } 1998 } 1999 2000 //look for any incomplete package installations 2001 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2002 //clean up list 2003 for(int i = 0; i < deletePkgsList.size(); i++) { 2004 //clean up here 2005 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2006 } 2007 //delete tmp files 2008 deleteTempPackageFiles(); 2009 2010 // Remove any shared userIDs that have no associated packages 2011 mSettings.pruneSharedUsersLPw(); 2012 2013 if (!mOnlyCore) { 2014 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2015 SystemClock.uptimeMillis()); 2016 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2017 2018 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2019 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2020 2021 /** 2022 * Remove disable package settings for any updated system 2023 * apps that were removed via an OTA. If they're not a 2024 * previously-updated app, remove them completely. 2025 * Otherwise, just revoke their system-level permissions. 2026 */ 2027 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2028 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2029 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2030 2031 String msg; 2032 if (deletedPkg == null) { 2033 msg = "Updated system package " + deletedAppName 2034 + " no longer exists; wiping its data"; 2035 removeDataDirsLI(null, deletedAppName); 2036 } else { 2037 msg = "Updated system app + " + deletedAppName 2038 + " no longer present; removing system privileges for " 2039 + deletedAppName; 2040 2041 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2042 2043 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2044 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2045 } 2046 logCriticalInfo(Log.WARN, msg); 2047 } 2048 2049 /** 2050 * Make sure all system apps that we expected to appear on 2051 * the userdata partition actually showed up. If they never 2052 * appeared, crawl back and revive the system version. 2053 */ 2054 for (int i = 0; i < expectingBetter.size(); i++) { 2055 final String packageName = expectingBetter.keyAt(i); 2056 if (!mPackages.containsKey(packageName)) { 2057 final File scanFile = expectingBetter.valueAt(i); 2058 2059 logCriticalInfo(Log.WARN, "Expected better " + packageName 2060 + " but never showed up; reverting to system"); 2061 2062 final int reparseFlags; 2063 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2064 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2065 | PackageParser.PARSE_IS_SYSTEM_DIR 2066 | PackageParser.PARSE_IS_PRIVILEGED; 2067 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2068 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR; 2070 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2071 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2072 | PackageParser.PARSE_IS_SYSTEM_DIR; 2073 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2074 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2075 | PackageParser.PARSE_IS_SYSTEM_DIR; 2076 } else { 2077 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2078 continue; 2079 } 2080 2081 mSettings.enableSystemPackageLPw(packageName); 2082 2083 try { 2084 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2085 } catch (PackageManagerException e) { 2086 Slog.e(TAG, "Failed to parse original system package: " 2087 + e.getMessage()); 2088 } 2089 } 2090 } 2091 } 2092 2093 // Now that we know all of the shared libraries, update all clients to have 2094 // the correct library paths. 2095 updateAllSharedLibrariesLPw(); 2096 2097 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2098 // NOTE: We ignore potential failures here during a system scan (like 2099 // the rest of the commands above) because there's precious little we 2100 // can do about it. A settings error is reported, though. 2101 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2102 false /* force dexopt */, false /* defer dexopt */); 2103 } 2104 2105 // Now that we know all the packages we are keeping, 2106 // read and update their last usage times. 2107 mPackageUsage.readLP(); 2108 2109 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2110 SystemClock.uptimeMillis()); 2111 Slog.i(TAG, "Time to scan packages: " 2112 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2113 + " seconds"); 2114 2115 // If the platform SDK has changed since the last time we booted, 2116 // we need to re-grant app permission to catch any new ones that 2117 // appear. This is really a hack, and means that apps can in some 2118 // cases get permissions that the user didn't initially explicitly 2119 // allow... it would be nice to have some better way to handle 2120 // this situation. 2121 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2122 != mSdkVersion; 2123 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2124 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2125 + "; regranting permissions for internal storage"); 2126 mSettings.mInternalSdkPlatform = mSdkVersion; 2127 2128 // For now runtime permissions are toggled via a system property. 2129 if (!RUNTIME_PERMISSIONS_ENABLED) { 2130 // Remove the runtime permissions state if the feature 2131 // was disabled by flipping the system property. 2132 mSettings.deleteRuntimePermissionsFiles(); 2133 } 2134 2135 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2136 | (regrantPermissions 2137 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2138 : 0)); 2139 2140 // If this is the first boot, and it is a normal boot, then 2141 // we need to initialize the default preferred apps. 2142 if (!mRestoredSettings && !onlyCore) { 2143 mSettings.readDefaultPreferredAppsLPw(this, 0); 2144 } 2145 2146 // If this is first boot after an OTA, and a normal boot, then 2147 // we need to clear code cache directories. 2148 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2149 if (mIsUpgrade && !onlyCore) { 2150 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2151 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2152 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2153 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2154 } 2155 mSettings.mFingerprint = Build.FINGERPRINT; 2156 } 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 primeDomainVerificationsLPw(false); 2176 2177 } // synchronized (mPackages) 2178 } // synchronized (mInstallLock) 2179 2180 // Now after opening every single application zip, make sure they 2181 // are all flushed. Not really needed, but keeps things nice and 2182 // tidy. 2183 Runtime.getRuntime().gc(); 2184 } 2185 2186 @Override 2187 public boolean isFirstBoot() { 2188 return !mRestoredSettings; 2189 } 2190 2191 @Override 2192 public boolean isOnlyCoreApps() { 2193 return mOnlyCore; 2194 } 2195 2196 @Override 2197 public boolean isUpgrade() { 2198 return mIsUpgrade; 2199 } 2200 2201 private String getRequiredVerifierLPr() { 2202 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2203 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2204 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2205 2206 String requiredVerifier = null; 2207 2208 final int N = receivers.size(); 2209 for (int i = 0; i < N; i++) { 2210 final ResolveInfo info = receivers.get(i); 2211 2212 if (info.activityInfo == null) { 2213 continue; 2214 } 2215 2216 final String packageName = info.activityInfo.packageName; 2217 2218 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2219 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2220 continue; 2221 } 2222 2223 if (requiredVerifier != null) { 2224 throw new RuntimeException("There can be only one required verifier"); 2225 } 2226 2227 requiredVerifier = packageName; 2228 } 2229 2230 return requiredVerifier; 2231 } 2232 2233 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2234 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2235 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2236 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2237 2238 ComponentName verifierComponentName = null; 2239 2240 int priority = -1000; 2241 final int N = receivers.size(); 2242 for (int i = 0; i < N; i++) { 2243 final ResolveInfo info = receivers.get(i); 2244 2245 if (info.activityInfo == null) { 2246 continue; 2247 } 2248 2249 final String packageName = info.activityInfo.packageName; 2250 2251 final PackageSetting ps = mSettings.mPackages.get(packageName); 2252 if (ps == null) { 2253 continue; 2254 } 2255 2256 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2257 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2258 continue; 2259 } 2260 2261 // Select the IntentFilterVerifier with the highest priority 2262 if (priority < info.priority) { 2263 priority = info.priority; 2264 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2265 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2266 " with priority: " + info.priority); 2267 } 2268 } 2269 2270 return verifierComponentName; 2271 } 2272 2273 private void primeDomainVerificationsLPw(boolean logging) { 2274 Slog.d(TAG, "Start priming domain verification"); 2275 boolean updated = false; 2276 ArrayList<String> allHosts = new ArrayList<>(); 2277 for (PackageParser.Package pkg : mPackages.values()) { 2278 final String packageName = pkg.packageName; 2279 if (!hasDomainURLs(pkg)) { 2280 if (logging) { 2281 Slog.d(TAG, "No priming domain verifications for " + 2282 "package with no domain URLs: " + packageName); 2283 } 2284 continue; 2285 } 2286 if (!pkg.isSystemApp()) { 2287 if (logging) { 2288 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2289 packageName); 2290 } 2291 continue; 2292 } 2293 for (PackageParser.Activity a : pkg.activities) { 2294 for (ActivityIntentInfo filter : a.intents) { 2295 if (hasValidDomains(filter, false)) { 2296 allHosts.addAll(filter.getHostsList()); 2297 } 2298 } 2299 } 2300 if (allHosts.size() == 0) { 2301 allHosts.add("*"); 2302 } 2303 IntentFilterVerificationInfo ivi = 2304 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2305 if (ivi != null) { 2306 // We will always log this 2307 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 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 allHosts.clear(); 2317 } 2318 if (updated) { 2319 scheduleWriteSettingsLocked(); 2320 } 2321 Slog.d(TAG, "End priming domain verification"); 2322 } 2323 2324 @Override 2325 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2326 throws RemoteException { 2327 try { 2328 return super.onTransact(code, data, reply, flags); 2329 } catch (RuntimeException e) { 2330 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2331 Slog.wtf(TAG, "Package Manager Crash", e); 2332 } 2333 throw e; 2334 } 2335 } 2336 2337 void cleanupInstallFailedPackage(PackageSetting ps) { 2338 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2339 2340 removeDataDirsLI(ps.volumeUuid, ps.name); 2341 if (ps.codePath != null) { 2342 if (ps.codePath.isDirectory()) { 2343 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2344 } else { 2345 ps.codePath.delete(); 2346 } 2347 } 2348 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2349 if (ps.resourcePath.isDirectory()) { 2350 FileUtils.deleteContents(ps.resourcePath); 2351 } 2352 ps.resourcePath.delete(); 2353 } 2354 mSettings.removePackageLPw(ps.name); 2355 } 2356 2357 static int[] appendInts(int[] cur, int[] add) { 2358 if (add == null) return cur; 2359 if (cur == null) return add; 2360 final int N = add.length; 2361 for (int i=0; i<N; i++) { 2362 cur = appendInt(cur, add[i]); 2363 } 2364 return cur; 2365 } 2366 2367 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2368 if (!sUserManager.exists(userId)) return null; 2369 final PackageSetting ps = (PackageSetting) p.mExtras; 2370 if (ps == null) { 2371 return null; 2372 } 2373 2374 final PermissionsState permissionsState = ps.getPermissionsState(); 2375 2376 final int[] gids = permissionsState.computeGids(userId); 2377 final Set<String> permissions = permissionsState.getPermissions(userId); 2378 final PackageUserState state = ps.readUserState(userId); 2379 2380 return PackageParser.generatePackageInfo(p, gids, flags, 2381 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2382 } 2383 2384 @Override 2385 public boolean isPackageFrozen(String packageName) { 2386 synchronized (mPackages) { 2387 final PackageSetting ps = mSettings.mPackages.get(packageName); 2388 if (ps != null) { 2389 return ps.frozen; 2390 } 2391 } 2392 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2393 return true; 2394 } 2395 2396 @Override 2397 public boolean isPackageAvailable(String packageName, int userId) { 2398 if (!sUserManager.exists(userId)) return false; 2399 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2400 synchronized (mPackages) { 2401 PackageParser.Package p = mPackages.get(packageName); 2402 if (p != null) { 2403 final PackageSetting ps = (PackageSetting) p.mExtras; 2404 if (ps != null) { 2405 final PackageUserState state = ps.readUserState(userId); 2406 if (state != null) { 2407 return PackageParser.isAvailable(state); 2408 } 2409 } 2410 } 2411 } 2412 return false; 2413 } 2414 2415 @Override 2416 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2417 if (!sUserManager.exists(userId)) return null; 2418 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2419 // reader 2420 synchronized (mPackages) { 2421 PackageParser.Package p = mPackages.get(packageName); 2422 if (DEBUG_PACKAGE_INFO) 2423 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2424 if (p != null) { 2425 return generatePackageInfo(p, flags, userId); 2426 } 2427 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2428 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2429 } 2430 } 2431 return null; 2432 } 2433 2434 @Override 2435 public String[] currentToCanonicalPackageNames(String[] names) { 2436 String[] out = new String[names.length]; 2437 // reader 2438 synchronized (mPackages) { 2439 for (int i=names.length-1; i>=0; i--) { 2440 PackageSetting ps = mSettings.mPackages.get(names[i]); 2441 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2442 } 2443 } 2444 return out; 2445 } 2446 2447 @Override 2448 public String[] canonicalToCurrentPackageNames(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 String cur = mSettings.mRenamedPackages.get(names[i]); 2454 out[i] = cur != null ? cur : names[i]; 2455 } 2456 } 2457 return out; 2458 } 2459 2460 @Override 2461 public int getPackageUid(String packageName, int userId) { 2462 if (!sUserManager.exists(userId)) return -1; 2463 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2464 2465 // reader 2466 synchronized (mPackages) { 2467 PackageParser.Package p = mPackages.get(packageName); 2468 if(p != null) { 2469 return UserHandle.getUid(userId, p.applicationInfo.uid); 2470 } 2471 PackageSetting ps = mSettings.mPackages.get(packageName); 2472 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2473 return -1; 2474 } 2475 p = ps.pkg; 2476 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2477 } 2478 } 2479 2480 @Override 2481 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2482 if (!sUserManager.exists(userId)) { 2483 return null; 2484 } 2485 2486 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2487 "getPackageGids"); 2488 2489 // reader 2490 synchronized (mPackages) { 2491 PackageParser.Package p = mPackages.get(packageName); 2492 if (DEBUG_PACKAGE_INFO) { 2493 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2494 } 2495 if (p != null) { 2496 PackageSetting ps = (PackageSetting) p.mExtras; 2497 return ps.getPermissionsState().computeGids(userId); 2498 } 2499 } 2500 2501 return null; 2502 } 2503 2504 static PermissionInfo generatePermissionInfo( 2505 BasePermission bp, int flags) { 2506 if (bp.perm != null) { 2507 return PackageParser.generatePermissionInfo(bp.perm, flags); 2508 } 2509 PermissionInfo pi = new PermissionInfo(); 2510 pi.name = bp.name; 2511 pi.packageName = bp.sourcePackage; 2512 pi.nonLocalizedLabel = bp.name; 2513 pi.protectionLevel = bp.protectionLevel; 2514 return pi; 2515 } 2516 2517 @Override 2518 public PermissionInfo getPermissionInfo(String name, int flags) { 2519 // reader 2520 synchronized (mPackages) { 2521 final BasePermission p = mSettings.mPermissions.get(name); 2522 if (p != null) { 2523 return generatePermissionInfo(p, flags); 2524 } 2525 return null; 2526 } 2527 } 2528 2529 @Override 2530 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2531 // reader 2532 synchronized (mPackages) { 2533 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2534 for (BasePermission p : mSettings.mPermissions.values()) { 2535 if (group == null) { 2536 if (p.perm == null || p.perm.info.group == null) { 2537 out.add(generatePermissionInfo(p, flags)); 2538 } 2539 } else { 2540 if (p.perm != null && group.equals(p.perm.info.group)) { 2541 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2542 } 2543 } 2544 } 2545 2546 if (out.size() > 0) { 2547 return out; 2548 } 2549 return mPermissionGroups.containsKey(group) ? out : null; 2550 } 2551 } 2552 2553 @Override 2554 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2555 // reader 2556 synchronized (mPackages) { 2557 return PackageParser.generatePermissionGroupInfo( 2558 mPermissionGroups.get(name), flags); 2559 } 2560 } 2561 2562 @Override 2563 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2564 // reader 2565 synchronized (mPackages) { 2566 final int N = mPermissionGroups.size(); 2567 ArrayList<PermissionGroupInfo> out 2568 = new ArrayList<PermissionGroupInfo>(N); 2569 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2570 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2571 } 2572 return out; 2573 } 2574 } 2575 2576 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2577 int userId) { 2578 if (!sUserManager.exists(userId)) return null; 2579 PackageSetting ps = mSettings.mPackages.get(packageName); 2580 if (ps != null) { 2581 if (ps.pkg == null) { 2582 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2583 flags, userId); 2584 if (pInfo != null) { 2585 return pInfo.applicationInfo; 2586 } 2587 return null; 2588 } 2589 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2590 ps.readUserState(userId), userId); 2591 } 2592 return null; 2593 } 2594 2595 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2596 int userId) { 2597 if (!sUserManager.exists(userId)) return null; 2598 PackageSetting ps = mSettings.mPackages.get(packageName); 2599 if (ps != null) { 2600 PackageParser.Package pkg = ps.pkg; 2601 if (pkg == null) { 2602 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2603 return null; 2604 } 2605 // Only data remains, so we aren't worried about code paths 2606 pkg = new PackageParser.Package(packageName); 2607 pkg.applicationInfo.packageName = packageName; 2608 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2609 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2610 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2611 packageName, userId).getAbsolutePath(); 2612 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2613 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2614 } 2615 return generatePackageInfo(pkg, flags, userId); 2616 } 2617 return null; 2618 } 2619 2620 @Override 2621 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2622 if (!sUserManager.exists(userId)) return null; 2623 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2624 // writer 2625 synchronized (mPackages) { 2626 PackageParser.Package p = mPackages.get(packageName); 2627 if (DEBUG_PACKAGE_INFO) Log.v( 2628 TAG, "getApplicationInfo " + packageName 2629 + ": " + p); 2630 if (p != null) { 2631 PackageSetting ps = mSettings.mPackages.get(packageName); 2632 if (ps == null) return null; 2633 // Note: isEnabledLP() does not apply here - always return info 2634 return PackageParser.generateApplicationInfo( 2635 p, flags, ps.readUserState(userId), userId); 2636 } 2637 if ("android".equals(packageName)||"system".equals(packageName)) { 2638 return mAndroidApplication; 2639 } 2640 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2641 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2642 } 2643 } 2644 return null; 2645 } 2646 2647 @Override 2648 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2649 final IPackageDataObserver observer) { 2650 mContext.enforceCallingOrSelfPermission( 2651 android.Manifest.permission.CLEAR_APP_CACHE, null); 2652 // Queue up an async operation since clearing cache may take a little while. 2653 mHandler.post(new Runnable() { 2654 public void run() { 2655 mHandler.removeCallbacks(this); 2656 int retCode = -1; 2657 synchronized (mInstallLock) { 2658 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2659 if (retCode < 0) { 2660 Slog.w(TAG, "Couldn't clear application caches"); 2661 } 2662 } 2663 if (observer != null) { 2664 try { 2665 observer.onRemoveCompleted(null, (retCode >= 0)); 2666 } catch (RemoteException e) { 2667 Slog.w(TAG, "RemoveException when invoking call back"); 2668 } 2669 } 2670 } 2671 }); 2672 } 2673 2674 @Override 2675 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2676 final IntentSender pi) { 2677 mContext.enforceCallingOrSelfPermission( 2678 android.Manifest.permission.CLEAR_APP_CACHE, null); 2679 // Queue up an async operation since clearing cache may take a little while. 2680 mHandler.post(new Runnable() { 2681 public void run() { 2682 mHandler.removeCallbacks(this); 2683 int retCode = -1; 2684 synchronized (mInstallLock) { 2685 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2686 if (retCode < 0) { 2687 Slog.w(TAG, "Couldn't clear application caches"); 2688 } 2689 } 2690 if(pi != null) { 2691 try { 2692 // Callback via pending intent 2693 int code = (retCode >= 0) ? 1 : 0; 2694 pi.sendIntent(null, code, null, 2695 null, null); 2696 } catch (SendIntentException e1) { 2697 Slog.i(TAG, "Failed to send pending intent"); 2698 } 2699 } 2700 } 2701 }); 2702 } 2703 2704 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2705 synchronized (mInstallLock) { 2706 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2707 throw new IOException("Failed to free enough space"); 2708 } 2709 } 2710 } 2711 2712 @Override 2713 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2714 if (!sUserManager.exists(userId)) return null; 2715 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2716 synchronized (mPackages) { 2717 PackageParser.Activity a = mActivities.mActivities.get(component); 2718 2719 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2720 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2721 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2722 if (ps == null) return null; 2723 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2724 userId); 2725 } 2726 if (mResolveComponentName.equals(component)) { 2727 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2728 new PackageUserState(), userId); 2729 } 2730 } 2731 return null; 2732 } 2733 2734 @Override 2735 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2736 String resolvedType) { 2737 synchronized (mPackages) { 2738 PackageParser.Activity a = mActivities.mActivities.get(component); 2739 if (a == null) { 2740 return false; 2741 } 2742 for (int i=0; i<a.intents.size(); i++) { 2743 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2744 intent.getData(), intent.getCategories(), TAG) >= 0) { 2745 return true; 2746 } 2747 } 2748 return false; 2749 } 2750 } 2751 2752 @Override 2753 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2754 if (!sUserManager.exists(userId)) return null; 2755 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2756 synchronized (mPackages) { 2757 PackageParser.Activity a = mReceivers.mActivities.get(component); 2758 if (DEBUG_PACKAGE_INFO) Log.v( 2759 TAG, "getReceiverInfo " + component + ": " + a); 2760 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2761 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2762 if (ps == null) return null; 2763 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2764 userId); 2765 } 2766 } 2767 return null; 2768 } 2769 2770 @Override 2771 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2772 if (!sUserManager.exists(userId)) return null; 2773 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2774 synchronized (mPackages) { 2775 PackageParser.Service s = mServices.mServices.get(component); 2776 if (DEBUG_PACKAGE_INFO) Log.v( 2777 TAG, "getServiceInfo " + component + ": " + s); 2778 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2779 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2780 if (ps == null) return null; 2781 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2782 userId); 2783 } 2784 } 2785 return null; 2786 } 2787 2788 @Override 2789 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2790 if (!sUserManager.exists(userId)) return null; 2791 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2792 synchronized (mPackages) { 2793 PackageParser.Provider p = mProviders.mProviders.get(component); 2794 if (DEBUG_PACKAGE_INFO) Log.v( 2795 TAG, "getProviderInfo " + component + ": " + p); 2796 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2797 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2798 if (ps == null) return null; 2799 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2800 userId); 2801 } 2802 } 2803 return null; 2804 } 2805 2806 @Override 2807 public String[] getSystemSharedLibraryNames() { 2808 Set<String> libSet; 2809 synchronized (mPackages) { 2810 libSet = mSharedLibraries.keySet(); 2811 int size = libSet.size(); 2812 if (size > 0) { 2813 String[] libs = new String[size]; 2814 libSet.toArray(libs); 2815 return libs; 2816 } 2817 } 2818 return null; 2819 } 2820 2821 /** 2822 * @hide 2823 */ 2824 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2825 synchronized (mPackages) { 2826 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2827 if (lib != null && lib.apk != null) { 2828 return mPackages.get(lib.apk); 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public FeatureInfo[] getSystemAvailableFeatures() { 2836 Collection<FeatureInfo> featSet; 2837 synchronized (mPackages) { 2838 featSet = mAvailableFeatures.values(); 2839 int size = featSet.size(); 2840 if (size > 0) { 2841 FeatureInfo[] features = new FeatureInfo[size+1]; 2842 featSet.toArray(features); 2843 FeatureInfo fi = new FeatureInfo(); 2844 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2845 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2846 features[size] = fi; 2847 return features; 2848 } 2849 } 2850 return null; 2851 } 2852 2853 @Override 2854 public boolean hasSystemFeature(String name) { 2855 synchronized (mPackages) { 2856 return mAvailableFeatures.containsKey(name); 2857 } 2858 } 2859 2860 private void checkValidCaller(int uid, int userId) { 2861 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2862 return; 2863 2864 throw new SecurityException("Caller uid=" + uid 2865 + " is not privileged to communicate with user=" + userId); 2866 } 2867 2868 @Override 2869 public int checkPermission(String permName, String pkgName, int userId) { 2870 if (!sUserManager.exists(userId)) { 2871 return PackageManager.PERMISSION_DENIED; 2872 } 2873 2874 synchronized (mPackages) { 2875 final PackageParser.Package p = mPackages.get(pkgName); 2876 if (p != null && p.mExtras != null) { 2877 final PackageSetting ps = (PackageSetting) p.mExtras; 2878 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2879 return PackageManager.PERMISSION_GRANTED; 2880 } 2881 } 2882 } 2883 2884 return PackageManager.PERMISSION_DENIED; 2885 } 2886 2887 @Override 2888 public int checkUidPermission(String permName, int uid) { 2889 final int userId = UserHandle.getUserId(uid); 2890 2891 if (!sUserManager.exists(userId)) { 2892 return PackageManager.PERMISSION_DENIED; 2893 } 2894 2895 synchronized (mPackages) { 2896 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2897 if (obj != null) { 2898 final SettingBase ps = (SettingBase) obj; 2899 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2900 return PackageManager.PERMISSION_GRANTED; 2901 } 2902 } else { 2903 ArraySet<String> perms = mSystemPermissions.get(uid); 2904 if (perms != null && perms.contains(permName)) { 2905 return PackageManager.PERMISSION_GRANTED; 2906 } 2907 } 2908 } 2909 2910 return PackageManager.PERMISSION_DENIED; 2911 } 2912 2913 /** 2914 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2915 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2916 * @param checkShell TODO(yamasani): 2917 * @param message the message to log on security exception 2918 */ 2919 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2920 boolean checkShell, String message) { 2921 if (userId < 0) { 2922 throw new IllegalArgumentException("Invalid userId " + userId); 2923 } 2924 if (checkShell) { 2925 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2926 } 2927 if (userId == UserHandle.getUserId(callingUid)) return; 2928 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2929 if (requireFullPermission) { 2930 mContext.enforceCallingOrSelfPermission( 2931 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2932 } else { 2933 try { 2934 mContext.enforceCallingOrSelfPermission( 2935 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2936 } catch (SecurityException se) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2939 } 2940 } 2941 } 2942 } 2943 2944 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2945 if (callingUid == Process.SHELL_UID) { 2946 if (userHandle >= 0 2947 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2948 throw new SecurityException("Shell does not have permission to access user " 2949 + userHandle); 2950 } else if (userHandle < 0) { 2951 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2952 + Debug.getCallers(3)); 2953 } 2954 } 2955 } 2956 2957 private BasePermission findPermissionTreeLP(String permName) { 2958 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2959 if (permName.startsWith(bp.name) && 2960 permName.length() > bp.name.length() && 2961 permName.charAt(bp.name.length()) == '.') { 2962 return bp; 2963 } 2964 } 2965 return null; 2966 } 2967 2968 private BasePermission checkPermissionTreeLP(String permName) { 2969 if (permName != null) { 2970 BasePermission bp = findPermissionTreeLP(permName); 2971 if (bp != null) { 2972 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2973 return bp; 2974 } 2975 throw new SecurityException("Calling uid " 2976 + Binder.getCallingUid() 2977 + " is not allowed to add to permission tree " 2978 + bp.name + " owned by uid " + bp.uid); 2979 } 2980 } 2981 throw new SecurityException("No permission tree found for " + permName); 2982 } 2983 2984 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2985 if (s1 == null) { 2986 return s2 == null; 2987 } 2988 if (s2 == null) { 2989 return false; 2990 } 2991 if (s1.getClass() != s2.getClass()) { 2992 return false; 2993 } 2994 return s1.equals(s2); 2995 } 2996 2997 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2998 if (pi1.icon != pi2.icon) return false; 2999 if (pi1.logo != pi2.logo) return false; 3000 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3001 if (!compareStrings(pi1.name, pi2.name)) return false; 3002 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3003 // We'll take care of setting this one. 3004 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3005 // These are not currently stored in settings. 3006 //if (!compareStrings(pi1.group, pi2.group)) return false; 3007 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3008 //if (pi1.labelRes != pi2.labelRes) return false; 3009 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3010 return true; 3011 } 3012 3013 int permissionInfoFootprint(PermissionInfo info) { 3014 int size = info.name.length(); 3015 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3016 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3017 return size; 3018 } 3019 3020 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3021 int size = 0; 3022 for (BasePermission perm : mSettings.mPermissions.values()) { 3023 if (perm.uid == tree.uid) { 3024 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3025 } 3026 } 3027 return size; 3028 } 3029 3030 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3031 // We calculate the max size of permissions defined by this uid and throw 3032 // if that plus the size of 'info' would exceed our stated maximum. 3033 if (tree.uid != Process.SYSTEM_UID) { 3034 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3035 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3036 throw new SecurityException("Permission tree size cap exceeded"); 3037 } 3038 } 3039 } 3040 3041 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3042 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3043 throw new SecurityException("Label must be specified in permission"); 3044 } 3045 BasePermission tree = checkPermissionTreeLP(info.name); 3046 BasePermission bp = mSettings.mPermissions.get(info.name); 3047 boolean added = bp == null; 3048 boolean changed = true; 3049 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3050 if (added) { 3051 enforcePermissionCapLocked(info, tree); 3052 bp = new BasePermission(info.name, tree.sourcePackage, 3053 BasePermission.TYPE_DYNAMIC); 3054 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3055 throw new SecurityException( 3056 "Not allowed to modify non-dynamic permission " 3057 + info.name); 3058 } else { 3059 if (bp.protectionLevel == fixedLevel 3060 && bp.perm.owner.equals(tree.perm.owner) 3061 && bp.uid == tree.uid 3062 && comparePermissionInfos(bp.perm.info, info)) { 3063 changed = false; 3064 } 3065 } 3066 bp.protectionLevel = fixedLevel; 3067 info = new PermissionInfo(info); 3068 info.protectionLevel = fixedLevel; 3069 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3070 bp.perm.info.packageName = tree.perm.info.packageName; 3071 bp.uid = tree.uid; 3072 if (added) { 3073 mSettings.mPermissions.put(info.name, bp); 3074 } 3075 if (changed) { 3076 if (!async) { 3077 mSettings.writeLPr(); 3078 } else { 3079 scheduleWriteSettingsLocked(); 3080 } 3081 } 3082 return added; 3083 } 3084 3085 @Override 3086 public boolean addPermission(PermissionInfo info) { 3087 synchronized (mPackages) { 3088 return addPermissionLocked(info, false); 3089 } 3090 } 3091 3092 @Override 3093 public boolean addPermissionAsync(PermissionInfo info) { 3094 synchronized (mPackages) { 3095 return addPermissionLocked(info, true); 3096 } 3097 } 3098 3099 @Override 3100 public void removePermission(String name) { 3101 synchronized (mPackages) { 3102 checkPermissionTreeLP(name); 3103 BasePermission bp = mSettings.mPermissions.get(name); 3104 if (bp != null) { 3105 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3106 throw new SecurityException( 3107 "Not allowed to modify non-dynamic permission " 3108 + name); 3109 } 3110 mSettings.mPermissions.remove(name); 3111 mSettings.writeLPr(); 3112 } 3113 } 3114 } 3115 3116 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3117 BasePermission bp) { 3118 int index = pkg.requestedPermissions.indexOf(bp.name); 3119 if (index == -1) { 3120 throw new SecurityException("Package " + pkg.packageName 3121 + " has not requested permission " + bp.name); 3122 } 3123 if (!bp.isRuntime()) { 3124 throw new SecurityException("Permission " + bp.name 3125 + " is not a changeable permission type"); 3126 } 3127 } 3128 3129 @Override 3130 public boolean grantPermission(String packageName, String name, int userId) { 3131 if (!RUNTIME_PERMISSIONS_ENABLED) { 3132 return false; 3133 } 3134 3135 if (!sUserManager.exists(userId)) { 3136 return false; 3137 } 3138 3139 mContext.enforceCallingOrSelfPermission( 3140 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3141 "grantPermission"); 3142 3143 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3144 "grantPermission"); 3145 3146 boolean gidsChanged = false; 3147 final SettingBase sb; 3148 3149 synchronized (mPackages) { 3150 final PackageParser.Package pkg = mPackages.get(packageName); 3151 if (pkg == null) { 3152 throw new IllegalArgumentException("Unknown package: " + packageName); 3153 } 3154 3155 final BasePermission bp = mSettings.mPermissions.get(name); 3156 if (bp == null) { 3157 throw new IllegalArgumentException("Unknown permission: " + name); 3158 } 3159 3160 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3161 3162 sb = (SettingBase) pkg.mExtras; 3163 if (sb == null) { 3164 throw new IllegalArgumentException("Unknown package: " + packageName); 3165 } 3166 3167 final PermissionsState permissionsState = sb.getPermissionsState(); 3168 3169 final int result = permissionsState.grantRuntimePermission(bp, userId); 3170 switch (result) { 3171 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3172 return false; 3173 } 3174 3175 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3176 gidsChanged = true; 3177 } break; 3178 } 3179 3180 // Not critical if that is lost - app has to request again. 3181 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3182 } 3183 3184 if (gidsChanged) { 3185 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3186 } 3187 3188 return true; 3189 } 3190 3191 @Override 3192 public boolean revokePermission(String packageName, String name, int userId) { 3193 if (!RUNTIME_PERMISSIONS_ENABLED) { 3194 return false; 3195 } 3196 3197 if (!sUserManager.exists(userId)) { 3198 return false; 3199 } 3200 3201 mContext.enforceCallingOrSelfPermission( 3202 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3203 "revokePermission"); 3204 3205 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3206 "revokePermission"); 3207 3208 final SettingBase sb; 3209 3210 synchronized (mPackages) { 3211 final PackageParser.Package pkg = mPackages.get(packageName); 3212 if (pkg == null) { 3213 throw new IllegalArgumentException("Unknown package: " + packageName); 3214 } 3215 3216 final BasePermission bp = mSettings.mPermissions.get(name); 3217 if (bp == null) { 3218 throw new IllegalArgumentException("Unknown permission: " + name); 3219 } 3220 3221 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3222 3223 sb = (SettingBase) pkg.mExtras; 3224 if (sb == null) { 3225 throw new IllegalArgumentException("Unknown package: " + packageName); 3226 } 3227 3228 final PermissionsState permissionsState = sb.getPermissionsState(); 3229 3230 if (permissionsState.revokeRuntimePermission(bp, userId) == 3231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3232 return false; 3233 } 3234 3235 // Critical, after this call all should never have the permission. 3236 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3237 } 3238 3239 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3240 3241 return true; 3242 } 3243 3244 @Override 3245 public boolean isProtectedBroadcast(String actionName) { 3246 synchronized (mPackages) { 3247 return mProtectedBroadcasts.contains(actionName); 3248 } 3249 } 3250 3251 @Override 3252 public int checkSignatures(String pkg1, String pkg2) { 3253 synchronized (mPackages) { 3254 final PackageParser.Package p1 = mPackages.get(pkg1); 3255 final PackageParser.Package p2 = mPackages.get(pkg2); 3256 if (p1 == null || p1.mExtras == null 3257 || p2 == null || p2.mExtras == null) { 3258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3259 } 3260 return compareSignatures(p1.mSignatures, p2.mSignatures); 3261 } 3262 } 3263 3264 @Override 3265 public int checkUidSignatures(int uid1, int uid2) { 3266 // Map to base uids. 3267 uid1 = UserHandle.getAppId(uid1); 3268 uid2 = UserHandle.getAppId(uid2); 3269 // reader 3270 synchronized (mPackages) { 3271 Signature[] s1; 3272 Signature[] s2; 3273 Object obj = mSettings.getUserIdLPr(uid1); 3274 if (obj != null) { 3275 if (obj instanceof SharedUserSetting) { 3276 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3277 } else if (obj instanceof PackageSetting) { 3278 s1 = ((PackageSetting)obj).signatures.mSignatures; 3279 } else { 3280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3281 } 3282 } else { 3283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3284 } 3285 obj = mSettings.getUserIdLPr(uid2); 3286 if (obj != null) { 3287 if (obj instanceof SharedUserSetting) { 3288 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3289 } else if (obj instanceof PackageSetting) { 3290 s2 = ((PackageSetting)obj).signatures.mSignatures; 3291 } else { 3292 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3293 } 3294 } else { 3295 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3296 } 3297 return compareSignatures(s1, s2); 3298 } 3299 } 3300 3301 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3302 final long identity = Binder.clearCallingIdentity(); 3303 try { 3304 if (sb instanceof SharedUserSetting) { 3305 SharedUserSetting sus = (SharedUserSetting) sb; 3306 final int packageCount = sus.packages.size(); 3307 for (int i = 0; i < packageCount; i++) { 3308 PackageSetting susPs = sus.packages.valueAt(i); 3309 if (userId == UserHandle.USER_ALL) { 3310 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3311 } else { 3312 final int uid = UserHandle.getUid(userId, susPs.appId); 3313 killUid(uid, reason); 3314 } 3315 } 3316 } else if (sb instanceof PackageSetting) { 3317 PackageSetting ps = (PackageSetting) sb; 3318 if (userId == UserHandle.USER_ALL) { 3319 killApplication(ps.pkg.packageName, ps.appId, reason); 3320 } else { 3321 final int uid = UserHandle.getUid(userId, ps.appId); 3322 killUid(uid, reason); 3323 } 3324 } 3325 } finally { 3326 Binder.restoreCallingIdentity(identity); 3327 } 3328 } 3329 3330 private static void killUid(int uid, String reason) { 3331 IActivityManager am = ActivityManagerNative.getDefault(); 3332 if (am != null) { 3333 try { 3334 am.killUid(uid, reason); 3335 } catch (RemoteException e) { 3336 /* ignore - same process */ 3337 } 3338 } 3339 } 3340 3341 /** 3342 * Compares two sets of signatures. Returns: 3343 * <br /> 3344 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3345 * <br /> 3346 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3347 * <br /> 3348 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3349 * <br /> 3350 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3351 * <br /> 3352 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3353 */ 3354 static int compareSignatures(Signature[] s1, Signature[] s2) { 3355 if (s1 == null) { 3356 return s2 == null 3357 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3358 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3359 } 3360 3361 if (s2 == null) { 3362 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3363 } 3364 3365 if (s1.length != s2.length) { 3366 return PackageManager.SIGNATURE_NO_MATCH; 3367 } 3368 3369 // Since both signature sets are of size 1, we can compare without HashSets. 3370 if (s1.length == 1) { 3371 return s1[0].equals(s2[0]) ? 3372 PackageManager.SIGNATURE_MATCH : 3373 PackageManager.SIGNATURE_NO_MATCH; 3374 } 3375 3376 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3377 for (Signature sig : s1) { 3378 set1.add(sig); 3379 } 3380 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3381 for (Signature sig : s2) { 3382 set2.add(sig); 3383 } 3384 // Make sure s2 contains all signatures in s1. 3385 if (set1.equals(set2)) { 3386 return PackageManager.SIGNATURE_MATCH; 3387 } 3388 return PackageManager.SIGNATURE_NO_MATCH; 3389 } 3390 3391 /** 3392 * If the database version for this type of package (internal storage or 3393 * external storage) is less than the version where package signatures 3394 * were updated, return true. 3395 */ 3396 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3397 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3398 DatabaseVersion.SIGNATURE_END_ENTITY)) 3399 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3400 DatabaseVersion.SIGNATURE_END_ENTITY)); 3401 } 3402 3403 /** 3404 * Used for backward compatibility to make sure any packages with 3405 * certificate chains get upgraded to the new style. {@code existingSigs} 3406 * will be in the old format (since they were stored on disk from before the 3407 * system upgrade) and {@code scannedSigs} will be in the newer format. 3408 */ 3409 private int compareSignaturesCompat(PackageSignatures existingSigs, 3410 PackageParser.Package scannedPkg) { 3411 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3412 return PackageManager.SIGNATURE_NO_MATCH; 3413 } 3414 3415 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3416 for (Signature sig : existingSigs.mSignatures) { 3417 existingSet.add(sig); 3418 } 3419 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3420 for (Signature sig : scannedPkg.mSignatures) { 3421 try { 3422 Signature[] chainSignatures = sig.getChainSignatures(); 3423 for (Signature chainSig : chainSignatures) { 3424 scannedCompatSet.add(chainSig); 3425 } 3426 } catch (CertificateEncodingException e) { 3427 scannedCompatSet.add(sig); 3428 } 3429 } 3430 /* 3431 * Make sure the expanded scanned set contains all signatures in the 3432 * existing one. 3433 */ 3434 if (scannedCompatSet.equals(existingSet)) { 3435 // Migrate the old signatures to the new scheme. 3436 existingSigs.assignSignatures(scannedPkg.mSignatures); 3437 // The new KeySets will be re-added later in the scanning process. 3438 synchronized (mPackages) { 3439 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3440 } 3441 return PackageManager.SIGNATURE_MATCH; 3442 } 3443 return PackageManager.SIGNATURE_NO_MATCH; 3444 } 3445 3446 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3447 if (isExternal(scannedPkg)) { 3448 return mSettings.isExternalDatabaseVersionOlderThan( 3449 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3450 } else { 3451 return mSettings.isInternalDatabaseVersionOlderThan( 3452 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3453 } 3454 } 3455 3456 private int compareSignaturesRecover(PackageSignatures existingSigs, 3457 PackageParser.Package scannedPkg) { 3458 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3459 return PackageManager.SIGNATURE_NO_MATCH; 3460 } 3461 3462 String msg = null; 3463 try { 3464 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3465 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3466 + scannedPkg.packageName); 3467 return PackageManager.SIGNATURE_MATCH; 3468 } 3469 } catch (CertificateException e) { 3470 msg = e.getMessage(); 3471 } 3472 3473 logCriticalInfo(Log.INFO, 3474 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3475 return PackageManager.SIGNATURE_NO_MATCH; 3476 } 3477 3478 @Override 3479 public String[] getPackagesForUid(int uid) { 3480 uid = UserHandle.getAppId(uid); 3481 // reader 3482 synchronized (mPackages) { 3483 Object obj = mSettings.getUserIdLPr(uid); 3484 if (obj instanceof SharedUserSetting) { 3485 final SharedUserSetting sus = (SharedUserSetting) obj; 3486 final int N = sus.packages.size(); 3487 final String[] res = new String[N]; 3488 final Iterator<PackageSetting> it = sus.packages.iterator(); 3489 int i = 0; 3490 while (it.hasNext()) { 3491 res[i++] = it.next().name; 3492 } 3493 return res; 3494 } else if (obj instanceof PackageSetting) { 3495 final PackageSetting ps = (PackageSetting) obj; 3496 return new String[] { ps.name }; 3497 } 3498 } 3499 return null; 3500 } 3501 3502 @Override 3503 public String getNameForUid(int uid) { 3504 // reader 3505 synchronized (mPackages) { 3506 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3507 if (obj instanceof SharedUserSetting) { 3508 final SharedUserSetting sus = (SharedUserSetting) obj; 3509 return sus.name + ":" + sus.userId; 3510 } else if (obj instanceof PackageSetting) { 3511 final PackageSetting ps = (PackageSetting) obj; 3512 return ps.name; 3513 } 3514 } 3515 return null; 3516 } 3517 3518 @Override 3519 public int getUidForSharedUser(String sharedUserName) { 3520 if(sharedUserName == null) { 3521 return -1; 3522 } 3523 // reader 3524 synchronized (mPackages) { 3525 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3526 if (suid == null) { 3527 return -1; 3528 } 3529 return suid.userId; 3530 } 3531 } 3532 3533 @Override 3534 public int getFlagsForUid(int uid) { 3535 synchronized (mPackages) { 3536 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3537 if (obj instanceof SharedUserSetting) { 3538 final SharedUserSetting sus = (SharedUserSetting) obj; 3539 return sus.pkgFlags; 3540 } else if (obj instanceof PackageSetting) { 3541 final PackageSetting ps = (PackageSetting) obj; 3542 return ps.pkgFlags; 3543 } 3544 } 3545 return 0; 3546 } 3547 3548 @Override 3549 public int getPrivateFlagsForUid(int uid) { 3550 synchronized (mPackages) { 3551 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3552 if (obj instanceof SharedUserSetting) { 3553 final SharedUserSetting sus = (SharedUserSetting) obj; 3554 return sus.pkgPrivateFlags; 3555 } else if (obj instanceof PackageSetting) { 3556 final PackageSetting ps = (PackageSetting) obj; 3557 return ps.pkgPrivateFlags; 3558 } 3559 } 3560 return 0; 3561 } 3562 3563 @Override 3564 public boolean isUidPrivileged(int uid) { 3565 uid = UserHandle.getAppId(uid); 3566 // reader 3567 synchronized (mPackages) { 3568 Object obj = mSettings.getUserIdLPr(uid); 3569 if (obj instanceof SharedUserSetting) { 3570 final SharedUserSetting sus = (SharedUserSetting) obj; 3571 final Iterator<PackageSetting> it = sus.packages.iterator(); 3572 while (it.hasNext()) { 3573 if (it.next().isPrivileged()) { 3574 return true; 3575 } 3576 } 3577 } else if (obj instanceof PackageSetting) { 3578 final PackageSetting ps = (PackageSetting) obj; 3579 return ps.isPrivileged(); 3580 } 3581 } 3582 return false; 3583 } 3584 3585 @Override 3586 public String[] getAppOpPermissionPackages(String permissionName) { 3587 synchronized (mPackages) { 3588 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3589 if (pkgs == null) { 3590 return null; 3591 } 3592 return pkgs.toArray(new String[pkgs.size()]); 3593 } 3594 } 3595 3596 @Override 3597 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3598 int flags, int userId) { 3599 if (!sUserManager.exists(userId)) return null; 3600 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3601 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3602 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3603 } 3604 3605 @Override 3606 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3607 IntentFilter filter, int match, ComponentName activity) { 3608 final int userId = UserHandle.getCallingUserId(); 3609 if (DEBUG_PREFERRED) { 3610 Log.v(TAG, "setLastChosenActivity intent=" + intent 3611 + " resolvedType=" + resolvedType 3612 + " flags=" + flags 3613 + " filter=" + filter 3614 + " match=" + match 3615 + " activity=" + activity); 3616 filter.dump(new PrintStreamPrinter(System.out), " "); 3617 } 3618 intent.setComponent(null); 3619 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3620 // Find any earlier preferred or last chosen entries and nuke them 3621 findPreferredActivity(intent, resolvedType, 3622 flags, query, 0, false, true, false, userId); 3623 // Add the new activity as the last chosen for this filter 3624 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3625 "Setting last chosen"); 3626 } 3627 3628 @Override 3629 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3630 final int userId = UserHandle.getCallingUserId(); 3631 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3632 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3633 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3634 false, false, false, userId); 3635 } 3636 3637 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3638 int flags, List<ResolveInfo> query, int userId) { 3639 if (query != null) { 3640 final int N = query.size(); 3641 if (N == 1) { 3642 return query.get(0); 3643 } else if (N > 1) { 3644 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3645 // If there is more than one activity with the same priority, 3646 // then let the user decide between them. 3647 ResolveInfo r0 = query.get(0); 3648 ResolveInfo r1 = query.get(1); 3649 if (DEBUG_INTENT_MATCHING || debug) { 3650 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3651 + r1.activityInfo.name + "=" + r1.priority); 3652 } 3653 // If the first activity has a higher priority, or a different 3654 // default, then it is always desireable to pick it. 3655 if (r0.priority != r1.priority 3656 || r0.preferredOrder != r1.preferredOrder 3657 || r0.isDefault != r1.isDefault) { 3658 return query.get(0); 3659 } 3660 // If we have saved a preference for a preferred activity for 3661 // this Intent, use that. 3662 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3663 flags, query, r0.priority, true, false, debug, userId); 3664 if (ri != null) { 3665 return ri; 3666 } 3667 if (userId != 0) { 3668 ri = new ResolveInfo(mResolveInfo); 3669 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3670 ri.activityInfo.applicationInfo = new ApplicationInfo( 3671 ri.activityInfo.applicationInfo); 3672 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3673 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3674 return ri; 3675 } 3676 return mResolveInfo; 3677 } 3678 } 3679 return null; 3680 } 3681 3682 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3683 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3684 final int N = query.size(); 3685 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3686 .get(userId); 3687 // Get the list of persistent preferred activities that handle the intent 3688 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3689 List<PersistentPreferredActivity> pprefs = ppir != null 3690 ? ppir.queryIntent(intent, resolvedType, 3691 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3692 : null; 3693 if (pprefs != null && pprefs.size() > 0) { 3694 final int M = pprefs.size(); 3695 for (int i=0; i<M; i++) { 3696 final PersistentPreferredActivity ppa = pprefs.get(i); 3697 if (DEBUG_PREFERRED || debug) { 3698 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3699 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3700 + "\n component=" + ppa.mComponent); 3701 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3702 } 3703 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3704 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3705 if (DEBUG_PREFERRED || debug) { 3706 Slog.v(TAG, "Found persistent preferred activity:"); 3707 if (ai != null) { 3708 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3709 } else { 3710 Slog.v(TAG, " null"); 3711 } 3712 } 3713 if (ai == null) { 3714 // This previously registered persistent preferred activity 3715 // component is no longer known. Ignore it and do NOT remove it. 3716 continue; 3717 } 3718 for (int j=0; j<N; j++) { 3719 final ResolveInfo ri = query.get(j); 3720 if (!ri.activityInfo.applicationInfo.packageName 3721 .equals(ai.applicationInfo.packageName)) { 3722 continue; 3723 } 3724 if (!ri.activityInfo.name.equals(ai.name)) { 3725 continue; 3726 } 3727 // Found a persistent preference that can handle the intent. 3728 if (DEBUG_PREFERRED || debug) { 3729 Slog.v(TAG, "Returning persistent preferred activity: " + 3730 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3731 } 3732 return ri; 3733 } 3734 } 3735 } 3736 return null; 3737 } 3738 3739 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3740 List<ResolveInfo> query, int priority, boolean always, 3741 boolean removeMatches, boolean debug, int userId) { 3742 if (!sUserManager.exists(userId)) return null; 3743 // writer 3744 synchronized (mPackages) { 3745 if (intent.getSelector() != null) { 3746 intent = intent.getSelector(); 3747 } 3748 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3749 3750 // Try to find a matching persistent preferred activity. 3751 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3752 debug, userId); 3753 3754 // If a persistent preferred activity matched, use it. 3755 if (pri != null) { 3756 return pri; 3757 } 3758 3759 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3760 // Get the list of preferred activities that handle the intent 3761 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3762 List<PreferredActivity> prefs = pir != null 3763 ? pir.queryIntent(intent, resolvedType, 3764 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3765 : null; 3766 if (prefs != null && prefs.size() > 0) { 3767 boolean changed = false; 3768 try { 3769 // First figure out how good the original match set is. 3770 // We will only allow preferred activities that came 3771 // from the same match quality. 3772 int match = 0; 3773 3774 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3775 3776 final int N = query.size(); 3777 for (int j=0; j<N; j++) { 3778 final ResolveInfo ri = query.get(j); 3779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3780 + ": 0x" + Integer.toHexString(match)); 3781 if (ri.match > match) { 3782 match = ri.match; 3783 } 3784 } 3785 3786 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3787 + Integer.toHexString(match)); 3788 3789 match &= IntentFilter.MATCH_CATEGORY_MASK; 3790 final int M = prefs.size(); 3791 for (int i=0; i<M; i++) { 3792 final PreferredActivity pa = prefs.get(i); 3793 if (DEBUG_PREFERRED || debug) { 3794 Slog.v(TAG, "Checking PreferredActivity ds=" 3795 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3796 + "\n component=" + pa.mPref.mComponent); 3797 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3798 } 3799 if (pa.mPref.mMatch != match) { 3800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3801 + Integer.toHexString(pa.mPref.mMatch)); 3802 continue; 3803 } 3804 // If it's not an "always" type preferred activity and that's what we're 3805 // looking for, skip it. 3806 if (always && !pa.mPref.mAlways) { 3807 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3808 continue; 3809 } 3810 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3811 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3812 if (DEBUG_PREFERRED || debug) { 3813 Slog.v(TAG, "Found preferred activity:"); 3814 if (ai != null) { 3815 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3816 } else { 3817 Slog.v(TAG, " null"); 3818 } 3819 } 3820 if (ai == null) { 3821 // This previously registered preferred activity 3822 // component is no longer known. Most likely an update 3823 // to the app was installed and in the new version this 3824 // component no longer exists. Clean it up by removing 3825 // it from the preferred activities list, and skip it. 3826 Slog.w(TAG, "Removing dangling preferred activity: " 3827 + pa.mPref.mComponent); 3828 pir.removeFilter(pa); 3829 changed = true; 3830 continue; 3831 } 3832 for (int j=0; j<N; j++) { 3833 final ResolveInfo ri = query.get(j); 3834 if (!ri.activityInfo.applicationInfo.packageName 3835 .equals(ai.applicationInfo.packageName)) { 3836 continue; 3837 } 3838 if (!ri.activityInfo.name.equals(ai.name)) { 3839 continue; 3840 } 3841 3842 if (removeMatches) { 3843 pir.removeFilter(pa); 3844 changed = true; 3845 if (DEBUG_PREFERRED) { 3846 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3847 } 3848 break; 3849 } 3850 3851 // Okay we found a previously set preferred or last chosen app. 3852 // If the result set is different from when this 3853 // was created, we need to clear it and re-ask the 3854 // user their preference, if we're looking for an "always" type entry. 3855 if (always && !pa.mPref.sameSet(query)) { 3856 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3857 + intent + " type " + resolvedType); 3858 if (DEBUG_PREFERRED) { 3859 Slog.v(TAG, "Removing preferred activity since set changed " 3860 + pa.mPref.mComponent); 3861 } 3862 pir.removeFilter(pa); 3863 // Re-add the filter as a "last chosen" entry (!always) 3864 PreferredActivity lastChosen = new PreferredActivity( 3865 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3866 pir.addFilter(lastChosen); 3867 changed = true; 3868 return null; 3869 } 3870 3871 // Yay! Either the set matched or we're looking for the last chosen 3872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3873 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3874 return ri; 3875 } 3876 } 3877 } finally { 3878 if (changed) { 3879 if (DEBUG_PREFERRED) { 3880 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3881 } 3882 scheduleWritePackageRestrictionsLocked(userId); 3883 } 3884 } 3885 } 3886 } 3887 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3888 return null; 3889 } 3890 3891 /* 3892 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3893 */ 3894 @Override 3895 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3896 int targetUserId) { 3897 mContext.enforceCallingOrSelfPermission( 3898 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3899 List<CrossProfileIntentFilter> matches = 3900 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3901 if (matches != null) { 3902 int size = matches.size(); 3903 for (int i = 0; i < size; i++) { 3904 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3905 } 3906 } 3907 return false; 3908 } 3909 3910 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3911 String resolvedType, int userId) { 3912 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3913 if (resolver != null) { 3914 return resolver.queryIntent(intent, resolvedType, false, userId); 3915 } 3916 return null; 3917 } 3918 3919 @Override 3920 public List<ResolveInfo> queryIntentActivities(Intent intent, 3921 String resolvedType, int flags, int userId) { 3922 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3924 ComponentName comp = intent.getComponent(); 3925 if (comp == null) { 3926 if (intent.getSelector() != null) { 3927 intent = intent.getSelector(); 3928 comp = intent.getComponent(); 3929 } 3930 } 3931 3932 if (comp != null) { 3933 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3934 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3935 if (ai != null) { 3936 final ResolveInfo ri = new ResolveInfo(); 3937 ri.activityInfo = ai; 3938 list.add(ri); 3939 } 3940 return list; 3941 } 3942 3943 // reader 3944 synchronized (mPackages) { 3945 final String pkgName = intent.getPackage(); 3946 if (pkgName == null) { 3947 List<CrossProfileIntentFilter> matchingFilters = 3948 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3949 // Check for results that need to skip the current profile. 3950 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3951 resolvedType, flags, userId); 3952 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3953 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3954 result.add(resolveInfo); 3955 return filterIfNotPrimaryUser(result, userId); 3956 } 3957 3958 // Check for results in the current profile. 3959 List<ResolveInfo> result = mActivities.queryIntent( 3960 intent, resolvedType, flags, userId); 3961 3962 // Check for cross profile results. 3963 resolveInfo = queryCrossProfileIntents( 3964 matchingFilters, intent, resolvedType, flags, userId); 3965 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3966 result.add(resolveInfo); 3967 Collections.sort(result, mResolvePrioritySorter); 3968 } 3969 result = filterIfNotPrimaryUser(result, userId); 3970 if (result.size() > 1 && hasWebURI(intent)) { 3971 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3972 } 3973 return result; 3974 } 3975 final PackageParser.Package pkg = mPackages.get(pkgName); 3976 if (pkg != null) { 3977 return filterIfNotPrimaryUser( 3978 mActivities.queryIntentForPackage( 3979 intent, resolvedType, flags, pkg.activities, userId), 3980 userId); 3981 } 3982 return new ArrayList<ResolveInfo>(); 3983 } 3984 } 3985 3986 private boolean isUserEnabled(int userId) { 3987 long callingId = Binder.clearCallingIdentity(); 3988 try { 3989 UserInfo userInfo = sUserManager.getUserInfo(userId); 3990 return userInfo != null && userInfo.isEnabled(); 3991 } finally { 3992 Binder.restoreCallingIdentity(callingId); 3993 } 3994 } 3995 3996 /** 3997 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3998 * 3999 * @return filtered list 4000 */ 4001 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4002 if (userId == UserHandle.USER_OWNER) { 4003 return resolveInfos; 4004 } 4005 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4006 ResolveInfo info = resolveInfos.get(i); 4007 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4008 resolveInfos.remove(i); 4009 } 4010 } 4011 return resolveInfos; 4012 } 4013 4014 private static boolean hasWebURI(Intent intent) { 4015 if (intent.getData() == null) { 4016 return false; 4017 } 4018 final String scheme = intent.getScheme(); 4019 if (TextUtils.isEmpty(scheme)) { 4020 return false; 4021 } 4022 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4023 } 4024 4025 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4026 int flags, List<ResolveInfo> candidates) { 4027 if (DEBUG_PREFERRED) { 4028 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4029 candidates.size()); 4030 } 4031 4032 final int userId = UserHandle.getCallingUserId(); 4033 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4034 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4035 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4036 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4037 4038 synchronized (mPackages) { 4039 final int count = candidates.size(); 4040 // First, try to use the domain prefered App 4041 for (int n=0; n<count; n++) { 4042 ResolveInfo info = candidates.get(n); 4043 String packageName = info.activityInfo.packageName; 4044 PackageSetting ps = mSettings.mPackages.get(packageName); 4045 if (ps != null) { 4046 // Add to the special match all list (Browser use case) 4047 if (info.handleAllWebDataURI) { 4048 matchAllList.add(info); 4049 continue; 4050 } 4051 // Try to get the status from User settings first 4052 int status = getDomainVerificationStatusLPr(ps, userId); 4053 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4054 result.add(info); 4055 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4056 neverList.add(info); 4057 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4058 undefinedList.add(info); 4059 } 4060 } 4061 } 4062 // If there is nothing selected, add all candidates and remove the ones that the User 4063 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4064 // also remove any Browser Apps ones. 4065 // If there is still none after this pass, add all undefined one and Browser Apps and 4066 // let the User decide with the Disambiguation dialog if there are several ones. 4067 if (result.size() == 0) { 4068 result.addAll(candidates); 4069 } 4070 result.removeAll(neverList); 4071 result.removeAll(matchAllList); 4072 if (result.size() == 0) { 4073 result.addAll(undefinedList); 4074 if ((flags & MATCH_ALL) != 0) { 4075 result.addAll(matchAllList); 4076 } else { 4077 // Try to add the Default Browser if we can 4078 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4079 UserHandle.myUserId()); 4080 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4081 boolean defaultBrowserFound = false; 4082 final int browserCount = matchAllList.size(); 4083 for (int n=0; n<browserCount; n++) { 4084 ResolveInfo browser = matchAllList.get(n); 4085 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4086 result.add(browser); 4087 defaultBrowserFound = true; 4088 break; 4089 } 4090 } 4091 if (!defaultBrowserFound) { 4092 result.addAll(matchAllList); 4093 } 4094 } else { 4095 result.addAll(matchAllList); 4096 } 4097 } 4098 } 4099 } 4100 if (DEBUG_PREFERRED) { 4101 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4102 result.size()); 4103 } 4104 return result; 4105 } 4106 4107 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4108 int status = ps.getDomainVerificationStatusForUser(userId); 4109 // if none available, get the master status 4110 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4111 if (ps.getIntentFilterVerificationInfo() != null) { 4112 status = ps.getIntentFilterVerificationInfo().getStatus(); 4113 } 4114 } 4115 return status; 4116 } 4117 4118 private ResolveInfo querySkipCurrentProfileIntents( 4119 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4120 int flags, int sourceUserId) { 4121 if (matchingFilters != null) { 4122 int size = matchingFilters.size(); 4123 for (int i = 0; i < size; i ++) { 4124 CrossProfileIntentFilter filter = matchingFilters.get(i); 4125 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4126 // Checking if there are activities in the target user that can handle the 4127 // intent. 4128 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4129 flags, sourceUserId); 4130 if (resolveInfo != null) { 4131 return resolveInfo; 4132 } 4133 } 4134 } 4135 } 4136 return null; 4137 } 4138 4139 // Return matching ResolveInfo if any for skip current profile intent filters. 4140 private ResolveInfo queryCrossProfileIntents( 4141 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4142 int flags, int sourceUserId) { 4143 if (matchingFilters != null) { 4144 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4145 // match the same intent. For performance reasons, it is better not to 4146 // run queryIntent twice for the same userId 4147 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4148 int size = matchingFilters.size(); 4149 for (int i = 0; i < size; i++) { 4150 CrossProfileIntentFilter filter = matchingFilters.get(i); 4151 int targetUserId = filter.getTargetUserId(); 4152 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4153 && !alreadyTriedUserIds.get(targetUserId)) { 4154 // Checking if there are activities in the target user that can handle the 4155 // intent. 4156 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4157 flags, sourceUserId); 4158 if (resolveInfo != null) return resolveInfo; 4159 alreadyTriedUserIds.put(targetUserId, true); 4160 } 4161 } 4162 } 4163 return null; 4164 } 4165 4166 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4167 String resolvedType, int flags, int sourceUserId) { 4168 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4169 resolvedType, flags, filter.getTargetUserId()); 4170 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4171 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4172 } 4173 return null; 4174 } 4175 4176 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4177 int sourceUserId, int targetUserId) { 4178 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4179 String className; 4180 if (targetUserId == UserHandle.USER_OWNER) { 4181 className = FORWARD_INTENT_TO_USER_OWNER; 4182 } else { 4183 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4184 } 4185 ComponentName forwardingActivityComponentName = new ComponentName( 4186 mAndroidApplication.packageName, className); 4187 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4188 sourceUserId); 4189 if (targetUserId == UserHandle.USER_OWNER) { 4190 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4191 forwardingResolveInfo.noResourceId = true; 4192 } 4193 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4194 forwardingResolveInfo.priority = 0; 4195 forwardingResolveInfo.preferredOrder = 0; 4196 forwardingResolveInfo.match = 0; 4197 forwardingResolveInfo.isDefault = true; 4198 forwardingResolveInfo.filter = filter; 4199 forwardingResolveInfo.targetUserId = targetUserId; 4200 return forwardingResolveInfo; 4201 } 4202 4203 @Override 4204 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4205 Intent[] specifics, String[] specificTypes, Intent intent, 4206 String resolvedType, int flags, int userId) { 4207 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4208 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4209 false, "query intent activity options"); 4210 final String resultsAction = intent.getAction(); 4211 4212 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4213 | PackageManager.GET_RESOLVED_FILTER, userId); 4214 4215 if (DEBUG_INTENT_MATCHING) { 4216 Log.v(TAG, "Query " + intent + ": " + results); 4217 } 4218 4219 int specificsPos = 0; 4220 int N; 4221 4222 // todo: note that the algorithm used here is O(N^2). This 4223 // isn't a problem in our current environment, but if we start running 4224 // into situations where we have more than 5 or 10 matches then this 4225 // should probably be changed to something smarter... 4226 4227 // First we go through and resolve each of the specific items 4228 // that were supplied, taking care of removing any corresponding 4229 // duplicate items in the generic resolve list. 4230 if (specifics != null) { 4231 for (int i=0; i<specifics.length; i++) { 4232 final Intent sintent = specifics[i]; 4233 if (sintent == null) { 4234 continue; 4235 } 4236 4237 if (DEBUG_INTENT_MATCHING) { 4238 Log.v(TAG, "Specific #" + i + ": " + sintent); 4239 } 4240 4241 String action = sintent.getAction(); 4242 if (resultsAction != null && resultsAction.equals(action)) { 4243 // If this action was explicitly requested, then don't 4244 // remove things that have it. 4245 action = null; 4246 } 4247 4248 ResolveInfo ri = null; 4249 ActivityInfo ai = null; 4250 4251 ComponentName comp = sintent.getComponent(); 4252 if (comp == null) { 4253 ri = resolveIntent( 4254 sintent, 4255 specificTypes != null ? specificTypes[i] : null, 4256 flags, userId); 4257 if (ri == null) { 4258 continue; 4259 } 4260 if (ri == mResolveInfo) { 4261 // ACK! Must do something better with this. 4262 } 4263 ai = ri.activityInfo; 4264 comp = new ComponentName(ai.applicationInfo.packageName, 4265 ai.name); 4266 } else { 4267 ai = getActivityInfo(comp, flags, userId); 4268 if (ai == null) { 4269 continue; 4270 } 4271 } 4272 4273 // Look for any generic query activities that are duplicates 4274 // of this specific one, and remove them from the results. 4275 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4276 N = results.size(); 4277 int j; 4278 for (j=specificsPos; j<N; j++) { 4279 ResolveInfo sri = results.get(j); 4280 if ((sri.activityInfo.name.equals(comp.getClassName()) 4281 && sri.activityInfo.applicationInfo.packageName.equals( 4282 comp.getPackageName())) 4283 || (action != null && sri.filter.matchAction(action))) { 4284 results.remove(j); 4285 if (DEBUG_INTENT_MATCHING) Log.v( 4286 TAG, "Removing duplicate item from " + j 4287 + " due to specific " + specificsPos); 4288 if (ri == null) { 4289 ri = sri; 4290 } 4291 j--; 4292 N--; 4293 } 4294 } 4295 4296 // Add this specific item to its proper place. 4297 if (ri == null) { 4298 ri = new ResolveInfo(); 4299 ri.activityInfo = ai; 4300 } 4301 results.add(specificsPos, ri); 4302 ri.specificIndex = i; 4303 specificsPos++; 4304 } 4305 } 4306 4307 // Now we go through the remaining generic results and remove any 4308 // duplicate actions that are found here. 4309 N = results.size(); 4310 for (int i=specificsPos; i<N-1; i++) { 4311 final ResolveInfo rii = results.get(i); 4312 if (rii.filter == null) { 4313 continue; 4314 } 4315 4316 // Iterate over all of the actions of this result's intent 4317 // filter... typically this should be just one. 4318 final Iterator<String> it = rii.filter.actionsIterator(); 4319 if (it == null) { 4320 continue; 4321 } 4322 while (it.hasNext()) { 4323 final String action = it.next(); 4324 if (resultsAction != null && resultsAction.equals(action)) { 4325 // If this action was explicitly requested, then don't 4326 // remove things that have it. 4327 continue; 4328 } 4329 for (int j=i+1; j<N; j++) { 4330 final ResolveInfo rij = results.get(j); 4331 if (rij.filter != null && rij.filter.hasAction(action)) { 4332 results.remove(j); 4333 if (DEBUG_INTENT_MATCHING) Log.v( 4334 TAG, "Removing duplicate item from " + j 4335 + " due to action " + action + " at " + i); 4336 j--; 4337 N--; 4338 } 4339 } 4340 } 4341 4342 // If the caller didn't request filter information, drop it now 4343 // so we don't have to marshall/unmarshall it. 4344 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4345 rii.filter = null; 4346 } 4347 } 4348 4349 // Filter out the caller activity if so requested. 4350 if (caller != null) { 4351 N = results.size(); 4352 for (int i=0; i<N; i++) { 4353 ActivityInfo ainfo = results.get(i).activityInfo; 4354 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4355 && caller.getClassName().equals(ainfo.name)) { 4356 results.remove(i); 4357 break; 4358 } 4359 } 4360 } 4361 4362 // If the caller didn't request filter information, 4363 // drop them now so we don't have to 4364 // marshall/unmarshall it. 4365 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4366 N = results.size(); 4367 for (int i=0; i<N; i++) { 4368 results.get(i).filter = null; 4369 } 4370 } 4371 4372 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4373 return results; 4374 } 4375 4376 @Override 4377 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4378 int userId) { 4379 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4380 ComponentName comp = intent.getComponent(); 4381 if (comp == null) { 4382 if (intent.getSelector() != null) { 4383 intent = intent.getSelector(); 4384 comp = intent.getComponent(); 4385 } 4386 } 4387 if (comp != null) { 4388 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4389 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4390 if (ai != null) { 4391 ResolveInfo ri = new ResolveInfo(); 4392 ri.activityInfo = ai; 4393 list.add(ri); 4394 } 4395 return list; 4396 } 4397 4398 // reader 4399 synchronized (mPackages) { 4400 String pkgName = intent.getPackage(); 4401 if (pkgName == null) { 4402 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4403 } 4404 final PackageParser.Package pkg = mPackages.get(pkgName); 4405 if (pkg != null) { 4406 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4407 userId); 4408 } 4409 return null; 4410 } 4411 } 4412 4413 @Override 4414 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4415 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4416 if (!sUserManager.exists(userId)) return null; 4417 if (query != null) { 4418 if (query.size() >= 1) { 4419 // If there is more than one service with the same priority, 4420 // just arbitrarily pick the first one. 4421 return query.get(0); 4422 } 4423 } 4424 return null; 4425 } 4426 4427 @Override 4428 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4429 int userId) { 4430 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4431 ComponentName comp = intent.getComponent(); 4432 if (comp == null) { 4433 if (intent.getSelector() != null) { 4434 intent = intent.getSelector(); 4435 comp = intent.getComponent(); 4436 } 4437 } 4438 if (comp != null) { 4439 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4440 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4441 if (si != null) { 4442 final ResolveInfo ri = new ResolveInfo(); 4443 ri.serviceInfo = si; 4444 list.add(ri); 4445 } 4446 return list; 4447 } 4448 4449 // reader 4450 synchronized (mPackages) { 4451 String pkgName = intent.getPackage(); 4452 if (pkgName == null) { 4453 return mServices.queryIntent(intent, resolvedType, flags, userId); 4454 } 4455 final PackageParser.Package pkg = mPackages.get(pkgName); 4456 if (pkg != null) { 4457 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4458 userId); 4459 } 4460 return null; 4461 } 4462 } 4463 4464 @Override 4465 public List<ResolveInfo> queryIntentContentProviders( 4466 Intent intent, String resolvedType, int flags, int userId) { 4467 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4468 ComponentName comp = intent.getComponent(); 4469 if (comp == null) { 4470 if (intent.getSelector() != null) { 4471 intent = intent.getSelector(); 4472 comp = intent.getComponent(); 4473 } 4474 } 4475 if (comp != null) { 4476 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4477 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4478 if (pi != null) { 4479 final ResolveInfo ri = new ResolveInfo(); 4480 ri.providerInfo = pi; 4481 list.add(ri); 4482 } 4483 return list; 4484 } 4485 4486 // reader 4487 synchronized (mPackages) { 4488 String pkgName = intent.getPackage(); 4489 if (pkgName == null) { 4490 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4491 } 4492 final PackageParser.Package pkg = mPackages.get(pkgName); 4493 if (pkg != null) { 4494 return mProviders.queryIntentForPackage( 4495 intent, resolvedType, flags, pkg.providers, userId); 4496 } 4497 return null; 4498 } 4499 } 4500 4501 @Override 4502 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4503 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4504 4505 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4506 4507 // writer 4508 synchronized (mPackages) { 4509 ArrayList<PackageInfo> list; 4510 if (listUninstalled) { 4511 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4512 for (PackageSetting ps : mSettings.mPackages.values()) { 4513 PackageInfo pi; 4514 if (ps.pkg != null) { 4515 pi = generatePackageInfo(ps.pkg, flags, userId); 4516 } else { 4517 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4518 } 4519 if (pi != null) { 4520 list.add(pi); 4521 } 4522 } 4523 } else { 4524 list = new ArrayList<PackageInfo>(mPackages.size()); 4525 for (PackageParser.Package p : mPackages.values()) { 4526 PackageInfo pi = generatePackageInfo(p, flags, userId); 4527 if (pi != null) { 4528 list.add(pi); 4529 } 4530 } 4531 } 4532 4533 return new ParceledListSlice<PackageInfo>(list); 4534 } 4535 } 4536 4537 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4538 String[] permissions, boolean[] tmp, int flags, int userId) { 4539 int numMatch = 0; 4540 final PermissionsState permissionsState = ps.getPermissionsState(); 4541 for (int i=0; i<permissions.length; i++) { 4542 final String permission = permissions[i]; 4543 if (permissionsState.hasPermission(permission, userId)) { 4544 tmp[i] = true; 4545 numMatch++; 4546 } else { 4547 tmp[i] = false; 4548 } 4549 } 4550 if (numMatch == 0) { 4551 return; 4552 } 4553 PackageInfo pi; 4554 if (ps.pkg != null) { 4555 pi = generatePackageInfo(ps.pkg, flags, userId); 4556 } else { 4557 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4558 } 4559 // The above might return null in cases of uninstalled apps or install-state 4560 // skew across users/profiles. 4561 if (pi != null) { 4562 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4563 if (numMatch == permissions.length) { 4564 pi.requestedPermissions = permissions; 4565 } else { 4566 pi.requestedPermissions = new String[numMatch]; 4567 numMatch = 0; 4568 for (int i=0; i<permissions.length; i++) { 4569 if (tmp[i]) { 4570 pi.requestedPermissions[numMatch] = permissions[i]; 4571 numMatch++; 4572 } 4573 } 4574 } 4575 } 4576 list.add(pi); 4577 } 4578 } 4579 4580 @Override 4581 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4582 String[] permissions, int flags, int userId) { 4583 if (!sUserManager.exists(userId)) return null; 4584 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4585 4586 // writer 4587 synchronized (mPackages) { 4588 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4589 boolean[] tmpBools = new boolean[permissions.length]; 4590 if (listUninstalled) { 4591 for (PackageSetting ps : mSettings.mPackages.values()) { 4592 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4593 } 4594 } else { 4595 for (PackageParser.Package pkg : mPackages.values()) { 4596 PackageSetting ps = (PackageSetting)pkg.mExtras; 4597 if (ps != null) { 4598 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4599 userId); 4600 } 4601 } 4602 } 4603 4604 return new ParceledListSlice<PackageInfo>(list); 4605 } 4606 } 4607 4608 @Override 4609 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4610 if (!sUserManager.exists(userId)) return null; 4611 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4612 4613 // writer 4614 synchronized (mPackages) { 4615 ArrayList<ApplicationInfo> list; 4616 if (listUninstalled) { 4617 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4618 for (PackageSetting ps : mSettings.mPackages.values()) { 4619 ApplicationInfo ai; 4620 if (ps.pkg != null) { 4621 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4622 ps.readUserState(userId), userId); 4623 } else { 4624 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4625 } 4626 if (ai != null) { 4627 list.add(ai); 4628 } 4629 } 4630 } else { 4631 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4632 for (PackageParser.Package p : mPackages.values()) { 4633 if (p.mExtras != null) { 4634 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4635 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4636 if (ai != null) { 4637 list.add(ai); 4638 } 4639 } 4640 } 4641 } 4642 4643 return new ParceledListSlice<ApplicationInfo>(list); 4644 } 4645 } 4646 4647 public List<ApplicationInfo> getPersistentApplications(int flags) { 4648 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4649 4650 // reader 4651 synchronized (mPackages) { 4652 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4653 final int userId = UserHandle.getCallingUserId(); 4654 while (i.hasNext()) { 4655 final PackageParser.Package p = i.next(); 4656 if (p.applicationInfo != null 4657 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4658 && (!mSafeMode || isSystemApp(p))) { 4659 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4660 if (ps != null) { 4661 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4662 ps.readUserState(userId), userId); 4663 if (ai != null) { 4664 finalList.add(ai); 4665 } 4666 } 4667 } 4668 } 4669 } 4670 4671 return finalList; 4672 } 4673 4674 @Override 4675 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4676 if (!sUserManager.exists(userId)) return null; 4677 // reader 4678 synchronized (mPackages) { 4679 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4680 PackageSetting ps = provider != null 4681 ? mSettings.mPackages.get(provider.owner.packageName) 4682 : null; 4683 return ps != null 4684 && mSettings.isEnabledLPr(provider.info, flags, userId) 4685 && (!mSafeMode || (provider.info.applicationInfo.flags 4686 &ApplicationInfo.FLAG_SYSTEM) != 0) 4687 ? PackageParser.generateProviderInfo(provider, flags, 4688 ps.readUserState(userId), userId) 4689 : null; 4690 } 4691 } 4692 4693 /** 4694 * @deprecated 4695 */ 4696 @Deprecated 4697 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4698 // reader 4699 synchronized (mPackages) { 4700 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4701 .entrySet().iterator(); 4702 final int userId = UserHandle.getCallingUserId(); 4703 while (i.hasNext()) { 4704 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4705 PackageParser.Provider p = entry.getValue(); 4706 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4707 4708 if (ps != null && p.syncable 4709 && (!mSafeMode || (p.info.applicationInfo.flags 4710 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4711 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4712 ps.readUserState(userId), userId); 4713 if (info != null) { 4714 outNames.add(entry.getKey()); 4715 outInfo.add(info); 4716 } 4717 } 4718 } 4719 } 4720 } 4721 4722 @Override 4723 public List<ProviderInfo> queryContentProviders(String processName, 4724 int uid, int flags) { 4725 ArrayList<ProviderInfo> finalList = null; 4726 // reader 4727 synchronized (mPackages) { 4728 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4729 final int userId = processName != null ? 4730 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4731 while (i.hasNext()) { 4732 final PackageParser.Provider p = i.next(); 4733 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4734 if (ps != null && p.info.authority != null 4735 && (processName == null 4736 || (p.info.processName.equals(processName) 4737 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4738 && mSettings.isEnabledLPr(p.info, flags, userId) 4739 && (!mSafeMode 4740 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4741 if (finalList == null) { 4742 finalList = new ArrayList<ProviderInfo>(3); 4743 } 4744 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4745 ps.readUserState(userId), userId); 4746 if (info != null) { 4747 finalList.add(info); 4748 } 4749 } 4750 } 4751 } 4752 4753 if (finalList != null) { 4754 Collections.sort(finalList, mProviderInitOrderSorter); 4755 } 4756 4757 return finalList; 4758 } 4759 4760 @Override 4761 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4762 int flags) { 4763 // reader 4764 synchronized (mPackages) { 4765 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4766 return PackageParser.generateInstrumentationInfo(i, flags); 4767 } 4768 } 4769 4770 @Override 4771 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4772 int flags) { 4773 ArrayList<InstrumentationInfo> finalList = 4774 new ArrayList<InstrumentationInfo>(); 4775 4776 // reader 4777 synchronized (mPackages) { 4778 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4779 while (i.hasNext()) { 4780 final PackageParser.Instrumentation p = i.next(); 4781 if (targetPackage == null 4782 || targetPackage.equals(p.info.targetPackage)) { 4783 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4784 flags); 4785 if (ii != null) { 4786 finalList.add(ii); 4787 } 4788 } 4789 } 4790 } 4791 4792 return finalList; 4793 } 4794 4795 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4796 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4797 if (overlays == null) { 4798 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4799 return; 4800 } 4801 for (PackageParser.Package opkg : overlays.values()) { 4802 // Not much to do if idmap fails: we already logged the error 4803 // and we certainly don't want to abort installation of pkg simply 4804 // because an overlay didn't fit properly. For these reasons, 4805 // ignore the return value of createIdmapForPackagePairLI. 4806 createIdmapForPackagePairLI(pkg, opkg); 4807 } 4808 } 4809 4810 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4811 PackageParser.Package opkg) { 4812 if (!opkg.mTrustedOverlay) { 4813 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4814 opkg.baseCodePath + ": overlay not trusted"); 4815 return false; 4816 } 4817 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4818 if (overlaySet == null) { 4819 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4820 opkg.baseCodePath + " but target package has no known overlays"); 4821 return false; 4822 } 4823 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4824 // TODO: generate idmap for split APKs 4825 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4826 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4827 + opkg.baseCodePath); 4828 return false; 4829 } 4830 PackageParser.Package[] overlayArray = 4831 overlaySet.values().toArray(new PackageParser.Package[0]); 4832 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4833 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4834 return p1.mOverlayPriority - p2.mOverlayPriority; 4835 } 4836 }; 4837 Arrays.sort(overlayArray, cmp); 4838 4839 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4840 int i = 0; 4841 for (PackageParser.Package p : overlayArray) { 4842 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4843 } 4844 return true; 4845 } 4846 4847 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4848 final File[] files = dir.listFiles(); 4849 if (ArrayUtils.isEmpty(files)) { 4850 Log.d(TAG, "No files in app dir " + dir); 4851 return; 4852 } 4853 4854 if (DEBUG_PACKAGE_SCANNING) { 4855 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4856 + " flags=0x" + Integer.toHexString(parseFlags)); 4857 } 4858 4859 for (File file : files) { 4860 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4861 && !PackageInstallerService.isStageName(file.getName()); 4862 if (!isPackage) { 4863 // Ignore entries which are not packages 4864 continue; 4865 } 4866 try { 4867 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4868 scanFlags, currentTime, null); 4869 } catch (PackageManagerException e) { 4870 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4871 4872 // Delete invalid userdata apps 4873 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4874 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4875 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4876 if (file.isDirectory()) { 4877 mInstaller.rmPackageDir(file.getAbsolutePath()); 4878 } else { 4879 file.delete(); 4880 } 4881 } 4882 } 4883 } 4884 } 4885 4886 private static File getSettingsProblemFile() { 4887 File dataDir = Environment.getDataDirectory(); 4888 File systemDir = new File(dataDir, "system"); 4889 File fname = new File(systemDir, "uiderrors.txt"); 4890 return fname; 4891 } 4892 4893 static void reportSettingsProblem(int priority, String msg) { 4894 logCriticalInfo(priority, msg); 4895 } 4896 4897 static void logCriticalInfo(int priority, String msg) { 4898 Slog.println(priority, TAG, msg); 4899 EventLogTags.writePmCriticalInfo(msg); 4900 try { 4901 File fname = getSettingsProblemFile(); 4902 FileOutputStream out = new FileOutputStream(fname, true); 4903 PrintWriter pw = new FastPrintWriter(out); 4904 SimpleDateFormat formatter = new SimpleDateFormat(); 4905 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4906 pw.println(dateString + ": " + msg); 4907 pw.close(); 4908 FileUtils.setPermissions( 4909 fname.toString(), 4910 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4911 -1, -1); 4912 } catch (java.io.IOException e) { 4913 } 4914 } 4915 4916 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4917 PackageParser.Package pkg, File srcFile, int parseFlags) 4918 throws PackageManagerException { 4919 if (ps != null 4920 && ps.codePath.equals(srcFile) 4921 && ps.timeStamp == srcFile.lastModified() 4922 && !isCompatSignatureUpdateNeeded(pkg) 4923 && !isRecoverSignatureUpdateNeeded(pkg)) { 4924 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4925 if (ps.signatures.mSignatures != null 4926 && ps.signatures.mSignatures.length != 0 4927 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4928 // Optimization: reuse the existing cached certificates 4929 // if the package appears to be unchanged. 4930 pkg.mSignatures = ps.signatures.mSignatures; 4931 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4932 synchronized (mPackages) { 4933 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4934 } 4935 return; 4936 } 4937 4938 Slog.w(TAG, "PackageSetting for " + ps.name 4939 + " is missing signatures. Collecting certs again to recover them."); 4940 } else { 4941 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4942 } 4943 4944 try { 4945 pp.collectCertificates(pkg, parseFlags); 4946 pp.collectManifestDigest(pkg); 4947 } catch (PackageParserException e) { 4948 throw PackageManagerException.from(e); 4949 } 4950 } 4951 4952 /* 4953 * Scan a package and return the newly parsed package. 4954 * Returns null in case of errors and the error code is stored in mLastScanError 4955 */ 4956 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4957 long currentTime, UserHandle user) throws PackageManagerException { 4958 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4959 parseFlags |= mDefParseFlags; 4960 PackageParser pp = new PackageParser(); 4961 pp.setSeparateProcesses(mSeparateProcesses); 4962 pp.setOnlyCoreApps(mOnlyCore); 4963 pp.setDisplayMetrics(mMetrics); 4964 4965 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4966 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4967 } 4968 4969 final PackageParser.Package pkg; 4970 try { 4971 pkg = pp.parsePackage(scanFile, parseFlags); 4972 } catch (PackageParserException e) { 4973 throw PackageManagerException.from(e); 4974 } 4975 4976 PackageSetting ps = null; 4977 PackageSetting updatedPkg; 4978 // reader 4979 synchronized (mPackages) { 4980 // Look to see if we already know about this package. 4981 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4982 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4983 // This package has been renamed to its original name. Let's 4984 // use that. 4985 ps = mSettings.peekPackageLPr(oldName); 4986 } 4987 // If there was no original package, see one for the real package name. 4988 if (ps == null) { 4989 ps = mSettings.peekPackageLPr(pkg.packageName); 4990 } 4991 // Check to see if this package could be hiding/updating a system 4992 // package. Must look for it either under the original or real 4993 // package name depending on our state. 4994 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4995 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4996 } 4997 boolean updatedPkgBetter = false; 4998 // First check if this is a system package that may involve an update 4999 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5000 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5001 // it needs to drop FLAG_PRIVILEGED. 5002 if (locationIsPrivileged(scanFile)) { 5003 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5004 } else { 5005 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5006 } 5007 5008 if (ps != null && !ps.codePath.equals(scanFile)) { 5009 // The path has changed from what was last scanned... check the 5010 // version of the new path against what we have stored to determine 5011 // what to do. 5012 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5013 if (pkg.mVersionCode <= ps.versionCode) { 5014 // The system package has been updated and the code path does not match 5015 // Ignore entry. Skip it. 5016 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5017 + " ignored: updated version " + ps.versionCode 5018 + " better than this " + pkg.mVersionCode); 5019 if (!updatedPkg.codePath.equals(scanFile)) { 5020 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5021 + ps.name + " changing from " + updatedPkg.codePathString 5022 + " to " + scanFile); 5023 updatedPkg.codePath = scanFile; 5024 updatedPkg.codePathString = scanFile.toString(); 5025 updatedPkg.resourcePath = scanFile; 5026 updatedPkg.resourcePathString = scanFile.toString(); 5027 } 5028 updatedPkg.pkg = pkg; 5029 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5030 } else { 5031 // The current app on the system partition is better than 5032 // what we have updated to on the data partition; switch 5033 // back to the system partition version. 5034 // At this point, its safely assumed that package installation for 5035 // apps in system partition will go through. If not there won't be a working 5036 // version of the app 5037 // writer 5038 synchronized (mPackages) { 5039 // Just remove the loaded entries from package lists. 5040 mPackages.remove(ps.name); 5041 } 5042 5043 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5044 + " reverting from " + ps.codePathString 5045 + ": new version " + pkg.mVersionCode 5046 + " better than installed " + ps.versionCode); 5047 5048 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5049 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5050 synchronized (mInstallLock) { 5051 args.cleanUpResourcesLI(); 5052 } 5053 synchronized (mPackages) { 5054 mSettings.enableSystemPackageLPw(ps.name); 5055 } 5056 updatedPkgBetter = true; 5057 } 5058 } 5059 } 5060 5061 if (updatedPkg != null) { 5062 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5063 // initially 5064 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5065 5066 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5067 // flag set initially 5068 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5069 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5070 } 5071 } 5072 5073 // Verify certificates against what was last scanned 5074 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5075 5076 /* 5077 * A new system app appeared, but we already had a non-system one of the 5078 * same name installed earlier. 5079 */ 5080 boolean shouldHideSystemApp = false; 5081 if (updatedPkg == null && ps != null 5082 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5083 /* 5084 * Check to make sure the signatures match first. If they don't, 5085 * wipe the installed application and its data. 5086 */ 5087 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5088 != PackageManager.SIGNATURE_MATCH) { 5089 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5090 + " signatures don't match existing userdata copy; removing"); 5091 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5092 ps = null; 5093 } else { 5094 /* 5095 * If the newly-added system app is an older version than the 5096 * already installed version, hide it. It will be scanned later 5097 * and re-added like an update. 5098 */ 5099 if (pkg.mVersionCode <= ps.versionCode) { 5100 shouldHideSystemApp = true; 5101 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5102 + " but new version " + pkg.mVersionCode + " better than installed " 5103 + ps.versionCode + "; hiding system"); 5104 } else { 5105 /* 5106 * The newly found system app is a newer version that the 5107 * one previously installed. Simply remove the 5108 * already-installed application and replace it with our own 5109 * while keeping the application data. 5110 */ 5111 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5112 + " reverting from " + ps.codePathString + ": new version " 5113 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5114 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5115 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5116 synchronized (mInstallLock) { 5117 args.cleanUpResourcesLI(); 5118 } 5119 } 5120 } 5121 } 5122 5123 // The apk is forward locked (not public) if its code and resources 5124 // are kept in different files. (except for app in either system or 5125 // vendor path). 5126 // TODO grab this value from PackageSettings 5127 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5128 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5129 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5130 } 5131 } 5132 5133 // TODO: extend to support forward-locked splits 5134 String resourcePath = null; 5135 String baseResourcePath = null; 5136 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5137 if (ps != null && ps.resourcePathString != null) { 5138 resourcePath = ps.resourcePathString; 5139 baseResourcePath = ps.resourcePathString; 5140 } else { 5141 // Should not happen at all. Just log an error. 5142 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5143 } 5144 } else { 5145 resourcePath = pkg.codePath; 5146 baseResourcePath = pkg.baseCodePath; 5147 } 5148 5149 // Set application objects path explicitly. 5150 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5151 pkg.applicationInfo.setCodePath(pkg.codePath); 5152 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5153 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5154 pkg.applicationInfo.setResourcePath(resourcePath); 5155 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5156 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5157 5158 // Note that we invoke the following method only if we are about to unpack an application 5159 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5160 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5161 5162 /* 5163 * If the system app should be overridden by a previously installed 5164 * data, hide the system app now and let the /data/app scan pick it up 5165 * again. 5166 */ 5167 if (shouldHideSystemApp) { 5168 synchronized (mPackages) { 5169 /* 5170 * We have to grant systems permissions before we hide, because 5171 * grantPermissions will assume the package update is trying to 5172 * expand its permissions. 5173 */ 5174 grantPermissionsLPw(pkg, true, pkg.packageName); 5175 mSettings.disableSystemPackageLPw(pkg.packageName); 5176 } 5177 } 5178 5179 return scannedPkg; 5180 } 5181 5182 private static String fixProcessName(String defProcessName, 5183 String processName, int uid) { 5184 if (processName == null) { 5185 return defProcessName; 5186 } 5187 return processName; 5188 } 5189 5190 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5191 throws PackageManagerException { 5192 if (pkgSetting.signatures.mSignatures != null) { 5193 // Already existing package. Make sure signatures match 5194 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5195 == PackageManager.SIGNATURE_MATCH; 5196 if (!match) { 5197 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5198 == PackageManager.SIGNATURE_MATCH; 5199 } 5200 if (!match) { 5201 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5202 == PackageManager.SIGNATURE_MATCH; 5203 } 5204 if (!match) { 5205 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5206 + pkg.packageName + " signatures do not match the " 5207 + "previously installed version; ignoring!"); 5208 } 5209 } 5210 5211 // Check for shared user signatures 5212 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5213 // Already existing package. Make sure signatures match 5214 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5215 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5216 if (!match) { 5217 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5218 == PackageManager.SIGNATURE_MATCH; 5219 } 5220 if (!match) { 5221 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5222 == PackageManager.SIGNATURE_MATCH; 5223 } 5224 if (!match) { 5225 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5226 "Package " + pkg.packageName 5227 + " has no signatures that match those in shared user " 5228 + pkgSetting.sharedUser.name + "; ignoring!"); 5229 } 5230 } 5231 } 5232 5233 /** 5234 * Enforces that only the system UID or root's UID can call a method exposed 5235 * via Binder. 5236 * 5237 * @param message used as message if SecurityException is thrown 5238 * @throws SecurityException if the caller is not system or root 5239 */ 5240 private static final void enforceSystemOrRoot(String message) { 5241 final int uid = Binder.getCallingUid(); 5242 if (uid != Process.SYSTEM_UID && uid != 0) { 5243 throw new SecurityException(message); 5244 } 5245 } 5246 5247 @Override 5248 public void performBootDexOpt() { 5249 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5250 5251 // Before everything else, see whether we need to fstrim. 5252 try { 5253 IMountService ms = PackageHelper.getMountService(); 5254 if (ms != null) { 5255 final boolean isUpgrade = isUpgrade(); 5256 boolean doTrim = isUpgrade; 5257 if (doTrim) { 5258 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5259 } else { 5260 final long interval = android.provider.Settings.Global.getLong( 5261 mContext.getContentResolver(), 5262 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5263 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5264 if (interval > 0) { 5265 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5266 if (timeSinceLast > interval) { 5267 doTrim = true; 5268 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5269 + "; running immediately"); 5270 } 5271 } 5272 } 5273 if (doTrim) { 5274 if (!isFirstBoot()) { 5275 try { 5276 ActivityManagerNative.getDefault().showBootMessage( 5277 mContext.getResources().getString( 5278 R.string.android_upgrading_fstrim), true); 5279 } catch (RemoteException e) { 5280 } 5281 } 5282 ms.runMaintenance(); 5283 } 5284 } else { 5285 Slog.e(TAG, "Mount service unavailable!"); 5286 } 5287 } catch (RemoteException e) { 5288 // Can't happen; MountService is local 5289 } 5290 5291 final ArraySet<PackageParser.Package> pkgs; 5292 synchronized (mPackages) { 5293 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5294 } 5295 5296 if (pkgs != null) { 5297 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5298 // in case the device runs out of space. 5299 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5300 // Give priority to core apps. 5301 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5302 PackageParser.Package pkg = it.next(); 5303 if (pkg.coreApp) { 5304 if (DEBUG_DEXOPT) { 5305 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5306 } 5307 sortedPkgs.add(pkg); 5308 it.remove(); 5309 } 5310 } 5311 // Give priority to system apps that listen for pre boot complete. 5312 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5313 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5314 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5315 PackageParser.Package pkg = it.next(); 5316 if (pkgNames.contains(pkg.packageName)) { 5317 if (DEBUG_DEXOPT) { 5318 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5319 } 5320 sortedPkgs.add(pkg); 5321 it.remove(); 5322 } 5323 } 5324 // Give priority to system apps. 5325 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5326 PackageParser.Package pkg = it.next(); 5327 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5328 if (DEBUG_DEXOPT) { 5329 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5330 } 5331 sortedPkgs.add(pkg); 5332 it.remove(); 5333 } 5334 } 5335 // Give priority to updated system apps. 5336 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5337 PackageParser.Package pkg = it.next(); 5338 if (pkg.isUpdatedSystemApp()) { 5339 if (DEBUG_DEXOPT) { 5340 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5341 } 5342 sortedPkgs.add(pkg); 5343 it.remove(); 5344 } 5345 } 5346 // Give priority to apps that listen for boot complete. 5347 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5348 pkgNames = getPackageNamesForIntent(intent); 5349 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5350 PackageParser.Package pkg = it.next(); 5351 if (pkgNames.contains(pkg.packageName)) { 5352 if (DEBUG_DEXOPT) { 5353 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5354 } 5355 sortedPkgs.add(pkg); 5356 it.remove(); 5357 } 5358 } 5359 // Filter out packages that aren't recently used. 5360 filterRecentlyUsedApps(pkgs); 5361 // Add all remaining apps. 5362 for (PackageParser.Package pkg : pkgs) { 5363 if (DEBUG_DEXOPT) { 5364 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5365 } 5366 sortedPkgs.add(pkg); 5367 } 5368 5369 // If we want to be lazy, filter everything that wasn't recently used. 5370 if (mLazyDexOpt) { 5371 filterRecentlyUsedApps(sortedPkgs); 5372 } 5373 5374 int i = 0; 5375 int total = sortedPkgs.size(); 5376 File dataDir = Environment.getDataDirectory(); 5377 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5378 if (lowThreshold == 0) { 5379 throw new IllegalStateException("Invalid low memory threshold"); 5380 } 5381 for (PackageParser.Package pkg : sortedPkgs) { 5382 long usableSpace = dataDir.getUsableSpace(); 5383 if (usableSpace < lowThreshold) { 5384 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5385 break; 5386 } 5387 performBootDexOpt(pkg, ++i, total); 5388 } 5389 } 5390 } 5391 5392 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5393 // Filter out packages that aren't recently used. 5394 // 5395 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5396 // should do a full dexopt. 5397 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5398 int total = pkgs.size(); 5399 int skipped = 0; 5400 long now = System.currentTimeMillis(); 5401 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5402 PackageParser.Package pkg = i.next(); 5403 long then = pkg.mLastPackageUsageTimeInMills; 5404 if (then + mDexOptLRUThresholdInMills < now) { 5405 if (DEBUG_DEXOPT) { 5406 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5407 ((then == 0) ? "never" : new Date(then))); 5408 } 5409 i.remove(); 5410 skipped++; 5411 } 5412 } 5413 if (DEBUG_DEXOPT) { 5414 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5415 } 5416 } 5417 } 5418 5419 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5420 List<ResolveInfo> ris = null; 5421 try { 5422 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5423 intent, null, 0, UserHandle.USER_OWNER); 5424 } catch (RemoteException e) { 5425 } 5426 ArraySet<String> pkgNames = new ArraySet<String>(); 5427 if (ris != null) { 5428 for (ResolveInfo ri : ris) { 5429 pkgNames.add(ri.activityInfo.packageName); 5430 } 5431 } 5432 return pkgNames; 5433 } 5434 5435 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5436 if (DEBUG_DEXOPT) { 5437 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5438 } 5439 if (!isFirstBoot()) { 5440 try { 5441 ActivityManagerNative.getDefault().showBootMessage( 5442 mContext.getResources().getString(R.string.android_upgrading_apk, 5443 curr, total), true); 5444 } catch (RemoteException e) { 5445 } 5446 } 5447 PackageParser.Package p = pkg; 5448 synchronized (mInstallLock) { 5449 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5450 false /* force dex */, false /* defer */, true /* include dependencies */); 5451 } 5452 } 5453 5454 @Override 5455 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5456 return performDexOpt(packageName, instructionSet, false); 5457 } 5458 5459 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5460 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5461 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5462 if (!dexopt && !updateUsage) { 5463 // We aren't going to dexopt or update usage, so bail early. 5464 return false; 5465 } 5466 PackageParser.Package p; 5467 final String targetInstructionSet; 5468 synchronized (mPackages) { 5469 p = mPackages.get(packageName); 5470 if (p == null) { 5471 return false; 5472 } 5473 if (updateUsage) { 5474 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5475 } 5476 mPackageUsage.write(false); 5477 if (!dexopt) { 5478 // We aren't going to dexopt, so bail early. 5479 return false; 5480 } 5481 5482 targetInstructionSet = instructionSet != null ? instructionSet : 5483 getPrimaryInstructionSet(p.applicationInfo); 5484 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5485 return false; 5486 } 5487 } 5488 5489 synchronized (mInstallLock) { 5490 final String[] instructionSets = new String[] { targetInstructionSet }; 5491 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5492 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5493 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5494 } 5495 } 5496 5497 public ArraySet<String> getPackagesThatNeedDexOpt() { 5498 ArraySet<String> pkgs = null; 5499 synchronized (mPackages) { 5500 for (PackageParser.Package p : mPackages.values()) { 5501 if (DEBUG_DEXOPT) { 5502 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5503 } 5504 if (!p.mDexOptPerformed.isEmpty()) { 5505 continue; 5506 } 5507 if (pkgs == null) { 5508 pkgs = new ArraySet<String>(); 5509 } 5510 pkgs.add(p.packageName); 5511 } 5512 } 5513 return pkgs; 5514 } 5515 5516 public void shutdown() { 5517 mPackageUsage.write(true); 5518 } 5519 5520 @Override 5521 public void forceDexOpt(String packageName) { 5522 enforceSystemOrRoot("forceDexOpt"); 5523 5524 PackageParser.Package pkg; 5525 synchronized (mPackages) { 5526 pkg = mPackages.get(packageName); 5527 if (pkg == null) { 5528 throw new IllegalArgumentException("Missing package: " + packageName); 5529 } 5530 } 5531 5532 synchronized (mInstallLock) { 5533 final String[] instructionSets = new String[] { 5534 getPrimaryInstructionSet(pkg.applicationInfo) }; 5535 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5536 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5537 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5538 throw new IllegalStateException("Failed to dexopt: " + res); 5539 } 5540 } 5541 } 5542 5543 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5544 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5545 Slog.w(TAG, "Unable to update from " + oldPkg.name 5546 + " to " + newPkg.packageName 5547 + ": old package not in system partition"); 5548 return false; 5549 } else if (mPackages.get(oldPkg.name) != null) { 5550 Slog.w(TAG, "Unable to update from " + oldPkg.name 5551 + " to " + newPkg.packageName 5552 + ": old package still exists"); 5553 return false; 5554 } 5555 return true; 5556 } 5557 5558 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5559 int[] users = sUserManager.getUserIds(); 5560 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5561 if (res < 0) { 5562 return res; 5563 } 5564 for (int user : users) { 5565 if (user != 0) { 5566 res = mInstaller.createUserData(volumeUuid, packageName, 5567 UserHandle.getUid(user, uid), user, seinfo); 5568 if (res < 0) { 5569 return res; 5570 } 5571 } 5572 } 5573 return res; 5574 } 5575 5576 private int removeDataDirsLI(String volumeUuid, String packageName) { 5577 int[] users = sUserManager.getUserIds(); 5578 int res = 0; 5579 for (int user : users) { 5580 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5581 if (resInner < 0) { 5582 res = resInner; 5583 } 5584 } 5585 5586 return res; 5587 } 5588 5589 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5590 int[] users = sUserManager.getUserIds(); 5591 int res = 0; 5592 for (int user : users) { 5593 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5594 if (resInner < 0) { 5595 res = resInner; 5596 } 5597 } 5598 return res; 5599 } 5600 5601 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5602 PackageParser.Package changingLib) { 5603 if (file.path != null) { 5604 usesLibraryFiles.add(file.path); 5605 return; 5606 } 5607 PackageParser.Package p = mPackages.get(file.apk); 5608 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5609 // If we are doing this while in the middle of updating a library apk, 5610 // then we need to make sure to use that new apk for determining the 5611 // dependencies here. (We haven't yet finished committing the new apk 5612 // to the package manager state.) 5613 if (p == null || p.packageName.equals(changingLib.packageName)) { 5614 p = changingLib; 5615 } 5616 } 5617 if (p != null) { 5618 usesLibraryFiles.addAll(p.getAllCodePaths()); 5619 } 5620 } 5621 5622 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5623 PackageParser.Package changingLib) throws PackageManagerException { 5624 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5625 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5626 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5627 for (int i=0; i<N; i++) { 5628 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5629 if (file == null) { 5630 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5631 "Package " + pkg.packageName + " requires unavailable shared library " 5632 + pkg.usesLibraries.get(i) + "; failing!"); 5633 } 5634 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5635 } 5636 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5637 for (int i=0; i<N; i++) { 5638 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5639 if (file == null) { 5640 Slog.w(TAG, "Package " + pkg.packageName 5641 + " desires unavailable shared library " 5642 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5643 } else { 5644 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5645 } 5646 } 5647 N = usesLibraryFiles.size(); 5648 if (N > 0) { 5649 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5650 } else { 5651 pkg.usesLibraryFiles = null; 5652 } 5653 } 5654 } 5655 5656 private static boolean hasString(List<String> list, List<String> which) { 5657 if (list == null) { 5658 return false; 5659 } 5660 for (int i=list.size()-1; i>=0; i--) { 5661 for (int j=which.size()-1; j>=0; j--) { 5662 if (which.get(j).equals(list.get(i))) { 5663 return true; 5664 } 5665 } 5666 } 5667 return false; 5668 } 5669 5670 private void updateAllSharedLibrariesLPw() { 5671 for (PackageParser.Package pkg : mPackages.values()) { 5672 try { 5673 updateSharedLibrariesLPw(pkg, null); 5674 } catch (PackageManagerException e) { 5675 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5676 } 5677 } 5678 } 5679 5680 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5681 PackageParser.Package changingPkg) { 5682 ArrayList<PackageParser.Package> res = null; 5683 for (PackageParser.Package pkg : mPackages.values()) { 5684 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5685 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5686 if (res == null) { 5687 res = new ArrayList<PackageParser.Package>(); 5688 } 5689 res.add(pkg); 5690 try { 5691 updateSharedLibrariesLPw(pkg, changingPkg); 5692 } catch (PackageManagerException e) { 5693 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5694 } 5695 } 5696 } 5697 return res; 5698 } 5699 5700 /** 5701 * Derive the value of the {@code cpuAbiOverride} based on the provided 5702 * value and an optional stored value from the package settings. 5703 */ 5704 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5705 String cpuAbiOverride = null; 5706 5707 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5708 cpuAbiOverride = null; 5709 } else if (abiOverride != null) { 5710 cpuAbiOverride = abiOverride; 5711 } else if (settings != null) { 5712 cpuAbiOverride = settings.cpuAbiOverrideString; 5713 } 5714 5715 return cpuAbiOverride; 5716 } 5717 5718 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5719 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5720 boolean success = false; 5721 try { 5722 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5723 currentTime, user); 5724 success = true; 5725 return res; 5726 } finally { 5727 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5728 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5729 } 5730 } 5731 } 5732 5733 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5734 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5735 final File scanFile = new File(pkg.codePath); 5736 if (pkg.applicationInfo.getCodePath() == null || 5737 pkg.applicationInfo.getResourcePath() == null) { 5738 // Bail out. The resource and code paths haven't been set. 5739 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5740 "Code and resource paths haven't been set correctly"); 5741 } 5742 5743 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5744 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5745 } else { 5746 // Only allow system apps to be flagged as core apps. 5747 pkg.coreApp = false; 5748 } 5749 5750 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5751 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5752 } 5753 5754 if (mCustomResolverComponentName != null && 5755 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5756 setUpCustomResolverActivity(pkg); 5757 } 5758 5759 if (pkg.packageName.equals("android")) { 5760 synchronized (mPackages) { 5761 if (mAndroidApplication != null) { 5762 Slog.w(TAG, "*************************************************"); 5763 Slog.w(TAG, "Core android package being redefined. Skipping."); 5764 Slog.w(TAG, " file=" + scanFile); 5765 Slog.w(TAG, "*************************************************"); 5766 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5767 "Core android package being redefined. Skipping."); 5768 } 5769 5770 // Set up information for our fall-back user intent resolution activity. 5771 mPlatformPackage = pkg; 5772 pkg.mVersionCode = mSdkVersion; 5773 mAndroidApplication = pkg.applicationInfo; 5774 5775 if (!mResolverReplaced) { 5776 mResolveActivity.applicationInfo = mAndroidApplication; 5777 mResolveActivity.name = ResolverActivity.class.getName(); 5778 mResolveActivity.packageName = mAndroidApplication.packageName; 5779 mResolveActivity.processName = "system:ui"; 5780 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5781 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5782 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5783 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5784 mResolveActivity.exported = true; 5785 mResolveActivity.enabled = true; 5786 mResolveInfo.activityInfo = mResolveActivity; 5787 mResolveInfo.priority = 0; 5788 mResolveInfo.preferredOrder = 0; 5789 mResolveInfo.match = 0; 5790 mResolveComponentName = new ComponentName( 5791 mAndroidApplication.packageName, mResolveActivity.name); 5792 } 5793 } 5794 } 5795 5796 if (DEBUG_PACKAGE_SCANNING) { 5797 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5798 Log.d(TAG, "Scanning package " + pkg.packageName); 5799 } 5800 5801 if (mPackages.containsKey(pkg.packageName) 5802 || mSharedLibraries.containsKey(pkg.packageName)) { 5803 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5804 "Application package " + pkg.packageName 5805 + " already installed. Skipping duplicate."); 5806 } 5807 5808 // If we're only installing presumed-existing packages, require that the 5809 // scanned APK is both already known and at the path previously established 5810 // for it. Previously unknown packages we pick up normally, but if we have an 5811 // a priori expectation about this package's install presence, enforce it. 5812 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5813 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5814 if (known != null) { 5815 if (DEBUG_PACKAGE_SCANNING) { 5816 Log.d(TAG, "Examining " + pkg.codePath 5817 + " and requiring known paths " + known.codePathString 5818 + " & " + known.resourcePathString); 5819 } 5820 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5821 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5822 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5823 "Application package " + pkg.packageName 5824 + " found at " + pkg.applicationInfo.getCodePath() 5825 + " but expected at " + known.codePathString + "; ignoring."); 5826 } 5827 } 5828 } 5829 5830 // Initialize package source and resource directories 5831 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5832 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5833 5834 SharedUserSetting suid = null; 5835 PackageSetting pkgSetting = null; 5836 5837 if (!isSystemApp(pkg)) { 5838 // Only system apps can use these features. 5839 pkg.mOriginalPackages = null; 5840 pkg.mRealPackage = null; 5841 pkg.mAdoptPermissions = null; 5842 } 5843 5844 // writer 5845 synchronized (mPackages) { 5846 if (pkg.mSharedUserId != null) { 5847 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5848 if (suid == null) { 5849 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5850 "Creating application package " + pkg.packageName 5851 + " for shared user failed"); 5852 } 5853 if (DEBUG_PACKAGE_SCANNING) { 5854 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5855 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5856 + "): packages=" + suid.packages); 5857 } 5858 } 5859 5860 // Check if we are renaming from an original package name. 5861 PackageSetting origPackage = null; 5862 String realName = null; 5863 if (pkg.mOriginalPackages != null) { 5864 // This package may need to be renamed to a previously 5865 // installed name. Let's check on that... 5866 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5867 if (pkg.mOriginalPackages.contains(renamed)) { 5868 // This package had originally been installed as the 5869 // original name, and we have already taken care of 5870 // transitioning to the new one. Just update the new 5871 // one to continue using the old name. 5872 realName = pkg.mRealPackage; 5873 if (!pkg.packageName.equals(renamed)) { 5874 // Callers into this function may have already taken 5875 // care of renaming the package; only do it here if 5876 // it is not already done. 5877 pkg.setPackageName(renamed); 5878 } 5879 5880 } else { 5881 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5882 if ((origPackage = mSettings.peekPackageLPr( 5883 pkg.mOriginalPackages.get(i))) != null) { 5884 // We do have the package already installed under its 5885 // original name... should we use it? 5886 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5887 // New package is not compatible with original. 5888 origPackage = null; 5889 continue; 5890 } else if (origPackage.sharedUser != null) { 5891 // Make sure uid is compatible between packages. 5892 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5893 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5894 + " to " + pkg.packageName + ": old uid " 5895 + origPackage.sharedUser.name 5896 + " differs from " + pkg.mSharedUserId); 5897 origPackage = null; 5898 continue; 5899 } 5900 } else { 5901 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5902 + pkg.packageName + " to old name " + origPackage.name); 5903 } 5904 break; 5905 } 5906 } 5907 } 5908 } 5909 5910 if (mTransferedPackages.contains(pkg.packageName)) { 5911 Slog.w(TAG, "Package " + pkg.packageName 5912 + " was transferred to another, but its .apk remains"); 5913 } 5914 5915 // Just create the setting, don't add it yet. For already existing packages 5916 // the PkgSetting exists already and doesn't have to be created. 5917 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5918 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5919 pkg.applicationInfo.primaryCpuAbi, 5920 pkg.applicationInfo.secondaryCpuAbi, 5921 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5922 user, false); 5923 if (pkgSetting == null) { 5924 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5925 "Creating application package " + pkg.packageName + " failed"); 5926 } 5927 5928 if (pkgSetting.origPackage != null) { 5929 // If we are first transitioning from an original package, 5930 // fix up the new package's name now. We need to do this after 5931 // looking up the package under its new name, so getPackageLP 5932 // can take care of fiddling things correctly. 5933 pkg.setPackageName(origPackage.name); 5934 5935 // File a report about this. 5936 String msg = "New package " + pkgSetting.realName 5937 + " renamed to replace old package " + pkgSetting.name; 5938 reportSettingsProblem(Log.WARN, msg); 5939 5940 // Make a note of it. 5941 mTransferedPackages.add(origPackage.name); 5942 5943 // No longer need to retain this. 5944 pkgSetting.origPackage = null; 5945 } 5946 5947 if (realName != null) { 5948 // Make a note of it. 5949 mTransferedPackages.add(pkg.packageName); 5950 } 5951 5952 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5954 } 5955 5956 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5957 // Check all shared libraries and map to their actual file path. 5958 // We only do this here for apps not on a system dir, because those 5959 // are the only ones that can fail an install due to this. We 5960 // will take care of the system apps by updating all of their 5961 // library paths after the scan is done. 5962 updateSharedLibrariesLPw(pkg, null); 5963 } 5964 5965 if (mFoundPolicyFile) { 5966 SELinuxMMAC.assignSeinfoValue(pkg); 5967 } 5968 5969 pkg.applicationInfo.uid = pkgSetting.appId; 5970 pkg.mExtras = pkgSetting; 5971 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5972 try { 5973 verifySignaturesLP(pkgSetting, pkg); 5974 // We just determined the app is signed correctly, so bring 5975 // over the latest parsed certs. 5976 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5977 } catch (PackageManagerException e) { 5978 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5979 throw e; 5980 } 5981 // The signature has changed, but this package is in the system 5982 // image... let's recover! 5983 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5984 // However... if this package is part of a shared user, but it 5985 // doesn't match the signature of the shared user, let's fail. 5986 // What this means is that you can't change the signatures 5987 // associated with an overall shared user, which doesn't seem all 5988 // that unreasonable. 5989 if (pkgSetting.sharedUser != null) { 5990 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5991 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5992 throw new PackageManagerException( 5993 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5994 "Signature mismatch for shared user : " 5995 + pkgSetting.sharedUser); 5996 } 5997 } 5998 // File a report about this. 5999 String msg = "System package " + pkg.packageName 6000 + " signature changed; retaining data."; 6001 reportSettingsProblem(Log.WARN, msg); 6002 } 6003 } else { 6004 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6005 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6006 + pkg.packageName + " upgrade keys do not match the " 6007 + "previously installed version"); 6008 } else { 6009 // We just determined the app is signed correctly, so bring 6010 // over the latest parsed certs. 6011 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6012 } 6013 } 6014 // Verify that this new package doesn't have any content providers 6015 // that conflict with existing packages. Only do this if the 6016 // package isn't already installed, since we don't want to break 6017 // things that are installed. 6018 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6019 final int N = pkg.providers.size(); 6020 int i; 6021 for (i=0; i<N; i++) { 6022 PackageParser.Provider p = pkg.providers.get(i); 6023 if (p.info.authority != null) { 6024 String names[] = p.info.authority.split(";"); 6025 for (int j = 0; j < names.length; j++) { 6026 if (mProvidersByAuthority.containsKey(names[j])) { 6027 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6028 final String otherPackageName = 6029 ((other != null && other.getComponentName() != null) ? 6030 other.getComponentName().getPackageName() : "?"); 6031 throw new PackageManagerException( 6032 INSTALL_FAILED_CONFLICTING_PROVIDER, 6033 "Can't install because provider name " + names[j] 6034 + " (in package " + pkg.applicationInfo.packageName 6035 + ") is already used by " + otherPackageName); 6036 } 6037 } 6038 } 6039 } 6040 } 6041 6042 if (pkg.mAdoptPermissions != null) { 6043 // This package wants to adopt ownership of permissions from 6044 // another package. 6045 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6046 final String origName = pkg.mAdoptPermissions.get(i); 6047 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6048 if (orig != null) { 6049 if (verifyPackageUpdateLPr(orig, pkg)) { 6050 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6051 + pkg.packageName); 6052 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6053 } 6054 } 6055 } 6056 } 6057 } 6058 6059 final String pkgName = pkg.packageName; 6060 6061 final long scanFileTime = scanFile.lastModified(); 6062 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6063 pkg.applicationInfo.processName = fixProcessName( 6064 pkg.applicationInfo.packageName, 6065 pkg.applicationInfo.processName, 6066 pkg.applicationInfo.uid); 6067 6068 File dataPath; 6069 if (mPlatformPackage == pkg) { 6070 // The system package is special. 6071 dataPath = new File(Environment.getDataDirectory(), "system"); 6072 6073 pkg.applicationInfo.dataDir = dataPath.getPath(); 6074 6075 } else { 6076 // This is a normal package, need to make its data directory. 6077 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6078 UserHandle.USER_OWNER); 6079 6080 boolean uidError = false; 6081 if (dataPath.exists()) { 6082 int currentUid = 0; 6083 try { 6084 StructStat stat = Os.stat(dataPath.getPath()); 6085 currentUid = stat.st_uid; 6086 } catch (ErrnoException e) { 6087 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6088 } 6089 6090 // If we have mismatched owners for the data path, we have a problem. 6091 if (currentUid != pkg.applicationInfo.uid) { 6092 boolean recovered = false; 6093 if (currentUid == 0) { 6094 // The directory somehow became owned by root. Wow. 6095 // This is probably because the system was stopped while 6096 // installd was in the middle of messing with its libs 6097 // directory. Ask installd to fix that. 6098 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6099 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6100 if (ret >= 0) { 6101 recovered = true; 6102 String msg = "Package " + pkg.packageName 6103 + " unexpectedly changed to uid 0; recovered to " + 6104 + pkg.applicationInfo.uid; 6105 reportSettingsProblem(Log.WARN, msg); 6106 } 6107 } 6108 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6109 || (scanFlags&SCAN_BOOTING) != 0)) { 6110 // If this is a system app, we can at least delete its 6111 // current data so the application will still work. 6112 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6113 if (ret >= 0) { 6114 // TODO: Kill the processes first 6115 // Old data gone! 6116 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6117 ? "System package " : "Third party package "; 6118 String msg = prefix + pkg.packageName 6119 + " has changed from uid: " 6120 + currentUid + " to " 6121 + pkg.applicationInfo.uid + "; old data erased"; 6122 reportSettingsProblem(Log.WARN, msg); 6123 recovered = true; 6124 6125 // And now re-install the app. 6126 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6127 pkg.applicationInfo.seinfo); 6128 if (ret == -1) { 6129 // Ack should not happen! 6130 msg = prefix + pkg.packageName 6131 + " could not have data directory re-created after delete."; 6132 reportSettingsProblem(Log.WARN, msg); 6133 throw new PackageManagerException( 6134 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6135 } 6136 } 6137 if (!recovered) { 6138 mHasSystemUidErrors = true; 6139 } 6140 } else if (!recovered) { 6141 // If we allow this install to proceed, we will be broken. 6142 // Abort, abort! 6143 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6144 "scanPackageLI"); 6145 } 6146 if (!recovered) { 6147 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6148 + pkg.applicationInfo.uid + "/fs_" 6149 + currentUid; 6150 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6151 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6152 String msg = "Package " + pkg.packageName 6153 + " has mismatched uid: " 6154 + currentUid + " on disk, " 6155 + pkg.applicationInfo.uid + " in settings"; 6156 // writer 6157 synchronized (mPackages) { 6158 mSettings.mReadMessages.append(msg); 6159 mSettings.mReadMessages.append('\n'); 6160 uidError = true; 6161 if (!pkgSetting.uidError) { 6162 reportSettingsProblem(Log.ERROR, msg); 6163 } 6164 } 6165 } 6166 } 6167 pkg.applicationInfo.dataDir = dataPath.getPath(); 6168 if (mShouldRestoreconData) { 6169 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6170 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6171 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6172 } 6173 } else { 6174 if (DEBUG_PACKAGE_SCANNING) { 6175 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6176 Log.v(TAG, "Want this data dir: " + dataPath); 6177 } 6178 //invoke installer to do the actual installation 6179 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6180 pkg.applicationInfo.seinfo); 6181 if (ret < 0) { 6182 // Error from installer 6183 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6184 "Unable to create data dirs [errorCode=" + ret + "]"); 6185 } 6186 6187 if (dataPath.exists()) { 6188 pkg.applicationInfo.dataDir = dataPath.getPath(); 6189 } else { 6190 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6191 pkg.applicationInfo.dataDir = null; 6192 } 6193 } 6194 6195 pkgSetting.uidError = uidError; 6196 } 6197 6198 final String path = scanFile.getPath(); 6199 final String codePath = pkg.applicationInfo.getCodePath(); 6200 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6201 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6202 setBundledAppAbisAndRoots(pkg, pkgSetting); 6203 6204 // If we haven't found any native libraries for the app, check if it has 6205 // renderscript code. We'll need to force the app to 32 bit if it has 6206 // renderscript bitcode. 6207 if (pkg.applicationInfo.primaryCpuAbi == null 6208 && pkg.applicationInfo.secondaryCpuAbi == null 6209 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6210 NativeLibraryHelper.Handle handle = null; 6211 try { 6212 handle = NativeLibraryHelper.Handle.create(scanFile); 6213 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6214 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6215 } 6216 } catch (IOException ioe) { 6217 Slog.w(TAG, "Error scanning system app : " + ioe); 6218 } finally { 6219 IoUtils.closeQuietly(handle); 6220 } 6221 } 6222 6223 setNativeLibraryPaths(pkg); 6224 } else { 6225 // TODO: We can probably be smarter about this stuff. For installed apps, 6226 // we can calculate this information at install time once and for all. For 6227 // system apps, we can probably assume that this information doesn't change 6228 // after the first boot scan. As things stand, we do lots of unnecessary work. 6229 6230 // Give ourselves some initial paths; we'll come back for another 6231 // pass once we've determined ABI below. 6232 setNativeLibraryPaths(pkg); 6233 6234 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6235 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6236 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6237 6238 NativeLibraryHelper.Handle handle = null; 6239 try { 6240 handle = NativeLibraryHelper.Handle.create(scanFile); 6241 // TODO(multiArch): This can be null for apps that didn't go through the 6242 // usual installation process. We can calculate it again, like we 6243 // do during install time. 6244 // 6245 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6246 // unnecessary. 6247 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6248 6249 // Null out the abis so that they can be recalculated. 6250 pkg.applicationInfo.primaryCpuAbi = null; 6251 pkg.applicationInfo.secondaryCpuAbi = null; 6252 if (isMultiArch(pkg.applicationInfo)) { 6253 // Warn if we've set an abiOverride for multi-lib packages.. 6254 // By definition, we need to copy both 32 and 64 bit libraries for 6255 // such packages. 6256 if (pkg.cpuAbiOverride != null 6257 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6258 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6259 } 6260 6261 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6262 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6263 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6264 if (isAsec) { 6265 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6266 } else { 6267 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6268 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6269 useIsaSpecificSubdirs); 6270 } 6271 } 6272 6273 maybeThrowExceptionForMultiArchCopy( 6274 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6275 6276 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6277 if (isAsec) { 6278 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6279 } else { 6280 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6281 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6282 useIsaSpecificSubdirs); 6283 } 6284 } 6285 6286 maybeThrowExceptionForMultiArchCopy( 6287 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6288 6289 if (abi64 >= 0) { 6290 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6291 } 6292 6293 if (abi32 >= 0) { 6294 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6295 if (abi64 >= 0) { 6296 pkg.applicationInfo.secondaryCpuAbi = abi; 6297 } else { 6298 pkg.applicationInfo.primaryCpuAbi = abi; 6299 } 6300 } 6301 } else { 6302 String[] abiList = (cpuAbiOverride != null) ? 6303 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6304 6305 // Enable gross and lame hacks for apps that are built with old 6306 // SDK tools. We must scan their APKs for renderscript bitcode and 6307 // not launch them if it's present. Don't bother checking on devices 6308 // that don't have 64 bit support. 6309 boolean needsRenderScriptOverride = false; 6310 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6311 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6312 abiList = Build.SUPPORTED_32_BIT_ABIS; 6313 needsRenderScriptOverride = true; 6314 } 6315 6316 final int copyRet; 6317 if (isAsec) { 6318 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6319 } else { 6320 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6321 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6322 } 6323 6324 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6325 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6326 "Error unpackaging native libs for app, errorCode=" + copyRet); 6327 } 6328 6329 if (copyRet >= 0) { 6330 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6331 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6332 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6333 } else if (needsRenderScriptOverride) { 6334 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6335 } 6336 } 6337 } catch (IOException ioe) { 6338 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6339 } finally { 6340 IoUtils.closeQuietly(handle); 6341 } 6342 6343 // Now that we've calculated the ABIs and determined if it's an internal app, 6344 // we will go ahead and populate the nativeLibraryPath. 6345 setNativeLibraryPaths(pkg); 6346 6347 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6348 final int[] userIds = sUserManager.getUserIds(); 6349 synchronized (mInstallLock) { 6350 // Create a native library symlink only if we have native libraries 6351 // and if the native libraries are 32 bit libraries. We do not provide 6352 // this symlink for 64 bit libraries. 6353 if (pkg.applicationInfo.primaryCpuAbi != null && 6354 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6355 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6356 for (int userId : userIds) { 6357 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6358 nativeLibPath, userId) < 0) { 6359 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6360 "Failed linking native library dir (user=" + userId + ")"); 6361 } 6362 } 6363 } 6364 } 6365 } 6366 6367 // This is a special case for the "system" package, where the ABI is 6368 // dictated by the zygote configuration (and init.rc). We should keep track 6369 // of this ABI so that we can deal with "normal" applications that run under 6370 // the same UID correctly. 6371 if (mPlatformPackage == pkg) { 6372 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6373 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6374 } 6375 6376 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6377 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6378 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6379 // Copy the derived override back to the parsed package, so that we can 6380 // update the package settings accordingly. 6381 pkg.cpuAbiOverride = cpuAbiOverride; 6382 6383 if (DEBUG_ABI_SELECTION) { 6384 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6385 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6386 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6387 } 6388 6389 // Push the derived path down into PackageSettings so we know what to 6390 // clean up at uninstall time. 6391 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6392 6393 if (DEBUG_ABI_SELECTION) { 6394 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6395 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6396 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6397 } 6398 6399 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6400 // We don't do this here during boot because we can do it all 6401 // at once after scanning all existing packages. 6402 // 6403 // We also do this *before* we perform dexopt on this package, so that 6404 // we can avoid redundant dexopts, and also to make sure we've got the 6405 // code and package path correct. 6406 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6407 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6408 } 6409 6410 if ((scanFlags & SCAN_NO_DEX) == 0) { 6411 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6412 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6413 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6414 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6415 } 6416 } 6417 if (mFactoryTest && pkg.requestedPermissions.contains( 6418 android.Manifest.permission.FACTORY_TEST)) { 6419 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6420 } 6421 6422 ArrayList<PackageParser.Package> clientLibPkgs = null; 6423 6424 // writer 6425 synchronized (mPackages) { 6426 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6427 // Only system apps can add new shared libraries. 6428 if (pkg.libraryNames != null) { 6429 for (int i=0; i<pkg.libraryNames.size(); i++) { 6430 String name = pkg.libraryNames.get(i); 6431 boolean allowed = false; 6432 if (pkg.isUpdatedSystemApp()) { 6433 // New library entries can only be added through the 6434 // system image. This is important to get rid of a lot 6435 // of nasty edge cases: for example if we allowed a non- 6436 // system update of the app to add a library, then uninstalling 6437 // the update would make the library go away, and assumptions 6438 // we made such as through app install filtering would now 6439 // have allowed apps on the device which aren't compatible 6440 // with it. Better to just have the restriction here, be 6441 // conservative, and create many fewer cases that can negatively 6442 // impact the user experience. 6443 final PackageSetting sysPs = mSettings 6444 .getDisabledSystemPkgLPr(pkg.packageName); 6445 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6446 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6447 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6448 allowed = true; 6449 allowed = true; 6450 break; 6451 } 6452 } 6453 } 6454 } else { 6455 allowed = true; 6456 } 6457 if (allowed) { 6458 if (!mSharedLibraries.containsKey(name)) { 6459 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6460 } else if (!name.equals(pkg.packageName)) { 6461 Slog.w(TAG, "Package " + pkg.packageName + " library " 6462 + name + " already exists; skipping"); 6463 } 6464 } else { 6465 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6466 + name + " that is not declared on system image; skipping"); 6467 } 6468 } 6469 if ((scanFlags&SCAN_BOOTING) == 0) { 6470 // If we are not booting, we need to update any applications 6471 // that are clients of our shared library. If we are booting, 6472 // this will all be done once the scan is complete. 6473 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6474 } 6475 } 6476 } 6477 } 6478 6479 // We also need to dexopt any apps that are dependent on this library. Note that 6480 // if these fail, we should abort the install since installing the library will 6481 // result in some apps being broken. 6482 if (clientLibPkgs != null) { 6483 if ((scanFlags & SCAN_NO_DEX) == 0) { 6484 for (int i = 0; i < clientLibPkgs.size(); i++) { 6485 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6486 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6487 null /* instruction sets */, forceDex, 6488 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6489 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6490 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6491 "scanPackageLI failed to dexopt clientLibPkgs"); 6492 } 6493 } 6494 } 6495 } 6496 6497 // Also need to kill any apps that are dependent on the library. 6498 if (clientLibPkgs != null) { 6499 for (int i=0; i<clientLibPkgs.size(); i++) { 6500 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6501 killApplication(clientPkg.applicationInfo.packageName, 6502 clientPkg.applicationInfo.uid, "update lib"); 6503 } 6504 } 6505 6506 // writer 6507 synchronized (mPackages) { 6508 // We don't expect installation to fail beyond this point 6509 6510 // Add the new setting to mSettings 6511 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6512 // Add the new setting to mPackages 6513 mPackages.put(pkg.applicationInfo.packageName, pkg); 6514 // Make sure we don't accidentally delete its data. 6515 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6516 while (iter.hasNext()) { 6517 PackageCleanItem item = iter.next(); 6518 if (pkgName.equals(item.packageName)) { 6519 iter.remove(); 6520 } 6521 } 6522 6523 // Take care of first install / last update times. 6524 if (currentTime != 0) { 6525 if (pkgSetting.firstInstallTime == 0) { 6526 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6527 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6528 pkgSetting.lastUpdateTime = currentTime; 6529 } 6530 } else if (pkgSetting.firstInstallTime == 0) { 6531 // We need *something*. Take time time stamp of the file. 6532 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6533 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6534 if (scanFileTime != pkgSetting.timeStamp) { 6535 // A package on the system image has changed; consider this 6536 // to be an update. 6537 pkgSetting.lastUpdateTime = scanFileTime; 6538 } 6539 } 6540 6541 // Add the package's KeySets to the global KeySetManagerService 6542 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6543 try { 6544 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6545 if (pkg.mKeySetMapping != null) { 6546 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6547 if (pkg.mUpgradeKeySets != null) { 6548 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6549 } 6550 } 6551 } catch (NullPointerException e) { 6552 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6553 } catch (IllegalArgumentException e) { 6554 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6555 } 6556 6557 int N = pkg.providers.size(); 6558 StringBuilder r = null; 6559 int i; 6560 for (i=0; i<N; i++) { 6561 PackageParser.Provider p = pkg.providers.get(i); 6562 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6563 p.info.processName, pkg.applicationInfo.uid); 6564 mProviders.addProvider(p); 6565 p.syncable = p.info.isSyncable; 6566 if (p.info.authority != null) { 6567 String names[] = p.info.authority.split(";"); 6568 p.info.authority = null; 6569 for (int j = 0; j < names.length; j++) { 6570 if (j == 1 && p.syncable) { 6571 // We only want the first authority for a provider to possibly be 6572 // syncable, so if we already added this provider using a different 6573 // authority clear the syncable flag. We copy the provider before 6574 // changing it because the mProviders object contains a reference 6575 // to a provider that we don't want to change. 6576 // Only do this for the second authority since the resulting provider 6577 // object can be the same for all future authorities for this provider. 6578 p = new PackageParser.Provider(p); 6579 p.syncable = false; 6580 } 6581 if (!mProvidersByAuthority.containsKey(names[j])) { 6582 mProvidersByAuthority.put(names[j], p); 6583 if (p.info.authority == null) { 6584 p.info.authority = names[j]; 6585 } else { 6586 p.info.authority = p.info.authority + ";" + names[j]; 6587 } 6588 if (DEBUG_PACKAGE_SCANNING) { 6589 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6590 Log.d(TAG, "Registered content provider: " + names[j] 6591 + ", className = " + p.info.name + ", isSyncable = " 6592 + p.info.isSyncable); 6593 } 6594 } else { 6595 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6596 Slog.w(TAG, "Skipping provider name " + names[j] + 6597 " (in package " + pkg.applicationInfo.packageName + 6598 "): name already used by " 6599 + ((other != null && other.getComponentName() != null) 6600 ? other.getComponentName().getPackageName() : "?")); 6601 } 6602 } 6603 } 6604 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6605 if (r == null) { 6606 r = new StringBuilder(256); 6607 } else { 6608 r.append(' '); 6609 } 6610 r.append(p.info.name); 6611 } 6612 } 6613 if (r != null) { 6614 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6615 } 6616 6617 N = pkg.services.size(); 6618 r = null; 6619 for (i=0; i<N; i++) { 6620 PackageParser.Service s = pkg.services.get(i); 6621 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6622 s.info.processName, pkg.applicationInfo.uid); 6623 mServices.addService(s); 6624 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6625 if (r == null) { 6626 r = new StringBuilder(256); 6627 } else { 6628 r.append(' '); 6629 } 6630 r.append(s.info.name); 6631 } 6632 } 6633 if (r != null) { 6634 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6635 } 6636 6637 N = pkg.receivers.size(); 6638 r = null; 6639 for (i=0; i<N; i++) { 6640 PackageParser.Activity a = pkg.receivers.get(i); 6641 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6642 a.info.processName, pkg.applicationInfo.uid); 6643 mReceivers.addActivity(a, "receiver"); 6644 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6645 if (r == null) { 6646 r = new StringBuilder(256); 6647 } else { 6648 r.append(' '); 6649 } 6650 r.append(a.info.name); 6651 } 6652 } 6653 if (r != null) { 6654 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6655 } 6656 6657 N = pkg.activities.size(); 6658 r = null; 6659 for (i=0; i<N; i++) { 6660 PackageParser.Activity a = pkg.activities.get(i); 6661 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6662 a.info.processName, pkg.applicationInfo.uid); 6663 mActivities.addActivity(a, "activity"); 6664 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6665 if (r == null) { 6666 r = new StringBuilder(256); 6667 } else { 6668 r.append(' '); 6669 } 6670 r.append(a.info.name); 6671 } 6672 } 6673 if (r != null) { 6674 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6675 } 6676 6677 N = pkg.permissionGroups.size(); 6678 r = null; 6679 for (i=0; i<N; i++) { 6680 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6681 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6682 if (cur == null) { 6683 mPermissionGroups.put(pg.info.name, pg); 6684 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6685 if (r == null) { 6686 r = new StringBuilder(256); 6687 } else { 6688 r.append(' '); 6689 } 6690 r.append(pg.info.name); 6691 } 6692 } else { 6693 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6694 + pg.info.packageName + " ignored: original from " 6695 + cur.info.packageName); 6696 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6697 if (r == null) { 6698 r = new StringBuilder(256); 6699 } else { 6700 r.append(' '); 6701 } 6702 r.append("DUP:"); 6703 r.append(pg.info.name); 6704 } 6705 } 6706 } 6707 if (r != null) { 6708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6709 } 6710 6711 N = pkg.permissions.size(); 6712 r = null; 6713 for (i=0; i<N; i++) { 6714 PackageParser.Permission p = pkg.permissions.get(i); 6715 6716 // Now that permission groups have a special meaning, we ignore permission 6717 // groups for legacy apps to prevent unexpected behavior. In particular, 6718 // permissions for one app being granted to someone just becuase they happen 6719 // to be in a group defined by another app (before this had no implications). 6720 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6721 p.group = mPermissionGroups.get(p.info.group); 6722 // Warn for a permission in an unknown group. 6723 if (p.info.group != null && p.group == null) { 6724 Slog.w(TAG, "Permission " + p.info.name + " from package " 6725 + p.info.packageName + " in an unknown group " + p.info.group); 6726 } 6727 } 6728 6729 ArrayMap<String, BasePermission> permissionMap = 6730 p.tree ? mSettings.mPermissionTrees 6731 : mSettings.mPermissions; 6732 BasePermission bp = permissionMap.get(p.info.name); 6733 6734 // Allow system apps to redefine non-system permissions 6735 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6736 final boolean currentOwnerIsSystem = (bp.perm != null 6737 && isSystemApp(bp.perm.owner)); 6738 if (isSystemApp(p.owner)) { 6739 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6740 // It's a built-in permission and no owner, take ownership now 6741 bp.packageSetting = pkgSetting; 6742 bp.perm = p; 6743 bp.uid = pkg.applicationInfo.uid; 6744 bp.sourcePackage = p.info.packageName; 6745 } else if (!currentOwnerIsSystem) { 6746 String msg = "New decl " + p.owner + " of permission " 6747 + p.info.name + " is system; overriding " + bp.sourcePackage; 6748 reportSettingsProblem(Log.WARN, msg); 6749 bp = null; 6750 } 6751 } 6752 } 6753 6754 if (bp == null) { 6755 bp = new BasePermission(p.info.name, p.info.packageName, 6756 BasePermission.TYPE_NORMAL); 6757 permissionMap.put(p.info.name, bp); 6758 } 6759 6760 if (bp.perm == null) { 6761 if (bp.sourcePackage == null 6762 || bp.sourcePackage.equals(p.info.packageName)) { 6763 BasePermission tree = findPermissionTreeLP(p.info.name); 6764 if (tree == null 6765 || tree.sourcePackage.equals(p.info.packageName)) { 6766 bp.packageSetting = pkgSetting; 6767 bp.perm = p; 6768 bp.uid = pkg.applicationInfo.uid; 6769 bp.sourcePackage = p.info.packageName; 6770 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6771 if (r == null) { 6772 r = new StringBuilder(256); 6773 } else { 6774 r.append(' '); 6775 } 6776 r.append(p.info.name); 6777 } 6778 } else { 6779 Slog.w(TAG, "Permission " + p.info.name + " from package " 6780 + p.info.packageName + " ignored: base tree " 6781 + tree.name + " is from package " 6782 + tree.sourcePackage); 6783 } 6784 } else { 6785 Slog.w(TAG, "Permission " + p.info.name + " from package " 6786 + p.info.packageName + " ignored: original from " 6787 + bp.sourcePackage); 6788 } 6789 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6790 if (r == null) { 6791 r = new StringBuilder(256); 6792 } else { 6793 r.append(' '); 6794 } 6795 r.append("DUP:"); 6796 r.append(p.info.name); 6797 } 6798 if (bp.perm == p) { 6799 bp.protectionLevel = p.info.protectionLevel; 6800 } 6801 } 6802 6803 if (r != null) { 6804 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6805 } 6806 6807 N = pkg.instrumentation.size(); 6808 r = null; 6809 for (i=0; i<N; i++) { 6810 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6811 a.info.packageName = pkg.applicationInfo.packageName; 6812 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6813 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6814 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6815 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6816 a.info.dataDir = pkg.applicationInfo.dataDir; 6817 6818 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6819 // need other information about the application, like the ABI and what not ? 6820 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6821 mInstrumentation.put(a.getComponentName(), a); 6822 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6823 if (r == null) { 6824 r = new StringBuilder(256); 6825 } else { 6826 r.append(' '); 6827 } 6828 r.append(a.info.name); 6829 } 6830 } 6831 if (r != null) { 6832 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6833 } 6834 6835 if (pkg.protectedBroadcasts != null) { 6836 N = pkg.protectedBroadcasts.size(); 6837 for (i=0; i<N; i++) { 6838 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6839 } 6840 } 6841 6842 pkgSetting.setTimeStamp(scanFileTime); 6843 6844 // Create idmap files for pairs of (packages, overlay packages). 6845 // Note: "android", ie framework-res.apk, is handled by native layers. 6846 if (pkg.mOverlayTarget != null) { 6847 // This is an overlay package. 6848 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6849 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6850 mOverlays.put(pkg.mOverlayTarget, 6851 new ArrayMap<String, PackageParser.Package>()); 6852 } 6853 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6854 map.put(pkg.packageName, pkg); 6855 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6856 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6857 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6858 "scanPackageLI failed to createIdmap"); 6859 } 6860 } 6861 } else if (mOverlays.containsKey(pkg.packageName) && 6862 !pkg.packageName.equals("android")) { 6863 // This is a regular package, with one or more known overlay packages. 6864 createIdmapsForPackageLI(pkg); 6865 } 6866 } 6867 6868 return pkg; 6869 } 6870 6871 /** 6872 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6873 * i.e, so that all packages can be run inside a single process if required. 6874 * 6875 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6876 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6877 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6878 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6879 * updating a package that belongs to a shared user. 6880 * 6881 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6882 * adds unnecessary complexity. 6883 */ 6884 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6885 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6886 String requiredInstructionSet = null; 6887 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6888 requiredInstructionSet = VMRuntime.getInstructionSet( 6889 scannedPackage.applicationInfo.primaryCpuAbi); 6890 } 6891 6892 PackageSetting requirer = null; 6893 for (PackageSetting ps : packagesForUser) { 6894 // If packagesForUser contains scannedPackage, we skip it. This will happen 6895 // when scannedPackage is an update of an existing package. Without this check, 6896 // we will never be able to change the ABI of any package belonging to a shared 6897 // user, even if it's compatible with other packages. 6898 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6899 if (ps.primaryCpuAbiString == null) { 6900 continue; 6901 } 6902 6903 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6904 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6905 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6906 // this but there's not much we can do. 6907 String errorMessage = "Instruction set mismatch, " 6908 + ((requirer == null) ? "[caller]" : requirer) 6909 + " requires " + requiredInstructionSet + " whereas " + ps 6910 + " requires " + instructionSet; 6911 Slog.w(TAG, errorMessage); 6912 } 6913 6914 if (requiredInstructionSet == null) { 6915 requiredInstructionSet = instructionSet; 6916 requirer = ps; 6917 } 6918 } 6919 } 6920 6921 if (requiredInstructionSet != null) { 6922 String adjustedAbi; 6923 if (requirer != null) { 6924 // requirer != null implies that either scannedPackage was null or that scannedPackage 6925 // did not require an ABI, in which case we have to adjust scannedPackage to match 6926 // the ABI of the set (which is the same as requirer's ABI) 6927 adjustedAbi = requirer.primaryCpuAbiString; 6928 if (scannedPackage != null) { 6929 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6930 } 6931 } else { 6932 // requirer == null implies that we're updating all ABIs in the set to 6933 // match scannedPackage. 6934 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6935 } 6936 6937 for (PackageSetting ps : packagesForUser) { 6938 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6939 if (ps.primaryCpuAbiString != null) { 6940 continue; 6941 } 6942 6943 ps.primaryCpuAbiString = adjustedAbi; 6944 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6945 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6946 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6947 6948 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6949 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6950 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6951 ps.primaryCpuAbiString = null; 6952 ps.pkg.applicationInfo.primaryCpuAbi = null; 6953 return; 6954 } else { 6955 mInstaller.rmdex(ps.codePathString, 6956 getDexCodeInstructionSet(getPreferredInstructionSet())); 6957 } 6958 } 6959 } 6960 } 6961 } 6962 } 6963 6964 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6965 synchronized (mPackages) { 6966 mResolverReplaced = true; 6967 // Set up information for custom user intent resolution activity. 6968 mResolveActivity.applicationInfo = pkg.applicationInfo; 6969 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6970 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6971 mResolveActivity.processName = pkg.applicationInfo.packageName; 6972 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6973 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6974 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6975 mResolveActivity.theme = 0; 6976 mResolveActivity.exported = true; 6977 mResolveActivity.enabled = true; 6978 mResolveInfo.activityInfo = mResolveActivity; 6979 mResolveInfo.priority = 0; 6980 mResolveInfo.preferredOrder = 0; 6981 mResolveInfo.match = 0; 6982 mResolveComponentName = mCustomResolverComponentName; 6983 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6984 mResolveComponentName); 6985 } 6986 } 6987 6988 private static String calculateBundledApkRoot(final String codePathString) { 6989 final File codePath = new File(codePathString); 6990 final File codeRoot; 6991 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6992 codeRoot = Environment.getRootDirectory(); 6993 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6994 codeRoot = Environment.getOemDirectory(); 6995 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6996 codeRoot = Environment.getVendorDirectory(); 6997 } else { 6998 // Unrecognized code path; take its top real segment as the apk root: 6999 // e.g. /something/app/blah.apk => /something 7000 try { 7001 File f = codePath.getCanonicalFile(); 7002 File parent = f.getParentFile(); // non-null because codePath is a file 7003 File tmp; 7004 while ((tmp = parent.getParentFile()) != null) { 7005 f = parent; 7006 parent = tmp; 7007 } 7008 codeRoot = f; 7009 Slog.w(TAG, "Unrecognized code path " 7010 + codePath + " - using " + codeRoot); 7011 } catch (IOException e) { 7012 // Can't canonicalize the code path -- shenanigans? 7013 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7014 return Environment.getRootDirectory().getPath(); 7015 } 7016 } 7017 return codeRoot.getPath(); 7018 } 7019 7020 /** 7021 * Derive and set the location of native libraries for the given package, 7022 * which varies depending on where and how the package was installed. 7023 */ 7024 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7025 final ApplicationInfo info = pkg.applicationInfo; 7026 final String codePath = pkg.codePath; 7027 final File codeFile = new File(codePath); 7028 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7029 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7030 7031 info.nativeLibraryRootDir = null; 7032 info.nativeLibraryRootRequiresIsa = false; 7033 info.nativeLibraryDir = null; 7034 info.secondaryNativeLibraryDir = null; 7035 7036 if (isApkFile(codeFile)) { 7037 // Monolithic install 7038 if (bundledApp) { 7039 // If "/system/lib64/apkname" exists, assume that is the per-package 7040 // native library directory to use; otherwise use "/system/lib/apkname". 7041 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7042 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7043 getPrimaryInstructionSet(info)); 7044 7045 // This is a bundled system app so choose the path based on the ABI. 7046 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7047 // is just the default path. 7048 final String apkName = deriveCodePathName(codePath); 7049 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7050 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7051 apkName).getAbsolutePath(); 7052 7053 if (info.secondaryCpuAbi != null) { 7054 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7055 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7056 secondaryLibDir, apkName).getAbsolutePath(); 7057 } 7058 } else if (asecApp) { 7059 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7060 .getAbsolutePath(); 7061 } else { 7062 final String apkName = deriveCodePathName(codePath); 7063 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7064 .getAbsolutePath(); 7065 } 7066 7067 info.nativeLibraryRootRequiresIsa = false; 7068 info.nativeLibraryDir = info.nativeLibraryRootDir; 7069 } else { 7070 // Cluster install 7071 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7072 info.nativeLibraryRootRequiresIsa = true; 7073 7074 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7075 getPrimaryInstructionSet(info)).getAbsolutePath(); 7076 7077 if (info.secondaryCpuAbi != null) { 7078 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7079 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7080 } 7081 } 7082 } 7083 7084 /** 7085 * Calculate the abis and roots for a bundled app. These can uniquely 7086 * be determined from the contents of the system partition, i.e whether 7087 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7088 * of this information, and instead assume that the system was built 7089 * sensibly. 7090 */ 7091 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7092 PackageSetting pkgSetting) { 7093 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7094 7095 // If "/system/lib64/apkname" exists, assume that is the per-package 7096 // native library directory to use; otherwise use "/system/lib/apkname". 7097 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7098 setBundledAppAbi(pkg, apkRoot, apkName); 7099 // pkgSetting might be null during rescan following uninstall of updates 7100 // to a bundled app, so accommodate that possibility. The settings in 7101 // that case will be established later from the parsed package. 7102 // 7103 // If the settings aren't null, sync them up with what we've just derived. 7104 // note that apkRoot isn't stored in the package settings. 7105 if (pkgSetting != null) { 7106 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7107 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7108 } 7109 } 7110 7111 /** 7112 * Deduces the ABI of a bundled app and sets the relevant fields on the 7113 * parsed pkg object. 7114 * 7115 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7116 * under which system libraries are installed. 7117 * @param apkName the name of the installed package. 7118 */ 7119 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7120 final File codeFile = new File(pkg.codePath); 7121 7122 final boolean has64BitLibs; 7123 final boolean has32BitLibs; 7124 if (isApkFile(codeFile)) { 7125 // Monolithic install 7126 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7127 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7128 } else { 7129 // Cluster install 7130 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7131 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7132 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7133 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7134 has64BitLibs = (new File(rootDir, isa)).exists(); 7135 } else { 7136 has64BitLibs = false; 7137 } 7138 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7139 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7140 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7141 has32BitLibs = (new File(rootDir, isa)).exists(); 7142 } else { 7143 has32BitLibs = false; 7144 } 7145 } 7146 7147 if (has64BitLibs && !has32BitLibs) { 7148 // The package has 64 bit libs, but not 32 bit libs. Its primary 7149 // ABI should be 64 bit. We can safely assume here that the bundled 7150 // native libraries correspond to the most preferred ABI in the list. 7151 7152 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7153 pkg.applicationInfo.secondaryCpuAbi = null; 7154 } else if (has32BitLibs && !has64BitLibs) { 7155 // The package has 32 bit libs but not 64 bit libs. Its primary 7156 // ABI should be 32 bit. 7157 7158 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7159 pkg.applicationInfo.secondaryCpuAbi = null; 7160 } else if (has32BitLibs && has64BitLibs) { 7161 // The application has both 64 and 32 bit bundled libraries. We check 7162 // here that the app declares multiArch support, and warn if it doesn't. 7163 // 7164 // We will be lenient here and record both ABIs. The primary will be the 7165 // ABI that's higher on the list, i.e, a device that's configured to prefer 7166 // 64 bit apps will see a 64 bit primary ABI, 7167 7168 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7169 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7170 } 7171 7172 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7173 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7174 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7175 } else { 7176 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7177 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7178 } 7179 } else { 7180 pkg.applicationInfo.primaryCpuAbi = null; 7181 pkg.applicationInfo.secondaryCpuAbi = null; 7182 } 7183 } 7184 7185 private void killApplication(String pkgName, int appId, String reason) { 7186 // Request the ActivityManager to kill the process(only for existing packages) 7187 // so that we do not end up in a confused state while the user is still using the older 7188 // version of the application while the new one gets installed. 7189 IActivityManager am = ActivityManagerNative.getDefault(); 7190 if (am != null) { 7191 try { 7192 am.killApplicationWithAppId(pkgName, appId, reason); 7193 } catch (RemoteException e) { 7194 } 7195 } 7196 } 7197 7198 void removePackageLI(PackageSetting ps, boolean chatty) { 7199 if (DEBUG_INSTALL) { 7200 if (chatty) 7201 Log.d(TAG, "Removing package " + ps.name); 7202 } 7203 7204 // writer 7205 synchronized (mPackages) { 7206 mPackages.remove(ps.name); 7207 final PackageParser.Package pkg = ps.pkg; 7208 if (pkg != null) { 7209 cleanPackageDataStructuresLILPw(pkg, chatty); 7210 } 7211 } 7212 } 7213 7214 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7215 if (DEBUG_INSTALL) { 7216 if (chatty) 7217 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7218 } 7219 7220 // writer 7221 synchronized (mPackages) { 7222 mPackages.remove(pkg.applicationInfo.packageName); 7223 cleanPackageDataStructuresLILPw(pkg, chatty); 7224 } 7225 } 7226 7227 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7228 int N = pkg.providers.size(); 7229 StringBuilder r = null; 7230 int i; 7231 for (i=0; i<N; i++) { 7232 PackageParser.Provider p = pkg.providers.get(i); 7233 mProviders.removeProvider(p); 7234 if (p.info.authority == null) { 7235 7236 /* There was another ContentProvider with this authority when 7237 * this app was installed so this authority is null, 7238 * Ignore it as we don't have to unregister the provider. 7239 */ 7240 continue; 7241 } 7242 String names[] = p.info.authority.split(";"); 7243 for (int j = 0; j < names.length; j++) { 7244 if (mProvidersByAuthority.get(names[j]) == p) { 7245 mProvidersByAuthority.remove(names[j]); 7246 if (DEBUG_REMOVE) { 7247 if (chatty) 7248 Log.d(TAG, "Unregistered content provider: " + names[j] 7249 + ", className = " + p.info.name + ", isSyncable = " 7250 + p.info.isSyncable); 7251 } 7252 } 7253 } 7254 if (DEBUG_REMOVE && chatty) { 7255 if (r == null) { 7256 r = new StringBuilder(256); 7257 } else { 7258 r.append(' '); 7259 } 7260 r.append(p.info.name); 7261 } 7262 } 7263 if (r != null) { 7264 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7265 } 7266 7267 N = pkg.services.size(); 7268 r = null; 7269 for (i=0; i<N; i++) { 7270 PackageParser.Service s = pkg.services.get(i); 7271 mServices.removeService(s); 7272 if (chatty) { 7273 if (r == null) { 7274 r = new StringBuilder(256); 7275 } else { 7276 r.append(' '); 7277 } 7278 r.append(s.info.name); 7279 } 7280 } 7281 if (r != null) { 7282 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7283 } 7284 7285 N = pkg.receivers.size(); 7286 r = null; 7287 for (i=0; i<N; i++) { 7288 PackageParser.Activity a = pkg.receivers.get(i); 7289 mReceivers.removeActivity(a, "receiver"); 7290 if (DEBUG_REMOVE && chatty) { 7291 if (r == null) { 7292 r = new StringBuilder(256); 7293 } else { 7294 r.append(' '); 7295 } 7296 r.append(a.info.name); 7297 } 7298 } 7299 if (r != null) { 7300 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7301 } 7302 7303 N = pkg.activities.size(); 7304 r = null; 7305 for (i=0; i<N; i++) { 7306 PackageParser.Activity a = pkg.activities.get(i); 7307 mActivities.removeActivity(a, "activity"); 7308 if (DEBUG_REMOVE && chatty) { 7309 if (r == null) { 7310 r = new StringBuilder(256); 7311 } else { 7312 r.append(' '); 7313 } 7314 r.append(a.info.name); 7315 } 7316 } 7317 if (r != null) { 7318 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7319 } 7320 7321 N = pkg.permissions.size(); 7322 r = null; 7323 for (i=0; i<N; i++) { 7324 PackageParser.Permission p = pkg.permissions.get(i); 7325 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7326 if (bp == null) { 7327 bp = mSettings.mPermissionTrees.get(p.info.name); 7328 } 7329 if (bp != null && bp.perm == p) { 7330 bp.perm = null; 7331 if (DEBUG_REMOVE && chatty) { 7332 if (r == null) { 7333 r = new StringBuilder(256); 7334 } else { 7335 r.append(' '); 7336 } 7337 r.append(p.info.name); 7338 } 7339 } 7340 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7341 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7342 if (appOpPerms != null) { 7343 appOpPerms.remove(pkg.packageName); 7344 } 7345 } 7346 } 7347 if (r != null) { 7348 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7349 } 7350 7351 N = pkg.requestedPermissions.size(); 7352 r = null; 7353 for (i=0; i<N; i++) { 7354 String perm = pkg.requestedPermissions.get(i); 7355 BasePermission bp = mSettings.mPermissions.get(perm); 7356 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7357 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7358 if (appOpPerms != null) { 7359 appOpPerms.remove(pkg.packageName); 7360 if (appOpPerms.isEmpty()) { 7361 mAppOpPermissionPackages.remove(perm); 7362 } 7363 } 7364 } 7365 } 7366 if (r != null) { 7367 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7368 } 7369 7370 N = pkg.instrumentation.size(); 7371 r = null; 7372 for (i=0; i<N; i++) { 7373 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7374 mInstrumentation.remove(a.getComponentName()); 7375 if (DEBUG_REMOVE && chatty) { 7376 if (r == null) { 7377 r = new StringBuilder(256); 7378 } else { 7379 r.append(' '); 7380 } 7381 r.append(a.info.name); 7382 } 7383 } 7384 if (r != null) { 7385 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7386 } 7387 7388 r = null; 7389 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7390 // Only system apps can hold shared libraries. 7391 if (pkg.libraryNames != null) { 7392 for (i=0; i<pkg.libraryNames.size(); i++) { 7393 String name = pkg.libraryNames.get(i); 7394 SharedLibraryEntry cur = mSharedLibraries.get(name); 7395 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7396 mSharedLibraries.remove(name); 7397 if (DEBUG_REMOVE && chatty) { 7398 if (r == null) { 7399 r = new StringBuilder(256); 7400 } else { 7401 r.append(' '); 7402 } 7403 r.append(name); 7404 } 7405 } 7406 } 7407 } 7408 } 7409 if (r != null) { 7410 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7411 } 7412 } 7413 7414 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7415 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7416 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7417 return true; 7418 } 7419 } 7420 return false; 7421 } 7422 7423 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7424 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7425 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7426 7427 private void updatePermissionsLPw(String changingPkg, 7428 PackageParser.Package pkgInfo, int flags) { 7429 // Make sure there are no dangling permission trees. 7430 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7431 while (it.hasNext()) { 7432 final BasePermission bp = it.next(); 7433 if (bp.packageSetting == null) { 7434 // We may not yet have parsed the package, so just see if 7435 // we still know about its settings. 7436 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7437 } 7438 if (bp.packageSetting == null) { 7439 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7440 + " from package " + bp.sourcePackage); 7441 it.remove(); 7442 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7443 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7444 Slog.i(TAG, "Removing old permission tree: " + bp.name 7445 + " from package " + bp.sourcePackage); 7446 flags |= UPDATE_PERMISSIONS_ALL; 7447 it.remove(); 7448 } 7449 } 7450 } 7451 7452 // Make sure all dynamic permissions have been assigned to a package, 7453 // and make sure there are no dangling permissions. 7454 it = mSettings.mPermissions.values().iterator(); 7455 while (it.hasNext()) { 7456 final BasePermission bp = it.next(); 7457 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7458 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7459 + bp.name + " pkg=" + bp.sourcePackage 7460 + " info=" + bp.pendingInfo); 7461 if (bp.packageSetting == null && bp.pendingInfo != null) { 7462 final BasePermission tree = findPermissionTreeLP(bp.name); 7463 if (tree != null && tree.perm != null) { 7464 bp.packageSetting = tree.packageSetting; 7465 bp.perm = new PackageParser.Permission(tree.perm.owner, 7466 new PermissionInfo(bp.pendingInfo)); 7467 bp.perm.info.packageName = tree.perm.info.packageName; 7468 bp.perm.info.name = bp.name; 7469 bp.uid = tree.uid; 7470 } 7471 } 7472 } 7473 if (bp.packageSetting == null) { 7474 // We may not yet have parsed the package, so just see if 7475 // we still know about its settings. 7476 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7477 } 7478 if (bp.packageSetting == null) { 7479 Slog.w(TAG, "Removing dangling permission: " + bp.name 7480 + " from package " + bp.sourcePackage); 7481 it.remove(); 7482 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7483 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7484 Slog.i(TAG, "Removing old permission: " + bp.name 7485 + " from package " + bp.sourcePackage); 7486 flags |= UPDATE_PERMISSIONS_ALL; 7487 it.remove(); 7488 } 7489 } 7490 } 7491 7492 // Now update the permissions for all packages, in particular 7493 // replace the granted permissions of the system packages. 7494 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7495 for (PackageParser.Package pkg : mPackages.values()) { 7496 if (pkg != pkgInfo) { 7497 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7498 changingPkg); 7499 } 7500 } 7501 } 7502 7503 if (pkgInfo != null) { 7504 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7505 } 7506 } 7507 7508 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7509 String packageOfInterest) { 7510 // IMPORTANT: There are two types of permissions: install and runtime. 7511 // Install time permissions are granted when the app is installed to 7512 // all device users and users added in the future. Runtime permissions 7513 // are granted at runtime explicitly to specific users. Normal and signature 7514 // protected permissions are install time permissions. Dangerous permissions 7515 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7516 // otherwise they are runtime permissions. This function does not manage 7517 // runtime permissions except for the case an app targeting Lollipop MR1 7518 // being upgraded to target a newer SDK, in which case dangerous permissions 7519 // are transformed from install time to runtime ones. 7520 7521 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7522 if (ps == null) { 7523 return; 7524 } 7525 7526 PermissionsState permissionsState = ps.getPermissionsState(); 7527 PermissionsState origPermissions = permissionsState; 7528 7529 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7530 7531 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7532 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7533 7534 boolean changedInstallPermission = false; 7535 7536 if (replace) { 7537 ps.installPermissionsFixed = false; 7538 if (!ps.isSharedUser()) { 7539 origPermissions = new PermissionsState(permissionsState); 7540 permissionsState.reset(); 7541 } 7542 } 7543 7544 permissionsState.setGlobalGids(mGlobalGids); 7545 7546 final int N = pkg.requestedPermissions.size(); 7547 for (int i=0; i<N; i++) { 7548 final String name = pkg.requestedPermissions.get(i); 7549 final BasePermission bp = mSettings.mPermissions.get(name); 7550 7551 if (DEBUG_INSTALL) { 7552 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7553 } 7554 7555 if (bp == null || bp.packageSetting == null) { 7556 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7557 Slog.w(TAG, "Unknown permission " + name 7558 + " in package " + pkg.packageName); 7559 } 7560 continue; 7561 } 7562 7563 final String perm = bp.name; 7564 boolean allowedSig = false; 7565 int grant = GRANT_DENIED; 7566 7567 // Keep track of app op permissions. 7568 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7569 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7570 if (pkgs == null) { 7571 pkgs = new ArraySet<>(); 7572 mAppOpPermissionPackages.put(bp.name, pkgs); 7573 } 7574 pkgs.add(pkg.packageName); 7575 } 7576 7577 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7578 switch (level) { 7579 case PermissionInfo.PROTECTION_NORMAL: { 7580 // For all apps normal permissions are install time ones. 7581 grant = GRANT_INSTALL; 7582 } break; 7583 7584 case PermissionInfo.PROTECTION_DANGEROUS: { 7585 if (!RUNTIME_PERMISSIONS_ENABLED 7586 || pkg.applicationInfo.targetSdkVersion 7587 <= 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 if (RUNTIME_PERMISSIONS_ENABLED) { 7727 for (int userId : changedRuntimePermissionUserIds) { 7728 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7729 } 7730 } 7731 } 7732 7733 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7734 boolean allowed = false; 7735 final int NP = PackageParser.NEW_PERMISSIONS.length; 7736 for (int ip=0; ip<NP; ip++) { 7737 final PackageParser.NewPermissionInfo npi 7738 = PackageParser.NEW_PERMISSIONS[ip]; 7739 if (npi.name.equals(perm) 7740 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7741 allowed = true; 7742 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7743 + pkg.packageName); 7744 break; 7745 } 7746 } 7747 return allowed; 7748 } 7749 7750 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7751 BasePermission bp, PermissionsState origPermissions) { 7752 boolean allowed; 7753 allowed = (compareSignatures( 7754 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7755 == PackageManager.SIGNATURE_MATCH) 7756 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7757 == PackageManager.SIGNATURE_MATCH); 7758 if (!allowed && (bp.protectionLevel 7759 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7760 if (isSystemApp(pkg)) { 7761 // For updated system applications, a system permission 7762 // is granted only if it had been defined by the original application. 7763 if (pkg.isUpdatedSystemApp()) { 7764 final PackageSetting sysPs = mSettings 7765 .getDisabledSystemPkgLPr(pkg.packageName); 7766 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7767 // If the original was granted this permission, we take 7768 // that grant decision as read and propagate it to the 7769 // update. 7770 if (sysPs.isPrivileged()) { 7771 allowed = true; 7772 } 7773 } else { 7774 // The system apk may have been updated with an older 7775 // version of the one on the data partition, but which 7776 // granted a new system permission that it didn't have 7777 // before. In this case we do want to allow the app to 7778 // now get the new permission if the ancestral apk is 7779 // privileged to get it. 7780 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7781 for (int j=0; 7782 j<sysPs.pkg.requestedPermissions.size(); j++) { 7783 if (perm.equals( 7784 sysPs.pkg.requestedPermissions.get(j))) { 7785 allowed = true; 7786 break; 7787 } 7788 } 7789 } 7790 } 7791 } else { 7792 allowed = isPrivilegedApp(pkg); 7793 } 7794 } 7795 } 7796 if (!allowed && (bp.protectionLevel 7797 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7798 // For development permissions, a development permission 7799 // is granted only if it was already granted. 7800 allowed = origPermissions.hasInstallPermission(perm); 7801 } 7802 return allowed; 7803 } 7804 7805 final class ActivityIntentResolver 7806 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7807 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7808 boolean defaultOnly, int userId) { 7809 if (!sUserManager.exists(userId)) return null; 7810 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7811 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7812 } 7813 7814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7815 int userId) { 7816 if (!sUserManager.exists(userId)) return null; 7817 mFlags = flags; 7818 return super.queryIntent(intent, resolvedType, 7819 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7820 } 7821 7822 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7823 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7824 if (!sUserManager.exists(userId)) return null; 7825 if (packageActivities == null) { 7826 return null; 7827 } 7828 mFlags = flags; 7829 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7830 final int N = packageActivities.size(); 7831 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7832 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7833 7834 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7835 for (int i = 0; i < N; ++i) { 7836 intentFilters = packageActivities.get(i).intents; 7837 if (intentFilters != null && intentFilters.size() > 0) { 7838 PackageParser.ActivityIntentInfo[] array = 7839 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7840 intentFilters.toArray(array); 7841 listCut.add(array); 7842 } 7843 } 7844 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7845 } 7846 7847 public final void addActivity(PackageParser.Activity a, String type) { 7848 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7849 mActivities.put(a.getComponentName(), a); 7850 if (DEBUG_SHOW_INFO) 7851 Log.v( 7852 TAG, " " + type + " " + 7853 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7854 if (DEBUG_SHOW_INFO) 7855 Log.v(TAG, " Class=" + a.info.name); 7856 final int NI = a.intents.size(); 7857 for (int j=0; j<NI; j++) { 7858 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7859 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7860 intent.setPriority(0); 7861 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7862 + a.className + " with priority > 0, forcing to 0"); 7863 } 7864 if (DEBUG_SHOW_INFO) { 7865 Log.v(TAG, " IntentFilter:"); 7866 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7867 } 7868 if (!intent.debugCheck()) { 7869 Log.w(TAG, "==> For Activity " + a.info.name); 7870 } 7871 addFilter(intent); 7872 } 7873 } 7874 7875 public final void removeActivity(PackageParser.Activity a, String type) { 7876 mActivities.remove(a.getComponentName()); 7877 if (DEBUG_SHOW_INFO) { 7878 Log.v(TAG, " " + type + " " 7879 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7880 : a.info.name) + ":"); 7881 Log.v(TAG, " Class=" + a.info.name); 7882 } 7883 final int NI = a.intents.size(); 7884 for (int j=0; j<NI; j++) { 7885 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7886 if (DEBUG_SHOW_INFO) { 7887 Log.v(TAG, " IntentFilter:"); 7888 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7889 } 7890 removeFilter(intent); 7891 } 7892 } 7893 7894 @Override 7895 protected boolean allowFilterResult( 7896 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7897 ActivityInfo filterAi = filter.activity.info; 7898 for (int i=dest.size()-1; i>=0; i--) { 7899 ActivityInfo destAi = dest.get(i).activityInfo; 7900 if (destAi.name == filterAi.name 7901 && destAi.packageName == filterAi.packageName) { 7902 return false; 7903 } 7904 } 7905 return true; 7906 } 7907 7908 @Override 7909 protected ActivityIntentInfo[] newArray(int size) { 7910 return new ActivityIntentInfo[size]; 7911 } 7912 7913 @Override 7914 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7915 if (!sUserManager.exists(userId)) return true; 7916 PackageParser.Package p = filter.activity.owner; 7917 if (p != null) { 7918 PackageSetting ps = (PackageSetting)p.mExtras; 7919 if (ps != null) { 7920 // System apps are never considered stopped for purposes of 7921 // filtering, because there may be no way for the user to 7922 // actually re-launch them. 7923 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7924 && ps.getStopped(userId); 7925 } 7926 } 7927 return false; 7928 } 7929 7930 @Override 7931 protected boolean isPackageForFilter(String packageName, 7932 PackageParser.ActivityIntentInfo info) { 7933 return packageName.equals(info.activity.owner.packageName); 7934 } 7935 7936 @Override 7937 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7938 int match, int userId) { 7939 if (!sUserManager.exists(userId)) return null; 7940 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7941 return null; 7942 } 7943 final PackageParser.Activity activity = info.activity; 7944 if (mSafeMode && (activity.info.applicationInfo.flags 7945 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7946 return null; 7947 } 7948 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7949 if (ps == null) { 7950 return null; 7951 } 7952 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7953 ps.readUserState(userId), userId); 7954 if (ai == null) { 7955 return null; 7956 } 7957 final ResolveInfo res = new ResolveInfo(); 7958 res.activityInfo = ai; 7959 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7960 res.filter = info; 7961 } 7962 if (info != null) { 7963 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7964 } 7965 res.priority = info.getPriority(); 7966 res.preferredOrder = activity.owner.mPreferredOrder; 7967 //System.out.println("Result: " + res.activityInfo.className + 7968 // " = " + res.priority); 7969 res.match = match; 7970 res.isDefault = info.hasDefault; 7971 res.labelRes = info.labelRes; 7972 res.nonLocalizedLabel = info.nonLocalizedLabel; 7973 if (userNeedsBadging(userId)) { 7974 res.noResourceId = true; 7975 } else { 7976 res.icon = info.icon; 7977 } 7978 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7979 return res; 7980 } 7981 7982 @Override 7983 protected void sortResults(List<ResolveInfo> results) { 7984 Collections.sort(results, mResolvePrioritySorter); 7985 } 7986 7987 @Override 7988 protected void dumpFilter(PrintWriter out, String prefix, 7989 PackageParser.ActivityIntentInfo filter) { 7990 out.print(prefix); out.print( 7991 Integer.toHexString(System.identityHashCode(filter.activity))); 7992 out.print(' '); 7993 filter.activity.printComponentShortName(out); 7994 out.print(" filter "); 7995 out.println(Integer.toHexString(System.identityHashCode(filter))); 7996 } 7997 7998 @Override 7999 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8000 return filter.activity; 8001 } 8002 8003 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8004 PackageParser.Activity activity = (PackageParser.Activity)label; 8005 out.print(prefix); out.print( 8006 Integer.toHexString(System.identityHashCode(activity))); 8007 out.print(' '); 8008 activity.printComponentShortName(out); 8009 if (count > 1) { 8010 out.print(" ("); out.print(count); out.print(" filters)"); 8011 } 8012 out.println(); 8013 } 8014 8015// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8016// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8017// final List<ResolveInfo> retList = Lists.newArrayList(); 8018// while (i.hasNext()) { 8019// final ResolveInfo resolveInfo = i.next(); 8020// if (isEnabledLP(resolveInfo.activityInfo)) { 8021// retList.add(resolveInfo); 8022// } 8023// } 8024// return retList; 8025// } 8026 8027 // Keys are String (activity class name), values are Activity. 8028 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8029 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8030 private int mFlags; 8031 } 8032 8033 private final class ServiceIntentResolver 8034 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8035 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8036 boolean defaultOnly, int userId) { 8037 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8038 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8039 } 8040 8041 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8042 int userId) { 8043 if (!sUserManager.exists(userId)) return null; 8044 mFlags = flags; 8045 return super.queryIntent(intent, resolvedType, 8046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8047 } 8048 8049 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8050 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8051 if (!sUserManager.exists(userId)) return null; 8052 if (packageServices == null) { 8053 return null; 8054 } 8055 mFlags = flags; 8056 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8057 final int N = packageServices.size(); 8058 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8059 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8060 8061 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8062 for (int i = 0; i < N; ++i) { 8063 intentFilters = packageServices.get(i).intents; 8064 if (intentFilters != null && intentFilters.size() > 0) { 8065 PackageParser.ServiceIntentInfo[] array = 8066 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8067 intentFilters.toArray(array); 8068 listCut.add(array); 8069 } 8070 } 8071 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8072 } 8073 8074 public final void addService(PackageParser.Service s) { 8075 mServices.put(s.getComponentName(), s); 8076 if (DEBUG_SHOW_INFO) { 8077 Log.v(TAG, " " 8078 + (s.info.nonLocalizedLabel != null 8079 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8080 Log.v(TAG, " Class=" + s.info.name); 8081 } 8082 final int NI = s.intents.size(); 8083 int j; 8084 for (j=0; j<NI; j++) { 8085 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8086 if (DEBUG_SHOW_INFO) { 8087 Log.v(TAG, " IntentFilter:"); 8088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8089 } 8090 if (!intent.debugCheck()) { 8091 Log.w(TAG, "==> For Service " + s.info.name); 8092 } 8093 addFilter(intent); 8094 } 8095 } 8096 8097 public final void removeService(PackageParser.Service s) { 8098 mServices.remove(s.getComponentName()); 8099 if (DEBUG_SHOW_INFO) { 8100 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8101 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8102 Log.v(TAG, " Class=" + s.info.name); 8103 } 8104 final int NI = s.intents.size(); 8105 int j; 8106 for (j=0; j<NI; j++) { 8107 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8108 if (DEBUG_SHOW_INFO) { 8109 Log.v(TAG, " IntentFilter:"); 8110 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8111 } 8112 removeFilter(intent); 8113 } 8114 } 8115 8116 @Override 8117 protected boolean allowFilterResult( 8118 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8119 ServiceInfo filterSi = filter.service.info; 8120 for (int i=dest.size()-1; i>=0; i--) { 8121 ServiceInfo destAi = dest.get(i).serviceInfo; 8122 if (destAi.name == filterSi.name 8123 && destAi.packageName == filterSi.packageName) { 8124 return false; 8125 } 8126 } 8127 return true; 8128 } 8129 8130 @Override 8131 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8132 return new PackageParser.ServiceIntentInfo[size]; 8133 } 8134 8135 @Override 8136 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8137 if (!sUserManager.exists(userId)) return true; 8138 PackageParser.Package p = filter.service.owner; 8139 if (p != null) { 8140 PackageSetting ps = (PackageSetting)p.mExtras; 8141 if (ps != null) { 8142 // System apps are never considered stopped for purposes of 8143 // filtering, because there may be no way for the user to 8144 // actually re-launch them. 8145 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8146 && ps.getStopped(userId); 8147 } 8148 } 8149 return false; 8150 } 8151 8152 @Override 8153 protected boolean isPackageForFilter(String packageName, 8154 PackageParser.ServiceIntentInfo info) { 8155 return packageName.equals(info.service.owner.packageName); 8156 } 8157 8158 @Override 8159 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8160 int match, int userId) { 8161 if (!sUserManager.exists(userId)) return null; 8162 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8163 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8164 return null; 8165 } 8166 final PackageParser.Service service = info.service; 8167 if (mSafeMode && (service.info.applicationInfo.flags 8168 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8169 return null; 8170 } 8171 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8172 if (ps == null) { 8173 return null; 8174 } 8175 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8176 ps.readUserState(userId), userId); 8177 if (si == null) { 8178 return null; 8179 } 8180 final ResolveInfo res = new ResolveInfo(); 8181 res.serviceInfo = si; 8182 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8183 res.filter = filter; 8184 } 8185 res.priority = info.getPriority(); 8186 res.preferredOrder = service.owner.mPreferredOrder; 8187 res.match = match; 8188 res.isDefault = info.hasDefault; 8189 res.labelRes = info.labelRes; 8190 res.nonLocalizedLabel = info.nonLocalizedLabel; 8191 res.icon = info.icon; 8192 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8193 return res; 8194 } 8195 8196 @Override 8197 protected void sortResults(List<ResolveInfo> results) { 8198 Collections.sort(results, mResolvePrioritySorter); 8199 } 8200 8201 @Override 8202 protected void dumpFilter(PrintWriter out, String prefix, 8203 PackageParser.ServiceIntentInfo filter) { 8204 out.print(prefix); out.print( 8205 Integer.toHexString(System.identityHashCode(filter.service))); 8206 out.print(' '); 8207 filter.service.printComponentShortName(out); 8208 out.print(" filter "); 8209 out.println(Integer.toHexString(System.identityHashCode(filter))); 8210 } 8211 8212 @Override 8213 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8214 return filter.service; 8215 } 8216 8217 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8218 PackageParser.Service service = (PackageParser.Service)label; 8219 out.print(prefix); out.print( 8220 Integer.toHexString(System.identityHashCode(service))); 8221 out.print(' '); 8222 service.printComponentShortName(out); 8223 if (count > 1) { 8224 out.print(" ("); out.print(count); out.print(" filters)"); 8225 } 8226 out.println(); 8227 } 8228 8229// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8230// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8231// final List<ResolveInfo> retList = Lists.newArrayList(); 8232// while (i.hasNext()) { 8233// final ResolveInfo resolveInfo = (ResolveInfo) i; 8234// if (isEnabledLP(resolveInfo.serviceInfo)) { 8235// retList.add(resolveInfo); 8236// } 8237// } 8238// return retList; 8239// } 8240 8241 // Keys are String (activity class name), values are Activity. 8242 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8243 = new ArrayMap<ComponentName, PackageParser.Service>(); 8244 private int mFlags; 8245 }; 8246 8247 private final class ProviderIntentResolver 8248 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8249 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8250 boolean defaultOnly, int userId) { 8251 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8252 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8253 } 8254 8255 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8256 int userId) { 8257 if (!sUserManager.exists(userId)) 8258 return null; 8259 mFlags = flags; 8260 return super.queryIntent(intent, resolvedType, 8261 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8262 } 8263 8264 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8265 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8266 if (!sUserManager.exists(userId)) 8267 return null; 8268 if (packageProviders == null) { 8269 return null; 8270 } 8271 mFlags = flags; 8272 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8273 final int N = packageProviders.size(); 8274 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8275 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8276 8277 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8278 for (int i = 0; i < N; ++i) { 8279 intentFilters = packageProviders.get(i).intents; 8280 if (intentFilters != null && intentFilters.size() > 0) { 8281 PackageParser.ProviderIntentInfo[] array = 8282 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8283 intentFilters.toArray(array); 8284 listCut.add(array); 8285 } 8286 } 8287 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8288 } 8289 8290 public final void addProvider(PackageParser.Provider p) { 8291 if (mProviders.containsKey(p.getComponentName())) { 8292 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8293 return; 8294 } 8295 8296 mProviders.put(p.getComponentName(), p); 8297 if (DEBUG_SHOW_INFO) { 8298 Log.v(TAG, " " 8299 + (p.info.nonLocalizedLabel != null 8300 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8301 Log.v(TAG, " Class=" + p.info.name); 8302 } 8303 final int NI = p.intents.size(); 8304 int j; 8305 for (j = 0; j < NI; j++) { 8306 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8307 if (DEBUG_SHOW_INFO) { 8308 Log.v(TAG, " IntentFilter:"); 8309 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8310 } 8311 if (!intent.debugCheck()) { 8312 Log.w(TAG, "==> For Provider " + p.info.name); 8313 } 8314 addFilter(intent); 8315 } 8316 } 8317 8318 public final void removeProvider(PackageParser.Provider p) { 8319 mProviders.remove(p.getComponentName()); 8320 if (DEBUG_SHOW_INFO) { 8321 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8322 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8323 Log.v(TAG, " Class=" + p.info.name); 8324 } 8325 final int NI = p.intents.size(); 8326 int j; 8327 for (j = 0; j < NI; j++) { 8328 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8329 if (DEBUG_SHOW_INFO) { 8330 Log.v(TAG, " IntentFilter:"); 8331 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8332 } 8333 removeFilter(intent); 8334 } 8335 } 8336 8337 @Override 8338 protected boolean allowFilterResult( 8339 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8340 ProviderInfo filterPi = filter.provider.info; 8341 for (int i = dest.size() - 1; i >= 0; i--) { 8342 ProviderInfo destPi = dest.get(i).providerInfo; 8343 if (destPi.name == filterPi.name 8344 && destPi.packageName == filterPi.packageName) { 8345 return false; 8346 } 8347 } 8348 return true; 8349 } 8350 8351 @Override 8352 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8353 return new PackageParser.ProviderIntentInfo[size]; 8354 } 8355 8356 @Override 8357 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8358 if (!sUserManager.exists(userId)) 8359 return true; 8360 PackageParser.Package p = filter.provider.owner; 8361 if (p != null) { 8362 PackageSetting ps = (PackageSetting) p.mExtras; 8363 if (ps != null) { 8364 // System apps are never considered stopped for purposes of 8365 // filtering, because there may be no way for the user to 8366 // actually re-launch them. 8367 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8368 && ps.getStopped(userId); 8369 } 8370 } 8371 return false; 8372 } 8373 8374 @Override 8375 protected boolean isPackageForFilter(String packageName, 8376 PackageParser.ProviderIntentInfo info) { 8377 return packageName.equals(info.provider.owner.packageName); 8378 } 8379 8380 @Override 8381 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8382 int match, int userId) { 8383 if (!sUserManager.exists(userId)) 8384 return null; 8385 final PackageParser.ProviderIntentInfo info = filter; 8386 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8387 return null; 8388 } 8389 final PackageParser.Provider provider = info.provider; 8390 if (mSafeMode && (provider.info.applicationInfo.flags 8391 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8392 return null; 8393 } 8394 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8395 if (ps == null) { 8396 return null; 8397 } 8398 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8399 ps.readUserState(userId), userId); 8400 if (pi == null) { 8401 return null; 8402 } 8403 final ResolveInfo res = new ResolveInfo(); 8404 res.providerInfo = pi; 8405 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8406 res.filter = filter; 8407 } 8408 res.priority = info.getPriority(); 8409 res.preferredOrder = provider.owner.mPreferredOrder; 8410 res.match = match; 8411 res.isDefault = info.hasDefault; 8412 res.labelRes = info.labelRes; 8413 res.nonLocalizedLabel = info.nonLocalizedLabel; 8414 res.icon = info.icon; 8415 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8416 return res; 8417 } 8418 8419 @Override 8420 protected void sortResults(List<ResolveInfo> results) { 8421 Collections.sort(results, mResolvePrioritySorter); 8422 } 8423 8424 @Override 8425 protected void dumpFilter(PrintWriter out, String prefix, 8426 PackageParser.ProviderIntentInfo filter) { 8427 out.print(prefix); 8428 out.print( 8429 Integer.toHexString(System.identityHashCode(filter.provider))); 8430 out.print(' '); 8431 filter.provider.printComponentShortName(out); 8432 out.print(" filter "); 8433 out.println(Integer.toHexString(System.identityHashCode(filter))); 8434 } 8435 8436 @Override 8437 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8438 return filter.provider; 8439 } 8440 8441 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8442 PackageParser.Provider provider = (PackageParser.Provider)label; 8443 out.print(prefix); out.print( 8444 Integer.toHexString(System.identityHashCode(provider))); 8445 out.print(' '); 8446 provider.printComponentShortName(out); 8447 if (count > 1) { 8448 out.print(" ("); out.print(count); out.print(" filters)"); 8449 } 8450 out.println(); 8451 } 8452 8453 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8454 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8455 private int mFlags; 8456 }; 8457 8458 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8459 new Comparator<ResolveInfo>() { 8460 public int compare(ResolveInfo r1, ResolveInfo r2) { 8461 int v1 = r1.priority; 8462 int v2 = r2.priority; 8463 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8464 if (v1 != v2) { 8465 return (v1 > v2) ? -1 : 1; 8466 } 8467 v1 = r1.preferredOrder; 8468 v2 = r2.preferredOrder; 8469 if (v1 != v2) { 8470 return (v1 > v2) ? -1 : 1; 8471 } 8472 if (r1.isDefault != r2.isDefault) { 8473 return r1.isDefault ? -1 : 1; 8474 } 8475 v1 = r1.match; 8476 v2 = r2.match; 8477 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8478 if (v1 != v2) { 8479 return (v1 > v2) ? -1 : 1; 8480 } 8481 if (r1.system != r2.system) { 8482 return r1.system ? -1 : 1; 8483 } 8484 return 0; 8485 } 8486 }; 8487 8488 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8489 new Comparator<ProviderInfo>() { 8490 public int compare(ProviderInfo p1, ProviderInfo p2) { 8491 final int v1 = p1.initOrder; 8492 final int v2 = p2.initOrder; 8493 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8494 } 8495 }; 8496 8497 final void sendPackageBroadcast(final String action, final String pkg, 8498 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8499 final int[] userIds) { 8500 mHandler.post(new Runnable() { 8501 @Override 8502 public void run() { 8503 try { 8504 final IActivityManager am = ActivityManagerNative.getDefault(); 8505 if (am == null) return; 8506 final int[] resolvedUserIds; 8507 if (userIds == null) { 8508 resolvedUserIds = am.getRunningUserIds(); 8509 } else { 8510 resolvedUserIds = userIds; 8511 } 8512 for (int id : resolvedUserIds) { 8513 final Intent intent = new Intent(action, 8514 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8515 if (extras != null) { 8516 intent.putExtras(extras); 8517 } 8518 if (targetPkg != null) { 8519 intent.setPackage(targetPkg); 8520 } 8521 // Modify the UID when posting to other users 8522 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8523 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8524 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8525 intent.putExtra(Intent.EXTRA_UID, uid); 8526 } 8527 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8528 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8529 if (DEBUG_BROADCASTS) { 8530 RuntimeException here = new RuntimeException("here"); 8531 here.fillInStackTrace(); 8532 Slog.d(TAG, "Sending to user " + id + ": " 8533 + intent.toShortString(false, true, false, false) 8534 + " " + intent.getExtras(), here); 8535 } 8536 am.broadcastIntent(null, intent, null, finishedReceiver, 8537 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8538 finishedReceiver != null, false, id); 8539 } 8540 } catch (RemoteException ex) { 8541 } 8542 } 8543 }); 8544 } 8545 8546 /** 8547 * Check if the external storage media is available. This is true if there 8548 * is a mounted external storage medium or if the external storage is 8549 * emulated. 8550 */ 8551 private boolean isExternalMediaAvailable() { 8552 return mMediaMounted || Environment.isExternalStorageEmulated(); 8553 } 8554 8555 @Override 8556 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8557 // writer 8558 synchronized (mPackages) { 8559 if (!isExternalMediaAvailable()) { 8560 // If the external storage is no longer mounted at this point, 8561 // the caller may not have been able to delete all of this 8562 // packages files and can not delete any more. Bail. 8563 return null; 8564 } 8565 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8566 if (lastPackage != null) { 8567 pkgs.remove(lastPackage); 8568 } 8569 if (pkgs.size() > 0) { 8570 return pkgs.get(0); 8571 } 8572 } 8573 return null; 8574 } 8575 8576 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8577 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8578 userId, andCode ? 1 : 0, packageName); 8579 if (mSystemReady) { 8580 msg.sendToTarget(); 8581 } else { 8582 if (mPostSystemReadyMessages == null) { 8583 mPostSystemReadyMessages = new ArrayList<>(); 8584 } 8585 mPostSystemReadyMessages.add(msg); 8586 } 8587 } 8588 8589 void startCleaningPackages() { 8590 // reader 8591 synchronized (mPackages) { 8592 if (!isExternalMediaAvailable()) { 8593 return; 8594 } 8595 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8596 return; 8597 } 8598 } 8599 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8600 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8601 IActivityManager am = ActivityManagerNative.getDefault(); 8602 if (am != null) { 8603 try { 8604 am.startService(null, intent, null, UserHandle.USER_OWNER); 8605 } catch (RemoteException e) { 8606 } 8607 } 8608 } 8609 8610 @Override 8611 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8612 int installFlags, String installerPackageName, VerificationParams verificationParams, 8613 String packageAbiOverride) { 8614 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8615 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8616 } 8617 8618 @Override 8619 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8620 int installFlags, String installerPackageName, VerificationParams verificationParams, 8621 String packageAbiOverride, int userId) { 8622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8623 8624 final int callingUid = Binder.getCallingUid(); 8625 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8626 8627 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8628 try { 8629 if (observer != null) { 8630 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8631 } 8632 } catch (RemoteException re) { 8633 } 8634 return; 8635 } 8636 8637 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8638 installFlags |= PackageManager.INSTALL_FROM_ADB; 8639 8640 } else { 8641 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8642 // about installerPackageName. 8643 8644 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8645 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8646 } 8647 8648 UserHandle user; 8649 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8650 user = UserHandle.ALL; 8651 } else { 8652 user = new UserHandle(userId); 8653 } 8654 8655 // Only system components can circumvent runtime permissions when installing. 8656 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8657 && mContext.checkCallingOrSelfPermission(Manifest.permission 8658 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8659 throw new SecurityException("You need the " 8660 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8661 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8662 } 8663 8664 verificationParams.setInstallerUid(callingUid); 8665 8666 final File originFile = new File(originPath); 8667 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8668 8669 final Message msg = mHandler.obtainMessage(INIT_COPY); 8670 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8671 null, verificationParams, user, packageAbiOverride); 8672 mHandler.sendMessage(msg); 8673 } 8674 8675 void installStage(String packageName, File stagedDir, String stagedCid, 8676 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8677 String installerPackageName, int installerUid, UserHandle user) { 8678 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8679 params.referrerUri, installerUid, null); 8680 8681 final OriginInfo origin; 8682 if (stagedDir != null) { 8683 origin = OriginInfo.fromStagedFile(stagedDir); 8684 } else { 8685 origin = OriginInfo.fromStagedContainer(stagedCid); 8686 } 8687 8688 final Message msg = mHandler.obtainMessage(INIT_COPY); 8689 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8690 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8691 mHandler.sendMessage(msg); 8692 } 8693 8694 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8695 Bundle extras = new Bundle(1); 8696 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8697 8698 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8699 packageName, extras, null, null, new int[] {userId}); 8700 try { 8701 IActivityManager am = ActivityManagerNative.getDefault(); 8702 final boolean isSystem = 8703 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8704 if (isSystem && am.isUserRunning(userId, false)) { 8705 // The just-installed/enabled app is bundled on the system, so presumed 8706 // to be able to run automatically without needing an explicit launch. 8707 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8708 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8709 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8710 .setPackage(packageName); 8711 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8712 android.app.AppOpsManager.OP_NONE, false, false, userId); 8713 } 8714 } catch (RemoteException e) { 8715 // shouldn't happen 8716 Slog.w(TAG, "Unable to bootstrap installed package", e); 8717 } 8718 } 8719 8720 @Override 8721 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8722 int userId) { 8723 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8724 PackageSetting pkgSetting; 8725 final int uid = Binder.getCallingUid(); 8726 enforceCrossUserPermission(uid, userId, true, true, 8727 "setApplicationHiddenSetting for user " + userId); 8728 8729 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8730 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8731 return false; 8732 } 8733 8734 long callingId = Binder.clearCallingIdentity(); 8735 try { 8736 boolean sendAdded = false; 8737 boolean sendRemoved = false; 8738 // writer 8739 synchronized (mPackages) { 8740 pkgSetting = mSettings.mPackages.get(packageName); 8741 if (pkgSetting == null) { 8742 return false; 8743 } 8744 if (pkgSetting.getHidden(userId) != hidden) { 8745 pkgSetting.setHidden(hidden, userId); 8746 mSettings.writePackageRestrictionsLPr(userId); 8747 if (hidden) { 8748 sendRemoved = true; 8749 } else { 8750 sendAdded = true; 8751 } 8752 } 8753 } 8754 if (sendAdded) { 8755 sendPackageAddedForUser(packageName, pkgSetting, userId); 8756 return true; 8757 } 8758 if (sendRemoved) { 8759 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8760 "hiding pkg"); 8761 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8762 } 8763 } finally { 8764 Binder.restoreCallingIdentity(callingId); 8765 } 8766 return false; 8767 } 8768 8769 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8770 int userId) { 8771 final PackageRemovedInfo info = new PackageRemovedInfo(); 8772 info.removedPackage = packageName; 8773 info.removedUsers = new int[] {userId}; 8774 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8775 info.sendBroadcast(false, false, false); 8776 } 8777 8778 /** 8779 * Returns true if application is not found or there was an error. Otherwise it returns 8780 * the hidden state of the package for the given user. 8781 */ 8782 @Override 8783 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8784 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8785 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8786 false, "getApplicationHidden for user " + userId); 8787 PackageSetting pkgSetting; 8788 long callingId = Binder.clearCallingIdentity(); 8789 try { 8790 // writer 8791 synchronized (mPackages) { 8792 pkgSetting = mSettings.mPackages.get(packageName); 8793 if (pkgSetting == null) { 8794 return true; 8795 } 8796 return pkgSetting.getHidden(userId); 8797 } 8798 } finally { 8799 Binder.restoreCallingIdentity(callingId); 8800 } 8801 } 8802 8803 /** 8804 * @hide 8805 */ 8806 @Override 8807 public int installExistingPackageAsUser(String packageName, int userId) { 8808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8809 null); 8810 PackageSetting pkgSetting; 8811 final int uid = Binder.getCallingUid(); 8812 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8813 + userId); 8814 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8815 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8816 } 8817 8818 long callingId = Binder.clearCallingIdentity(); 8819 try { 8820 boolean sendAdded = false; 8821 8822 // writer 8823 synchronized (mPackages) { 8824 pkgSetting = mSettings.mPackages.get(packageName); 8825 if (pkgSetting == null) { 8826 return PackageManager.INSTALL_FAILED_INVALID_URI; 8827 } 8828 if (!pkgSetting.getInstalled(userId)) { 8829 pkgSetting.setInstalled(true, userId); 8830 pkgSetting.setHidden(false, userId); 8831 mSettings.writePackageRestrictionsLPr(userId); 8832 sendAdded = true; 8833 } 8834 } 8835 8836 if (sendAdded) { 8837 sendPackageAddedForUser(packageName, pkgSetting, userId); 8838 } 8839 } finally { 8840 Binder.restoreCallingIdentity(callingId); 8841 } 8842 8843 return PackageManager.INSTALL_SUCCEEDED; 8844 } 8845 8846 boolean isUserRestricted(int userId, String restrictionKey) { 8847 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8848 if (restrictions.getBoolean(restrictionKey, false)) { 8849 Log.w(TAG, "User is restricted: " + restrictionKey); 8850 return true; 8851 } 8852 return false; 8853 } 8854 8855 @Override 8856 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8857 mContext.enforceCallingOrSelfPermission( 8858 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8859 "Only package verification agents can verify applications"); 8860 8861 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8862 final PackageVerificationResponse response = new PackageVerificationResponse( 8863 verificationCode, Binder.getCallingUid()); 8864 msg.arg1 = id; 8865 msg.obj = response; 8866 mHandler.sendMessage(msg); 8867 } 8868 8869 @Override 8870 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8871 long millisecondsToDelay) { 8872 mContext.enforceCallingOrSelfPermission( 8873 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8874 "Only package verification agents can extend verification timeouts"); 8875 8876 final PackageVerificationState state = mPendingVerification.get(id); 8877 final PackageVerificationResponse response = new PackageVerificationResponse( 8878 verificationCodeAtTimeout, Binder.getCallingUid()); 8879 8880 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8881 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8882 } 8883 if (millisecondsToDelay < 0) { 8884 millisecondsToDelay = 0; 8885 } 8886 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8887 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8888 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8889 } 8890 8891 if ((state != null) && !state.timeoutExtended()) { 8892 state.extendTimeout(); 8893 8894 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8895 msg.arg1 = id; 8896 msg.obj = response; 8897 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8898 } 8899 } 8900 8901 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8902 int verificationCode, UserHandle user) { 8903 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8904 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8905 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8906 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8907 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8908 8909 mContext.sendBroadcastAsUser(intent, user, 8910 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8911 } 8912 8913 private ComponentName matchComponentForVerifier(String packageName, 8914 List<ResolveInfo> receivers) { 8915 ActivityInfo targetReceiver = null; 8916 8917 final int NR = receivers.size(); 8918 for (int i = 0; i < NR; i++) { 8919 final ResolveInfo info = receivers.get(i); 8920 if (info.activityInfo == null) { 8921 continue; 8922 } 8923 8924 if (packageName.equals(info.activityInfo.packageName)) { 8925 targetReceiver = info.activityInfo; 8926 break; 8927 } 8928 } 8929 8930 if (targetReceiver == null) { 8931 return null; 8932 } 8933 8934 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8935 } 8936 8937 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8938 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8939 if (pkgInfo.verifiers.length == 0) { 8940 return null; 8941 } 8942 8943 final int N = pkgInfo.verifiers.length; 8944 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8945 for (int i = 0; i < N; i++) { 8946 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8947 8948 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8949 receivers); 8950 if (comp == null) { 8951 continue; 8952 } 8953 8954 final int verifierUid = getUidForVerifier(verifierInfo); 8955 if (verifierUid == -1) { 8956 continue; 8957 } 8958 8959 if (DEBUG_VERIFY) { 8960 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8961 + " with the correct signature"); 8962 } 8963 sufficientVerifiers.add(comp); 8964 verificationState.addSufficientVerifier(verifierUid); 8965 } 8966 8967 return sufficientVerifiers; 8968 } 8969 8970 private int getUidForVerifier(VerifierInfo verifierInfo) { 8971 synchronized (mPackages) { 8972 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8973 if (pkg == null) { 8974 return -1; 8975 } else if (pkg.mSignatures.length != 1) { 8976 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8977 + " has more than one signature; ignoring"); 8978 return -1; 8979 } 8980 8981 /* 8982 * If the public key of the package's signature does not match 8983 * our expected public key, then this is a different package and 8984 * we should skip. 8985 */ 8986 8987 final byte[] expectedPublicKey; 8988 try { 8989 final Signature verifierSig = pkg.mSignatures[0]; 8990 final PublicKey publicKey = verifierSig.getPublicKey(); 8991 expectedPublicKey = publicKey.getEncoded(); 8992 } catch (CertificateException e) { 8993 return -1; 8994 } 8995 8996 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8997 8998 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8999 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9000 + " does not have the expected public key; ignoring"); 9001 return -1; 9002 } 9003 9004 return pkg.applicationInfo.uid; 9005 } 9006 } 9007 9008 @Override 9009 public void finishPackageInstall(int token) { 9010 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9011 9012 if (DEBUG_INSTALL) { 9013 Slog.v(TAG, "BM finishing package install for " + token); 9014 } 9015 9016 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9017 mHandler.sendMessage(msg); 9018 } 9019 9020 /** 9021 * Get the verification agent timeout. 9022 * 9023 * @return verification timeout in milliseconds 9024 */ 9025 private long getVerificationTimeout() { 9026 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9027 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9028 DEFAULT_VERIFICATION_TIMEOUT); 9029 } 9030 9031 /** 9032 * Get the default verification agent response code. 9033 * 9034 * @return default verification response code 9035 */ 9036 private int getDefaultVerificationResponse() { 9037 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9038 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9039 DEFAULT_VERIFICATION_RESPONSE); 9040 } 9041 9042 /** 9043 * Check whether or not package verification has been enabled. 9044 * 9045 * @return true if verification should be performed 9046 */ 9047 private boolean isVerificationEnabled(int userId, int installFlags) { 9048 if (!DEFAULT_VERIFY_ENABLE) { 9049 return false; 9050 } 9051 9052 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9053 9054 // Check if installing from ADB 9055 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9056 // Do not run verification in a test harness environment 9057 if (ActivityManager.isRunningInTestHarness()) { 9058 return false; 9059 } 9060 if (ensureVerifyAppsEnabled) { 9061 return true; 9062 } 9063 // Check if the developer does not want package verification for ADB installs 9064 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9065 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9066 return false; 9067 } 9068 } 9069 9070 if (ensureVerifyAppsEnabled) { 9071 return true; 9072 } 9073 9074 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9075 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9076 } 9077 9078 @Override 9079 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9080 throws RemoteException { 9081 mContext.enforceCallingOrSelfPermission( 9082 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9083 "Only intentfilter verification agents can verify applications"); 9084 9085 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9086 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9087 Binder.getCallingUid(), verificationCode, failedDomains); 9088 msg.arg1 = id; 9089 msg.obj = response; 9090 mHandler.sendMessage(msg); 9091 } 9092 9093 @Override 9094 public int getIntentVerificationStatus(String packageName, int userId) { 9095 synchronized (mPackages) { 9096 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9097 } 9098 } 9099 9100 @Override 9101 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9102 boolean result = false; 9103 synchronized (mPackages) { 9104 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9105 } 9106 scheduleWritePackageRestrictionsLocked(userId); 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 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9143 } 9144 } 9145 9146 @Override 9147 public String getDefaultBrowserPackageName(int userId) { 9148 synchronized (mPackages) { 9149 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9150 } 9151 } 9152 9153 /** 9154 * Get the "allow unknown sources" setting. 9155 * 9156 * @return the current "allow unknown sources" setting 9157 */ 9158 private int getUnknownSourcesSettings() { 9159 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9160 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9161 -1); 9162 } 9163 9164 @Override 9165 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9166 final int uid = Binder.getCallingUid(); 9167 // writer 9168 synchronized (mPackages) { 9169 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9170 if (targetPackageSetting == null) { 9171 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9172 } 9173 9174 PackageSetting installerPackageSetting; 9175 if (installerPackageName != null) { 9176 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9177 if (installerPackageSetting == null) { 9178 throw new IllegalArgumentException("Unknown installer package: " 9179 + installerPackageName); 9180 } 9181 } else { 9182 installerPackageSetting = null; 9183 } 9184 9185 Signature[] callerSignature; 9186 Object obj = mSettings.getUserIdLPr(uid); 9187 if (obj != null) { 9188 if (obj instanceof SharedUserSetting) { 9189 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9190 } else if (obj instanceof PackageSetting) { 9191 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9192 } else { 9193 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9194 } 9195 } else { 9196 throw new SecurityException("Unknown calling uid " + uid); 9197 } 9198 9199 // Verify: can't set installerPackageName to a package that is 9200 // not signed with the same cert as the caller. 9201 if (installerPackageSetting != null) { 9202 if (compareSignatures(callerSignature, 9203 installerPackageSetting.signatures.mSignatures) 9204 != PackageManager.SIGNATURE_MATCH) { 9205 throw new SecurityException( 9206 "Caller does not have same cert as new installer package " 9207 + installerPackageName); 9208 } 9209 } 9210 9211 // Verify: if target already has an installer package, it must 9212 // be signed with the same cert as the caller. 9213 if (targetPackageSetting.installerPackageName != null) { 9214 PackageSetting setting = mSettings.mPackages.get( 9215 targetPackageSetting.installerPackageName); 9216 // If the currently set package isn't valid, then it's always 9217 // okay to change it. 9218 if (setting != null) { 9219 if (compareSignatures(callerSignature, 9220 setting.signatures.mSignatures) 9221 != PackageManager.SIGNATURE_MATCH) { 9222 throw new SecurityException( 9223 "Caller does not have same cert as old installer package " 9224 + targetPackageSetting.installerPackageName); 9225 } 9226 } 9227 } 9228 9229 // Okay! 9230 targetPackageSetting.installerPackageName = installerPackageName; 9231 scheduleWriteSettingsLocked(); 9232 } 9233 } 9234 9235 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9236 // Queue up an async operation since the package installation may take a little while. 9237 mHandler.post(new Runnable() { 9238 public void run() { 9239 mHandler.removeCallbacks(this); 9240 // Result object to be returned 9241 PackageInstalledInfo res = new PackageInstalledInfo(); 9242 res.returnCode = currentStatus; 9243 res.uid = -1; 9244 res.pkg = null; 9245 res.removedInfo = new PackageRemovedInfo(); 9246 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9247 args.doPreInstall(res.returnCode); 9248 synchronized (mInstallLock) { 9249 installPackageLI(args, res); 9250 } 9251 args.doPostInstall(res.returnCode, res.uid); 9252 } 9253 9254 // A restore should be performed at this point if (a) the install 9255 // succeeded, (b) the operation is not an update, and (c) the new 9256 // package has not opted out of backup participation. 9257 final boolean update = res.removedInfo.removedPackage != null; 9258 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9259 boolean doRestore = !update 9260 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9261 9262 // Set up the post-install work request bookkeeping. This will be used 9263 // and cleaned up by the post-install event handling regardless of whether 9264 // there's a restore pass performed. Token values are >= 1. 9265 int token; 9266 if (mNextInstallToken < 0) mNextInstallToken = 1; 9267 token = mNextInstallToken++; 9268 9269 PostInstallData data = new PostInstallData(args, res); 9270 mRunningInstalls.put(token, data); 9271 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9272 9273 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9274 // Pass responsibility to the Backup Manager. It will perform a 9275 // restore if appropriate, then pass responsibility back to the 9276 // Package Manager to run the post-install observer callbacks 9277 // and broadcasts. 9278 IBackupManager bm = IBackupManager.Stub.asInterface( 9279 ServiceManager.getService(Context.BACKUP_SERVICE)); 9280 if (bm != null) { 9281 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9282 + " to BM for possible restore"); 9283 try { 9284 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9285 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9286 } else { 9287 doRestore = false; 9288 } 9289 } catch (RemoteException e) { 9290 // can't happen; the backup manager is local 9291 } catch (Exception e) { 9292 Slog.e(TAG, "Exception trying to enqueue restore", e); 9293 doRestore = false; 9294 } 9295 } else { 9296 Slog.e(TAG, "Backup Manager not found!"); 9297 doRestore = false; 9298 } 9299 } 9300 9301 if (!doRestore) { 9302 // No restore possible, or the Backup Manager was mysteriously not 9303 // available -- just fire the post-install work request directly. 9304 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9305 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9306 mHandler.sendMessage(msg); 9307 } 9308 } 9309 }); 9310 } 9311 9312 private abstract class HandlerParams { 9313 private static final int MAX_RETRIES = 4; 9314 9315 /** 9316 * Number of times startCopy() has been attempted and had a non-fatal 9317 * error. 9318 */ 9319 private int mRetries = 0; 9320 9321 /** User handle for the user requesting the information or installation. */ 9322 private final UserHandle mUser; 9323 9324 HandlerParams(UserHandle user) { 9325 mUser = user; 9326 } 9327 9328 UserHandle getUser() { 9329 return mUser; 9330 } 9331 9332 final boolean startCopy() { 9333 boolean res; 9334 try { 9335 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9336 9337 if (++mRetries > MAX_RETRIES) { 9338 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9339 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9340 handleServiceError(); 9341 return false; 9342 } else { 9343 handleStartCopy(); 9344 res = true; 9345 } 9346 } catch (RemoteException e) { 9347 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9348 mHandler.sendEmptyMessage(MCS_RECONNECT); 9349 res = false; 9350 } 9351 handleReturnCode(); 9352 return res; 9353 } 9354 9355 final void serviceError() { 9356 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9357 handleServiceError(); 9358 handleReturnCode(); 9359 } 9360 9361 abstract void handleStartCopy() throws RemoteException; 9362 abstract void handleServiceError(); 9363 abstract void handleReturnCode(); 9364 } 9365 9366 class MeasureParams extends HandlerParams { 9367 private final PackageStats mStats; 9368 private boolean mSuccess; 9369 9370 private final IPackageStatsObserver mObserver; 9371 9372 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9373 super(new UserHandle(stats.userHandle)); 9374 mObserver = observer; 9375 mStats = stats; 9376 } 9377 9378 @Override 9379 public String toString() { 9380 return "MeasureParams{" 9381 + Integer.toHexString(System.identityHashCode(this)) 9382 + " " + mStats.packageName + "}"; 9383 } 9384 9385 @Override 9386 void handleStartCopy() throws RemoteException { 9387 synchronized (mInstallLock) { 9388 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9389 } 9390 9391 if (mSuccess) { 9392 final boolean mounted; 9393 if (Environment.isExternalStorageEmulated()) { 9394 mounted = true; 9395 } else { 9396 final String status = Environment.getExternalStorageState(); 9397 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9398 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9399 } 9400 9401 if (mounted) { 9402 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9403 9404 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9405 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9406 9407 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9408 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9409 9410 // Always subtract cache size, since it's a subdirectory 9411 mStats.externalDataSize -= mStats.externalCacheSize; 9412 9413 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9414 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9415 9416 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9417 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9418 } 9419 } 9420 } 9421 9422 @Override 9423 void handleReturnCode() { 9424 if (mObserver != null) { 9425 try { 9426 mObserver.onGetStatsCompleted(mStats, mSuccess); 9427 } catch (RemoteException e) { 9428 Slog.i(TAG, "Observer no longer exists."); 9429 } 9430 } 9431 } 9432 9433 @Override 9434 void handleServiceError() { 9435 Slog.e(TAG, "Could not measure application " + mStats.packageName 9436 + " external storage"); 9437 } 9438 } 9439 9440 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9441 throws RemoteException { 9442 long result = 0; 9443 for (File path : paths) { 9444 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9445 } 9446 return result; 9447 } 9448 9449 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9450 for (File path : paths) { 9451 try { 9452 mcs.clearDirectory(path.getAbsolutePath()); 9453 } catch (RemoteException e) { 9454 } 9455 } 9456 } 9457 9458 static class OriginInfo { 9459 /** 9460 * Location where install is coming from, before it has been 9461 * copied/renamed into place. This could be a single monolithic APK 9462 * file, or a cluster directory. This location may be untrusted. 9463 */ 9464 final File file; 9465 final String cid; 9466 9467 /** 9468 * Flag indicating that {@link #file} or {@link #cid} has already been 9469 * staged, meaning downstream users don't need to defensively copy the 9470 * contents. 9471 */ 9472 final boolean staged; 9473 9474 /** 9475 * Flag indicating that {@link #file} or {@link #cid} is an already 9476 * installed app that is being moved. 9477 */ 9478 final boolean existing; 9479 9480 final String resolvedPath; 9481 final File resolvedFile; 9482 9483 static OriginInfo fromNothing() { 9484 return new OriginInfo(null, null, false, false); 9485 } 9486 9487 static OriginInfo fromUntrustedFile(File file) { 9488 return new OriginInfo(file, null, false, false); 9489 } 9490 9491 static OriginInfo fromExistingFile(File file) { 9492 return new OriginInfo(file, null, false, true); 9493 } 9494 9495 static OriginInfo fromStagedFile(File file) { 9496 return new OriginInfo(file, null, true, false); 9497 } 9498 9499 static OriginInfo fromStagedContainer(String cid) { 9500 return new OriginInfo(null, cid, true, false); 9501 } 9502 9503 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9504 this.file = file; 9505 this.cid = cid; 9506 this.staged = staged; 9507 this.existing = existing; 9508 9509 if (cid != null) { 9510 resolvedPath = PackageHelper.getSdDir(cid); 9511 resolvedFile = new File(resolvedPath); 9512 } else if (file != null) { 9513 resolvedPath = file.getAbsolutePath(); 9514 resolvedFile = file; 9515 } else { 9516 resolvedPath = null; 9517 resolvedFile = null; 9518 } 9519 } 9520 } 9521 9522 class MoveInfo { 9523 final int moveId; 9524 final String fromUuid; 9525 final String toUuid; 9526 final String packageName; 9527 final String dataAppName; 9528 final int appId; 9529 final String seinfo; 9530 9531 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9532 String dataAppName, int appId, String seinfo) { 9533 this.moveId = moveId; 9534 this.fromUuid = fromUuid; 9535 this.toUuid = toUuid; 9536 this.packageName = packageName; 9537 this.dataAppName = dataAppName; 9538 this.appId = appId; 9539 this.seinfo = seinfo; 9540 } 9541 } 9542 9543 class InstallParams extends HandlerParams { 9544 final OriginInfo origin; 9545 final MoveInfo move; 9546 final IPackageInstallObserver2 observer; 9547 int installFlags; 9548 final String installerPackageName; 9549 final String volumeUuid; 9550 final VerificationParams verificationParams; 9551 private InstallArgs mArgs; 9552 private int mRet; 9553 final String packageAbiOverride; 9554 9555 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9556 int installFlags, String installerPackageName, String volumeUuid, 9557 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9558 super(user); 9559 this.origin = origin; 9560 this.move = move; 9561 this.observer = observer; 9562 this.installFlags = installFlags; 9563 this.installerPackageName = installerPackageName; 9564 this.volumeUuid = volumeUuid; 9565 this.verificationParams = verificationParams; 9566 this.packageAbiOverride = packageAbiOverride; 9567 } 9568 9569 @Override 9570 public String toString() { 9571 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9572 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9573 } 9574 9575 public ManifestDigest getManifestDigest() { 9576 if (verificationParams == null) { 9577 return null; 9578 } 9579 return verificationParams.getManifestDigest(); 9580 } 9581 9582 private int installLocationPolicy(PackageInfoLite pkgLite) { 9583 String packageName = pkgLite.packageName; 9584 int installLocation = pkgLite.installLocation; 9585 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9586 // reader 9587 synchronized (mPackages) { 9588 PackageParser.Package pkg = mPackages.get(packageName); 9589 if (pkg != null) { 9590 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9591 // Check for downgrading. 9592 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9593 try { 9594 checkDowngrade(pkg, pkgLite); 9595 } catch (PackageManagerException e) { 9596 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9597 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9598 } 9599 } 9600 // Check for updated system application. 9601 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9602 if (onSd) { 9603 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9604 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9605 } 9606 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9607 } else { 9608 if (onSd) { 9609 // Install flag overrides everything. 9610 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9611 } 9612 // If current upgrade specifies particular preference 9613 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9614 // Application explicitly specified internal. 9615 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9616 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9617 // App explictly prefers external. Let policy decide 9618 } else { 9619 // Prefer previous location 9620 if (isExternal(pkg)) { 9621 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9622 } 9623 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9624 } 9625 } 9626 } else { 9627 // Invalid install. Return error code 9628 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9629 } 9630 } 9631 } 9632 // All the special cases have been taken care of. 9633 // Return result based on recommended install location. 9634 if (onSd) { 9635 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9636 } 9637 return pkgLite.recommendedInstallLocation; 9638 } 9639 9640 /* 9641 * Invoke remote method to get package information and install 9642 * location values. Override install location based on default 9643 * policy if needed and then create install arguments based 9644 * on the install location. 9645 */ 9646 public void handleStartCopy() throws RemoteException { 9647 int ret = PackageManager.INSTALL_SUCCEEDED; 9648 9649 // If we're already staged, we've firmly committed to an install location 9650 if (origin.staged) { 9651 if (origin.file != null) { 9652 installFlags |= PackageManager.INSTALL_INTERNAL; 9653 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9654 } else if (origin.cid != null) { 9655 installFlags |= PackageManager.INSTALL_EXTERNAL; 9656 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9657 } else { 9658 throw new IllegalStateException("Invalid stage location"); 9659 } 9660 } 9661 9662 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9663 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9664 9665 PackageInfoLite pkgLite = null; 9666 9667 if (onInt && onSd) { 9668 // Check if both bits are set. 9669 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9670 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9671 } else { 9672 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9673 packageAbiOverride); 9674 9675 /* 9676 * If we have too little free space, try to free cache 9677 * before giving up. 9678 */ 9679 if (!origin.staged && pkgLite.recommendedInstallLocation 9680 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9681 // TODO: focus freeing disk space on the target device 9682 final StorageManager storage = StorageManager.from(mContext); 9683 final long lowThreshold = storage.getStorageLowBytes( 9684 Environment.getDataDirectory()); 9685 9686 final long sizeBytes = mContainerService.calculateInstalledSize( 9687 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9688 9689 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9690 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9691 installFlags, packageAbiOverride); 9692 } 9693 9694 /* 9695 * The cache free must have deleted the file we 9696 * downloaded to install. 9697 * 9698 * TODO: fix the "freeCache" call to not delete 9699 * the file we care about. 9700 */ 9701 if (pkgLite.recommendedInstallLocation 9702 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9703 pkgLite.recommendedInstallLocation 9704 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9705 } 9706 } 9707 } 9708 9709 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9710 int loc = pkgLite.recommendedInstallLocation; 9711 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9712 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9713 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9714 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9715 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9716 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9717 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9718 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9719 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9720 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9721 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9722 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9723 } else { 9724 // Override with defaults if needed. 9725 loc = installLocationPolicy(pkgLite); 9726 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9727 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9728 } else if (!onSd && !onInt) { 9729 // Override install location with flags 9730 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9731 // Set the flag to install on external media. 9732 installFlags |= PackageManager.INSTALL_EXTERNAL; 9733 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9734 } else { 9735 // Make sure the flag for installing on external 9736 // media is unset 9737 installFlags |= PackageManager.INSTALL_INTERNAL; 9738 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9739 } 9740 } 9741 } 9742 } 9743 9744 final InstallArgs args = createInstallArgs(this); 9745 mArgs = args; 9746 9747 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9748 /* 9749 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9750 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9751 */ 9752 int userIdentifier = getUser().getIdentifier(); 9753 if (userIdentifier == UserHandle.USER_ALL 9754 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9755 userIdentifier = UserHandle.USER_OWNER; 9756 } 9757 9758 /* 9759 * Determine if we have any installed package verifiers. If we 9760 * do, then we'll defer to them to verify the packages. 9761 */ 9762 final int requiredUid = mRequiredVerifierPackage == null ? -1 9763 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9764 if (!origin.existing && requiredUid != -1 9765 && isVerificationEnabled(userIdentifier, installFlags)) { 9766 final Intent verification = new Intent( 9767 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9768 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9769 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9770 PACKAGE_MIME_TYPE); 9771 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9772 9773 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9774 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9775 0 /* TODO: Which userId? */); 9776 9777 if (DEBUG_VERIFY) { 9778 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9779 + verification.toString() + " with " + pkgLite.verifiers.length 9780 + " optional verifiers"); 9781 } 9782 9783 final int verificationId = mPendingVerificationToken++; 9784 9785 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9786 9787 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9788 installerPackageName); 9789 9790 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9791 installFlags); 9792 9793 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9794 pkgLite.packageName); 9795 9796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9797 pkgLite.versionCode); 9798 9799 if (verificationParams != null) { 9800 if (verificationParams.getVerificationURI() != null) { 9801 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9802 verificationParams.getVerificationURI()); 9803 } 9804 if (verificationParams.getOriginatingURI() != null) { 9805 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9806 verificationParams.getOriginatingURI()); 9807 } 9808 if (verificationParams.getReferrer() != null) { 9809 verification.putExtra(Intent.EXTRA_REFERRER, 9810 verificationParams.getReferrer()); 9811 } 9812 if (verificationParams.getOriginatingUid() >= 0) { 9813 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9814 verificationParams.getOriginatingUid()); 9815 } 9816 if (verificationParams.getInstallerUid() >= 0) { 9817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9818 verificationParams.getInstallerUid()); 9819 } 9820 } 9821 9822 final PackageVerificationState verificationState = new PackageVerificationState( 9823 requiredUid, args); 9824 9825 mPendingVerification.append(verificationId, verificationState); 9826 9827 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9828 receivers, verificationState); 9829 9830 /* 9831 * If any sufficient verifiers were listed in the package 9832 * manifest, attempt to ask them. 9833 */ 9834 if (sufficientVerifiers != null) { 9835 final int N = sufficientVerifiers.size(); 9836 if (N == 0) { 9837 Slog.i(TAG, "Additional verifiers required, but none installed."); 9838 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9839 } else { 9840 for (int i = 0; i < N; i++) { 9841 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9842 9843 final Intent sufficientIntent = new Intent(verification); 9844 sufficientIntent.setComponent(verifierComponent); 9845 9846 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9847 } 9848 } 9849 } 9850 9851 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9852 mRequiredVerifierPackage, receivers); 9853 if (ret == PackageManager.INSTALL_SUCCEEDED 9854 && mRequiredVerifierPackage != null) { 9855 /* 9856 * Send the intent to the required verification agent, 9857 * but only start the verification timeout after the 9858 * target BroadcastReceivers have run. 9859 */ 9860 verification.setComponent(requiredVerifierComponent); 9861 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9862 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9863 new BroadcastReceiver() { 9864 @Override 9865 public void onReceive(Context context, Intent intent) { 9866 final Message msg = mHandler 9867 .obtainMessage(CHECK_PENDING_VERIFICATION); 9868 msg.arg1 = verificationId; 9869 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9870 } 9871 }, null, 0, null, null); 9872 9873 /* 9874 * We don't want the copy to proceed until verification 9875 * succeeds, so null out this field. 9876 */ 9877 mArgs = null; 9878 } 9879 } else { 9880 /* 9881 * No package verification is enabled, so immediately start 9882 * the remote call to initiate copy using temporary file. 9883 */ 9884 ret = args.copyApk(mContainerService, true); 9885 } 9886 } 9887 9888 mRet = ret; 9889 } 9890 9891 @Override 9892 void handleReturnCode() { 9893 // If mArgs is null, then MCS couldn't be reached. When it 9894 // reconnects, it will try again to install. At that point, this 9895 // will succeed. 9896 if (mArgs != null) { 9897 processPendingInstall(mArgs, mRet); 9898 } 9899 } 9900 9901 @Override 9902 void handleServiceError() { 9903 mArgs = createInstallArgs(this); 9904 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9905 } 9906 9907 public boolean isForwardLocked() { 9908 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9909 } 9910 } 9911 9912 /** 9913 * Used during creation of InstallArgs 9914 * 9915 * @param installFlags package installation flags 9916 * @return true if should be installed on external storage 9917 */ 9918 private static boolean installOnExternalAsec(int installFlags) { 9919 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9920 return false; 9921 } 9922 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9923 return true; 9924 } 9925 return false; 9926 } 9927 9928 /** 9929 * Used during creation of InstallArgs 9930 * 9931 * @param installFlags package installation flags 9932 * @return true if should be installed as forward locked 9933 */ 9934 private static boolean installForwardLocked(int installFlags) { 9935 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9936 } 9937 9938 private InstallArgs createInstallArgs(InstallParams params) { 9939 if (params.move != null) { 9940 return new MoveInstallArgs(params); 9941 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9942 return new AsecInstallArgs(params); 9943 } else { 9944 return new FileInstallArgs(params); 9945 } 9946 } 9947 9948 /** 9949 * Create args that describe an existing installed package. Typically used 9950 * when cleaning up old installs, or used as a move source. 9951 */ 9952 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9953 String resourcePath, String[] instructionSets) { 9954 final boolean isInAsec; 9955 if (installOnExternalAsec(installFlags)) { 9956 /* Apps on SD card are always in ASEC containers. */ 9957 isInAsec = true; 9958 } else if (installForwardLocked(installFlags) 9959 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9960 /* 9961 * Forward-locked apps are only in ASEC containers if they're the 9962 * new style 9963 */ 9964 isInAsec = true; 9965 } else { 9966 isInAsec = false; 9967 } 9968 9969 if (isInAsec) { 9970 return new AsecInstallArgs(codePath, instructionSets, 9971 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9972 } else { 9973 return new FileInstallArgs(codePath, resourcePath, instructionSets); 9974 } 9975 } 9976 9977 static abstract class InstallArgs { 9978 /** @see InstallParams#origin */ 9979 final OriginInfo origin; 9980 /** @see InstallParams#move */ 9981 final MoveInfo move; 9982 9983 final IPackageInstallObserver2 observer; 9984 // Always refers to PackageManager flags only 9985 final int installFlags; 9986 final String installerPackageName; 9987 final String volumeUuid; 9988 final ManifestDigest manifestDigest; 9989 final UserHandle user; 9990 final String abiOverride; 9991 9992 // The list of instruction sets supported by this app. This is currently 9993 // only used during the rmdex() phase to clean up resources. We can get rid of this 9994 // if we move dex files under the common app path. 9995 /* nullable */ String[] instructionSets; 9996 9997 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9998 int installFlags, String installerPackageName, String volumeUuid, 9999 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10000 String abiOverride) { 10001 this.origin = origin; 10002 this.move = move; 10003 this.installFlags = installFlags; 10004 this.observer = observer; 10005 this.installerPackageName = installerPackageName; 10006 this.volumeUuid = volumeUuid; 10007 this.manifestDigest = manifestDigest; 10008 this.user = user; 10009 this.instructionSets = instructionSets; 10010 this.abiOverride = abiOverride; 10011 } 10012 10013 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10014 abstract int doPreInstall(int status); 10015 10016 /** 10017 * Rename package into final resting place. All paths on the given 10018 * scanned package should be updated to reflect the rename. 10019 */ 10020 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10021 abstract int doPostInstall(int status, int uid); 10022 10023 /** @see PackageSettingBase#codePathString */ 10024 abstract String getCodePath(); 10025 /** @see PackageSettingBase#resourcePathString */ 10026 abstract String getResourcePath(); 10027 10028 // Need installer lock especially for dex file removal. 10029 abstract void cleanUpResourcesLI(); 10030 abstract boolean doPostDeleteLI(boolean delete); 10031 10032 /** 10033 * Called before the source arguments are copied. This is used mostly 10034 * for MoveParams when it needs to read the source file to put it in the 10035 * destination. 10036 */ 10037 int doPreCopy() { 10038 return PackageManager.INSTALL_SUCCEEDED; 10039 } 10040 10041 /** 10042 * Called after the source arguments are copied. This is used mostly for 10043 * MoveParams when it needs to read the source file to put it in the 10044 * destination. 10045 * 10046 * @return 10047 */ 10048 int doPostCopy(int uid) { 10049 return PackageManager.INSTALL_SUCCEEDED; 10050 } 10051 10052 protected boolean isFwdLocked() { 10053 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10054 } 10055 10056 protected boolean isExternalAsec() { 10057 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10058 } 10059 10060 UserHandle getUser() { 10061 return user; 10062 } 10063 } 10064 10065 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10066 if (!allCodePaths.isEmpty()) { 10067 if (instructionSets == null) { 10068 throw new IllegalStateException("instructionSet == null"); 10069 } 10070 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10071 for (String codePath : allCodePaths) { 10072 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10073 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10074 if (retCode < 0) { 10075 Slog.w(TAG, "Couldn't remove dex file for package: " 10076 + " at location " + codePath + ", retcode=" + retCode); 10077 // we don't consider this to be a failure of the core package deletion 10078 } 10079 } 10080 } 10081 } 10082 } 10083 10084 /** 10085 * Logic to handle installation of non-ASEC applications, including copying 10086 * and renaming logic. 10087 */ 10088 class FileInstallArgs extends InstallArgs { 10089 private File codeFile; 10090 private File resourceFile; 10091 10092 // Example topology: 10093 // /data/app/com.example/base.apk 10094 // /data/app/com.example/split_foo.apk 10095 // /data/app/com.example/lib/arm/libfoo.so 10096 // /data/app/com.example/lib/arm64/libfoo.so 10097 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10098 10099 /** New install */ 10100 FileInstallArgs(InstallParams params) { 10101 super(params.origin, params.move, params.observer, params.installFlags, 10102 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10103 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10104 if (isFwdLocked()) { 10105 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10106 } 10107 } 10108 10109 /** Existing install */ 10110 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10111 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10112 null); 10113 this.codeFile = (codePath != null) ? new File(codePath) : null; 10114 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10115 } 10116 10117 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10118 if (origin.staged) { 10119 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10120 codeFile = origin.file; 10121 resourceFile = origin.file; 10122 return PackageManager.INSTALL_SUCCEEDED; 10123 } 10124 10125 try { 10126 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10127 codeFile = tempDir; 10128 resourceFile = tempDir; 10129 } catch (IOException e) { 10130 Slog.w(TAG, "Failed to create copy file: " + e); 10131 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10132 } 10133 10134 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10135 @Override 10136 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10137 if (!FileUtils.isValidExtFilename(name)) { 10138 throw new IllegalArgumentException("Invalid filename: " + name); 10139 } 10140 try { 10141 final File file = new File(codeFile, name); 10142 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10143 O_RDWR | O_CREAT, 0644); 10144 Os.chmod(file.getAbsolutePath(), 0644); 10145 return new ParcelFileDescriptor(fd); 10146 } catch (ErrnoException e) { 10147 throw new RemoteException("Failed to open: " + e.getMessage()); 10148 } 10149 } 10150 }; 10151 10152 int ret = PackageManager.INSTALL_SUCCEEDED; 10153 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10154 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10155 Slog.e(TAG, "Failed to copy package"); 10156 return ret; 10157 } 10158 10159 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10160 NativeLibraryHelper.Handle handle = null; 10161 try { 10162 handle = NativeLibraryHelper.Handle.create(codeFile); 10163 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10164 abiOverride); 10165 } catch (IOException e) { 10166 Slog.e(TAG, "Copying native libraries failed", e); 10167 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10168 } finally { 10169 IoUtils.closeQuietly(handle); 10170 } 10171 10172 return ret; 10173 } 10174 10175 int doPreInstall(int status) { 10176 if (status != PackageManager.INSTALL_SUCCEEDED) { 10177 cleanUp(); 10178 } 10179 return status; 10180 } 10181 10182 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10183 if (status != PackageManager.INSTALL_SUCCEEDED) { 10184 cleanUp(); 10185 return false; 10186 } 10187 10188 final File targetDir = codeFile.getParentFile(); 10189 final File beforeCodeFile = codeFile; 10190 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10191 10192 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10193 try { 10194 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10195 } catch (ErrnoException e) { 10196 Slog.d(TAG, "Failed to rename", e); 10197 return false; 10198 } 10199 10200 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10201 Slog.d(TAG, "Failed to restorecon"); 10202 return false; 10203 } 10204 10205 // Reflect the rename internally 10206 codeFile = afterCodeFile; 10207 resourceFile = afterCodeFile; 10208 10209 // Reflect the rename in scanned details 10210 pkg.codePath = afterCodeFile.getAbsolutePath(); 10211 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10212 pkg.baseCodePath); 10213 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10214 pkg.splitCodePaths); 10215 10216 // Reflect the rename in app info 10217 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10218 pkg.applicationInfo.setCodePath(pkg.codePath); 10219 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10220 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10221 pkg.applicationInfo.setResourcePath(pkg.codePath); 10222 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10223 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10224 10225 return true; 10226 } 10227 10228 int doPostInstall(int status, int uid) { 10229 if (status != PackageManager.INSTALL_SUCCEEDED) { 10230 cleanUp(); 10231 } 10232 return status; 10233 } 10234 10235 @Override 10236 String getCodePath() { 10237 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10238 } 10239 10240 @Override 10241 String getResourcePath() { 10242 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10243 } 10244 10245 private boolean cleanUp() { 10246 if (codeFile == null || !codeFile.exists()) { 10247 return false; 10248 } 10249 10250 if (codeFile.isDirectory()) { 10251 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10252 } else { 10253 codeFile.delete(); 10254 } 10255 10256 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10257 resourceFile.delete(); 10258 } 10259 10260 return true; 10261 } 10262 10263 void cleanUpResourcesLI() { 10264 // Try enumerating all code paths before deleting 10265 List<String> allCodePaths = Collections.EMPTY_LIST; 10266 if (codeFile != null && codeFile.exists()) { 10267 try { 10268 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10269 allCodePaths = pkg.getAllCodePaths(); 10270 } catch (PackageParserException e) { 10271 // Ignored; we tried our best 10272 } 10273 } 10274 10275 cleanUp(); 10276 removeDexFiles(allCodePaths, instructionSets); 10277 } 10278 10279 boolean doPostDeleteLI(boolean delete) { 10280 // XXX err, shouldn't we respect the delete flag? 10281 cleanUpResourcesLI(); 10282 return true; 10283 } 10284 } 10285 10286 private boolean isAsecExternal(String cid) { 10287 final String asecPath = PackageHelper.getSdFilesystem(cid); 10288 return !asecPath.startsWith(mAsecInternalPath); 10289 } 10290 10291 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10292 PackageManagerException { 10293 if (copyRet < 0) { 10294 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10295 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10296 throw new PackageManagerException(copyRet, message); 10297 } 10298 } 10299 } 10300 10301 /** 10302 * Extract the MountService "container ID" from the full code path of an 10303 * .apk. 10304 */ 10305 static String cidFromCodePath(String fullCodePath) { 10306 int eidx = fullCodePath.lastIndexOf("/"); 10307 String subStr1 = fullCodePath.substring(0, eidx); 10308 int sidx = subStr1.lastIndexOf("/"); 10309 return subStr1.substring(sidx+1, eidx); 10310 } 10311 10312 /** 10313 * Logic to handle installation of ASEC applications, including copying and 10314 * renaming logic. 10315 */ 10316 class AsecInstallArgs extends InstallArgs { 10317 static final String RES_FILE_NAME = "pkg.apk"; 10318 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10319 10320 String cid; 10321 String packagePath; 10322 String resourcePath; 10323 10324 /** New install */ 10325 AsecInstallArgs(InstallParams params) { 10326 super(params.origin, params.move, params.observer, params.installFlags, 10327 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10328 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10329 } 10330 10331 /** Existing install */ 10332 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10333 boolean isExternal, boolean isForwardLocked) { 10334 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10335 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10336 instructionSets, null); 10337 // Hackily pretend we're still looking at a full code path 10338 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10339 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10340 } 10341 10342 // Extract cid from fullCodePath 10343 int eidx = fullCodePath.lastIndexOf("/"); 10344 String subStr1 = fullCodePath.substring(0, eidx); 10345 int sidx = subStr1.lastIndexOf("/"); 10346 cid = subStr1.substring(sidx+1, eidx); 10347 setMountPath(subStr1); 10348 } 10349 10350 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10351 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10352 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10353 instructionSets, null); 10354 this.cid = cid; 10355 setMountPath(PackageHelper.getSdDir(cid)); 10356 } 10357 10358 void createCopyFile() { 10359 cid = mInstallerService.allocateExternalStageCidLegacy(); 10360 } 10361 10362 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10363 if (origin.staged) { 10364 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10365 cid = origin.cid; 10366 setMountPath(PackageHelper.getSdDir(cid)); 10367 return PackageManager.INSTALL_SUCCEEDED; 10368 } 10369 10370 if (temp) { 10371 createCopyFile(); 10372 } else { 10373 /* 10374 * Pre-emptively destroy the container since it's destroyed if 10375 * copying fails due to it existing anyway. 10376 */ 10377 PackageHelper.destroySdDir(cid); 10378 } 10379 10380 final String newMountPath = imcs.copyPackageToContainer( 10381 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10382 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10383 10384 if (newMountPath != null) { 10385 setMountPath(newMountPath); 10386 return PackageManager.INSTALL_SUCCEEDED; 10387 } else { 10388 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10389 } 10390 } 10391 10392 @Override 10393 String getCodePath() { 10394 return packagePath; 10395 } 10396 10397 @Override 10398 String getResourcePath() { 10399 return resourcePath; 10400 } 10401 10402 int doPreInstall(int status) { 10403 if (status != PackageManager.INSTALL_SUCCEEDED) { 10404 // Destroy container 10405 PackageHelper.destroySdDir(cid); 10406 } else { 10407 boolean mounted = PackageHelper.isContainerMounted(cid); 10408 if (!mounted) { 10409 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10410 Process.SYSTEM_UID); 10411 if (newMountPath != null) { 10412 setMountPath(newMountPath); 10413 } else { 10414 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10415 } 10416 } 10417 } 10418 return status; 10419 } 10420 10421 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10422 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10423 String newMountPath = null; 10424 if (PackageHelper.isContainerMounted(cid)) { 10425 // Unmount the container 10426 if (!PackageHelper.unMountSdDir(cid)) { 10427 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10428 return false; 10429 } 10430 } 10431 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10432 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10433 " which might be stale. Will try to clean up."); 10434 // Clean up the stale container and proceed to recreate. 10435 if (!PackageHelper.destroySdDir(newCacheId)) { 10436 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10437 return false; 10438 } 10439 // Successfully cleaned up stale container. Try to rename again. 10440 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10441 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10442 + " inspite of cleaning it up."); 10443 return false; 10444 } 10445 } 10446 if (!PackageHelper.isContainerMounted(newCacheId)) { 10447 Slog.w(TAG, "Mounting container " + newCacheId); 10448 newMountPath = PackageHelper.mountSdDir(newCacheId, 10449 getEncryptKey(), Process.SYSTEM_UID); 10450 } else { 10451 newMountPath = PackageHelper.getSdDir(newCacheId); 10452 } 10453 if (newMountPath == null) { 10454 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10455 return false; 10456 } 10457 Log.i(TAG, "Succesfully renamed " + cid + 10458 " to " + newCacheId + 10459 " at new path: " + newMountPath); 10460 cid = newCacheId; 10461 10462 final File beforeCodeFile = new File(packagePath); 10463 setMountPath(newMountPath); 10464 final File afterCodeFile = new File(packagePath); 10465 10466 // Reflect the rename in scanned details 10467 pkg.codePath = afterCodeFile.getAbsolutePath(); 10468 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10469 pkg.baseCodePath); 10470 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10471 pkg.splitCodePaths); 10472 10473 // Reflect the rename in app info 10474 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10475 pkg.applicationInfo.setCodePath(pkg.codePath); 10476 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10477 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10478 pkg.applicationInfo.setResourcePath(pkg.codePath); 10479 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10480 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10481 10482 return true; 10483 } 10484 10485 private void setMountPath(String mountPath) { 10486 final File mountFile = new File(mountPath); 10487 10488 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10489 if (monolithicFile.exists()) { 10490 packagePath = monolithicFile.getAbsolutePath(); 10491 if (isFwdLocked()) { 10492 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10493 } else { 10494 resourcePath = packagePath; 10495 } 10496 } else { 10497 packagePath = mountFile.getAbsolutePath(); 10498 resourcePath = packagePath; 10499 } 10500 } 10501 10502 int doPostInstall(int status, int uid) { 10503 if (status != PackageManager.INSTALL_SUCCEEDED) { 10504 cleanUp(); 10505 } else { 10506 final int groupOwner; 10507 final String protectedFile; 10508 if (isFwdLocked()) { 10509 groupOwner = UserHandle.getSharedAppGid(uid); 10510 protectedFile = RES_FILE_NAME; 10511 } else { 10512 groupOwner = -1; 10513 protectedFile = null; 10514 } 10515 10516 if (uid < Process.FIRST_APPLICATION_UID 10517 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10518 Slog.e(TAG, "Failed to finalize " + cid); 10519 PackageHelper.destroySdDir(cid); 10520 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10521 } 10522 10523 boolean mounted = PackageHelper.isContainerMounted(cid); 10524 if (!mounted) { 10525 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10526 } 10527 } 10528 return status; 10529 } 10530 10531 private void cleanUp() { 10532 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10533 10534 // Destroy secure container 10535 PackageHelper.destroySdDir(cid); 10536 } 10537 10538 private List<String> getAllCodePaths() { 10539 final File codeFile = new File(getCodePath()); 10540 if (codeFile != null && codeFile.exists()) { 10541 try { 10542 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10543 return pkg.getAllCodePaths(); 10544 } catch (PackageParserException e) { 10545 // Ignored; we tried our best 10546 } 10547 } 10548 return Collections.EMPTY_LIST; 10549 } 10550 10551 void cleanUpResourcesLI() { 10552 // Enumerate all code paths before deleting 10553 cleanUpResourcesLI(getAllCodePaths()); 10554 } 10555 10556 private void cleanUpResourcesLI(List<String> allCodePaths) { 10557 cleanUp(); 10558 removeDexFiles(allCodePaths, instructionSets); 10559 } 10560 10561 String getPackageName() { 10562 return getAsecPackageName(cid); 10563 } 10564 10565 boolean doPostDeleteLI(boolean delete) { 10566 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10567 final List<String> allCodePaths = getAllCodePaths(); 10568 boolean mounted = PackageHelper.isContainerMounted(cid); 10569 if (mounted) { 10570 // Unmount first 10571 if (PackageHelper.unMountSdDir(cid)) { 10572 mounted = false; 10573 } 10574 } 10575 if (!mounted && delete) { 10576 cleanUpResourcesLI(allCodePaths); 10577 } 10578 return !mounted; 10579 } 10580 10581 @Override 10582 int doPreCopy() { 10583 if (isFwdLocked()) { 10584 if (!PackageHelper.fixSdPermissions(cid, 10585 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10586 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10587 } 10588 } 10589 10590 return PackageManager.INSTALL_SUCCEEDED; 10591 } 10592 10593 @Override 10594 int doPostCopy(int uid) { 10595 if (isFwdLocked()) { 10596 if (uid < Process.FIRST_APPLICATION_UID 10597 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10598 RES_FILE_NAME)) { 10599 Slog.e(TAG, "Failed to finalize " + cid); 10600 PackageHelper.destroySdDir(cid); 10601 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10602 } 10603 } 10604 10605 return PackageManager.INSTALL_SUCCEEDED; 10606 } 10607 } 10608 10609 /** 10610 * Logic to handle movement of existing installed applications. 10611 */ 10612 class MoveInstallArgs extends InstallArgs { 10613 private File codeFile; 10614 private File resourceFile; 10615 10616 /** New install */ 10617 MoveInstallArgs(InstallParams params) { 10618 super(params.origin, params.move, params.observer, params.installFlags, 10619 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10620 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10621 } 10622 10623 int copyApk(IMediaContainerService imcs, boolean temp) { 10624 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10625 + move.toUuid); 10626 synchronized (mInstaller) { 10627 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10628 move.dataAppName, move.appId, move.seinfo) != 0) { 10629 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10630 } 10631 } 10632 10633 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10634 resourceFile = codeFile; 10635 Slog.d(TAG, "codeFile after move is " + codeFile); 10636 10637 return PackageManager.INSTALL_SUCCEEDED; 10638 } 10639 10640 int doPreInstall(int status) { 10641 if (status != PackageManager.INSTALL_SUCCEEDED) { 10642 cleanUp(); 10643 } 10644 return status; 10645 } 10646 10647 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10648 if (status != PackageManager.INSTALL_SUCCEEDED) { 10649 cleanUp(); 10650 return false; 10651 } 10652 10653 // Reflect the move in app info 10654 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10655 pkg.applicationInfo.setCodePath(pkg.codePath); 10656 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10657 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10658 pkg.applicationInfo.setResourcePath(pkg.codePath); 10659 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10660 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10661 10662 return true; 10663 } 10664 10665 int doPostInstall(int status, int uid) { 10666 if (status != PackageManager.INSTALL_SUCCEEDED) { 10667 cleanUp(); 10668 } 10669 return status; 10670 } 10671 10672 @Override 10673 String getCodePath() { 10674 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10675 } 10676 10677 @Override 10678 String getResourcePath() { 10679 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10680 } 10681 10682 private boolean cleanUp() { 10683 if (codeFile == null || !codeFile.exists()) { 10684 return false; 10685 } 10686 10687 if (codeFile.isDirectory()) { 10688 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10689 } else { 10690 codeFile.delete(); 10691 } 10692 10693 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10694 resourceFile.delete(); 10695 } 10696 10697 return true; 10698 } 10699 10700 void cleanUpResourcesLI() { 10701 cleanUp(); 10702 } 10703 10704 boolean doPostDeleteLI(boolean delete) { 10705 // XXX err, shouldn't we respect the delete flag? 10706 cleanUpResourcesLI(); 10707 return true; 10708 } 10709 } 10710 10711 static String getAsecPackageName(String packageCid) { 10712 int idx = packageCid.lastIndexOf("-"); 10713 if (idx == -1) { 10714 return packageCid; 10715 } 10716 return packageCid.substring(0, idx); 10717 } 10718 10719 // Utility method used to create code paths based on package name and available index. 10720 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10721 String idxStr = ""; 10722 int idx = 1; 10723 // Fall back to default value of idx=1 if prefix is not 10724 // part of oldCodePath 10725 if (oldCodePath != null) { 10726 String subStr = oldCodePath; 10727 // Drop the suffix right away 10728 if (suffix != null && subStr.endsWith(suffix)) { 10729 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10730 } 10731 // If oldCodePath already contains prefix find out the 10732 // ending index to either increment or decrement. 10733 int sidx = subStr.lastIndexOf(prefix); 10734 if (sidx != -1) { 10735 subStr = subStr.substring(sidx + prefix.length()); 10736 if (subStr != null) { 10737 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10738 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10739 } 10740 try { 10741 idx = Integer.parseInt(subStr); 10742 if (idx <= 1) { 10743 idx++; 10744 } else { 10745 idx--; 10746 } 10747 } catch(NumberFormatException e) { 10748 } 10749 } 10750 } 10751 } 10752 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10753 return prefix + idxStr; 10754 } 10755 10756 private File getNextCodePath(File targetDir, String packageName) { 10757 int suffix = 1; 10758 File result; 10759 do { 10760 result = new File(targetDir, packageName + "-" + suffix); 10761 suffix++; 10762 } while (result.exists()); 10763 return result; 10764 } 10765 10766 // Utility method that returns the relative package path with respect 10767 // to the installation directory. Like say for /data/data/com.test-1.apk 10768 // string com.test-1 is returned. 10769 static String deriveCodePathName(String codePath) { 10770 if (codePath == null) { 10771 return null; 10772 } 10773 final File codeFile = new File(codePath); 10774 final String name = codeFile.getName(); 10775 if (codeFile.isDirectory()) { 10776 return name; 10777 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10778 final int lastDot = name.lastIndexOf('.'); 10779 return name.substring(0, lastDot); 10780 } else { 10781 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10782 return null; 10783 } 10784 } 10785 10786 class PackageInstalledInfo { 10787 String name; 10788 int uid; 10789 // The set of users that originally had this package installed. 10790 int[] origUsers; 10791 // The set of users that now have this package installed. 10792 int[] newUsers; 10793 PackageParser.Package pkg; 10794 int returnCode; 10795 String returnMsg; 10796 PackageRemovedInfo removedInfo; 10797 10798 public void setError(int code, String msg) { 10799 returnCode = code; 10800 returnMsg = msg; 10801 Slog.w(TAG, msg); 10802 } 10803 10804 public void setError(String msg, PackageParserException e) { 10805 returnCode = e.error; 10806 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10807 Slog.w(TAG, msg, e); 10808 } 10809 10810 public void setError(String msg, PackageManagerException e) { 10811 returnCode = e.error; 10812 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10813 Slog.w(TAG, msg, e); 10814 } 10815 10816 // In some error cases we want to convey more info back to the observer 10817 String origPackage; 10818 String origPermission; 10819 } 10820 10821 /* 10822 * Install a non-existing package. 10823 */ 10824 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10825 UserHandle user, String installerPackageName, String volumeUuid, 10826 PackageInstalledInfo res) { 10827 // Remember this for later, in case we need to rollback this install 10828 String pkgName = pkg.packageName; 10829 10830 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10831 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10832 UserHandle.USER_OWNER).exists(); 10833 synchronized(mPackages) { 10834 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10835 // A package with the same name is already installed, though 10836 // it has been renamed to an older name. The package we 10837 // are trying to install should be installed as an update to 10838 // the existing one, but that has not been requested, so bail. 10839 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10840 + " without first uninstalling package running as " 10841 + mSettings.mRenamedPackages.get(pkgName)); 10842 return; 10843 } 10844 if (mPackages.containsKey(pkgName)) { 10845 // Don't allow installation over an existing package with the same name. 10846 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10847 + " without first uninstalling."); 10848 return; 10849 } 10850 } 10851 10852 try { 10853 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10854 System.currentTimeMillis(), user); 10855 10856 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10857 // delete the partially installed application. the data directory will have to be 10858 // restored if it was already existing 10859 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10860 // remove package from internal structures. Note that we want deletePackageX to 10861 // delete the package data and cache directories that it created in 10862 // scanPackageLocked, unless those directories existed before we even tried to 10863 // install. 10864 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10865 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10866 res.removedInfo, true); 10867 } 10868 10869 } catch (PackageManagerException e) { 10870 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10871 } 10872 } 10873 10874 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10875 // Upgrade keysets are being used. Determine if new package has a superset of the 10876 // required keys. 10877 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10878 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10879 for (int i = 0; i < upgradeKeySets.length; i++) { 10880 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10881 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10882 return true; 10883 } 10884 } 10885 return false; 10886 } 10887 10888 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10889 UserHandle user, String installerPackageName, String volumeUuid, 10890 PackageInstalledInfo res) { 10891 final PackageParser.Package oldPackage; 10892 final String pkgName = pkg.packageName; 10893 final int[] allUsers; 10894 final boolean[] perUserInstalled; 10895 final boolean weFroze; 10896 10897 // First find the old package info and check signatures 10898 synchronized(mPackages) { 10899 oldPackage = mPackages.get(pkgName); 10900 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10901 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10902 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10903 // default to original signature matching 10904 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10905 != PackageManager.SIGNATURE_MATCH) { 10906 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10907 "New package has a different signature: " + pkgName); 10908 return; 10909 } 10910 } else { 10911 if(!checkUpgradeKeySetLP(ps, pkg)) { 10912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10913 "New package not signed by keys specified by upgrade-keysets: " 10914 + pkgName); 10915 return; 10916 } 10917 } 10918 10919 // In case of rollback, remember per-user/profile install state 10920 allUsers = sUserManager.getUserIds(); 10921 perUserInstalled = new boolean[allUsers.length]; 10922 for (int i = 0; i < allUsers.length; i++) { 10923 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10924 } 10925 10926 // Mark the app as frozen to prevent launching during the upgrade 10927 // process, and then kill all running instances 10928 if (!ps.frozen) { 10929 ps.frozen = true; 10930 weFroze = true; 10931 } else { 10932 weFroze = false; 10933 } 10934 } 10935 10936 // Now that we're guarded by frozen state, kill app during upgrade 10937 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 10938 10939 try { 10940 boolean sysPkg = (isSystemApp(oldPackage)); 10941 if (sysPkg) { 10942 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10943 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10944 } else { 10945 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10946 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10947 } 10948 } finally { 10949 // Regardless of success or failure of upgrade steps above, always 10950 // unfreeze the package if we froze it 10951 if (weFroze) { 10952 unfreezePackage(pkgName); 10953 } 10954 } 10955 } 10956 10957 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10958 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10959 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10960 String volumeUuid, PackageInstalledInfo res) { 10961 String pkgName = deletedPackage.packageName; 10962 boolean deletedPkg = true; 10963 boolean updatedSettings = false; 10964 10965 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10966 + deletedPackage); 10967 long origUpdateTime; 10968 if (pkg.mExtras != null) { 10969 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10970 } else { 10971 origUpdateTime = 0; 10972 } 10973 10974 // First delete the existing package while retaining the data directory 10975 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10976 res.removedInfo, true)) { 10977 // If the existing package wasn't successfully deleted 10978 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10979 deletedPkg = false; 10980 } else { 10981 // Successfully deleted the old package; proceed with replace. 10982 10983 // If deleted package lived in a container, give users a chance to 10984 // relinquish resources before killing. 10985 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10986 if (DEBUG_INSTALL) { 10987 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10988 } 10989 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10990 final ArrayList<String> pkgList = new ArrayList<String>(1); 10991 pkgList.add(deletedPackage.applicationInfo.packageName); 10992 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10993 } 10994 10995 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10996 try { 10997 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10998 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10999 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11000 perUserInstalled, res, user); 11001 updatedSettings = true; 11002 } catch (PackageManagerException e) { 11003 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11004 } 11005 } 11006 11007 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11008 // remove package from internal structures. Note that we want deletePackageX to 11009 // delete the package data and cache directories that it created in 11010 // scanPackageLocked, unless those directories existed before we even tried to 11011 // install. 11012 if(updatedSettings) { 11013 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11014 deletePackageLI( 11015 pkgName, null, true, allUsers, perUserInstalled, 11016 PackageManager.DELETE_KEEP_DATA, 11017 res.removedInfo, true); 11018 } 11019 // Since we failed to install the new package we need to restore the old 11020 // package that we deleted. 11021 if (deletedPkg) { 11022 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11023 File restoreFile = new File(deletedPackage.codePath); 11024 // Parse old package 11025 boolean oldExternal = isExternal(deletedPackage); 11026 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11027 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11028 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11029 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11030 try { 11031 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11032 } catch (PackageManagerException e) { 11033 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11034 + e.getMessage()); 11035 return; 11036 } 11037 // Restore of old package succeeded. Update permissions. 11038 // writer 11039 synchronized (mPackages) { 11040 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11041 UPDATE_PERMISSIONS_ALL); 11042 // can downgrade to reader 11043 mSettings.writeLPr(); 11044 } 11045 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11046 } 11047 } 11048 } 11049 11050 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11051 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11052 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11053 String volumeUuid, PackageInstalledInfo res) { 11054 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11055 + ", old=" + deletedPackage); 11056 boolean disabledSystem = false; 11057 boolean updatedSettings = false; 11058 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11059 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11060 != 0) { 11061 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11062 } 11063 String packageName = deletedPackage.packageName; 11064 if (packageName == null) { 11065 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11066 "Attempt to delete null packageName."); 11067 return; 11068 } 11069 PackageParser.Package oldPkg; 11070 PackageSetting oldPkgSetting; 11071 // reader 11072 synchronized (mPackages) { 11073 oldPkg = mPackages.get(packageName); 11074 oldPkgSetting = mSettings.mPackages.get(packageName); 11075 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11076 (oldPkgSetting == null)) { 11077 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11078 "Couldn't find package:" + packageName + " information"); 11079 return; 11080 } 11081 } 11082 11083 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11084 res.removedInfo.removedPackage = packageName; 11085 // Remove existing system package 11086 removePackageLI(oldPkgSetting, true); 11087 // writer 11088 synchronized (mPackages) { 11089 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11090 if (!disabledSystem && deletedPackage != null) { 11091 // We didn't need to disable the .apk as a current system package, 11092 // which means we are replacing another update that is already 11093 // installed. We need to make sure to delete the older one's .apk. 11094 res.removedInfo.args = createInstallArgsForExisting(0, 11095 deletedPackage.applicationInfo.getCodePath(), 11096 deletedPackage.applicationInfo.getResourcePath(), 11097 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11098 } else { 11099 res.removedInfo.args = null; 11100 } 11101 } 11102 11103 // Successfully disabled the old package. Now proceed with re-installation 11104 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11105 11106 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11107 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11108 11109 PackageParser.Package newPackage = null; 11110 try { 11111 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11112 if (newPackage.mExtras != null) { 11113 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11114 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11115 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11116 11117 // is the update attempting to change shared user? that isn't going to work... 11118 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11119 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11120 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11121 + " to " + newPkgSetting.sharedUser); 11122 updatedSettings = true; 11123 } 11124 } 11125 11126 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11127 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11128 perUserInstalled, res, user); 11129 updatedSettings = true; 11130 } 11131 11132 } catch (PackageManagerException e) { 11133 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11134 } 11135 11136 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11137 // Re installation failed. Restore old information 11138 // Remove new pkg information 11139 if (newPackage != null) { 11140 removeInstalledPackageLI(newPackage, true); 11141 } 11142 // Add back the old system package 11143 try { 11144 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11145 } catch (PackageManagerException e) { 11146 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11147 } 11148 // Restore the old system information in Settings 11149 synchronized (mPackages) { 11150 if (disabledSystem) { 11151 mSettings.enableSystemPackageLPw(packageName); 11152 } 11153 if (updatedSettings) { 11154 mSettings.setInstallerPackageName(packageName, 11155 oldPkgSetting.installerPackageName); 11156 } 11157 mSettings.writeLPr(); 11158 } 11159 } 11160 } 11161 11162 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11163 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11164 UserHandle user) { 11165 String pkgName = newPackage.packageName; 11166 synchronized (mPackages) { 11167 //write settings. the installStatus will be incomplete at this stage. 11168 //note that the new package setting would have already been 11169 //added to mPackages. It hasn't been persisted yet. 11170 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11171 mSettings.writeLPr(); 11172 } 11173 11174 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11175 11176 synchronized (mPackages) { 11177 updatePermissionsLPw(newPackage.packageName, newPackage, 11178 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11179 ? UPDATE_PERMISSIONS_ALL : 0)); 11180 // For system-bundled packages, we assume that installing an upgraded version 11181 // of the package implies that the user actually wants to run that new code, 11182 // so we enable the package. 11183 PackageSetting ps = mSettings.mPackages.get(pkgName); 11184 if (ps != null) { 11185 if (isSystemApp(newPackage)) { 11186 // NB: implicit assumption that system package upgrades apply to all users 11187 if (DEBUG_INSTALL) { 11188 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11189 } 11190 if (res.origUsers != null) { 11191 for (int userHandle : res.origUsers) { 11192 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11193 userHandle, installerPackageName); 11194 } 11195 } 11196 // Also convey the prior install/uninstall state 11197 if (allUsers != null && perUserInstalled != null) { 11198 for (int i = 0; i < allUsers.length; i++) { 11199 if (DEBUG_INSTALL) { 11200 Slog.d(TAG, " user " + allUsers[i] 11201 + " => " + perUserInstalled[i]); 11202 } 11203 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11204 } 11205 // these install state changes will be persisted in the 11206 // upcoming call to mSettings.writeLPr(). 11207 } 11208 } 11209 // It's implied that when a user requests installation, they want the app to be 11210 // installed and enabled. 11211 int userId = user.getIdentifier(); 11212 if (userId != UserHandle.USER_ALL) { 11213 ps.setInstalled(true, userId); 11214 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11215 } 11216 } 11217 res.name = pkgName; 11218 res.uid = newPackage.applicationInfo.uid; 11219 res.pkg = newPackage; 11220 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11221 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11222 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11223 //to update install status 11224 mSettings.writeLPr(); 11225 } 11226 } 11227 11228 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11229 final int installFlags = args.installFlags; 11230 final String installerPackageName = args.installerPackageName; 11231 final String volumeUuid = args.volumeUuid; 11232 final File tmpPackageFile = new File(args.getCodePath()); 11233 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11234 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11235 || (args.volumeUuid != null)); 11236 boolean replace = false; 11237 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11238 // Result object to be returned 11239 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11240 11241 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11242 // Retrieve PackageSettings and parse package 11243 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11244 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11245 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11246 PackageParser pp = new PackageParser(); 11247 pp.setSeparateProcesses(mSeparateProcesses); 11248 pp.setDisplayMetrics(mMetrics); 11249 11250 final PackageParser.Package pkg; 11251 try { 11252 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11253 } catch (PackageParserException e) { 11254 res.setError("Failed parse during installPackageLI", e); 11255 return; 11256 } 11257 11258 // Mark that we have an install time CPU ABI override. 11259 pkg.cpuAbiOverride = args.abiOverride; 11260 11261 String pkgName = res.name = pkg.packageName; 11262 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11263 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11264 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11265 return; 11266 } 11267 } 11268 11269 try { 11270 pp.collectCertificates(pkg, parseFlags); 11271 pp.collectManifestDigest(pkg); 11272 } catch (PackageParserException e) { 11273 res.setError("Failed collect during installPackageLI", e); 11274 return; 11275 } 11276 11277 /* If the installer passed in a manifest digest, compare it now. */ 11278 if (args.manifestDigest != null) { 11279 if (DEBUG_INSTALL) { 11280 final String parsedManifest = pkg.manifestDigest == null ? "null" 11281 : pkg.manifestDigest.toString(); 11282 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11283 + parsedManifest); 11284 } 11285 11286 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11287 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11288 return; 11289 } 11290 } else if (DEBUG_INSTALL) { 11291 final String parsedManifest = pkg.manifestDigest == null 11292 ? "null" : pkg.manifestDigest.toString(); 11293 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11294 } 11295 11296 // Get rid of all references to package scan path via parser. 11297 pp = null; 11298 String oldCodePath = null; 11299 boolean systemApp = false; 11300 synchronized (mPackages) { 11301 // Check if installing already existing package 11302 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11303 String oldName = mSettings.mRenamedPackages.get(pkgName); 11304 if (pkg.mOriginalPackages != null 11305 && pkg.mOriginalPackages.contains(oldName) 11306 && mPackages.containsKey(oldName)) { 11307 // This package is derived from an original package, 11308 // and this device has been updating from that original 11309 // name. We must continue using the original name, so 11310 // rename the new package here. 11311 pkg.setPackageName(oldName); 11312 pkgName = pkg.packageName; 11313 replace = true; 11314 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11315 + oldName + " pkgName=" + pkgName); 11316 } else if (mPackages.containsKey(pkgName)) { 11317 // This package, under its official name, already exists 11318 // on the device; we should replace it. 11319 replace = true; 11320 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11321 } 11322 } 11323 11324 PackageSetting ps = mSettings.mPackages.get(pkgName); 11325 if (ps != null) { 11326 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11327 11328 // Quick sanity check that we're signed correctly if updating; 11329 // we'll check this again later when scanning, but we want to 11330 // bail early here before tripping over redefined permissions. 11331 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11332 try { 11333 verifySignaturesLP(ps, pkg); 11334 } catch (PackageManagerException e) { 11335 res.setError(e.error, e.getMessage()); 11336 return; 11337 } 11338 } else { 11339 if (!checkUpgradeKeySetLP(ps, pkg)) { 11340 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11341 + pkg.packageName + " upgrade keys do not match the " 11342 + "previously installed version"); 11343 return; 11344 } 11345 } 11346 11347 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11348 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11349 systemApp = (ps.pkg.applicationInfo.flags & 11350 ApplicationInfo.FLAG_SYSTEM) != 0; 11351 } 11352 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11353 } 11354 11355 // Check whether the newly-scanned package wants to define an already-defined perm 11356 int N = pkg.permissions.size(); 11357 for (int i = N-1; i >= 0; i--) { 11358 PackageParser.Permission perm = pkg.permissions.get(i); 11359 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11360 if (bp != null) { 11361 // If the defining package is signed with our cert, it's okay. This 11362 // also includes the "updating the same package" case, of course. 11363 // "updating same package" could also involve key-rotation. 11364 final boolean sigsOk; 11365 if (!bp.sourcePackage.equals(pkg.packageName) 11366 || !(bp.packageSetting instanceof PackageSetting) 11367 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11368 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11369 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11370 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11371 } else { 11372 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11373 } 11374 if (!sigsOk) { 11375 // If the owning package is the system itself, we log but allow 11376 // install to proceed; we fail the install on all other permission 11377 // redefinitions. 11378 if (!bp.sourcePackage.equals("android")) { 11379 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11380 + pkg.packageName + " attempting to redeclare permission " 11381 + perm.info.name + " already owned by " + bp.sourcePackage); 11382 res.origPermission = perm.info.name; 11383 res.origPackage = bp.sourcePackage; 11384 return; 11385 } else { 11386 Slog.w(TAG, "Package " + pkg.packageName 11387 + " attempting to redeclare system permission " 11388 + perm.info.name + "; ignoring new declaration"); 11389 pkg.permissions.remove(i); 11390 } 11391 } 11392 } 11393 } 11394 11395 } 11396 11397 if (systemApp && onExternal) { 11398 // Disable updates to system apps on sdcard 11399 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11400 "Cannot install updates to system apps on sdcard"); 11401 return; 11402 } 11403 11404 if (args.move != null) { 11405 // We did an in-place move, so dex is ready to roll 11406 scanFlags |= SCAN_NO_DEX; 11407 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11408 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11409 scanFlags |= SCAN_NO_DEX; 11410 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11411 int result = mPackageDexOptimizer 11412 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11413 false /* defer */, false /* inclDependencies */); 11414 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11415 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11416 return; 11417 } 11418 } 11419 11420 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11421 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11422 return; 11423 } 11424 11425 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11426 11427 if (replace) { 11428 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11429 installerPackageName, volumeUuid, res); 11430 } else { 11431 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11432 args.user, installerPackageName, volumeUuid, res); 11433 } 11434 synchronized (mPackages) { 11435 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11436 if (ps != null) { 11437 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11438 } 11439 } 11440 } 11441 11442 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11443 if (mIntentFilterVerifierComponent == null) { 11444 Slog.d(TAG, "No IntentFilter verification will not be done as " 11445 + "there is no IntentFilterVerifier available!"); 11446 return; 11447 } 11448 11449 final int verifierUid = getPackageUid( 11450 mIntentFilterVerifierComponent.getPackageName(), 11451 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11452 11453 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11454 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11455 msg.obj = pkg; 11456 msg.arg1 = userId; 11457 msg.arg2 = verifierUid; 11458 11459 mHandler.sendMessage(msg); 11460 } 11461 11462 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11463 PackageParser.Package pkg) { 11464 int size = pkg.activities.size(); 11465 if (size == 0) { 11466 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11467 return; 11468 } 11469 11470 final boolean hasDomainURLs = hasDomainURLs(pkg); 11471 if (!hasDomainURLs) { 11472 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11473 return; 11474 } 11475 11476 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11477 + " Activities needs verification ..."); 11478 11479 final int verificationId = mIntentFilterVerificationToken++; 11480 int count = 0; 11481 final String packageName = pkg.packageName; 11482 ArrayList<String> allHosts = new ArrayList<>(); 11483 11484 synchronized (mPackages) { 11485 for (PackageParser.Activity a : pkg.activities) { 11486 for (ActivityIntentInfo filter : a.intents) { 11487 boolean needsFilterVerification = filter.needsVerification(); 11488 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11489 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11490 mIntentFilterVerifier.addOneIntentFilterVerification( 11491 verifierUid, userId, verificationId, filter, packageName); 11492 count++; 11493 } else if (!needsFilterVerification) { 11494 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11495 if (hasValidDomains(filter)) { 11496 ArrayList<String> hosts = filter.getHostsList(); 11497 if (hosts.size() > 0) { 11498 allHosts.addAll(hosts); 11499 } else { 11500 if (allHosts.isEmpty()) { 11501 allHosts.add("*"); 11502 } 11503 } 11504 } 11505 } else { 11506 Slog.d(TAG, "Verification already done for IntentFilter:" 11507 + filter.toString()); 11508 } 11509 } 11510 } 11511 } 11512 11513 if (count > 0) { 11514 mIntentFilterVerifier.startVerifications(userId); 11515 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11516 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11517 } else { 11518 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11519 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11520 packageName, allHosts) != null) { 11521 scheduleWriteSettingsLocked(); 11522 } 11523 } 11524 } 11525 11526 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11527 final ComponentName cn = filter.activity.getComponentName(); 11528 final String packageName = cn.getPackageName(); 11529 11530 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11531 packageName); 11532 if (ivi == null) { 11533 return true; 11534 } 11535 int status = ivi.getStatus(); 11536 switch (status) { 11537 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11538 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11539 return true; 11540 11541 default: 11542 // Nothing to do 11543 return false; 11544 } 11545 } 11546 11547 private static boolean isMultiArch(PackageSetting ps) { 11548 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11549 } 11550 11551 private static boolean isMultiArch(ApplicationInfo info) { 11552 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11553 } 11554 11555 private static boolean isExternal(PackageParser.Package pkg) { 11556 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11557 } 11558 11559 private static boolean isExternal(PackageSetting ps) { 11560 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11561 } 11562 11563 private static boolean isExternal(ApplicationInfo info) { 11564 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11565 } 11566 11567 private static boolean isSystemApp(PackageParser.Package pkg) { 11568 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11569 } 11570 11571 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11572 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11573 } 11574 11575 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11576 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11577 } 11578 11579 private static boolean isSystemApp(PackageSetting ps) { 11580 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11581 } 11582 11583 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11584 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11585 } 11586 11587 private int packageFlagsToInstallFlags(PackageSetting ps) { 11588 int installFlags = 0; 11589 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11590 // This existing package was an external ASEC install when we have 11591 // the external flag without a UUID 11592 installFlags |= PackageManager.INSTALL_EXTERNAL; 11593 } 11594 if (ps.isForwardLocked()) { 11595 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11596 } 11597 return installFlags; 11598 } 11599 11600 private void deleteTempPackageFiles() { 11601 final FilenameFilter filter = new FilenameFilter() { 11602 public boolean accept(File dir, String name) { 11603 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11604 } 11605 }; 11606 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11607 file.delete(); 11608 } 11609 } 11610 11611 @Override 11612 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11613 int flags) { 11614 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11615 flags); 11616 } 11617 11618 @Override 11619 public void deletePackage(final String packageName, 11620 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11621 mContext.enforceCallingOrSelfPermission( 11622 android.Manifest.permission.DELETE_PACKAGES, null); 11623 final int uid = Binder.getCallingUid(); 11624 if (UserHandle.getUserId(uid) != userId) { 11625 mContext.enforceCallingPermission( 11626 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11627 "deletePackage for user " + userId); 11628 } 11629 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11630 try { 11631 observer.onPackageDeleted(packageName, 11632 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11633 } catch (RemoteException re) { 11634 } 11635 return; 11636 } 11637 11638 boolean uninstallBlocked = false; 11639 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11640 int[] users = sUserManager.getUserIds(); 11641 for (int i = 0; i < users.length; ++i) { 11642 if (getBlockUninstallForUser(packageName, users[i])) { 11643 uninstallBlocked = true; 11644 break; 11645 } 11646 } 11647 } else { 11648 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11649 } 11650 if (uninstallBlocked) { 11651 try { 11652 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11653 null); 11654 } catch (RemoteException re) { 11655 } 11656 return; 11657 } 11658 11659 if (DEBUG_REMOVE) { 11660 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11661 } 11662 // Queue up an async operation since the package deletion may take a little while. 11663 mHandler.post(new Runnable() { 11664 public void run() { 11665 mHandler.removeCallbacks(this); 11666 final int returnCode = deletePackageX(packageName, userId, flags); 11667 if (observer != null) { 11668 try { 11669 observer.onPackageDeleted(packageName, returnCode, null); 11670 } catch (RemoteException e) { 11671 Log.i(TAG, "Observer no longer exists."); 11672 } //end catch 11673 } //end if 11674 } //end run 11675 }); 11676 } 11677 11678 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11679 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11680 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11681 try { 11682 if (dpm != null) { 11683 if (dpm.isDeviceOwner(packageName)) { 11684 return true; 11685 } 11686 int[] users; 11687 if (userId == UserHandle.USER_ALL) { 11688 users = sUserManager.getUserIds(); 11689 } else { 11690 users = new int[]{userId}; 11691 } 11692 for (int i = 0; i < users.length; ++i) { 11693 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11694 return true; 11695 } 11696 } 11697 } 11698 } catch (RemoteException e) { 11699 } 11700 return false; 11701 } 11702 11703 /** 11704 * This method is an internal method that could be get invoked either 11705 * to delete an installed package or to clean up a failed installation. 11706 * After deleting an installed package, a broadcast is sent to notify any 11707 * listeners that the package has been installed. For cleaning up a failed 11708 * installation, the broadcast is not necessary since the package's 11709 * installation wouldn't have sent the initial broadcast either 11710 * The key steps in deleting a package are 11711 * deleting the package information in internal structures like mPackages, 11712 * deleting the packages base directories through installd 11713 * updating mSettings to reflect current status 11714 * persisting settings for later use 11715 * sending a broadcast if necessary 11716 */ 11717 private int deletePackageX(String packageName, int userId, int flags) { 11718 final PackageRemovedInfo info = new PackageRemovedInfo(); 11719 final boolean res; 11720 11721 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11722 ? UserHandle.ALL : new UserHandle(userId); 11723 11724 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11725 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11726 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11727 } 11728 11729 boolean removedForAllUsers = false; 11730 boolean systemUpdate = false; 11731 11732 // for the uninstall-updates case and restricted profiles, remember the per- 11733 // userhandle installed state 11734 int[] allUsers; 11735 boolean[] perUserInstalled; 11736 synchronized (mPackages) { 11737 PackageSetting ps = mSettings.mPackages.get(packageName); 11738 allUsers = sUserManager.getUserIds(); 11739 perUserInstalled = new boolean[allUsers.length]; 11740 for (int i = 0; i < allUsers.length; i++) { 11741 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11742 } 11743 } 11744 11745 synchronized (mInstallLock) { 11746 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11747 res = deletePackageLI(packageName, removeForUser, 11748 true, allUsers, perUserInstalled, 11749 flags | REMOVE_CHATTY, info, true); 11750 systemUpdate = info.isRemovedPackageSystemUpdate; 11751 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11752 removedForAllUsers = true; 11753 } 11754 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11755 + " removedForAllUsers=" + removedForAllUsers); 11756 } 11757 11758 if (res) { 11759 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11760 11761 // If the removed package was a system update, the old system package 11762 // was re-enabled; we need to broadcast this information 11763 if (systemUpdate) { 11764 Bundle extras = new Bundle(1); 11765 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11766 ? info.removedAppId : info.uid); 11767 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11768 11769 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11770 extras, null, null, null); 11771 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11772 extras, null, null, null); 11773 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11774 null, packageName, null, null); 11775 } 11776 } 11777 // Force a gc here. 11778 Runtime.getRuntime().gc(); 11779 // Delete the resources here after sending the broadcast to let 11780 // other processes clean up before deleting resources. 11781 if (info.args != null) { 11782 synchronized (mInstallLock) { 11783 info.args.doPostDeleteLI(true); 11784 } 11785 } 11786 11787 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11788 } 11789 11790 class PackageRemovedInfo { 11791 String removedPackage; 11792 int uid = -1; 11793 int removedAppId = -1; 11794 int[] removedUsers = null; 11795 boolean isRemovedPackageSystemUpdate = false; 11796 // Clean up resources deleted packages. 11797 InstallArgs args = null; 11798 11799 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11800 Bundle extras = new Bundle(1); 11801 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11802 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11803 if (replacing) { 11804 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11805 } 11806 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11807 if (removedPackage != null) { 11808 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11809 extras, null, null, removedUsers); 11810 if (fullRemove && !replacing) { 11811 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11812 extras, null, null, removedUsers); 11813 } 11814 } 11815 if (removedAppId >= 0) { 11816 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11817 removedUsers); 11818 } 11819 } 11820 } 11821 11822 /* 11823 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11824 * flag is not set, the data directory is removed as well. 11825 * make sure this flag is set for partially installed apps. If not its meaningless to 11826 * delete a partially installed application. 11827 */ 11828 private void removePackageDataLI(PackageSetting ps, 11829 int[] allUserHandles, boolean[] perUserInstalled, 11830 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11831 String packageName = ps.name; 11832 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11833 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11834 // Retrieve object to delete permissions for shared user later on 11835 final PackageSetting deletedPs; 11836 // reader 11837 synchronized (mPackages) { 11838 deletedPs = mSettings.mPackages.get(packageName); 11839 if (outInfo != null) { 11840 outInfo.removedPackage = packageName; 11841 outInfo.removedUsers = deletedPs != null 11842 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11843 : null; 11844 } 11845 } 11846 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11847 removeDataDirsLI(ps.volumeUuid, packageName); 11848 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11849 } 11850 // writer 11851 synchronized (mPackages) { 11852 if (deletedPs != null) { 11853 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11854 if (outInfo != null) { 11855 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11856 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11857 } 11858 updatePermissionsLPw(deletedPs.name, null, 0); 11859 if (deletedPs.sharedUser != null) { 11860 // Remove permissions associated with package. Since runtime 11861 // permissions are per user we have to kill the removed package 11862 // or packages running under the shared user of the removed 11863 // package if revoking the permissions requested only by the removed 11864 // package is successful and this causes a change in gids. 11865 for (int userId : UserManagerService.getInstance().getUserIds()) { 11866 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11867 userId); 11868 if (userIdToKill == UserHandle.USER_ALL 11869 || userIdToKill >= UserHandle.USER_OWNER) { 11870 // If gids changed for this user, kill all affected packages. 11871 mHandler.post(new Runnable() { 11872 @Override 11873 public void run() { 11874 // This has to happen with no lock held. 11875 killSettingPackagesForUser(deletedPs, userIdToKill, 11876 KILL_APP_REASON_GIDS_CHANGED); 11877 } 11878 }); 11879 break; 11880 } 11881 } 11882 } 11883 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11884 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11885 } 11886 // make sure to preserve per-user disabled state if this removal was just 11887 // a downgrade of a system app to the factory package 11888 if (allUserHandles != null && perUserInstalled != null) { 11889 if (DEBUG_REMOVE) { 11890 Slog.d(TAG, "Propagating install state across downgrade"); 11891 } 11892 for (int i = 0; i < allUserHandles.length; i++) { 11893 if (DEBUG_REMOVE) { 11894 Slog.d(TAG, " user " + allUserHandles[i] 11895 + " => " + perUserInstalled[i]); 11896 } 11897 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11898 } 11899 } 11900 } 11901 // can downgrade to reader 11902 if (writeSettings) { 11903 // Save settings now 11904 mSettings.writeLPr(); 11905 } 11906 } 11907 if (outInfo != null) { 11908 // A user ID was deleted here. Go through all users and remove it 11909 // from KeyStore. 11910 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11911 } 11912 } 11913 11914 static boolean locationIsPrivileged(File path) { 11915 try { 11916 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11917 .getCanonicalPath(); 11918 return path.getCanonicalPath().startsWith(privilegedAppDir); 11919 } catch (IOException e) { 11920 Slog.e(TAG, "Unable to access code path " + path); 11921 } 11922 return false; 11923 } 11924 11925 /* 11926 * Tries to delete system package. 11927 */ 11928 private boolean deleteSystemPackageLI(PackageSetting newPs, 11929 int[] allUserHandles, boolean[] perUserInstalled, 11930 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11931 final boolean applyUserRestrictions 11932 = (allUserHandles != null) && (perUserInstalled != null); 11933 PackageSetting disabledPs = null; 11934 // Confirm if the system package has been updated 11935 // An updated system app can be deleted. This will also have to restore 11936 // the system pkg from system partition 11937 // reader 11938 synchronized (mPackages) { 11939 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11940 } 11941 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11942 + " disabledPs=" + disabledPs); 11943 if (disabledPs == null) { 11944 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11945 return false; 11946 } else if (DEBUG_REMOVE) { 11947 Slog.d(TAG, "Deleting system pkg from data partition"); 11948 } 11949 if (DEBUG_REMOVE) { 11950 if (applyUserRestrictions) { 11951 Slog.d(TAG, "Remembering install states:"); 11952 for (int i = 0; i < allUserHandles.length; i++) { 11953 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11954 } 11955 } 11956 } 11957 // Delete the updated package 11958 outInfo.isRemovedPackageSystemUpdate = true; 11959 if (disabledPs.versionCode < newPs.versionCode) { 11960 // Delete data for downgrades 11961 flags &= ~PackageManager.DELETE_KEEP_DATA; 11962 } else { 11963 // Preserve data by setting flag 11964 flags |= PackageManager.DELETE_KEEP_DATA; 11965 } 11966 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11967 allUserHandles, perUserInstalled, outInfo, writeSettings); 11968 if (!ret) { 11969 return false; 11970 } 11971 // writer 11972 synchronized (mPackages) { 11973 // Reinstate the old system package 11974 mSettings.enableSystemPackageLPw(newPs.name); 11975 // Remove any native libraries from the upgraded package. 11976 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11977 } 11978 // Install the system package 11979 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11980 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11981 if (locationIsPrivileged(disabledPs.codePath)) { 11982 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11983 } 11984 11985 final PackageParser.Package newPkg; 11986 try { 11987 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11988 } catch (PackageManagerException e) { 11989 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11990 return false; 11991 } 11992 11993 // writer 11994 synchronized (mPackages) { 11995 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11996 updatePermissionsLPw(newPkg.packageName, newPkg, 11997 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11998 if (applyUserRestrictions) { 11999 if (DEBUG_REMOVE) { 12000 Slog.d(TAG, "Propagating install state across reinstall"); 12001 } 12002 for (int i = 0; i < allUserHandles.length; i++) { 12003 if (DEBUG_REMOVE) { 12004 Slog.d(TAG, " user " + allUserHandles[i] 12005 + " => " + perUserInstalled[i]); 12006 } 12007 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12008 } 12009 // Regardless of writeSettings we need to ensure that this restriction 12010 // state propagation is persisted 12011 mSettings.writeAllUsersPackageRestrictionsLPr(); 12012 } 12013 // can downgrade to reader here 12014 if (writeSettings) { 12015 mSettings.writeLPr(); 12016 } 12017 } 12018 return true; 12019 } 12020 12021 private boolean deleteInstalledPackageLI(PackageSetting ps, 12022 boolean deleteCodeAndResources, int flags, 12023 int[] allUserHandles, boolean[] perUserInstalled, 12024 PackageRemovedInfo outInfo, boolean writeSettings) { 12025 if (outInfo != null) { 12026 outInfo.uid = ps.appId; 12027 } 12028 12029 // Delete package data from internal structures and also remove data if flag is set 12030 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12031 12032 // Delete application code and resources 12033 if (deleteCodeAndResources && (outInfo != null)) { 12034 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12035 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12036 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12037 } 12038 return true; 12039 } 12040 12041 @Override 12042 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12043 int userId) { 12044 mContext.enforceCallingOrSelfPermission( 12045 android.Manifest.permission.DELETE_PACKAGES, null); 12046 synchronized (mPackages) { 12047 PackageSetting ps = mSettings.mPackages.get(packageName); 12048 if (ps == null) { 12049 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12050 return false; 12051 } 12052 if (!ps.getInstalled(userId)) { 12053 // Can't block uninstall for an app that is not installed or enabled. 12054 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12055 return false; 12056 } 12057 ps.setBlockUninstall(blockUninstall, userId); 12058 mSettings.writePackageRestrictionsLPr(userId); 12059 } 12060 return true; 12061 } 12062 12063 @Override 12064 public boolean getBlockUninstallForUser(String packageName, int userId) { 12065 synchronized (mPackages) { 12066 PackageSetting ps = mSettings.mPackages.get(packageName); 12067 if (ps == null) { 12068 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12069 return false; 12070 } 12071 return ps.getBlockUninstall(userId); 12072 } 12073 } 12074 12075 /* 12076 * This method handles package deletion in general 12077 */ 12078 private boolean deletePackageLI(String packageName, UserHandle user, 12079 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12080 int flags, PackageRemovedInfo outInfo, 12081 boolean writeSettings) { 12082 if (packageName == null) { 12083 Slog.w(TAG, "Attempt to delete null packageName."); 12084 return false; 12085 } 12086 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12087 PackageSetting ps; 12088 boolean dataOnly = false; 12089 int removeUser = -1; 12090 int appId = -1; 12091 synchronized (mPackages) { 12092 ps = mSettings.mPackages.get(packageName); 12093 if (ps == null) { 12094 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12095 return false; 12096 } 12097 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12098 && user.getIdentifier() != UserHandle.USER_ALL) { 12099 // The caller is asking that the package only be deleted for a single 12100 // user. To do this, we just mark its uninstalled state and delete 12101 // its data. If this is a system app, we only allow this to happen if 12102 // they have set the special DELETE_SYSTEM_APP which requests different 12103 // semantics than normal for uninstalling system apps. 12104 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12105 ps.setUserState(user.getIdentifier(), 12106 COMPONENT_ENABLED_STATE_DEFAULT, 12107 false, //installed 12108 true, //stopped 12109 true, //notLaunched 12110 false, //hidden 12111 null, null, null, 12112 false, // blockUninstall 12113 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12114 if (!isSystemApp(ps)) { 12115 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12116 // Other user still have this package installed, so all 12117 // we need to do is clear this user's data and save that 12118 // it is uninstalled. 12119 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12120 removeUser = user.getIdentifier(); 12121 appId = ps.appId; 12122 scheduleWritePackageRestrictionsLocked(removeUser); 12123 } else { 12124 // We need to set it back to 'installed' so the uninstall 12125 // broadcasts will be sent correctly. 12126 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12127 ps.setInstalled(true, user.getIdentifier()); 12128 } 12129 } else { 12130 // This is a system app, so we assume that the 12131 // other users still have this package installed, so all 12132 // we need to do is clear this user's data and save that 12133 // it is uninstalled. 12134 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12135 removeUser = user.getIdentifier(); 12136 appId = ps.appId; 12137 scheduleWritePackageRestrictionsLocked(removeUser); 12138 } 12139 } 12140 } 12141 12142 if (removeUser >= 0) { 12143 // From above, we determined that we are deleting this only 12144 // for a single user. Continue the work here. 12145 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12146 if (outInfo != null) { 12147 outInfo.removedPackage = packageName; 12148 outInfo.removedAppId = appId; 12149 outInfo.removedUsers = new int[] {removeUser}; 12150 } 12151 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12152 removeKeystoreDataIfNeeded(removeUser, appId); 12153 schedulePackageCleaning(packageName, removeUser, false); 12154 synchronized (mPackages) { 12155 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12156 scheduleWritePackageRestrictionsLocked(removeUser); 12157 } 12158 } 12159 return true; 12160 } 12161 12162 if (dataOnly) { 12163 // Delete application data first 12164 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12165 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12166 return true; 12167 } 12168 12169 boolean ret = false; 12170 if (isSystemApp(ps)) { 12171 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12172 // When an updated system application is deleted we delete the existing resources as well and 12173 // fall back to existing code in system partition 12174 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12175 flags, outInfo, writeSettings); 12176 } else { 12177 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12178 // Kill application pre-emptively especially for apps on sd. 12179 killApplication(packageName, ps.appId, "uninstall pkg"); 12180 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12181 allUserHandles, perUserInstalled, 12182 outInfo, writeSettings); 12183 } 12184 12185 return ret; 12186 } 12187 12188 private final class ClearStorageConnection implements ServiceConnection { 12189 IMediaContainerService mContainerService; 12190 12191 @Override 12192 public void onServiceConnected(ComponentName name, IBinder service) { 12193 synchronized (this) { 12194 mContainerService = IMediaContainerService.Stub.asInterface(service); 12195 notifyAll(); 12196 } 12197 } 12198 12199 @Override 12200 public void onServiceDisconnected(ComponentName name) { 12201 } 12202 } 12203 12204 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12205 final boolean mounted; 12206 if (Environment.isExternalStorageEmulated()) { 12207 mounted = true; 12208 } else { 12209 final String status = Environment.getExternalStorageState(); 12210 12211 mounted = status.equals(Environment.MEDIA_MOUNTED) 12212 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12213 } 12214 12215 if (!mounted) { 12216 return; 12217 } 12218 12219 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12220 int[] users; 12221 if (userId == UserHandle.USER_ALL) { 12222 users = sUserManager.getUserIds(); 12223 } else { 12224 users = new int[] { userId }; 12225 } 12226 final ClearStorageConnection conn = new ClearStorageConnection(); 12227 if (mContext.bindServiceAsUser( 12228 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12229 try { 12230 for (int curUser : users) { 12231 long timeout = SystemClock.uptimeMillis() + 5000; 12232 synchronized (conn) { 12233 long now = SystemClock.uptimeMillis(); 12234 while (conn.mContainerService == null && now < timeout) { 12235 try { 12236 conn.wait(timeout - now); 12237 } catch (InterruptedException e) { 12238 } 12239 } 12240 } 12241 if (conn.mContainerService == null) { 12242 return; 12243 } 12244 12245 final UserEnvironment userEnv = new UserEnvironment(curUser); 12246 clearDirectory(conn.mContainerService, 12247 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12248 if (allData) { 12249 clearDirectory(conn.mContainerService, 12250 userEnv.buildExternalStorageAppDataDirs(packageName)); 12251 clearDirectory(conn.mContainerService, 12252 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12253 } 12254 } 12255 } finally { 12256 mContext.unbindService(conn); 12257 } 12258 } 12259 } 12260 12261 @Override 12262 public void clearApplicationUserData(final String packageName, 12263 final IPackageDataObserver observer, final int userId) { 12264 mContext.enforceCallingOrSelfPermission( 12265 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12266 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12267 // Queue up an async operation since the package deletion may take a little while. 12268 mHandler.post(new Runnable() { 12269 public void run() { 12270 mHandler.removeCallbacks(this); 12271 final boolean succeeded; 12272 synchronized (mInstallLock) { 12273 succeeded = clearApplicationUserDataLI(packageName, userId); 12274 } 12275 clearExternalStorageDataSync(packageName, userId, true); 12276 if (succeeded) { 12277 // invoke DeviceStorageMonitor's update method to clear any notifications 12278 DeviceStorageMonitorInternal 12279 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12280 if (dsm != null) { 12281 dsm.checkMemory(); 12282 } 12283 } 12284 if(observer != null) { 12285 try { 12286 observer.onRemoveCompleted(packageName, succeeded); 12287 } catch (RemoteException e) { 12288 Log.i(TAG, "Observer no longer exists."); 12289 } 12290 } //end if observer 12291 } //end run 12292 }); 12293 } 12294 12295 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12296 if (packageName == null) { 12297 Slog.w(TAG, "Attempt to delete null packageName."); 12298 return false; 12299 } 12300 12301 // Try finding details about the requested package 12302 PackageParser.Package pkg; 12303 synchronized (mPackages) { 12304 pkg = mPackages.get(packageName); 12305 if (pkg == null) { 12306 final PackageSetting ps = mSettings.mPackages.get(packageName); 12307 if (ps != null) { 12308 pkg = ps.pkg; 12309 } 12310 } 12311 } 12312 12313 if (pkg == null) { 12314 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12315 } 12316 12317 // Always delete data directories for package, even if we found no other 12318 // record of app. This helps users recover from UID mismatches without 12319 // resorting to a full data wipe. 12320 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12321 if (retCode < 0) { 12322 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12323 return false; 12324 } 12325 12326 if (pkg == null) { 12327 return false; 12328 } 12329 12330 if (pkg != null && pkg.applicationInfo != null) { 12331 final int appId = pkg.applicationInfo.uid; 12332 removeKeystoreDataIfNeeded(userId, appId); 12333 } 12334 12335 // Create a native library symlink only if we have native libraries 12336 // and if the native libraries are 32 bit libraries. We do not provide 12337 // this symlink for 64 bit libraries. 12338 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12339 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12340 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12341 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12342 nativeLibPath, userId) < 0) { 12343 Slog.w(TAG, "Failed linking native library dir"); 12344 return false; 12345 } 12346 } 12347 12348 return true; 12349 } 12350 12351 /** 12352 * Remove entries from the keystore daemon. Will only remove it if the 12353 * {@code appId} is valid. 12354 */ 12355 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12356 if (appId < 0) { 12357 return; 12358 } 12359 12360 final KeyStore keyStore = KeyStore.getInstance(); 12361 if (keyStore != null) { 12362 if (userId == UserHandle.USER_ALL) { 12363 for (final int individual : sUserManager.getUserIds()) { 12364 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12365 } 12366 } else { 12367 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12368 } 12369 } else { 12370 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12371 } 12372 } 12373 12374 @Override 12375 public void deleteApplicationCacheFiles(final String packageName, 12376 final IPackageDataObserver observer) { 12377 mContext.enforceCallingOrSelfPermission( 12378 android.Manifest.permission.DELETE_CACHE_FILES, null); 12379 // Queue up an async operation since the package deletion may take a little while. 12380 final int userId = UserHandle.getCallingUserId(); 12381 mHandler.post(new Runnable() { 12382 public void run() { 12383 mHandler.removeCallbacks(this); 12384 final boolean succeded; 12385 synchronized (mInstallLock) { 12386 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12387 } 12388 clearExternalStorageDataSync(packageName, userId, false); 12389 if(observer != null) { 12390 try { 12391 observer.onRemoveCompleted(packageName, succeded); 12392 } catch (RemoteException e) { 12393 Log.i(TAG, "Observer no longer exists."); 12394 } 12395 } //end if observer 12396 } //end run 12397 }); 12398 } 12399 12400 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12401 if (packageName == null) { 12402 Slog.w(TAG, "Attempt to delete null packageName."); 12403 return false; 12404 } 12405 PackageParser.Package p; 12406 synchronized (mPackages) { 12407 p = mPackages.get(packageName); 12408 } 12409 if (p == null) { 12410 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12411 return false; 12412 } 12413 final ApplicationInfo applicationInfo = p.applicationInfo; 12414 if (applicationInfo == null) { 12415 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12416 return false; 12417 } 12418 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12419 if (retCode < 0) { 12420 Slog.w(TAG, "Couldn't remove cache files for package: " 12421 + packageName + " u" + userId); 12422 return false; 12423 } 12424 return true; 12425 } 12426 12427 @Override 12428 public void getPackageSizeInfo(final String packageName, int userHandle, 12429 final IPackageStatsObserver observer) { 12430 mContext.enforceCallingOrSelfPermission( 12431 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12432 if (packageName == null) { 12433 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12434 } 12435 12436 PackageStats stats = new PackageStats(packageName, userHandle); 12437 12438 /* 12439 * Queue up an async operation since the package measurement may take a 12440 * little while. 12441 */ 12442 Message msg = mHandler.obtainMessage(INIT_COPY); 12443 msg.obj = new MeasureParams(stats, observer); 12444 mHandler.sendMessage(msg); 12445 } 12446 12447 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12448 PackageStats pStats) { 12449 if (packageName == null) { 12450 Slog.w(TAG, "Attempt to get size of null packageName."); 12451 return false; 12452 } 12453 PackageParser.Package p; 12454 boolean dataOnly = false; 12455 String libDirRoot = null; 12456 String asecPath = null; 12457 PackageSetting ps = null; 12458 synchronized (mPackages) { 12459 p = mPackages.get(packageName); 12460 ps = mSettings.mPackages.get(packageName); 12461 if(p == null) { 12462 dataOnly = true; 12463 if((ps == null) || (ps.pkg == null)) { 12464 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12465 return false; 12466 } 12467 p = ps.pkg; 12468 } 12469 if (ps != null) { 12470 libDirRoot = ps.legacyNativeLibraryPathString; 12471 } 12472 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12473 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12474 if (secureContainerId != null) { 12475 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12476 } 12477 } 12478 } 12479 String publicSrcDir = null; 12480 if(!dataOnly) { 12481 final ApplicationInfo applicationInfo = p.applicationInfo; 12482 if (applicationInfo == null) { 12483 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12484 return false; 12485 } 12486 if (p.isForwardLocked()) { 12487 publicSrcDir = applicationInfo.getBaseResourcePath(); 12488 } 12489 } 12490 // TODO: extend to measure size of split APKs 12491 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12492 // not just the first level. 12493 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12494 // just the primary. 12495 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12496 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12497 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12498 if (res < 0) { 12499 return false; 12500 } 12501 12502 // Fix-up for forward-locked applications in ASEC containers. 12503 if (!isExternal(p)) { 12504 pStats.codeSize += pStats.externalCodeSize; 12505 pStats.externalCodeSize = 0L; 12506 } 12507 12508 return true; 12509 } 12510 12511 12512 @Override 12513 public void addPackageToPreferred(String packageName) { 12514 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12515 } 12516 12517 @Override 12518 public void removePackageFromPreferred(String packageName) { 12519 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12520 } 12521 12522 @Override 12523 public List<PackageInfo> getPreferredPackages(int flags) { 12524 return new ArrayList<PackageInfo>(); 12525 } 12526 12527 private int getUidTargetSdkVersionLockedLPr(int uid) { 12528 Object obj = mSettings.getUserIdLPr(uid); 12529 if (obj instanceof SharedUserSetting) { 12530 final SharedUserSetting sus = (SharedUserSetting) obj; 12531 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12532 final Iterator<PackageSetting> it = sus.packages.iterator(); 12533 while (it.hasNext()) { 12534 final PackageSetting ps = it.next(); 12535 if (ps.pkg != null) { 12536 int v = ps.pkg.applicationInfo.targetSdkVersion; 12537 if (v < vers) vers = v; 12538 } 12539 } 12540 return vers; 12541 } else if (obj instanceof PackageSetting) { 12542 final PackageSetting ps = (PackageSetting) obj; 12543 if (ps.pkg != null) { 12544 return ps.pkg.applicationInfo.targetSdkVersion; 12545 } 12546 } 12547 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12548 } 12549 12550 @Override 12551 public void addPreferredActivity(IntentFilter filter, int match, 12552 ComponentName[] set, ComponentName activity, int userId) { 12553 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12554 "Adding preferred"); 12555 } 12556 12557 private void addPreferredActivityInternal(IntentFilter filter, int match, 12558 ComponentName[] set, ComponentName activity, boolean always, int userId, 12559 String opname) { 12560 // writer 12561 int callingUid = Binder.getCallingUid(); 12562 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12563 if (filter.countActions() == 0) { 12564 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12565 return; 12566 } 12567 synchronized (mPackages) { 12568 if (mContext.checkCallingOrSelfPermission( 12569 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12570 != PackageManager.PERMISSION_GRANTED) { 12571 if (getUidTargetSdkVersionLockedLPr(callingUid) 12572 < Build.VERSION_CODES.FROYO) { 12573 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12574 + callingUid); 12575 return; 12576 } 12577 mContext.enforceCallingOrSelfPermission( 12578 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12579 } 12580 12581 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12582 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12583 + userId + ":"); 12584 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12585 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12586 scheduleWritePackageRestrictionsLocked(userId); 12587 } 12588 } 12589 12590 @Override 12591 public void replacePreferredActivity(IntentFilter filter, int match, 12592 ComponentName[] set, ComponentName activity, int userId) { 12593 if (filter.countActions() != 1) { 12594 throw new IllegalArgumentException( 12595 "replacePreferredActivity expects filter to have only 1 action."); 12596 } 12597 if (filter.countDataAuthorities() != 0 12598 || filter.countDataPaths() != 0 12599 || filter.countDataSchemes() > 1 12600 || filter.countDataTypes() != 0) { 12601 throw new IllegalArgumentException( 12602 "replacePreferredActivity expects filter to have no data authorities, " + 12603 "paths, or types; and at most one scheme."); 12604 } 12605 12606 final int callingUid = Binder.getCallingUid(); 12607 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12608 synchronized (mPackages) { 12609 if (mContext.checkCallingOrSelfPermission( 12610 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12611 != PackageManager.PERMISSION_GRANTED) { 12612 if (getUidTargetSdkVersionLockedLPr(callingUid) 12613 < Build.VERSION_CODES.FROYO) { 12614 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12615 + Binder.getCallingUid()); 12616 return; 12617 } 12618 mContext.enforceCallingOrSelfPermission( 12619 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12620 } 12621 12622 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12623 if (pir != null) { 12624 // Get all of the existing entries that exactly match this filter. 12625 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12626 if (existing != null && existing.size() == 1) { 12627 PreferredActivity cur = existing.get(0); 12628 if (DEBUG_PREFERRED) { 12629 Slog.i(TAG, "Checking replace of preferred:"); 12630 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12631 if (!cur.mPref.mAlways) { 12632 Slog.i(TAG, " -- CUR; not mAlways!"); 12633 } else { 12634 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12635 Slog.i(TAG, " -- CUR: mSet=" 12636 + Arrays.toString(cur.mPref.mSetComponents)); 12637 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12638 Slog.i(TAG, " -- NEW: mMatch=" 12639 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12640 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12641 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12642 } 12643 } 12644 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12645 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12646 && cur.mPref.sameSet(set)) { 12647 // Setting the preferred activity to what it happens to be already 12648 if (DEBUG_PREFERRED) { 12649 Slog.i(TAG, "Replacing with same preferred activity " 12650 + cur.mPref.mShortComponent + " for user " 12651 + userId + ":"); 12652 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12653 } 12654 return; 12655 } 12656 } 12657 12658 if (existing != null) { 12659 if (DEBUG_PREFERRED) { 12660 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12661 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12662 } 12663 for (int i = 0; i < existing.size(); i++) { 12664 PreferredActivity pa = existing.get(i); 12665 if (DEBUG_PREFERRED) { 12666 Slog.i(TAG, "Removing existing preferred activity " 12667 + pa.mPref.mComponent + ":"); 12668 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12669 } 12670 pir.removeFilter(pa); 12671 } 12672 } 12673 } 12674 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12675 "Replacing preferred"); 12676 } 12677 } 12678 12679 @Override 12680 public void clearPackagePreferredActivities(String packageName) { 12681 final int uid = Binder.getCallingUid(); 12682 // writer 12683 synchronized (mPackages) { 12684 PackageParser.Package pkg = mPackages.get(packageName); 12685 if (pkg == null || pkg.applicationInfo.uid != uid) { 12686 if (mContext.checkCallingOrSelfPermission( 12687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12688 != PackageManager.PERMISSION_GRANTED) { 12689 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12690 < Build.VERSION_CODES.FROYO) { 12691 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12692 + Binder.getCallingUid()); 12693 return; 12694 } 12695 mContext.enforceCallingOrSelfPermission( 12696 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12697 } 12698 } 12699 12700 int user = UserHandle.getCallingUserId(); 12701 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12702 scheduleWritePackageRestrictionsLocked(user); 12703 } 12704 } 12705 } 12706 12707 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12708 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12709 ArrayList<PreferredActivity> removed = null; 12710 boolean changed = false; 12711 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12712 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12713 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12714 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12715 continue; 12716 } 12717 Iterator<PreferredActivity> it = pir.filterIterator(); 12718 while (it.hasNext()) { 12719 PreferredActivity pa = it.next(); 12720 // Mark entry for removal only if it matches the package name 12721 // and the entry is of type "always". 12722 if (packageName == null || 12723 (pa.mPref.mComponent.getPackageName().equals(packageName) 12724 && pa.mPref.mAlways)) { 12725 if (removed == null) { 12726 removed = new ArrayList<PreferredActivity>(); 12727 } 12728 removed.add(pa); 12729 } 12730 } 12731 if (removed != null) { 12732 for (int j=0; j<removed.size(); j++) { 12733 PreferredActivity pa = removed.get(j); 12734 pir.removeFilter(pa); 12735 } 12736 changed = true; 12737 } 12738 } 12739 return changed; 12740 } 12741 12742 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12743 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12744 if (userId == UserHandle.USER_ALL) { 12745 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12746 for (int oneUserId : sUserManager.getUserIds()) { 12747 scheduleWritePackageRestrictionsLocked(oneUserId); 12748 } 12749 } else { 12750 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12751 scheduleWritePackageRestrictionsLocked(userId); 12752 } 12753 } 12754 12755 @Override 12756 public void resetPreferredActivities(int userId) { 12757 /* TODO: Actually use userId. Why is it being passed in? */ 12758 mContext.enforceCallingOrSelfPermission( 12759 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12760 // writer 12761 synchronized (mPackages) { 12762 int user = UserHandle.getCallingUserId(); 12763 clearPackagePreferredActivitiesLPw(null, user); 12764 mSettings.readDefaultPreferredAppsLPw(this, user); 12765 scheduleWritePackageRestrictionsLocked(user); 12766 } 12767 } 12768 12769 @Override 12770 public int getPreferredActivities(List<IntentFilter> outFilters, 12771 List<ComponentName> outActivities, String packageName) { 12772 12773 int num = 0; 12774 final int userId = UserHandle.getCallingUserId(); 12775 // reader 12776 synchronized (mPackages) { 12777 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12778 if (pir != null) { 12779 final Iterator<PreferredActivity> it = pir.filterIterator(); 12780 while (it.hasNext()) { 12781 final PreferredActivity pa = it.next(); 12782 if (packageName == null 12783 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12784 && pa.mPref.mAlways)) { 12785 if (outFilters != null) { 12786 outFilters.add(new IntentFilter(pa)); 12787 } 12788 if (outActivities != null) { 12789 outActivities.add(pa.mPref.mComponent); 12790 } 12791 } 12792 } 12793 } 12794 } 12795 12796 return num; 12797 } 12798 12799 @Override 12800 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12801 int userId) { 12802 int callingUid = Binder.getCallingUid(); 12803 if (callingUid != Process.SYSTEM_UID) { 12804 throw new SecurityException( 12805 "addPersistentPreferredActivity can only be run by the system"); 12806 } 12807 if (filter.countActions() == 0) { 12808 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12809 return; 12810 } 12811 synchronized (mPackages) { 12812 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12813 " :"); 12814 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12815 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12816 new PersistentPreferredActivity(filter, activity)); 12817 scheduleWritePackageRestrictionsLocked(userId); 12818 } 12819 } 12820 12821 @Override 12822 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12823 int callingUid = Binder.getCallingUid(); 12824 if (callingUid != Process.SYSTEM_UID) { 12825 throw new SecurityException( 12826 "clearPackagePersistentPreferredActivities can only be run by the system"); 12827 } 12828 ArrayList<PersistentPreferredActivity> removed = null; 12829 boolean changed = false; 12830 synchronized (mPackages) { 12831 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12832 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12833 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12834 .valueAt(i); 12835 if (userId != thisUserId) { 12836 continue; 12837 } 12838 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12839 while (it.hasNext()) { 12840 PersistentPreferredActivity ppa = it.next(); 12841 // Mark entry for removal only if it matches the package name. 12842 if (ppa.mComponent.getPackageName().equals(packageName)) { 12843 if (removed == null) { 12844 removed = new ArrayList<PersistentPreferredActivity>(); 12845 } 12846 removed.add(ppa); 12847 } 12848 } 12849 if (removed != null) { 12850 for (int j=0; j<removed.size(); j++) { 12851 PersistentPreferredActivity ppa = removed.get(j); 12852 ppir.removeFilter(ppa); 12853 } 12854 changed = true; 12855 } 12856 } 12857 12858 if (changed) { 12859 scheduleWritePackageRestrictionsLocked(userId); 12860 } 12861 } 12862 } 12863 12864 /** 12865 * Non-Binder method, support for the backup/restore mechanism: write the 12866 * full set of preferred activities in its canonical XML format. Returns true 12867 * on success; false otherwise. 12868 */ 12869 @Override 12870 public byte[] getPreferredActivityBackup(int userId) { 12871 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12872 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12873 } 12874 12875 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12876 try { 12877 final XmlSerializer serializer = new FastXmlSerializer(); 12878 serializer.setOutput(dataStream, "utf-8"); 12879 serializer.startDocument(null, true); 12880 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12881 12882 synchronized (mPackages) { 12883 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12884 } 12885 12886 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12887 serializer.endDocument(); 12888 serializer.flush(); 12889 } catch (Exception e) { 12890 if (DEBUG_BACKUP) { 12891 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12892 } 12893 return null; 12894 } 12895 12896 return dataStream.toByteArray(); 12897 } 12898 12899 @Override 12900 public void restorePreferredActivities(byte[] backup, int userId) { 12901 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12902 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12903 } 12904 12905 try { 12906 final XmlPullParser parser = Xml.newPullParser(); 12907 parser.setInput(new ByteArrayInputStream(backup), null); 12908 12909 int type; 12910 while ((type = parser.next()) != XmlPullParser.START_TAG 12911 && type != XmlPullParser.END_DOCUMENT) { 12912 } 12913 if (type != XmlPullParser.START_TAG) { 12914 // oops didn't find a start tag?! 12915 if (DEBUG_BACKUP) { 12916 Slog.e(TAG, "Didn't find start tag during restore"); 12917 } 12918 return; 12919 } 12920 12921 // this is supposed to be TAG_PREFERRED_BACKUP 12922 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12923 if (DEBUG_BACKUP) { 12924 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12925 } 12926 return; 12927 } 12928 12929 // skip interfering stuff, then we're aligned with the backing implementation 12930 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12931 synchronized (mPackages) { 12932 mSettings.readPreferredActivitiesLPw(parser, userId); 12933 } 12934 } catch (Exception e) { 12935 if (DEBUG_BACKUP) { 12936 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12937 } 12938 } 12939 } 12940 12941 @Override 12942 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12943 int sourceUserId, int targetUserId, int flags) { 12944 mContext.enforceCallingOrSelfPermission( 12945 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12946 int callingUid = Binder.getCallingUid(); 12947 enforceOwnerRights(ownerPackage, callingUid); 12948 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12949 if (intentFilter.countActions() == 0) { 12950 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12951 return; 12952 } 12953 synchronized (mPackages) { 12954 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12955 ownerPackage, targetUserId, flags); 12956 CrossProfileIntentResolver resolver = 12957 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12958 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12959 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12960 if (existing != null) { 12961 int size = existing.size(); 12962 for (int i = 0; i < size; i++) { 12963 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12964 return; 12965 } 12966 } 12967 } 12968 resolver.addFilter(newFilter); 12969 scheduleWritePackageRestrictionsLocked(sourceUserId); 12970 } 12971 } 12972 12973 @Override 12974 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12975 mContext.enforceCallingOrSelfPermission( 12976 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12977 int callingUid = Binder.getCallingUid(); 12978 enforceOwnerRights(ownerPackage, callingUid); 12979 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12980 synchronized (mPackages) { 12981 CrossProfileIntentResolver resolver = 12982 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12983 ArraySet<CrossProfileIntentFilter> set = 12984 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12985 for (CrossProfileIntentFilter filter : set) { 12986 if (filter.getOwnerPackage().equals(ownerPackage)) { 12987 resolver.removeFilter(filter); 12988 } 12989 } 12990 scheduleWritePackageRestrictionsLocked(sourceUserId); 12991 } 12992 } 12993 12994 // Enforcing that callingUid is owning pkg on userId 12995 private void enforceOwnerRights(String pkg, int callingUid) { 12996 // The system owns everything. 12997 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12998 return; 12999 } 13000 int callingUserId = UserHandle.getUserId(callingUid); 13001 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13002 if (pi == null) { 13003 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13004 + callingUserId); 13005 } 13006 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13007 throw new SecurityException("Calling uid " + callingUid 13008 + " does not own package " + pkg); 13009 } 13010 } 13011 13012 @Override 13013 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13014 Intent intent = new Intent(Intent.ACTION_MAIN); 13015 intent.addCategory(Intent.CATEGORY_HOME); 13016 13017 final int callingUserId = UserHandle.getCallingUserId(); 13018 List<ResolveInfo> list = queryIntentActivities(intent, null, 13019 PackageManager.GET_META_DATA, callingUserId); 13020 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13021 true, false, false, callingUserId); 13022 13023 allHomeCandidates.clear(); 13024 if (list != null) { 13025 for (ResolveInfo ri : list) { 13026 allHomeCandidates.add(ri); 13027 } 13028 } 13029 return (preferred == null || preferred.activityInfo == null) 13030 ? null 13031 : new ComponentName(preferred.activityInfo.packageName, 13032 preferred.activityInfo.name); 13033 } 13034 13035 @Override 13036 public void setApplicationEnabledSetting(String appPackageName, 13037 int newState, int flags, int userId, String callingPackage) { 13038 if (!sUserManager.exists(userId)) return; 13039 if (callingPackage == null) { 13040 callingPackage = Integer.toString(Binder.getCallingUid()); 13041 } 13042 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13043 } 13044 13045 @Override 13046 public void setComponentEnabledSetting(ComponentName componentName, 13047 int newState, int flags, int userId) { 13048 if (!sUserManager.exists(userId)) return; 13049 setEnabledSetting(componentName.getPackageName(), 13050 componentName.getClassName(), newState, flags, userId, null); 13051 } 13052 13053 private void setEnabledSetting(final String packageName, String className, int newState, 13054 final int flags, int userId, String callingPackage) { 13055 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13056 || newState == COMPONENT_ENABLED_STATE_ENABLED 13057 || newState == COMPONENT_ENABLED_STATE_DISABLED 13058 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13059 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13060 throw new IllegalArgumentException("Invalid new component state: " 13061 + newState); 13062 } 13063 PackageSetting pkgSetting; 13064 final int uid = Binder.getCallingUid(); 13065 final int permission = mContext.checkCallingOrSelfPermission( 13066 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13067 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13068 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13069 boolean sendNow = false; 13070 boolean isApp = (className == null); 13071 String componentName = isApp ? packageName : className; 13072 int packageUid = -1; 13073 ArrayList<String> components; 13074 13075 // writer 13076 synchronized (mPackages) { 13077 pkgSetting = mSettings.mPackages.get(packageName); 13078 if (pkgSetting == null) { 13079 if (className == null) { 13080 throw new IllegalArgumentException( 13081 "Unknown package: " + packageName); 13082 } 13083 throw new IllegalArgumentException( 13084 "Unknown component: " + packageName 13085 + "/" + className); 13086 } 13087 // Allow root and verify that userId is not being specified by a different user 13088 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13089 throw new SecurityException( 13090 "Permission Denial: attempt to change component state from pid=" 13091 + Binder.getCallingPid() 13092 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13093 } 13094 if (className == null) { 13095 // We're dealing with an application/package level state change 13096 if (pkgSetting.getEnabled(userId) == newState) { 13097 // Nothing to do 13098 return; 13099 } 13100 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13101 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13102 // Don't care about who enables an app. 13103 callingPackage = null; 13104 } 13105 pkgSetting.setEnabled(newState, userId, callingPackage); 13106 // pkgSetting.pkg.mSetEnabled = newState; 13107 } else { 13108 // We're dealing with a component level state change 13109 // First, verify that this is a valid class name. 13110 PackageParser.Package pkg = pkgSetting.pkg; 13111 if (pkg == null || !pkg.hasComponentClassName(className)) { 13112 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13113 throw new IllegalArgumentException("Component class " + className 13114 + " does not exist in " + packageName); 13115 } else { 13116 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13117 + className + " does not exist in " + packageName); 13118 } 13119 } 13120 switch (newState) { 13121 case COMPONENT_ENABLED_STATE_ENABLED: 13122 if (!pkgSetting.enableComponentLPw(className, userId)) { 13123 return; 13124 } 13125 break; 13126 case COMPONENT_ENABLED_STATE_DISABLED: 13127 if (!pkgSetting.disableComponentLPw(className, userId)) { 13128 return; 13129 } 13130 break; 13131 case COMPONENT_ENABLED_STATE_DEFAULT: 13132 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13133 return; 13134 } 13135 break; 13136 default: 13137 Slog.e(TAG, "Invalid new component state: " + newState); 13138 return; 13139 } 13140 } 13141 scheduleWritePackageRestrictionsLocked(userId); 13142 components = mPendingBroadcasts.get(userId, packageName); 13143 final boolean newPackage = components == null; 13144 if (newPackage) { 13145 components = new ArrayList<String>(); 13146 } 13147 if (!components.contains(componentName)) { 13148 components.add(componentName); 13149 } 13150 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13151 sendNow = true; 13152 // Purge entry from pending broadcast list if another one exists already 13153 // since we are sending one right away. 13154 mPendingBroadcasts.remove(userId, packageName); 13155 } else { 13156 if (newPackage) { 13157 mPendingBroadcasts.put(userId, packageName, components); 13158 } 13159 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13160 // Schedule a message 13161 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13162 } 13163 } 13164 } 13165 13166 long callingId = Binder.clearCallingIdentity(); 13167 try { 13168 if (sendNow) { 13169 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13170 sendPackageChangedBroadcast(packageName, 13171 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13172 } 13173 } finally { 13174 Binder.restoreCallingIdentity(callingId); 13175 } 13176 } 13177 13178 private void sendPackageChangedBroadcast(String packageName, 13179 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13180 if (DEBUG_INSTALL) 13181 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13182 + componentNames); 13183 Bundle extras = new Bundle(4); 13184 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13185 String nameList[] = new String[componentNames.size()]; 13186 componentNames.toArray(nameList); 13187 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13188 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13189 extras.putInt(Intent.EXTRA_UID, packageUid); 13190 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13191 new int[] {UserHandle.getUserId(packageUid)}); 13192 } 13193 13194 @Override 13195 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13196 if (!sUserManager.exists(userId)) return; 13197 final int uid = Binder.getCallingUid(); 13198 final int permission = mContext.checkCallingOrSelfPermission( 13199 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13200 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13201 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13202 // writer 13203 synchronized (mPackages) { 13204 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13205 allowedByPermission, uid, userId)) { 13206 scheduleWritePackageRestrictionsLocked(userId); 13207 } 13208 } 13209 } 13210 13211 @Override 13212 public String getInstallerPackageName(String packageName) { 13213 // reader 13214 synchronized (mPackages) { 13215 return mSettings.getInstallerPackageNameLPr(packageName); 13216 } 13217 } 13218 13219 @Override 13220 public int getApplicationEnabledSetting(String packageName, int userId) { 13221 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13222 int uid = Binder.getCallingUid(); 13223 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13224 // reader 13225 synchronized (mPackages) { 13226 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13227 } 13228 } 13229 13230 @Override 13231 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13232 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13233 int uid = Binder.getCallingUid(); 13234 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13235 // reader 13236 synchronized (mPackages) { 13237 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13238 } 13239 } 13240 13241 @Override 13242 public void enterSafeMode() { 13243 enforceSystemOrRoot("Only the system can request entering safe mode"); 13244 13245 if (!mSystemReady) { 13246 mSafeMode = true; 13247 } 13248 } 13249 13250 @Override 13251 public void systemReady() { 13252 mSystemReady = true; 13253 13254 // Read the compatibilty setting when the system is ready. 13255 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13256 mContext.getContentResolver(), 13257 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13258 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13259 if (DEBUG_SETTINGS) { 13260 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13261 } 13262 13263 synchronized (mPackages) { 13264 // Verify that all of the preferred activity components actually 13265 // exist. It is possible for applications to be updated and at 13266 // that point remove a previously declared activity component that 13267 // had been set as a preferred activity. We try to clean this up 13268 // the next time we encounter that preferred activity, but it is 13269 // possible for the user flow to never be able to return to that 13270 // situation so here we do a sanity check to make sure we haven't 13271 // left any junk around. 13272 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13273 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13274 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13275 removed.clear(); 13276 for (PreferredActivity pa : pir.filterSet()) { 13277 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13278 removed.add(pa); 13279 } 13280 } 13281 if (removed.size() > 0) { 13282 for (int r=0; r<removed.size(); r++) { 13283 PreferredActivity pa = removed.get(r); 13284 Slog.w(TAG, "Removing dangling preferred activity: " 13285 + pa.mPref.mComponent); 13286 pir.removeFilter(pa); 13287 } 13288 mSettings.writePackageRestrictionsLPr( 13289 mSettings.mPreferredActivities.keyAt(i)); 13290 } 13291 } 13292 } 13293 sUserManager.systemReady(); 13294 13295 // Kick off any messages waiting for system ready 13296 if (mPostSystemReadyMessages != null) { 13297 for (Message msg : mPostSystemReadyMessages) { 13298 msg.sendToTarget(); 13299 } 13300 mPostSystemReadyMessages = null; 13301 } 13302 13303 // Watch for external volumes that come and go over time 13304 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13305 storage.registerListener(mStorageListener); 13306 13307 mInstallerService.systemReady(); 13308 } 13309 13310 @Override 13311 public boolean isSafeMode() { 13312 return mSafeMode; 13313 } 13314 13315 @Override 13316 public boolean hasSystemUidErrors() { 13317 return mHasSystemUidErrors; 13318 } 13319 13320 static String arrayToString(int[] array) { 13321 StringBuffer buf = new StringBuffer(128); 13322 buf.append('['); 13323 if (array != null) { 13324 for (int i=0; i<array.length; i++) { 13325 if (i > 0) buf.append(", "); 13326 buf.append(array[i]); 13327 } 13328 } 13329 buf.append(']'); 13330 return buf.toString(); 13331 } 13332 13333 static class DumpState { 13334 public static final int DUMP_LIBS = 1 << 0; 13335 public static final int DUMP_FEATURES = 1 << 1; 13336 public static final int DUMP_RESOLVERS = 1 << 2; 13337 public static final int DUMP_PERMISSIONS = 1 << 3; 13338 public static final int DUMP_PACKAGES = 1 << 4; 13339 public static final int DUMP_SHARED_USERS = 1 << 5; 13340 public static final int DUMP_MESSAGES = 1 << 6; 13341 public static final int DUMP_PROVIDERS = 1 << 7; 13342 public static final int DUMP_VERIFIERS = 1 << 8; 13343 public static final int DUMP_PREFERRED = 1 << 9; 13344 public static final int DUMP_PREFERRED_XML = 1 << 10; 13345 public static final int DUMP_KEYSETS = 1 << 11; 13346 public static final int DUMP_VERSION = 1 << 12; 13347 public static final int DUMP_INSTALLS = 1 << 13; 13348 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13349 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13350 13351 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13352 13353 private int mTypes; 13354 13355 private int mOptions; 13356 13357 private boolean mTitlePrinted; 13358 13359 private SharedUserSetting mSharedUser; 13360 13361 public boolean isDumping(int type) { 13362 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13363 return true; 13364 } 13365 13366 return (mTypes & type) != 0; 13367 } 13368 13369 public void setDump(int type) { 13370 mTypes |= type; 13371 } 13372 13373 public boolean isOptionEnabled(int option) { 13374 return (mOptions & option) != 0; 13375 } 13376 13377 public void setOptionEnabled(int option) { 13378 mOptions |= option; 13379 } 13380 13381 public boolean onTitlePrinted() { 13382 final boolean printed = mTitlePrinted; 13383 mTitlePrinted = true; 13384 return printed; 13385 } 13386 13387 public boolean getTitlePrinted() { 13388 return mTitlePrinted; 13389 } 13390 13391 public void setTitlePrinted(boolean enabled) { 13392 mTitlePrinted = enabled; 13393 } 13394 13395 public SharedUserSetting getSharedUser() { 13396 return mSharedUser; 13397 } 13398 13399 public void setSharedUser(SharedUserSetting user) { 13400 mSharedUser = user; 13401 } 13402 } 13403 13404 @Override 13405 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13406 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13407 != PackageManager.PERMISSION_GRANTED) { 13408 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13409 + Binder.getCallingPid() 13410 + ", uid=" + Binder.getCallingUid() 13411 + " without permission " 13412 + android.Manifest.permission.DUMP); 13413 return; 13414 } 13415 13416 DumpState dumpState = new DumpState(); 13417 boolean fullPreferred = false; 13418 boolean checkin = false; 13419 13420 String packageName = null; 13421 13422 int opti = 0; 13423 while (opti < args.length) { 13424 String opt = args[opti]; 13425 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13426 break; 13427 } 13428 opti++; 13429 13430 if ("-a".equals(opt)) { 13431 // Right now we only know how to print all. 13432 } else if ("-h".equals(opt)) { 13433 pw.println("Package manager dump options:"); 13434 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13435 pw.println(" --checkin: dump for a checkin"); 13436 pw.println(" -f: print details of intent filters"); 13437 pw.println(" -h: print this help"); 13438 pw.println(" cmd may be one of:"); 13439 pw.println(" l[ibraries]: list known shared libraries"); 13440 pw.println(" f[ibraries]: list device features"); 13441 pw.println(" k[eysets]: print known keysets"); 13442 pw.println(" r[esolvers]: dump intent resolvers"); 13443 pw.println(" perm[issions]: dump permissions"); 13444 pw.println(" pref[erred]: print preferred package settings"); 13445 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13446 pw.println(" prov[iders]: dump content providers"); 13447 pw.println(" p[ackages]: dump installed packages"); 13448 pw.println(" s[hared-users]: dump shared user IDs"); 13449 pw.println(" m[essages]: print collected runtime messages"); 13450 pw.println(" v[erifiers]: print package verifier info"); 13451 pw.println(" version: print database version info"); 13452 pw.println(" write: write current settings now"); 13453 pw.println(" <package.name>: info about given package"); 13454 pw.println(" installs: details about install sessions"); 13455 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13456 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13457 return; 13458 } else if ("--checkin".equals(opt)) { 13459 checkin = true; 13460 } else if ("-f".equals(opt)) { 13461 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13462 } else { 13463 pw.println("Unknown argument: " + opt + "; use -h for help"); 13464 } 13465 } 13466 13467 // Is the caller requesting to dump a particular piece of data? 13468 if (opti < args.length) { 13469 String cmd = args[opti]; 13470 opti++; 13471 // Is this a package name? 13472 if ("android".equals(cmd) || cmd.contains(".")) { 13473 packageName = cmd; 13474 // When dumping a single package, we always dump all of its 13475 // filter information since the amount of data will be reasonable. 13476 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13477 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13478 dumpState.setDump(DumpState.DUMP_LIBS); 13479 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13480 dumpState.setDump(DumpState.DUMP_FEATURES); 13481 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13482 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13483 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13484 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13485 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13486 dumpState.setDump(DumpState.DUMP_PREFERRED); 13487 } else if ("preferred-xml".equals(cmd)) { 13488 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13489 if (opti < args.length && "--full".equals(args[opti])) { 13490 fullPreferred = true; 13491 opti++; 13492 } 13493 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13494 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13495 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13496 dumpState.setDump(DumpState.DUMP_PACKAGES); 13497 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13498 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13499 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13500 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13501 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13502 dumpState.setDump(DumpState.DUMP_MESSAGES); 13503 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13504 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13505 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13506 || "intent-filter-verifiers".equals(cmd)) { 13507 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13508 } else if ("version".equals(cmd)) { 13509 dumpState.setDump(DumpState.DUMP_VERSION); 13510 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13511 dumpState.setDump(DumpState.DUMP_KEYSETS); 13512 } else if ("installs".equals(cmd)) { 13513 dumpState.setDump(DumpState.DUMP_INSTALLS); 13514 } else if ("write".equals(cmd)) { 13515 synchronized (mPackages) { 13516 mSettings.writeLPr(); 13517 pw.println("Settings written."); 13518 return; 13519 } 13520 } 13521 } 13522 13523 if (checkin) { 13524 pw.println("vers,1"); 13525 } 13526 13527 // reader 13528 synchronized (mPackages) { 13529 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13530 if (!checkin) { 13531 if (dumpState.onTitlePrinted()) 13532 pw.println(); 13533 pw.println("Database versions:"); 13534 pw.print(" SDK Version:"); 13535 pw.print(" internal="); 13536 pw.print(mSettings.mInternalSdkPlatform); 13537 pw.print(" external="); 13538 pw.println(mSettings.mExternalSdkPlatform); 13539 pw.print(" DB Version:"); 13540 pw.print(" internal="); 13541 pw.print(mSettings.mInternalDatabaseVersion); 13542 pw.print(" external="); 13543 pw.println(mSettings.mExternalDatabaseVersion); 13544 } 13545 } 13546 13547 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13548 if (!checkin) { 13549 if (dumpState.onTitlePrinted()) 13550 pw.println(); 13551 pw.println("Verifiers:"); 13552 pw.print(" Required: "); 13553 pw.print(mRequiredVerifierPackage); 13554 pw.print(" (uid="); 13555 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13556 pw.println(")"); 13557 } else if (mRequiredVerifierPackage != null) { 13558 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13559 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13560 } 13561 } 13562 13563 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13564 packageName == null) { 13565 if (mIntentFilterVerifierComponent != null) { 13566 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13567 if (!checkin) { 13568 if (dumpState.onTitlePrinted()) 13569 pw.println(); 13570 pw.println("Intent Filter Verifier:"); 13571 pw.print(" Using: "); 13572 pw.print(verifierPackageName); 13573 pw.print(" (uid="); 13574 pw.print(getPackageUid(verifierPackageName, 0)); 13575 pw.println(")"); 13576 } else if (verifierPackageName != null) { 13577 pw.print("ifv,"); pw.print(verifierPackageName); 13578 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13579 } 13580 } else { 13581 pw.println(); 13582 pw.println("No Intent Filter Verifier available!"); 13583 } 13584 } 13585 13586 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13587 boolean printedHeader = false; 13588 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13589 while (it.hasNext()) { 13590 String name = it.next(); 13591 SharedLibraryEntry ent = mSharedLibraries.get(name); 13592 if (!checkin) { 13593 if (!printedHeader) { 13594 if (dumpState.onTitlePrinted()) 13595 pw.println(); 13596 pw.println("Libraries:"); 13597 printedHeader = true; 13598 } 13599 pw.print(" "); 13600 } else { 13601 pw.print("lib,"); 13602 } 13603 pw.print(name); 13604 if (!checkin) { 13605 pw.print(" -> "); 13606 } 13607 if (ent.path != null) { 13608 if (!checkin) { 13609 pw.print("(jar) "); 13610 pw.print(ent.path); 13611 } else { 13612 pw.print(",jar,"); 13613 pw.print(ent.path); 13614 } 13615 } else { 13616 if (!checkin) { 13617 pw.print("(apk) "); 13618 pw.print(ent.apk); 13619 } else { 13620 pw.print(",apk,"); 13621 pw.print(ent.apk); 13622 } 13623 } 13624 pw.println(); 13625 } 13626 } 13627 13628 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13629 if (dumpState.onTitlePrinted()) 13630 pw.println(); 13631 if (!checkin) { 13632 pw.println("Features:"); 13633 } 13634 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13635 while (it.hasNext()) { 13636 String name = it.next(); 13637 if (!checkin) { 13638 pw.print(" "); 13639 } else { 13640 pw.print("feat,"); 13641 } 13642 pw.println(name); 13643 } 13644 } 13645 13646 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13647 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13648 : "Activity Resolver Table:", " ", packageName, 13649 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13650 dumpState.setTitlePrinted(true); 13651 } 13652 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13653 : "Receiver Resolver Table:", " ", packageName, 13654 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13655 dumpState.setTitlePrinted(true); 13656 } 13657 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13658 : "Service Resolver Table:", " ", packageName, 13659 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13660 dumpState.setTitlePrinted(true); 13661 } 13662 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13663 : "Provider Resolver Table:", " ", packageName, 13664 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13665 dumpState.setTitlePrinted(true); 13666 } 13667 } 13668 13669 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13670 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13671 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13672 int user = mSettings.mPreferredActivities.keyAt(i); 13673 if (pir.dump(pw, 13674 dumpState.getTitlePrinted() 13675 ? "\nPreferred Activities User " + user + ":" 13676 : "Preferred Activities User " + user + ":", " ", 13677 packageName, true, false)) { 13678 dumpState.setTitlePrinted(true); 13679 } 13680 } 13681 } 13682 13683 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13684 pw.flush(); 13685 FileOutputStream fout = new FileOutputStream(fd); 13686 BufferedOutputStream str = new BufferedOutputStream(fout); 13687 XmlSerializer serializer = new FastXmlSerializer(); 13688 try { 13689 serializer.setOutput(str, "utf-8"); 13690 serializer.startDocument(null, true); 13691 serializer.setFeature( 13692 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13693 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13694 serializer.endDocument(); 13695 serializer.flush(); 13696 } catch (IllegalArgumentException e) { 13697 pw.println("Failed writing: " + e); 13698 } catch (IllegalStateException e) { 13699 pw.println("Failed writing: " + e); 13700 } catch (IOException e) { 13701 pw.println("Failed writing: " + e); 13702 } 13703 } 13704 13705 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13706 pw.println(); 13707 int count = mSettings.mPackages.size(); 13708 if (count == 0) { 13709 pw.println("No domain preferred apps!"); 13710 pw.println(); 13711 } else { 13712 final String prefix = " "; 13713 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13714 if (allPackageSettings.size() == 0) { 13715 pw.println("No domain preferred apps!"); 13716 pw.println(); 13717 } else { 13718 pw.println("Domain preferred apps status:"); 13719 pw.println(); 13720 count = 0; 13721 for (PackageSetting ps : allPackageSettings) { 13722 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13723 if (ivi == null || ivi.getPackageName() == null) continue; 13724 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13725 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13726 pw.println(prefix + "Status: " + ivi.getStatusString()); 13727 pw.println(); 13728 count++; 13729 } 13730 if (count == 0) { 13731 pw.println(prefix + "No domain preferred app status!"); 13732 pw.println(); 13733 } 13734 for (int userId : sUserManager.getUserIds()) { 13735 pw.println("Domain preferred apps for User " + userId + ":"); 13736 pw.println(); 13737 count = 0; 13738 for (PackageSetting ps : allPackageSettings) { 13739 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13740 if (ivi == null || ivi.getPackageName() == null) { 13741 continue; 13742 } 13743 final int status = ps.getDomainVerificationStatusForUser(userId); 13744 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13745 continue; 13746 } 13747 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13748 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13749 String statusStr = IntentFilterVerificationInfo. 13750 getStatusStringFromValue(status); 13751 pw.println(prefix + "Status: " + statusStr); 13752 pw.println(); 13753 count++; 13754 } 13755 if (count == 0) { 13756 pw.println(prefix + "No domain preferred apps!"); 13757 pw.println(); 13758 } 13759 } 13760 } 13761 } 13762 } 13763 13764 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13765 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13766 if (packageName == null) { 13767 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13768 if (iperm == 0) { 13769 if (dumpState.onTitlePrinted()) 13770 pw.println(); 13771 pw.println("AppOp Permissions:"); 13772 } 13773 pw.print(" AppOp Permission "); 13774 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13775 pw.println(":"); 13776 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13777 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13778 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13779 } 13780 } 13781 } 13782 } 13783 13784 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13785 boolean printedSomething = false; 13786 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13787 if (packageName != null && !packageName.equals(p.info.packageName)) { 13788 continue; 13789 } 13790 if (!printedSomething) { 13791 if (dumpState.onTitlePrinted()) 13792 pw.println(); 13793 pw.println("Registered ContentProviders:"); 13794 printedSomething = true; 13795 } 13796 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13797 pw.print(" "); pw.println(p.toString()); 13798 } 13799 printedSomething = false; 13800 for (Map.Entry<String, PackageParser.Provider> entry : 13801 mProvidersByAuthority.entrySet()) { 13802 PackageParser.Provider p = entry.getValue(); 13803 if (packageName != null && !packageName.equals(p.info.packageName)) { 13804 continue; 13805 } 13806 if (!printedSomething) { 13807 if (dumpState.onTitlePrinted()) 13808 pw.println(); 13809 pw.println("ContentProvider Authorities:"); 13810 printedSomething = true; 13811 } 13812 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13813 pw.print(" "); pw.println(p.toString()); 13814 if (p.info != null && p.info.applicationInfo != null) { 13815 final String appInfo = p.info.applicationInfo.toString(); 13816 pw.print(" applicationInfo="); pw.println(appInfo); 13817 } 13818 } 13819 } 13820 13821 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13822 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13823 } 13824 13825 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13826 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13827 } 13828 13829 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13830 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13831 } 13832 13833 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13834 // XXX should handle packageName != null by dumping only install data that 13835 // the given package is involved with. 13836 if (dumpState.onTitlePrinted()) pw.println(); 13837 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13838 } 13839 13840 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13841 if (dumpState.onTitlePrinted()) pw.println(); 13842 mSettings.dumpReadMessagesLPr(pw, dumpState); 13843 13844 pw.println(); 13845 pw.println("Package warning messages:"); 13846 BufferedReader in = null; 13847 String line = null; 13848 try { 13849 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13850 while ((line = in.readLine()) != null) { 13851 if (line.contains("ignored: updated version")) continue; 13852 pw.println(line); 13853 } 13854 } catch (IOException ignored) { 13855 } finally { 13856 IoUtils.closeQuietly(in); 13857 } 13858 } 13859 13860 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13861 BufferedReader in = null; 13862 String line = null; 13863 try { 13864 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13865 while ((line = in.readLine()) != null) { 13866 if (line.contains("ignored: updated version")) continue; 13867 pw.print("msg,"); 13868 pw.println(line); 13869 } 13870 } catch (IOException ignored) { 13871 } finally { 13872 IoUtils.closeQuietly(in); 13873 } 13874 } 13875 } 13876 } 13877 13878 // ------- apps on sdcard specific code ------- 13879 static final boolean DEBUG_SD_INSTALL = false; 13880 13881 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13882 13883 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13884 13885 private boolean mMediaMounted = false; 13886 13887 static String getEncryptKey() { 13888 try { 13889 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13890 SD_ENCRYPTION_KEYSTORE_NAME); 13891 if (sdEncKey == null) { 13892 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13893 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13894 if (sdEncKey == null) { 13895 Slog.e(TAG, "Failed to create encryption keys"); 13896 return null; 13897 } 13898 } 13899 return sdEncKey; 13900 } catch (NoSuchAlgorithmException nsae) { 13901 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13902 return null; 13903 } catch (IOException ioe) { 13904 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13905 return null; 13906 } 13907 } 13908 13909 /* 13910 * Update media status on PackageManager. 13911 */ 13912 @Override 13913 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13914 int callingUid = Binder.getCallingUid(); 13915 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13916 throw new SecurityException("Media status can only be updated by the system"); 13917 } 13918 // reader; this apparently protects mMediaMounted, but should probably 13919 // be a different lock in that case. 13920 synchronized (mPackages) { 13921 Log.i(TAG, "Updating external media status from " 13922 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13923 + (mediaStatus ? "mounted" : "unmounted")); 13924 if (DEBUG_SD_INSTALL) 13925 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13926 + ", mMediaMounted=" + mMediaMounted); 13927 if (mediaStatus == mMediaMounted) { 13928 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13929 : 0, -1); 13930 mHandler.sendMessage(msg); 13931 return; 13932 } 13933 mMediaMounted = mediaStatus; 13934 } 13935 // Queue up an async operation since the package installation may take a 13936 // little while. 13937 mHandler.post(new Runnable() { 13938 public void run() { 13939 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13940 } 13941 }); 13942 } 13943 13944 /** 13945 * Called by MountService when the initial ASECs to scan are available. 13946 * Should block until all the ASEC containers are finished being scanned. 13947 */ 13948 public void scanAvailableAsecs() { 13949 updateExternalMediaStatusInner(true, false, false); 13950 if (mShouldRestoreconData) { 13951 SELinuxMMAC.setRestoreconDone(); 13952 mShouldRestoreconData = false; 13953 } 13954 } 13955 13956 /* 13957 * Collect information of applications on external media, map them against 13958 * existing containers and update information based on current mount status. 13959 * Please note that we always have to report status if reportStatus has been 13960 * set to true especially when unloading packages. 13961 */ 13962 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13963 boolean externalStorage) { 13964 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13965 int[] uidArr = EmptyArray.INT; 13966 13967 final String[] list = PackageHelper.getSecureContainerList(); 13968 if (ArrayUtils.isEmpty(list)) { 13969 Log.i(TAG, "No secure containers found"); 13970 } else { 13971 // Process list of secure containers and categorize them 13972 // as active or stale based on their package internal state. 13973 13974 // reader 13975 synchronized (mPackages) { 13976 for (String cid : list) { 13977 // Leave stages untouched for now; installer service owns them 13978 if (PackageInstallerService.isStageName(cid)) continue; 13979 13980 if (DEBUG_SD_INSTALL) 13981 Log.i(TAG, "Processing container " + cid); 13982 String pkgName = getAsecPackageName(cid); 13983 if (pkgName == null) { 13984 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13985 continue; 13986 } 13987 if (DEBUG_SD_INSTALL) 13988 Log.i(TAG, "Looking for pkg : " + pkgName); 13989 13990 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13991 if (ps == null) { 13992 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13993 continue; 13994 } 13995 13996 /* 13997 * Skip packages that are not external if we're unmounting 13998 * external storage. 13999 */ 14000 if (externalStorage && !isMounted && !isExternal(ps)) { 14001 continue; 14002 } 14003 14004 final AsecInstallArgs args = new AsecInstallArgs(cid, 14005 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14006 // The package status is changed only if the code path 14007 // matches between settings and the container id. 14008 if (ps.codePathString != null 14009 && ps.codePathString.startsWith(args.getCodePath())) { 14010 if (DEBUG_SD_INSTALL) { 14011 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14012 + " at code path: " + ps.codePathString); 14013 } 14014 14015 // We do have a valid package installed on sdcard 14016 processCids.put(args, ps.codePathString); 14017 final int uid = ps.appId; 14018 if (uid != -1) { 14019 uidArr = ArrayUtils.appendInt(uidArr, uid); 14020 } 14021 } else { 14022 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14023 + ps.codePathString); 14024 } 14025 } 14026 } 14027 14028 Arrays.sort(uidArr); 14029 } 14030 14031 // Process packages with valid entries. 14032 if (isMounted) { 14033 if (DEBUG_SD_INSTALL) 14034 Log.i(TAG, "Loading packages"); 14035 loadMediaPackages(processCids, uidArr); 14036 startCleaningPackages(); 14037 mInstallerService.onSecureContainersAvailable(); 14038 } else { 14039 if (DEBUG_SD_INSTALL) 14040 Log.i(TAG, "Unloading packages"); 14041 unloadMediaPackages(processCids, uidArr, reportStatus); 14042 } 14043 } 14044 14045 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14046 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14047 final int size = infos.size(); 14048 final String[] packageNames = new String[size]; 14049 final int[] packageUids = new int[size]; 14050 for (int i = 0; i < size; i++) { 14051 final ApplicationInfo info = infos.get(i); 14052 packageNames[i] = info.packageName; 14053 packageUids[i] = info.uid; 14054 } 14055 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14056 finishedReceiver); 14057 } 14058 14059 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14060 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14061 sendResourcesChangedBroadcast(mediaStatus, replacing, 14062 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14063 } 14064 14065 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14066 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14067 int size = pkgList.length; 14068 if (size > 0) { 14069 // Send broadcasts here 14070 Bundle extras = new Bundle(); 14071 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14072 if (uidArr != null) { 14073 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14074 } 14075 if (replacing) { 14076 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14077 } 14078 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14079 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14080 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14081 } 14082 } 14083 14084 /* 14085 * Look at potentially valid container ids from processCids If package 14086 * information doesn't match the one on record or package scanning fails, 14087 * the cid is added to list of removeCids. We currently don't delete stale 14088 * containers. 14089 */ 14090 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14091 ArrayList<String> pkgList = new ArrayList<String>(); 14092 Set<AsecInstallArgs> keys = processCids.keySet(); 14093 14094 for (AsecInstallArgs args : keys) { 14095 String codePath = processCids.get(args); 14096 if (DEBUG_SD_INSTALL) 14097 Log.i(TAG, "Loading container : " + args.cid); 14098 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14099 try { 14100 // Make sure there are no container errors first. 14101 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14102 Slog.e(TAG, "Failed to mount cid : " + args.cid 14103 + " when installing from sdcard"); 14104 continue; 14105 } 14106 // Check code path here. 14107 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14108 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14109 + " does not match one in settings " + codePath); 14110 continue; 14111 } 14112 // Parse package 14113 int parseFlags = mDefParseFlags; 14114 if (args.isExternalAsec()) { 14115 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14116 } 14117 if (args.isFwdLocked()) { 14118 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14119 } 14120 14121 synchronized (mInstallLock) { 14122 PackageParser.Package pkg = null; 14123 try { 14124 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14125 } catch (PackageManagerException e) { 14126 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14127 } 14128 // Scan the package 14129 if (pkg != null) { 14130 /* 14131 * TODO why is the lock being held? doPostInstall is 14132 * called in other places without the lock. This needs 14133 * to be straightened out. 14134 */ 14135 // writer 14136 synchronized (mPackages) { 14137 retCode = PackageManager.INSTALL_SUCCEEDED; 14138 pkgList.add(pkg.packageName); 14139 // Post process args 14140 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14141 pkg.applicationInfo.uid); 14142 } 14143 } else { 14144 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14145 } 14146 } 14147 14148 } finally { 14149 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14150 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14151 } 14152 } 14153 } 14154 // writer 14155 synchronized (mPackages) { 14156 // If the platform SDK has changed since the last time we booted, 14157 // we need to re-grant app permission to catch any new ones that 14158 // appear. This is really a hack, and means that apps can in some 14159 // cases get permissions that the user didn't initially explicitly 14160 // allow... it would be nice to have some better way to handle 14161 // this situation. 14162 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14163 if (regrantPermissions) 14164 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14165 + mSdkVersion + "; regranting permissions for external storage"); 14166 mSettings.mExternalSdkPlatform = mSdkVersion; 14167 14168 // Make sure group IDs have been assigned, and any permission 14169 // changes in other apps are accounted for 14170 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14171 | (regrantPermissions 14172 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14173 : 0)); 14174 14175 mSettings.updateExternalDatabaseVersion(); 14176 14177 // can downgrade to reader 14178 // Persist settings 14179 mSettings.writeLPr(); 14180 } 14181 // Send a broadcast to let everyone know we are done processing 14182 if (pkgList.size() > 0) { 14183 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14184 } 14185 } 14186 14187 /* 14188 * Utility method to unload a list of specified containers 14189 */ 14190 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14191 // Just unmount all valid containers. 14192 for (AsecInstallArgs arg : cidArgs) { 14193 synchronized (mInstallLock) { 14194 arg.doPostDeleteLI(false); 14195 } 14196 } 14197 } 14198 14199 /* 14200 * Unload packages mounted on external media. This involves deleting package 14201 * data from internal structures, sending broadcasts about diabled packages, 14202 * gc'ing to free up references, unmounting all secure containers 14203 * corresponding to packages on external media, and posting a 14204 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14205 * that we always have to post this message if status has been requested no 14206 * matter what. 14207 */ 14208 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14209 final boolean reportStatus) { 14210 if (DEBUG_SD_INSTALL) 14211 Log.i(TAG, "unloading media packages"); 14212 ArrayList<String> pkgList = new ArrayList<String>(); 14213 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14214 final Set<AsecInstallArgs> keys = processCids.keySet(); 14215 for (AsecInstallArgs args : keys) { 14216 String pkgName = args.getPackageName(); 14217 if (DEBUG_SD_INSTALL) 14218 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14219 // Delete package internally 14220 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14221 synchronized (mInstallLock) { 14222 boolean res = deletePackageLI(pkgName, null, false, null, null, 14223 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14224 if (res) { 14225 pkgList.add(pkgName); 14226 } else { 14227 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14228 failedList.add(args); 14229 } 14230 } 14231 } 14232 14233 // reader 14234 synchronized (mPackages) { 14235 // We didn't update the settings after removing each package; 14236 // write them now for all packages. 14237 mSettings.writeLPr(); 14238 } 14239 14240 // We have to absolutely send UPDATED_MEDIA_STATUS only 14241 // after confirming that all the receivers processed the ordered 14242 // broadcast when packages get disabled, force a gc to clean things up. 14243 // and unload all the containers. 14244 if (pkgList.size() > 0) { 14245 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14246 new IIntentReceiver.Stub() { 14247 public void performReceive(Intent intent, int resultCode, String data, 14248 Bundle extras, boolean ordered, boolean sticky, 14249 int sendingUser) throws RemoteException { 14250 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14251 reportStatus ? 1 : 0, 1, keys); 14252 mHandler.sendMessage(msg); 14253 } 14254 }); 14255 } else { 14256 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14257 keys); 14258 mHandler.sendMessage(msg); 14259 } 14260 } 14261 14262 private void loadPrivatePackages(VolumeInfo vol) { 14263 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14264 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14265 synchronized (mInstallLock) { 14266 synchronized (mPackages) { 14267 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14268 for (PackageSetting ps : packages) { 14269 final PackageParser.Package pkg; 14270 try { 14271 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14272 loaded.add(pkg.applicationInfo); 14273 } catch (PackageManagerException e) { 14274 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14275 } 14276 } 14277 14278 // TODO: regrant any permissions that changed based since original install 14279 14280 mSettings.writeLPr(); 14281 } 14282 } 14283 14284 Slog.d(TAG, "Loaded packages " + loaded); 14285 sendResourcesChangedBroadcast(true, false, loaded, null); 14286 } 14287 14288 private void unloadPrivatePackages(VolumeInfo vol) { 14289 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14290 synchronized (mInstallLock) { 14291 synchronized (mPackages) { 14292 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14293 for (PackageSetting ps : packages) { 14294 if (ps.pkg == null) continue; 14295 14296 final ApplicationInfo info = ps.pkg.applicationInfo; 14297 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14298 if (deletePackageLI(ps.name, null, false, null, null, 14299 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14300 unloaded.add(info); 14301 } else { 14302 Slog.w(TAG, "Failed to unload " + ps.codePath); 14303 } 14304 } 14305 14306 mSettings.writeLPr(); 14307 } 14308 } 14309 14310 Slog.d(TAG, "Unloaded packages " + unloaded); 14311 sendResourcesChangedBroadcast(false, false, unloaded, null); 14312 } 14313 14314 private void unfreezePackage(String packageName) { 14315 synchronized (mPackages) { 14316 final PackageSetting ps = mSettings.mPackages.get(packageName); 14317 if (ps != null) { 14318 ps.frozen = false; 14319 } 14320 } 14321 } 14322 14323 @Override 14324 public int movePackage(final String packageName, final String volumeUuid) { 14325 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14326 14327 final int moveId = mNextMoveId.getAndIncrement(); 14328 try { 14329 movePackageInternal(packageName, volumeUuid, moveId); 14330 } catch (PackageManagerException e) { 14331 Slog.d(TAG, "Failed to move " + packageName, e); 14332 mMoveCallbacks.notifyStatusChanged(moveId, 14333 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14334 } 14335 return moveId; 14336 } 14337 14338 private void movePackageInternal(final String packageName, final String volumeUuid, 14339 final int moveId) throws PackageManagerException { 14340 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14341 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14342 final PackageManager pm = mContext.getPackageManager(); 14343 14344 final boolean currentAsec; 14345 final String currentVolumeUuid; 14346 final File codeFile; 14347 final String installerPackageName; 14348 final String packageAbiOverride; 14349 final int appId; 14350 final String seinfo; 14351 final String label; 14352 14353 // reader 14354 synchronized (mPackages) { 14355 final PackageParser.Package pkg = mPackages.get(packageName); 14356 final PackageSetting ps = mSettings.mPackages.get(packageName); 14357 if (pkg == null || ps == null) { 14358 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14359 } 14360 14361 if (pkg.applicationInfo.isSystemApp()) { 14362 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14363 "Cannot move system application"); 14364 } 14365 14366 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14367 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14368 "Package already moved to " + volumeUuid); 14369 } 14370 14371 final File probe = new File(pkg.codePath); 14372 final File probeOat = new File(probe, "oat"); 14373 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14374 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14375 "Move only supported for modern cluster style installs"); 14376 } 14377 14378 if (ps.frozen) { 14379 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14380 "Failed to move already frozen package"); 14381 } 14382 ps.frozen = true; 14383 14384 currentAsec = pkg.applicationInfo.isForwardLocked() 14385 || pkg.applicationInfo.isExternalAsec(); 14386 currentVolumeUuid = ps.volumeUuid; 14387 codeFile = new File(pkg.codePath); 14388 installerPackageName = ps.installerPackageName; 14389 packageAbiOverride = ps.cpuAbiOverrideString; 14390 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14391 seinfo = pkg.applicationInfo.seinfo; 14392 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14393 } 14394 14395 // Now that we're guarded by frozen state, kill app during move 14396 killApplication(packageName, appId, "move pkg"); 14397 14398 final Bundle extras = new Bundle(); 14399 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14400 extras.putString(Intent.EXTRA_TITLE, label); 14401 mMoveCallbacks.notifyCreated(moveId, extras); 14402 14403 int installFlags; 14404 final boolean moveCompleteApp; 14405 final File measurePath; 14406 14407 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14408 installFlags = INSTALL_INTERNAL; 14409 moveCompleteApp = !currentAsec; 14410 measurePath = Environment.getDataAppDirectory(volumeUuid); 14411 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14412 installFlags = INSTALL_EXTERNAL; 14413 moveCompleteApp = false; 14414 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14415 } else { 14416 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14417 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14418 || !volume.isMountedWritable()) { 14419 unfreezePackage(packageName); 14420 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14421 "Move location not mounted private volume"); 14422 } 14423 14424 Preconditions.checkState(!currentAsec); 14425 14426 installFlags = INSTALL_INTERNAL; 14427 moveCompleteApp = true; 14428 measurePath = Environment.getDataAppDirectory(volumeUuid); 14429 } 14430 14431 final PackageStats stats = new PackageStats(null, -1); 14432 synchronized (mInstaller) { 14433 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14434 unfreezePackage(packageName); 14435 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14436 "Failed to measure package size"); 14437 } 14438 } 14439 14440 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14441 14442 final long startFreeBytes = measurePath.getFreeSpace(); 14443 final long sizeBytes; 14444 if (moveCompleteApp) { 14445 sizeBytes = stats.codeSize + stats.dataSize; 14446 } else { 14447 sizeBytes = stats.codeSize; 14448 } 14449 14450 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14451 unfreezePackage(packageName); 14452 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14453 "Not enough free space to move"); 14454 } 14455 14456 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14457 14458 final CountDownLatch installedLatch = new CountDownLatch(1); 14459 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14460 @Override 14461 public void onUserActionRequired(Intent intent) throws RemoteException { 14462 throw new IllegalStateException(); 14463 } 14464 14465 @Override 14466 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14467 Bundle extras) throws RemoteException { 14468 Slog.d(TAG, "Install result for move: " 14469 + PackageManager.installStatusToString(returnCode, msg)); 14470 14471 installedLatch.countDown(); 14472 14473 // Regardless of success or failure of the move operation, 14474 // always unfreeze the package 14475 unfreezePackage(packageName); 14476 14477 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14478 switch (status) { 14479 case PackageInstaller.STATUS_SUCCESS: 14480 mMoveCallbacks.notifyStatusChanged(moveId, 14481 PackageManager.MOVE_SUCCEEDED); 14482 break; 14483 case PackageInstaller.STATUS_FAILURE_STORAGE: 14484 mMoveCallbacks.notifyStatusChanged(moveId, 14485 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14486 break; 14487 default: 14488 mMoveCallbacks.notifyStatusChanged(moveId, 14489 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14490 break; 14491 } 14492 } 14493 }; 14494 14495 final MoveInfo move; 14496 if (moveCompleteApp) { 14497 // Kick off a thread to report progress estimates 14498 new Thread() { 14499 @Override 14500 public void run() { 14501 while (true) { 14502 try { 14503 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14504 break; 14505 } 14506 } catch (InterruptedException ignored) { 14507 } 14508 14509 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14510 final int progress = 10 + (int) MathUtils.constrain( 14511 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14512 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14513 } 14514 } 14515 }.start(); 14516 14517 final String dataAppName = codeFile.getName(); 14518 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14519 dataAppName, appId, seinfo); 14520 } else { 14521 move = null; 14522 } 14523 14524 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14525 14526 final Message msg = mHandler.obtainMessage(INIT_COPY); 14527 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14528 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14529 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14530 mHandler.sendMessage(msg); 14531 } 14532 14533 @Override 14534 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14535 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14536 14537 final int realMoveId = mNextMoveId.getAndIncrement(); 14538 final Bundle extras = new Bundle(); 14539 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14540 mMoveCallbacks.notifyCreated(realMoveId, extras); 14541 14542 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14543 @Override 14544 public void onCreated(int moveId, Bundle extras) { 14545 // Ignored 14546 } 14547 14548 @Override 14549 public void onStatusChanged(int moveId, int status, long estMillis) { 14550 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14551 } 14552 }; 14553 14554 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14555 storage.setPrimaryStorageUuid(volumeUuid, callback); 14556 return realMoveId; 14557 } 14558 14559 @Override 14560 public int getMoveStatus(int moveId) { 14561 mContext.enforceCallingOrSelfPermission( 14562 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14563 return mMoveCallbacks.mLastStatus.get(moveId); 14564 } 14565 14566 @Override 14567 public void registerMoveCallback(IPackageMoveObserver callback) { 14568 mContext.enforceCallingOrSelfPermission( 14569 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14570 mMoveCallbacks.register(callback); 14571 } 14572 14573 @Override 14574 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14575 mContext.enforceCallingOrSelfPermission( 14576 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14577 mMoveCallbacks.unregister(callback); 14578 } 14579 14580 @Override 14581 public boolean setInstallLocation(int loc) { 14582 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14583 null); 14584 if (getInstallLocation() == loc) { 14585 return true; 14586 } 14587 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14588 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14589 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14590 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14591 return true; 14592 } 14593 return false; 14594 } 14595 14596 @Override 14597 public int getInstallLocation() { 14598 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14599 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14600 PackageHelper.APP_INSTALL_AUTO); 14601 } 14602 14603 /** Called by UserManagerService */ 14604 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14605 mDirtyUsers.remove(userHandle); 14606 mSettings.removeUserLPw(userHandle); 14607 mPendingBroadcasts.remove(userHandle); 14608 if (mInstaller != null) { 14609 // Technically, we shouldn't be doing this with the package lock 14610 // held. However, this is very rare, and there is already so much 14611 // other disk I/O going on, that we'll let it slide for now. 14612 final StorageManager storage = StorageManager.from(mContext); 14613 final List<VolumeInfo> vols = storage.getVolumes(); 14614 for (VolumeInfo vol : vols) { 14615 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14616 final String volumeUuid = vol.getFsUuid(); 14617 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14618 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14619 } 14620 } 14621 } 14622 mUserNeedsBadging.delete(userHandle); 14623 removeUnusedPackagesLILPw(userManager, userHandle); 14624 } 14625 14626 /** 14627 * We're removing userHandle and would like to remove any downloaded packages 14628 * that are no longer in use by any other user. 14629 * @param userHandle the user being removed 14630 */ 14631 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14632 final boolean DEBUG_CLEAN_APKS = false; 14633 int [] users = userManager.getUserIdsLPr(); 14634 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14635 while (psit.hasNext()) { 14636 PackageSetting ps = psit.next(); 14637 if (ps.pkg == null) { 14638 continue; 14639 } 14640 final String packageName = ps.pkg.packageName; 14641 // Skip over if system app 14642 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14643 continue; 14644 } 14645 if (DEBUG_CLEAN_APKS) { 14646 Slog.i(TAG, "Checking package " + packageName); 14647 } 14648 boolean keep = false; 14649 for (int i = 0; i < users.length; i++) { 14650 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14651 keep = true; 14652 if (DEBUG_CLEAN_APKS) { 14653 Slog.i(TAG, " Keeping package " + packageName + " for user " 14654 + users[i]); 14655 } 14656 break; 14657 } 14658 } 14659 if (!keep) { 14660 if (DEBUG_CLEAN_APKS) { 14661 Slog.i(TAG, " Removing package " + packageName); 14662 } 14663 mHandler.post(new Runnable() { 14664 public void run() { 14665 deletePackageX(packageName, userHandle, 0); 14666 } //end run 14667 }); 14668 } 14669 } 14670 } 14671 14672 /** Called by UserManagerService */ 14673 void createNewUserLILPw(int userHandle, File path) { 14674 if (mInstaller != null) { 14675 mInstaller.createUserConfig(userHandle); 14676 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14677 } 14678 } 14679 14680 void newUserCreatedLILPw(int userHandle) { 14681 // Adding a user requires updating runtime permissions for system apps. 14682 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14683 } 14684 14685 @Override 14686 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14687 mContext.enforceCallingOrSelfPermission( 14688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14689 "Only package verification agents can read the verifier device identity"); 14690 14691 synchronized (mPackages) { 14692 return mSettings.getVerifierDeviceIdentityLPw(); 14693 } 14694 } 14695 14696 @Override 14697 public void setPermissionEnforced(String permission, boolean enforced) { 14698 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14699 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14700 synchronized (mPackages) { 14701 if (mSettings.mReadExternalStorageEnforced == null 14702 || mSettings.mReadExternalStorageEnforced != enforced) { 14703 mSettings.mReadExternalStorageEnforced = enforced; 14704 mSettings.writeLPr(); 14705 } 14706 } 14707 // kill any non-foreground processes so we restart them and 14708 // grant/revoke the GID. 14709 final IActivityManager am = ActivityManagerNative.getDefault(); 14710 if (am != null) { 14711 final long token = Binder.clearCallingIdentity(); 14712 try { 14713 am.killProcessesBelowForeground("setPermissionEnforcement"); 14714 } catch (RemoteException e) { 14715 } finally { 14716 Binder.restoreCallingIdentity(token); 14717 } 14718 } 14719 } else { 14720 throw new IllegalArgumentException("No selective enforcement for " + permission); 14721 } 14722 } 14723 14724 @Override 14725 @Deprecated 14726 public boolean isPermissionEnforced(String permission) { 14727 return true; 14728 } 14729 14730 @Override 14731 public boolean isStorageLow() { 14732 final long token = Binder.clearCallingIdentity(); 14733 try { 14734 final DeviceStorageMonitorInternal 14735 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14736 if (dsm != null) { 14737 return dsm.isMemoryLow(); 14738 } else { 14739 return false; 14740 } 14741 } finally { 14742 Binder.restoreCallingIdentity(token); 14743 } 14744 } 14745 14746 @Override 14747 public IPackageInstaller getPackageInstaller() { 14748 return mInstallerService; 14749 } 14750 14751 private boolean userNeedsBadging(int userId) { 14752 int index = mUserNeedsBadging.indexOfKey(userId); 14753 if (index < 0) { 14754 final UserInfo userInfo; 14755 final long token = Binder.clearCallingIdentity(); 14756 try { 14757 userInfo = sUserManager.getUserInfo(userId); 14758 } finally { 14759 Binder.restoreCallingIdentity(token); 14760 } 14761 final boolean b; 14762 if (userInfo != null && userInfo.isManagedProfile()) { 14763 b = true; 14764 } else { 14765 b = false; 14766 } 14767 mUserNeedsBadging.put(userId, b); 14768 return b; 14769 } 14770 return mUserNeedsBadging.valueAt(index); 14771 } 14772 14773 @Override 14774 public KeySet getKeySetByAlias(String packageName, String alias) { 14775 if (packageName == null || alias == null) { 14776 return null; 14777 } 14778 synchronized(mPackages) { 14779 final PackageParser.Package pkg = mPackages.get(packageName); 14780 if (pkg == null) { 14781 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14782 throw new IllegalArgumentException("Unknown package: " + packageName); 14783 } 14784 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14785 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14786 } 14787 } 14788 14789 @Override 14790 public KeySet getSigningKeySet(String packageName) { 14791 if (packageName == null) { 14792 return null; 14793 } 14794 synchronized(mPackages) { 14795 final PackageParser.Package pkg = mPackages.get(packageName); 14796 if (pkg == null) { 14797 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14798 throw new IllegalArgumentException("Unknown package: " + packageName); 14799 } 14800 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14801 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14802 throw new SecurityException("May not access signing KeySet of other apps."); 14803 } 14804 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14805 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14806 } 14807 } 14808 14809 @Override 14810 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14811 if (packageName == null || ks == null) { 14812 return false; 14813 } 14814 synchronized(mPackages) { 14815 final PackageParser.Package pkg = mPackages.get(packageName); 14816 if (pkg == null) { 14817 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14818 throw new IllegalArgumentException("Unknown package: " + packageName); 14819 } 14820 IBinder ksh = ks.getToken(); 14821 if (ksh instanceof KeySetHandle) { 14822 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14823 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14824 } 14825 return false; 14826 } 14827 } 14828 14829 @Override 14830 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14831 if (packageName == null || ks == null) { 14832 return false; 14833 } 14834 synchronized(mPackages) { 14835 final PackageParser.Package pkg = mPackages.get(packageName); 14836 if (pkg == null) { 14837 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14838 throw new IllegalArgumentException("Unknown package: " + packageName); 14839 } 14840 IBinder ksh = ks.getToken(); 14841 if (ksh instanceof KeySetHandle) { 14842 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14843 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14844 } 14845 return false; 14846 } 14847 } 14848 14849 public void getUsageStatsIfNoPackageUsageInfo() { 14850 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14851 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14852 if (usm == null) { 14853 throw new IllegalStateException("UsageStatsManager must be initialized"); 14854 } 14855 long now = System.currentTimeMillis(); 14856 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14857 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14858 String packageName = entry.getKey(); 14859 PackageParser.Package pkg = mPackages.get(packageName); 14860 if (pkg == null) { 14861 continue; 14862 } 14863 UsageStats usage = entry.getValue(); 14864 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14865 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14866 } 14867 } 14868 } 14869 14870 /** 14871 * Check and throw if the given before/after packages would be considered a 14872 * downgrade. 14873 */ 14874 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14875 throws PackageManagerException { 14876 if (after.versionCode < before.mVersionCode) { 14877 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14878 "Update version code " + after.versionCode + " is older than current " 14879 + before.mVersionCode); 14880 } else if (after.versionCode == before.mVersionCode) { 14881 if (after.baseRevisionCode < before.baseRevisionCode) { 14882 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14883 "Update base revision code " + after.baseRevisionCode 14884 + " is older than current " + before.baseRevisionCode); 14885 } 14886 14887 if (!ArrayUtils.isEmpty(after.splitNames)) { 14888 for (int i = 0; i < after.splitNames.length; i++) { 14889 final String splitName = after.splitNames[i]; 14890 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14891 if (j != -1) { 14892 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14893 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14894 "Update split " + splitName + " revision code " 14895 + after.splitRevisionCodes[i] + " is older than current " 14896 + before.splitRevisionCodes[j]); 14897 } 14898 } 14899 } 14900 } 14901 } 14902 } 14903 14904 private static class MoveCallbacks extends Handler { 14905 private static final int MSG_CREATED = 1; 14906 private static final int MSG_STATUS_CHANGED = 2; 14907 14908 private final RemoteCallbackList<IPackageMoveObserver> 14909 mCallbacks = new RemoteCallbackList<>(); 14910 14911 private final SparseIntArray mLastStatus = new SparseIntArray(); 14912 14913 public MoveCallbacks(Looper looper) { 14914 super(looper); 14915 } 14916 14917 public void register(IPackageMoveObserver callback) { 14918 mCallbacks.register(callback); 14919 } 14920 14921 public void unregister(IPackageMoveObserver callback) { 14922 mCallbacks.unregister(callback); 14923 } 14924 14925 @Override 14926 public void handleMessage(Message msg) { 14927 final SomeArgs args = (SomeArgs) msg.obj; 14928 final int n = mCallbacks.beginBroadcast(); 14929 for (int i = 0; i < n; i++) { 14930 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14931 try { 14932 invokeCallback(callback, msg.what, args); 14933 } catch (RemoteException ignored) { 14934 } 14935 } 14936 mCallbacks.finishBroadcast(); 14937 args.recycle(); 14938 } 14939 14940 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14941 throws RemoteException { 14942 switch (what) { 14943 case MSG_CREATED: { 14944 callback.onCreated(args.argi1, (Bundle) args.arg2); 14945 break; 14946 } 14947 case MSG_STATUS_CHANGED: { 14948 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14949 break; 14950 } 14951 } 14952 } 14953 14954 private void notifyCreated(int moveId, Bundle extras) { 14955 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 14956 14957 final SomeArgs args = SomeArgs.obtain(); 14958 args.argi1 = moveId; 14959 args.arg2 = extras; 14960 obtainMessage(MSG_CREATED, args).sendToTarget(); 14961 } 14962 14963 private void notifyStatusChanged(int moveId, int status) { 14964 notifyStatusChanged(moveId, status, -1); 14965 } 14966 14967 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14968 Slog.v(TAG, "Move " + moveId + " status " + status); 14969 14970 final SomeArgs args = SomeArgs.obtain(); 14971 args.argi1 = moveId; 14972 args.argi2 = status; 14973 args.arg3 = estMillis; 14974 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14975 14976 synchronized (mLastStatus) { 14977 mLastStatus.put(moveId, status); 14978 } 14979 } 14980 } 14981} 14982