PackageManagerService.java revision e31b820dad4c5f2b19ee10479a675a139ad3c61e
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.PrintStreamPrinter; 175import android.util.Slog; 176import android.util.SparseArray; 177import android.util.SparseBooleanArray; 178import android.util.SparseIntArray; 179import android.util.Xml; 180import android.view.Display; 181 182import dalvik.system.DexFile; 183import dalvik.system.VMRuntime; 184 185import libcore.io.IoUtils; 186import libcore.util.EmptyArray; 187 188import com.android.internal.R; 189import com.android.internal.app.IMediaContainerService; 190import com.android.internal.app.ResolverActivity; 191import com.android.internal.content.NativeLibraryHelper; 192import com.android.internal.content.PackageHelper; 193import com.android.internal.os.IParcelFileDescriptorFactory; 194import com.android.internal.os.SomeArgs; 195import com.android.internal.util.ArrayUtils; 196import com.android.internal.util.FastPrintWriter; 197import com.android.internal.util.FastXmlSerializer; 198import com.android.internal.util.IndentingPrintWriter; 199import com.android.internal.util.Preconditions; 200import com.android.server.EventLogTags; 201import com.android.server.FgThread; 202import com.android.server.IntentResolver; 203import com.android.server.LocalServices; 204import com.android.server.ServiceThread; 205import com.android.server.SystemConfig; 206import com.android.server.Watchdog; 207import com.android.server.pm.Settings.DatabaseVersion; 208import com.android.server.storage.DeviceStorageMonitorInternal; 209 210import org.xmlpull.v1.XmlPullParser; 211import org.xmlpull.v1.XmlSerializer; 212 213import java.io.BufferedInputStream; 214import java.io.BufferedOutputStream; 215import java.io.BufferedReader; 216import java.io.ByteArrayInputStream; 217import java.io.ByteArrayOutputStream; 218import java.io.File; 219import java.io.FileDescriptor; 220import java.io.FileNotFoundException; 221import java.io.FileOutputStream; 222import java.io.FileReader; 223import java.io.FilenameFilter; 224import java.io.IOException; 225import java.io.InputStream; 226import java.io.PrintWriter; 227import java.nio.charset.StandardCharsets; 228import java.security.NoSuchAlgorithmException; 229import java.security.PublicKey; 230import java.security.cert.CertificateEncodingException; 231import java.security.cert.CertificateException; 232import java.text.SimpleDateFormat; 233import java.util.ArrayList; 234import java.util.Arrays; 235import java.util.Collection; 236import java.util.Collections; 237import java.util.Comparator; 238import java.util.Date; 239import java.util.Iterator; 240import java.util.List; 241import java.util.Map; 242import java.util.Objects; 243import java.util.Set; 244import java.util.concurrent.atomic.AtomicBoolean; 245import java.util.concurrent.atomic.AtomicInteger; 246import java.util.concurrent.atomic.AtomicLong; 247 248/** 249 * Keep track of all those .apks everywhere. 250 * 251 * This is very central to the platform's security; please run the unit 252 * tests whenever making modifications here: 253 * 254mmm frameworks/base/tests/AndroidTests 255adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 256adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 257 * 258 * {@hide} 259 */ 260public class PackageManagerService extends IPackageManager.Stub { 261 static final String TAG = "PackageManager"; 262 static final boolean DEBUG_SETTINGS = false; 263 static final boolean DEBUG_PREFERRED = false; 264 static final boolean DEBUG_UPGRADE = false; 265 private static final boolean DEBUG_BACKUP = true; 266 private static final boolean DEBUG_INSTALL = false; 267 private static final boolean DEBUG_REMOVE = false; 268 private static final boolean DEBUG_BROADCASTS = false; 269 private static final boolean DEBUG_SHOW_INFO = false; 270 private static final boolean DEBUG_PACKAGE_INFO = false; 271 private static final boolean DEBUG_INTENT_MATCHING = false; 272 private static final boolean DEBUG_PACKAGE_SCANNING = false; 273 private static final boolean DEBUG_VERIFY = false; 274 private static final boolean DEBUG_DEXOPT = false; 275 private static final boolean DEBUG_ABI_SELECTION = false; 276 277 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 278 279 private static final int RADIO_UID = Process.PHONE_UID; 280 private static final int LOG_UID = Process.LOG_UID; 281 private static final int NFC_UID = Process.NFC_UID; 282 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 283 private static final int SHELL_UID = Process.SHELL_UID; 284 285 // Cap the size of permission trees that 3rd party apps can define 286 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 287 288 // Suffix used during package installation when copying/moving 289 // package apks to install directory. 290 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 291 292 static final int SCAN_NO_DEX = 1<<1; 293 static final int SCAN_FORCE_DEX = 1<<2; 294 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 295 static final int SCAN_NEW_INSTALL = 1<<4; 296 static final int SCAN_NO_PATHS = 1<<5; 297 static final int SCAN_UPDATE_TIME = 1<<6; 298 static final int SCAN_DEFER_DEX = 1<<7; 299 static final int SCAN_BOOTING = 1<<8; 300 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 301 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 302 static final int SCAN_REQUIRE_KNOWN = 1<<12; 303 304 static final int REMOVE_CHATTY = 1<<16; 305 306 /** 307 * Timeout (in milliseconds) after which the watchdog should declare that 308 * our handler thread is wedged. The usual default for such things is one 309 * minute but we sometimes do very lengthy I/O operations on this thread, 310 * such as installing multi-gigabyte applications, so ours needs to be longer. 311 */ 312 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 313 314 /** 315 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 316 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 317 * settings entry if available, otherwise we use the hardcoded default. If it's been 318 * more than this long since the last fstrim, we force one during the boot sequence. 319 * 320 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 321 * one gets run at the next available charging+idle time. This final mandatory 322 * no-fstrim check kicks in only of the other scheduling criteria is never met. 323 */ 324 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 325 326 /** 327 * Whether verification is enabled by default. 328 */ 329 private static final boolean DEFAULT_VERIFY_ENABLE = true; 330 331 /** 332 * The default maximum time to wait for the verification agent to return in 333 * milliseconds. 334 */ 335 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 336 337 /** 338 * The default response for package verification timeout. 339 * 340 * This can be either PackageManager.VERIFICATION_ALLOW or 341 * PackageManager.VERIFICATION_REJECT. 342 */ 343 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 344 345 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 346 347 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 348 DEFAULT_CONTAINER_PACKAGE, 349 "com.android.defcontainer.DefaultContainerService"); 350 351 private static final String KILL_APP_REASON_GIDS_CHANGED = 352 "permission grant or revoke changed gids"; 353 354 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 355 "permissions revoked"; 356 357 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 358 359 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 360 361 /** Permission grant: not grant the permission. */ 362 private static final int GRANT_DENIED = 1; 363 364 /** Permission grant: grant the permission as an install permission. */ 365 private static final int GRANT_INSTALL = 2; 366 367 /** Permission grant: grant the permission as a runtime one. */ 368 private static final int GRANT_RUNTIME = 3; 369 370 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 371 private static final int GRANT_UPGRADE = 4; 372 373 final ServiceThread mHandlerThread; 374 375 final PackageHandler mHandler; 376 377 /** 378 * Messages for {@link #mHandler} that need to wait for system ready before 379 * being dispatched. 380 */ 381 private ArrayList<Message> mPostSystemReadyMessages; 382 383 final int mSdkVersion = Build.VERSION.SDK_INT; 384 385 final Context mContext; 386 final boolean mFactoryTest; 387 final boolean mOnlyCore; 388 final boolean mLazyDexOpt; 389 final long mDexOptLRUThresholdInMills; 390 final DisplayMetrics mMetrics; 391 final int mDefParseFlags; 392 final String[] mSeparateProcesses; 393 final boolean mIsUpgrade; 394 395 // This is where all application persistent data goes. 396 final File mAppDataDir; 397 398 // This is where all application persistent data goes for secondary users. 399 final File mUserAppDataDir; 400 401 /** The location for ASEC container files on internal storage. */ 402 final String mAsecInternalPath; 403 404 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 405 // LOCK HELD. Can be called with mInstallLock held. 406 final Installer mInstaller; 407 408 /** Directory where installed third-party apps stored */ 409 final File mAppInstallDir; 410 411 /** 412 * Directory to which applications installed internally have their 413 * 32 bit native libraries copied. 414 */ 415 private File mAppLib32InstallDir; 416 417 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 418 // apps. 419 final File mDrmAppPrivateInstallDir; 420 421 // ---------------------------------------------------------------- 422 423 // Lock for state used when installing and doing other long running 424 // operations. Methods that must be called with this lock held have 425 // the suffix "LI". 426 final Object mInstallLock = new Object(); 427 428 // ---------------------------------------------------------------- 429 430 // Keys are String (package name), values are Package. This also serves 431 // as the lock for the global state. Methods that must be called with 432 // this lock held have the prefix "LP". 433 final ArrayMap<String, PackageParser.Package> mPackages = 434 new ArrayMap<String, PackageParser.Package>(); 435 436 // Tracks available target package names -> overlay package paths. 437 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 438 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 439 440 final Settings mSettings; 441 boolean mRestoredSettings; 442 443 // System configuration read by SystemConfig. 444 final int[] mGlobalGids; 445 final SparseArray<ArraySet<String>> mSystemPermissions; 446 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 447 448 // If mac_permissions.xml was found for seinfo labeling. 449 boolean mFoundPolicyFile; 450 451 // If a recursive restorecon of /data/data/<pkg> is needed. 452 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 453 454 public static final class SharedLibraryEntry { 455 public final String path; 456 public final String apk; 457 458 SharedLibraryEntry(String _path, String _apk) { 459 path = _path; 460 apk = _apk; 461 } 462 } 463 464 // Currently known shared libraries. 465 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 466 new ArrayMap<String, SharedLibraryEntry>(); 467 468 // All available activities, for your resolving pleasure. 469 final ActivityIntentResolver mActivities = 470 new ActivityIntentResolver(); 471 472 // All available receivers, for your resolving pleasure. 473 final ActivityIntentResolver mReceivers = 474 new ActivityIntentResolver(); 475 476 // All available services, for your resolving pleasure. 477 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 478 479 // All available providers, for your resolving pleasure. 480 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 481 482 // Mapping from provider base names (first directory in content URI codePath) 483 // to the provider information. 484 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 485 new ArrayMap<String, PackageParser.Provider>(); 486 487 // Mapping from instrumentation class names to info about them. 488 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 489 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 490 491 // Mapping from permission names to info about them. 492 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 493 new ArrayMap<String, PackageParser.PermissionGroup>(); 494 495 // Packages whose data we have transfered into another package, thus 496 // should no longer exist. 497 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 498 499 // Broadcast actions that are only available to the system. 500 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 501 502 /** List of packages waiting for verification. */ 503 final SparseArray<PackageVerificationState> mPendingVerification 504 = new SparseArray<PackageVerificationState>(); 505 506 /** Set of packages associated with each app op permission. */ 507 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 508 509 final PackageInstallerService mInstallerService; 510 511 private final PackageDexOptimizer mPackageDexOptimizer; 512 513 private AtomicInteger mNextMoveId = new AtomicInteger(); 514 private final MoveCallbacks mMoveCallbacks; 515 516 // Cache of users who need badging. 517 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 518 519 /** Token for keys in mPendingVerification. */ 520 private int mPendingVerificationToken = 0; 521 522 volatile boolean mSystemReady; 523 volatile boolean mSafeMode; 524 volatile boolean mHasSystemUidErrors; 525 526 ApplicationInfo mAndroidApplication; 527 final ActivityInfo mResolveActivity = new ActivityInfo(); 528 final ResolveInfo mResolveInfo = new ResolveInfo(); 529 ComponentName mResolveComponentName; 530 PackageParser.Package mPlatformPackage; 531 ComponentName mCustomResolverComponentName; 532 533 boolean mResolverReplaced = false; 534 535 private final ComponentName mIntentFilterVerifierComponent; 536 private int mIntentFilterVerificationToken = 0; 537 538 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 539 = new SparseArray<IntentFilterVerificationState>(); 540 541 private interface IntentFilterVerifier<T extends IntentFilter> { 542 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 543 T filter, String packageName); 544 void startVerifications(int userId); 545 void receiveVerificationResponse(int verificationId); 546 } 547 548 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 549 private Context mContext; 550 private ComponentName mIntentFilterVerifierComponent; 551 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 552 553 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 554 mContext = context; 555 mIntentFilterVerifierComponent = verifierComponent; 556 } 557 558 private String getDefaultScheme() { 559 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 560 return IntentFilter.SCHEME_HTTP; 561 } 562 563 @Override 564 public void startVerifications(int userId) { 565 // Launch verifications requests 566 int count = mCurrentIntentFilterVerifications.size(); 567 for (int n=0; n<count; n++) { 568 int verificationId = mCurrentIntentFilterVerifications.get(n); 569 final IntentFilterVerificationState ivs = 570 mIntentFilterVerificationStates.get(verificationId); 571 572 String packageName = ivs.getPackageName(); 573 574 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 575 final int filterCount = filters.size(); 576 ArraySet<String> domainsSet = new ArraySet<>(); 577 for (int m=0; m<filterCount; m++) { 578 PackageParser.ActivityIntentInfo filter = filters.get(m); 579 domainsSet.addAll(filter.getHostsList()); 580 } 581 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 582 synchronized (mPackages) { 583 if (mSettings.createIntentFilterVerificationIfNeededLPw( 584 packageName, domainsList) != null) { 585 scheduleWriteSettingsLocked(); 586 } 587 } 588 sendVerificationRequest(userId, verificationId, ivs); 589 } 590 mCurrentIntentFilterVerifications.clear(); 591 } 592 593 private void sendVerificationRequest(int userId, int verificationId, 594 IntentFilterVerificationState ivs) { 595 596 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 599 verificationId); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 602 getDefaultScheme()); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 605 ivs.getHostsString()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 608 ivs.getPackageName()); 609 verificationIntent.setComponent(mIntentFilterVerifierComponent); 610 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 611 612 UserHandle user = new UserHandle(userId); 613 mContext.sendBroadcastAsUser(verificationIntent, user); 614 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 615 } 616 617 public void receiveVerificationResponse(int verificationId) { 618 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 619 620 final boolean verified = ivs.isVerified(); 621 622 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 623 final int count = filters.size(); 624 for (int n=0; n<count; n++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(n); 626 filter.setVerified(verified); 627 628 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 629 + verified + " and hosts:" + ivs.getHostsString()); 630 } 631 632 mIntentFilterVerificationStates.remove(verificationId); 633 634 final String packageName = ivs.getPackageName(); 635 IntentFilterVerificationInfo ivi = null; 636 637 synchronized (mPackages) { 638 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 639 } 640 if (ivi == null) { 641 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 642 + verificationId + " packageName:" + packageName); 643 return; 644 } 645 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 646 + verificationId); 647 648 synchronized (mPackages) { 649 if (verified) { 650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 651 } else { 652 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 653 } 654 scheduleWriteSettingsLocked(); 655 656 final int userId = ivs.getUserId(); 657 if (userId != UserHandle.USER_ALL) { 658 final int userStatus = 659 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 660 661 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 662 boolean needUpdate = false; 663 664 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 665 // already been set by the User thru the Disambiguation dialog 666 switch (userStatus) { 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 } else { 671 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 672 } 673 needUpdate = true; 674 break; 675 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 needUpdate = true; 680 } 681 break; 682 683 default: 684 // Nothing to do 685 } 686 687 if (needUpdate) { 688 mSettings.updateIntentFilterVerificationStatusLPw( 689 packageName, updatedStatus, userId); 690 scheduleWritePackageRestrictionsLocked(userId); 691 } 692 } 693 } 694 } 695 696 @Override 697 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 698 ActivityIntentInfo filter, String packageName) { 699 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 700 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 701 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 702 return false; 703 } 704 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 705 if (ivs == null) { 706 ivs = createDomainVerificationState(verifierId, userId, verificationId, 707 packageName); 708 } 709 if (!hasValidDomains(filter)) { 710 return false; 711 } 712 ivs.addFilter(filter); 713 return true; 714 } 715 716 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 717 int userId, int verificationId, String packageName) { 718 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 719 verifierId, userId, packageName); 720 ivs.setPendingState(); 721 synchronized (mPackages) { 722 mIntentFilterVerificationStates.append(verificationId, ivs); 723 mCurrentIntentFilterVerifications.add(verificationId); 724 } 725 return ivs; 726 } 727 } 728 729 private static boolean hasValidDomains(ActivityIntentInfo filter) { 730 return hasValidDomains(filter, true); 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 734 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 735 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 736 if (!hasHTTPorHTTPS) { 737 if (logging) { 738 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 739 } 740 return false; 741 } 742 return true; 743 } 744 745 private IntentFilterVerifier mIntentFilterVerifier; 746 747 // Set of pending broadcasts for aggregating enable/disable of components. 748 static class PendingPackageBroadcasts { 749 // for each user id, a map of <package name -> components within that package> 750 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 751 752 public PendingPackageBroadcasts() { 753 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 754 } 755 756 public ArrayList<String> get(int userId, String packageName) { 757 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 758 return packages.get(packageName); 759 } 760 761 public void put(int userId, String packageName, ArrayList<String> components) { 762 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 763 packages.put(packageName, components); 764 } 765 766 public void remove(int userId, String packageName) { 767 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 768 if (packages != null) { 769 packages.remove(packageName); 770 } 771 } 772 773 public void remove(int userId) { 774 mUidMap.remove(userId); 775 } 776 777 public int userIdCount() { 778 return mUidMap.size(); 779 } 780 781 public int userIdAt(int n) { 782 return mUidMap.keyAt(n); 783 } 784 785 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 786 return mUidMap.get(userId); 787 } 788 789 public int size() { 790 // total number of pending broadcast entries across all userIds 791 int num = 0; 792 for (int i = 0; i< mUidMap.size(); i++) { 793 num += mUidMap.valueAt(i).size(); 794 } 795 return num; 796 } 797 798 public void clear() { 799 mUidMap.clear(); 800 } 801 802 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 803 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 804 if (map == null) { 805 map = new ArrayMap<String, ArrayList<String>>(); 806 mUidMap.put(userId, map); 807 } 808 return map; 809 } 810 } 811 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 812 813 // Service Connection to remote media container service to copy 814 // package uri's from external media onto secure containers 815 // or internal storage. 816 private IMediaContainerService mContainerService = null; 817 818 static final int SEND_PENDING_BROADCAST = 1; 819 static final int MCS_BOUND = 3; 820 static final int END_COPY = 4; 821 static final int INIT_COPY = 5; 822 static final int MCS_UNBIND = 6; 823 static final int START_CLEANING_PACKAGE = 7; 824 static final int FIND_INSTALL_LOC = 8; 825 static final int POST_INSTALL = 9; 826 static final int MCS_RECONNECT = 10; 827 static final int MCS_GIVE_UP = 11; 828 static final int UPDATED_MEDIA_STATUS = 12; 829 static final int WRITE_SETTINGS = 13; 830 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 831 static final int PACKAGE_VERIFIED = 15; 832 static final int CHECK_PENDING_VERIFICATION = 16; 833 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 834 static final int INTENT_FILTER_VERIFIED = 18; 835 836 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 837 838 // Delay time in millisecs 839 static final int BROADCAST_DELAY = 10 * 1000; 840 841 static UserManagerService sUserManager; 842 843 // Stores a list of users whose package restrictions file needs to be updated 844 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 845 846 final private DefaultContainerConnection mDefContainerConn = 847 new DefaultContainerConnection(); 848 class DefaultContainerConnection implements ServiceConnection { 849 public void onServiceConnected(ComponentName name, IBinder service) { 850 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 851 IMediaContainerService imcs = 852 IMediaContainerService.Stub.asInterface(service); 853 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 854 } 855 856 public void onServiceDisconnected(ComponentName name) { 857 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 858 } 859 }; 860 861 // Recordkeeping of restore-after-install operations that are currently in flight 862 // between the Package Manager and the Backup Manager 863 class PostInstallData { 864 public InstallArgs args; 865 public PackageInstalledInfo res; 866 867 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 868 args = _a; 869 res = _r; 870 } 871 }; 872 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 873 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 874 875 // backup/restore of preferred activity state 876 private static final String TAG_PREFERRED_BACKUP = "pa"; 877 878 private final String mRequiredVerifierPackage; 879 880 private final PackageUsage mPackageUsage = new PackageUsage(); 881 882 private class PackageUsage { 883 private static final int WRITE_INTERVAL 884 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 885 886 private final Object mFileLock = new Object(); 887 private final AtomicLong mLastWritten = new AtomicLong(0); 888 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 889 890 private boolean mIsHistoricalPackageUsageAvailable = true; 891 892 boolean isHistoricalPackageUsageAvailable() { 893 return mIsHistoricalPackageUsageAvailable; 894 } 895 896 void write(boolean force) { 897 if (force) { 898 writeInternal(); 899 return; 900 } 901 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 902 && !DEBUG_DEXOPT) { 903 return; 904 } 905 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 906 new Thread("PackageUsage_DiskWriter") { 907 @Override 908 public void run() { 909 try { 910 writeInternal(); 911 } finally { 912 mBackgroundWriteRunning.set(false); 913 } 914 } 915 }.start(); 916 } 917 } 918 919 private void writeInternal() { 920 synchronized (mPackages) { 921 synchronized (mFileLock) { 922 AtomicFile file = getFile(); 923 FileOutputStream f = null; 924 try { 925 f = file.startWrite(); 926 BufferedOutputStream out = new BufferedOutputStream(f); 927 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 928 StringBuilder sb = new StringBuilder(); 929 for (PackageParser.Package pkg : mPackages.values()) { 930 if (pkg.mLastPackageUsageTimeInMills == 0) { 931 continue; 932 } 933 sb.setLength(0); 934 sb.append(pkg.packageName); 935 sb.append(' '); 936 sb.append((long)pkg.mLastPackageUsageTimeInMills); 937 sb.append('\n'); 938 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 939 } 940 out.flush(); 941 file.finishWrite(f); 942 } catch (IOException e) { 943 if (f != null) { 944 file.failWrite(f); 945 } 946 Log.e(TAG, "Failed to write package usage times", e); 947 } 948 } 949 } 950 mLastWritten.set(SystemClock.elapsedRealtime()); 951 } 952 953 void readLP() { 954 synchronized (mFileLock) { 955 AtomicFile file = getFile(); 956 BufferedInputStream in = null; 957 try { 958 in = new BufferedInputStream(file.openRead()); 959 StringBuffer sb = new StringBuffer(); 960 while (true) { 961 String packageName = readToken(in, sb, ' '); 962 if (packageName == null) { 963 break; 964 } 965 String timeInMillisString = readToken(in, sb, '\n'); 966 if (timeInMillisString == null) { 967 throw new IOException("Failed to find last usage time for package " 968 + packageName); 969 } 970 PackageParser.Package pkg = mPackages.get(packageName); 971 if (pkg == null) { 972 continue; 973 } 974 long timeInMillis; 975 try { 976 timeInMillis = Long.parseLong(timeInMillisString.toString()); 977 } catch (NumberFormatException e) { 978 throw new IOException("Failed to parse " + timeInMillisString 979 + " as a long.", e); 980 } 981 pkg.mLastPackageUsageTimeInMills = timeInMillis; 982 } 983 } catch (FileNotFoundException expected) { 984 mIsHistoricalPackageUsageAvailable = false; 985 } catch (IOException e) { 986 Log.w(TAG, "Failed to read package usage times", e); 987 } finally { 988 IoUtils.closeQuietly(in); 989 } 990 } 991 mLastWritten.set(SystemClock.elapsedRealtime()); 992 } 993 994 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 995 throws IOException { 996 sb.setLength(0); 997 while (true) { 998 int ch = in.read(); 999 if (ch == -1) { 1000 if (sb.length() == 0) { 1001 return null; 1002 } 1003 throw new IOException("Unexpected EOF"); 1004 } 1005 if (ch == endOfToken) { 1006 return sb.toString(); 1007 } 1008 sb.append((char)ch); 1009 } 1010 } 1011 1012 private AtomicFile getFile() { 1013 File dataDir = Environment.getDataDirectory(); 1014 File systemDir = new File(dataDir, "system"); 1015 File fname = new File(systemDir, "package-usage.list"); 1016 return new AtomicFile(fname); 1017 } 1018 } 1019 1020 class PackageHandler extends Handler { 1021 private boolean mBound = false; 1022 final ArrayList<HandlerParams> mPendingInstalls = 1023 new ArrayList<HandlerParams>(); 1024 1025 private boolean connectToService() { 1026 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1027 " DefaultContainerService"); 1028 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1029 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1030 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1031 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1033 mBound = true; 1034 return true; 1035 } 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 return false; 1038 } 1039 1040 private void disconnectService() { 1041 mContainerService = null; 1042 mBound = false; 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1044 mContext.unbindService(mDefContainerConn); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 } 1047 1048 PackageHandler(Looper looper) { 1049 super(looper); 1050 } 1051 1052 public void handleMessage(Message msg) { 1053 try { 1054 doHandleMessage(msg); 1055 } finally { 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 } 1059 1060 void doHandleMessage(Message msg) { 1061 switch (msg.what) { 1062 case INIT_COPY: { 1063 HandlerParams params = (HandlerParams) msg.obj; 1064 int idx = mPendingInstalls.size(); 1065 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1066 // If a bind was already initiated we dont really 1067 // need to do anything. The pending install 1068 // will be processed later on. 1069 if (!mBound) { 1070 // If this is the only one pending we might 1071 // have to bind to the service again. 1072 if (!connectToService()) { 1073 Slog.e(TAG, "Failed to bind to media container service"); 1074 params.serviceError(); 1075 return; 1076 } else { 1077 // Once we bind to the service, the first 1078 // pending request will be processed. 1079 mPendingInstalls.add(idx, params); 1080 } 1081 } else { 1082 mPendingInstalls.add(idx, params); 1083 // Already bound to the service. Just make 1084 // sure we trigger off processing the first request. 1085 if (idx == 0) { 1086 mHandler.sendEmptyMessage(MCS_BOUND); 1087 } 1088 } 1089 break; 1090 } 1091 case MCS_BOUND: { 1092 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1093 if (msg.obj != null) { 1094 mContainerService = (IMediaContainerService) msg.obj; 1095 } 1096 if (mContainerService == null) { 1097 // Something seriously wrong. Bail out 1098 Slog.e(TAG, "Cannot bind to media container service"); 1099 for (HandlerParams params : mPendingInstalls) { 1100 // Indicate service bind error 1101 params.serviceError(); 1102 } 1103 mPendingInstalls.clear(); 1104 } else if (mPendingInstalls.size() > 0) { 1105 HandlerParams params = mPendingInstalls.get(0); 1106 if (params != null) { 1107 if (params.startCopy()) { 1108 // We are done... look for more work or to 1109 // go idle. 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, 1111 "Checking for more work or unbind..."); 1112 // Delete pending install 1113 if (mPendingInstalls.size() > 0) { 1114 mPendingInstalls.remove(0); 1115 } 1116 if (mPendingInstalls.size() == 0) { 1117 if (mBound) { 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Posting delayed MCS_UNBIND"); 1120 removeMessages(MCS_UNBIND); 1121 Message ubmsg = obtainMessage(MCS_UNBIND); 1122 // Unbind after a little delay, to avoid 1123 // continual thrashing. 1124 sendMessageDelayed(ubmsg, 10000); 1125 } 1126 } else { 1127 // There are more pending requests in queue. 1128 // Just post MCS_BOUND message to trigger processing 1129 // of next pending install. 1130 if (DEBUG_SD_INSTALL) Log.i(TAG, 1131 "Posting MCS_BOUND for next work"); 1132 mHandler.sendEmptyMessage(MCS_BOUND); 1133 } 1134 } 1135 } 1136 } else { 1137 // Should never happen ideally. 1138 Slog.w(TAG, "Empty queue"); 1139 } 1140 break; 1141 } 1142 case MCS_RECONNECT: { 1143 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1144 if (mPendingInstalls.size() > 0) { 1145 if (mBound) { 1146 disconnectService(); 1147 } 1148 if (!connectToService()) { 1149 Slog.e(TAG, "Failed to bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_UNBIND: { 1160 // If there is no actual work left, then time to unbind. 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1162 1163 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1164 if (mBound) { 1165 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1166 1167 disconnectService(); 1168 } 1169 } else if (mPendingInstalls.size() > 0) { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 1176 break; 1177 } 1178 case MCS_GIVE_UP: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1180 mPendingInstalls.remove(0); 1181 break; 1182 } 1183 case SEND_PENDING_BROADCAST: { 1184 String packages[]; 1185 ArrayList<String> components[]; 1186 int size = 0; 1187 int uids[]; 1188 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1189 synchronized (mPackages) { 1190 if (mPendingBroadcasts == null) { 1191 return; 1192 } 1193 size = mPendingBroadcasts.size(); 1194 if (size <= 0) { 1195 // Nothing to be done. Just return 1196 return; 1197 } 1198 packages = new String[size]; 1199 components = new ArrayList[size]; 1200 uids = new int[size]; 1201 int i = 0; // filling out the above arrays 1202 1203 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1204 int packageUserId = mPendingBroadcasts.userIdAt(n); 1205 Iterator<Map.Entry<String, ArrayList<String>>> it 1206 = mPendingBroadcasts.packagesForUserId(packageUserId) 1207 .entrySet().iterator(); 1208 while (it.hasNext() && i < size) { 1209 Map.Entry<String, ArrayList<String>> ent = it.next(); 1210 packages[i] = ent.getKey(); 1211 components[i] = ent.getValue(); 1212 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1213 uids[i] = (ps != null) 1214 ? UserHandle.getUid(packageUserId, ps.appId) 1215 : -1; 1216 i++; 1217 } 1218 } 1219 size = i; 1220 mPendingBroadcasts.clear(); 1221 } 1222 // Send broadcasts 1223 for (int i = 0; i < size; i++) { 1224 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 break; 1228 } 1229 case START_CLEANING_PACKAGE: { 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 final String packageName = (String)msg.obj; 1232 final int userId = msg.arg1; 1233 final boolean andCode = msg.arg2 != 0; 1234 synchronized (mPackages) { 1235 if (userId == UserHandle.USER_ALL) { 1236 int[] users = sUserManager.getUserIds(); 1237 for (int user : users) { 1238 mSettings.addPackageToCleanLPw( 1239 new PackageCleanItem(user, packageName, andCode)); 1240 } 1241 } else { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(userId, packageName, andCode)); 1244 } 1245 } 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 startCleaningPackages(); 1248 } break; 1249 case POST_INSTALL: { 1250 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1251 PostInstallData data = mRunningInstalls.get(msg.arg1); 1252 mRunningInstalls.delete(msg.arg1); 1253 boolean deleteOld = false; 1254 1255 if (data != null) { 1256 InstallArgs args = data.args; 1257 PackageInstalledInfo res = data.res; 1258 1259 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1260 res.removedInfo.sendBroadcast(false, true, false); 1261 Bundle extras = new Bundle(1); 1262 extras.putInt(Intent.EXTRA_UID, res.uid); 1263 1264 // Now that we successfully installed the package, grant runtime 1265 // permissions if requested before broadcasting the install. 1266 if ((args.installFlags 1267 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1268 grantRequestedRuntimePermissions(res.pkg, 1269 args.user.getIdentifier()); 1270 } 1271 1272 // Determine the set of users who are adding this 1273 // package for the first time vs. those who are seeing 1274 // an update. 1275 int[] firstUsers; 1276 int[] updateUsers = new int[0]; 1277 if (res.origUsers == null || res.origUsers.length == 0) { 1278 firstUsers = res.newUsers; 1279 } else { 1280 firstUsers = new int[0]; 1281 for (int i=0; i<res.newUsers.length; i++) { 1282 int user = res.newUsers[i]; 1283 boolean isNew = true; 1284 for (int j=0; j<res.origUsers.length; j++) { 1285 if (res.origUsers[j] == user) { 1286 isNew = false; 1287 break; 1288 } 1289 } 1290 if (isNew) { 1291 int[] newFirst = new int[firstUsers.length+1]; 1292 System.arraycopy(firstUsers, 0, newFirst, 0, 1293 firstUsers.length); 1294 newFirst[firstUsers.length] = user; 1295 firstUsers = newFirst; 1296 } else { 1297 int[] newUpdate = new int[updateUsers.length+1]; 1298 System.arraycopy(updateUsers, 0, newUpdate, 0, 1299 updateUsers.length); 1300 newUpdate[updateUsers.length] = user; 1301 updateUsers = newUpdate; 1302 } 1303 } 1304 } 1305 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1306 res.pkg.applicationInfo.packageName, 1307 extras, null, null, firstUsers); 1308 final boolean update = res.removedInfo.removedPackage != null; 1309 if (update) { 1310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1311 } 1312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1313 res.pkg.applicationInfo.packageName, 1314 extras, null, null, updateUsers); 1315 if (update) { 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1320 null, null, 1321 res.pkg.applicationInfo.packageName, null, updateUsers); 1322 1323 // treat asec-hosted packages like removable media on upgrade 1324 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1325 if (DEBUG_INSTALL) { 1326 Slog.i(TAG, "upgrading pkg " + res.pkg 1327 + " is ASEC-hosted -> AVAILABLE"); 1328 } 1329 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1330 ArrayList<String> pkgList = new ArrayList<String>(1); 1331 pkgList.add(res.pkg.applicationInfo.packageName); 1332 sendResourcesChangedBroadcast(true, true, 1333 pkgList,uidArray, null); 1334 } 1335 } 1336 if (res.removedInfo.args != null) { 1337 // Remove the replaced package's older resources safely now 1338 deleteOld = true; 1339 } 1340 1341 // Log current value of "unknown sources" setting 1342 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1343 getUnknownSourcesSettings()); 1344 } 1345 // Force a gc to clear up things 1346 Runtime.getRuntime().gc(); 1347 // We delete after a gc for applications on sdcard. 1348 if (deleteOld) { 1349 synchronized (mInstallLock) { 1350 res.removedInfo.args.doPostDeleteLI(true); 1351 } 1352 } 1353 if (args.observer != null) { 1354 try { 1355 Bundle extras = extrasForInstallResult(res); 1356 args.observer.onPackageInstalled(res.name, res.returnCode, 1357 res.returnMsg, extras); 1358 } catch (RemoteException e) { 1359 Slog.i(TAG, "Observer no longer exists."); 1360 } 1361 } 1362 } else { 1363 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1364 } 1365 } break; 1366 case UPDATED_MEDIA_STATUS: { 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1368 boolean reportStatus = msg.arg1 == 1; 1369 boolean doGc = msg.arg2 == 1; 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1371 if (doGc) { 1372 // Force a gc to clear up stale containers. 1373 Runtime.getRuntime().gc(); 1374 } 1375 if (msg.obj != null) { 1376 @SuppressWarnings("unchecked") 1377 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1379 // Unload containers 1380 unloadAllContainers(args); 1381 } 1382 if (reportStatus) { 1383 try { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1385 PackageHelper.getMountService().finishMediaUpdate(); 1386 } catch (RemoteException e) { 1387 Log.e(TAG, "MountService not running?"); 1388 } 1389 } 1390 } break; 1391 case WRITE_SETTINGS: { 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1393 synchronized (mPackages) { 1394 removeMessages(WRITE_SETTINGS); 1395 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1396 mSettings.writeLPr(); 1397 mDirtyUsers.clear(); 1398 } 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } break; 1401 case WRITE_PACKAGE_RESTRICTIONS: { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1403 synchronized (mPackages) { 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 for (int userId : mDirtyUsers) { 1406 mSettings.writePackageRestrictionsLPr(userId); 1407 } 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case CHECK_PENDING_VERIFICATION: { 1413 final int verificationId = msg.arg1; 1414 final PackageVerificationState state = mPendingVerification.get(verificationId); 1415 1416 if ((state != null) && !state.timeoutExtended()) { 1417 final InstallArgs args = state.getInstallArgs(); 1418 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1419 1420 Slog.i(TAG, "Verification timed out for " + originUri); 1421 mPendingVerification.remove(verificationId); 1422 1423 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1424 1425 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1426 Slog.i(TAG, "Continuing with installation of " + originUri); 1427 state.setVerifierResponse(Binder.getCallingUid(), 1428 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1429 broadcastPackageVerified(verificationId, originUri, 1430 PackageManager.VERIFICATION_ALLOW, 1431 state.getInstallArgs().getUser()); 1432 try { 1433 ret = args.copyApk(mContainerService, true); 1434 } catch (RemoteException e) { 1435 Slog.e(TAG, "Could not contact the ContainerService"); 1436 } 1437 } else { 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_REJECT, 1440 state.getInstallArgs().getUser()); 1441 } 1442 1443 processPendingInstall(args, ret); 1444 mHandler.sendEmptyMessage(MCS_UNBIND); 1445 } 1446 break; 1447 } 1448 case PACKAGE_VERIFIED: { 1449 final int verificationId = msg.arg1; 1450 1451 final PackageVerificationState state = mPendingVerification.get(verificationId); 1452 if (state == null) { 1453 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1454 break; 1455 } 1456 1457 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1458 1459 state.setVerifierResponse(response.callerUid, response.code); 1460 1461 if (state.isVerificationComplete()) { 1462 mPendingVerification.remove(verificationId); 1463 1464 final InstallArgs args = state.getInstallArgs(); 1465 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1466 1467 int ret; 1468 if (state.isInstallAllowed()) { 1469 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1470 broadcastPackageVerified(verificationId, originUri, 1471 response.code, state.getInstallArgs().getUser()); 1472 try { 1473 ret = args.copyApk(mContainerService, true); 1474 } catch (RemoteException e) { 1475 Slog.e(TAG, "Could not contact the ContainerService"); 1476 } 1477 } else { 1478 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1479 } 1480 1481 processPendingInstall(args, ret); 1482 1483 mHandler.sendEmptyMessage(MCS_UNBIND); 1484 } 1485 1486 break; 1487 } 1488 case START_INTENT_FILTER_VERIFICATIONS: { 1489 int userId = msg.arg1; 1490 int verifierUid = msg.arg2; 1491 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1492 1493 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1494 break; 1495 } 1496 case INTENT_FILTER_VERIFIED: { 1497 final int verificationId = msg.arg1; 1498 1499 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1500 verificationId); 1501 if (state == null) { 1502 Slog.w(TAG, "Invalid IntentFilter verification token " 1503 + verificationId + " received"); 1504 break; 1505 } 1506 1507 final int userId = state.getUserId(); 1508 1509 Slog.d(TAG, "Processing IntentFilter verification with token:" 1510 + verificationId + " and userId:" + userId); 1511 1512 final IntentFilterVerificationResponse response = 1513 (IntentFilterVerificationResponse) msg.obj; 1514 1515 state.setVerifierResponse(response.callerUid, response.code); 1516 1517 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1518 + " and userId:" + userId 1519 + " is settings verifier response with response code:" 1520 + response.code); 1521 1522 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1523 Slog.d(TAG, "Domains failing verification: " 1524 + response.getFailedDomainsString()); 1525 } 1526 1527 if (state.isVerificationComplete()) { 1528 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1529 } else { 1530 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1531 + " was not said to be complete"); 1532 } 1533 1534 break; 1535 } 1536 } 1537 } 1538 } 1539 1540 private StorageEventListener mStorageListener = new StorageEventListener() { 1541 @Override 1542 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1543 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1544 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1545 // TODO: ensure that private directories exist for all active users 1546 // TODO: remove user data whose serial number doesn't match 1547 loadPrivatePackages(vol); 1548 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1549 unloadPrivatePackages(vol); 1550 } 1551 } 1552 1553 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1554 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1555 updateExternalMediaStatus(true, false); 1556 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1557 updateExternalMediaStatus(false, false); 1558 } 1559 } 1560 } 1561 1562 @Override 1563 public void onVolumeForgotten(String fsUuid) { 1564 // TODO: remove all packages hosted on this uuid 1565 } 1566 }; 1567 1568 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1569 if (userId >= UserHandle.USER_OWNER) { 1570 grantRequestedRuntimePermissionsForUser(pkg, userId); 1571 } else if (userId == UserHandle.USER_ALL) { 1572 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1573 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1574 } 1575 } 1576 } 1577 1578 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1579 SettingBase sb = (SettingBase) pkg.mExtras; 1580 if (sb == null) { 1581 return; 1582 } 1583 1584 PermissionsState permissionsState = sb.getPermissionsState(); 1585 1586 for (String permission : pkg.requestedPermissions) { 1587 BasePermission bp = mSettings.mPermissions.get(permission); 1588 if (bp != null && bp.isRuntime()) { 1589 permissionsState.grantRuntimePermission(bp, userId); 1590 } 1591 } 1592 } 1593 1594 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1595 Bundle extras = null; 1596 switch (res.returnCode) { 1597 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1598 extras = new Bundle(); 1599 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1600 res.origPermission); 1601 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1602 res.origPackage); 1603 break; 1604 } 1605 } 1606 return extras; 1607 } 1608 1609 void scheduleWriteSettingsLocked() { 1610 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1611 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1612 } 1613 } 1614 1615 void scheduleWritePackageRestrictionsLocked(int userId) { 1616 if (!sUserManager.exists(userId)) return; 1617 mDirtyUsers.add(userId); 1618 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1619 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1620 } 1621 } 1622 1623 public static PackageManagerService main(Context context, Installer installer, 1624 boolean factoryTest, boolean onlyCore) { 1625 PackageManagerService m = new PackageManagerService(context, installer, 1626 factoryTest, onlyCore); 1627 ServiceManager.addService("package", m); 1628 return m; 1629 } 1630 1631 static String[] splitString(String str, char sep) { 1632 int count = 1; 1633 int i = 0; 1634 while ((i=str.indexOf(sep, i)) >= 0) { 1635 count++; 1636 i++; 1637 } 1638 1639 String[] res = new String[count]; 1640 i=0; 1641 count = 0; 1642 int lastI=0; 1643 while ((i=str.indexOf(sep, i)) >= 0) { 1644 res[count] = str.substring(lastI, i); 1645 count++; 1646 i++; 1647 lastI = i; 1648 } 1649 res[count] = str.substring(lastI, str.length()); 1650 return res; 1651 } 1652 1653 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1654 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1655 Context.DISPLAY_SERVICE); 1656 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1657 } 1658 1659 public PackageManagerService(Context context, Installer installer, 1660 boolean factoryTest, boolean onlyCore) { 1661 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1662 SystemClock.uptimeMillis()); 1663 1664 if (mSdkVersion <= 0) { 1665 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1666 } 1667 1668 mContext = context; 1669 mFactoryTest = factoryTest; 1670 mOnlyCore = onlyCore; 1671 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1672 mMetrics = new DisplayMetrics(); 1673 mSettings = new Settings(mPackages); 1674 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1675 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1676 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1677 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1678 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1679 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1680 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1681 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1682 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1683 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1684 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1685 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1686 1687 // TODO: add a property to control this? 1688 long dexOptLRUThresholdInMinutes; 1689 if (mLazyDexOpt) { 1690 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1691 } else { 1692 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1693 } 1694 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1695 1696 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1697 if (separateProcesses != null && separateProcesses.length() > 0) { 1698 if ("*".equals(separateProcesses)) { 1699 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1700 mSeparateProcesses = null; 1701 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1702 } else { 1703 mDefParseFlags = 0; 1704 mSeparateProcesses = separateProcesses.split(","); 1705 Slog.w(TAG, "Running with debug.separate_processes: " 1706 + separateProcesses); 1707 } 1708 } else { 1709 mDefParseFlags = 0; 1710 mSeparateProcesses = null; 1711 } 1712 1713 mInstaller = installer; 1714 mPackageDexOptimizer = new PackageDexOptimizer(this); 1715 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1716 1717 getDefaultDisplayMetrics(context, mMetrics); 1718 1719 SystemConfig systemConfig = SystemConfig.getInstance(); 1720 mGlobalGids = systemConfig.getGlobalGids(); 1721 mSystemPermissions = systemConfig.getSystemPermissions(); 1722 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1723 1724 synchronized (mInstallLock) { 1725 // writer 1726 synchronized (mPackages) { 1727 mHandlerThread = new ServiceThread(TAG, 1728 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1729 mHandlerThread.start(); 1730 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1731 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1732 1733 File dataDir = Environment.getDataDirectory(); 1734 mAppDataDir = new File(dataDir, "data"); 1735 mAppInstallDir = new File(dataDir, "app"); 1736 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1737 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1738 mUserAppDataDir = new File(dataDir, "user"); 1739 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1740 1741 sUserManager = new UserManagerService(context, this, 1742 mInstallLock, mPackages); 1743 1744 // Propagate permission configuration in to package manager. 1745 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1746 = systemConfig.getPermissions(); 1747 for (int i=0; i<permConfig.size(); i++) { 1748 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1749 BasePermission bp = mSettings.mPermissions.get(perm.name); 1750 if (bp == null) { 1751 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1752 mSettings.mPermissions.put(perm.name, bp); 1753 } 1754 if (perm.gids != null) { 1755 bp.setGids(perm.gids, perm.perUser); 1756 } 1757 } 1758 1759 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1760 for (int i=0; i<libConfig.size(); i++) { 1761 mSharedLibraries.put(libConfig.keyAt(i), 1762 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1763 } 1764 1765 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1766 1767 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1768 mSdkVersion, mOnlyCore); 1769 1770 String customResolverActivity = Resources.getSystem().getString( 1771 R.string.config_customResolverActivity); 1772 if (TextUtils.isEmpty(customResolverActivity)) { 1773 customResolverActivity = null; 1774 } else { 1775 mCustomResolverComponentName = ComponentName.unflattenFromString( 1776 customResolverActivity); 1777 } 1778 1779 long startTime = SystemClock.uptimeMillis(); 1780 1781 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1782 startTime); 1783 1784 // Set flag to monitor and not change apk file paths when 1785 // scanning install directories. 1786 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1787 1788 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1789 1790 /** 1791 * Add everything in the in the boot class path to the 1792 * list of process files because dexopt will have been run 1793 * if necessary during zygote startup. 1794 */ 1795 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1796 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1797 1798 if (bootClassPath != null) { 1799 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1800 for (String element : bootClassPathElements) { 1801 alreadyDexOpted.add(element); 1802 } 1803 } else { 1804 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1805 } 1806 1807 if (systemServerClassPath != null) { 1808 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1809 for (String element : systemServerClassPathElements) { 1810 alreadyDexOpted.add(element); 1811 } 1812 } else { 1813 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1814 } 1815 1816 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1817 final String[] dexCodeInstructionSets = 1818 getDexCodeInstructionSets( 1819 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1820 1821 /** 1822 * Ensure all external libraries have had dexopt run on them. 1823 */ 1824 if (mSharedLibraries.size() > 0) { 1825 // NOTE: For now, we're compiling these system "shared libraries" 1826 // (and framework jars) into all available architectures. It's possible 1827 // to compile them only when we come across an app that uses them (there's 1828 // already logic for that in scanPackageLI) but that adds some complexity. 1829 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1830 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1831 final String lib = libEntry.path; 1832 if (lib == null) { 1833 continue; 1834 } 1835 1836 try { 1837 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1838 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1839 alreadyDexOpted.add(lib); 1840 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1841 } 1842 } catch (FileNotFoundException e) { 1843 Slog.w(TAG, "Library not found: " + lib); 1844 } catch (IOException e) { 1845 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1846 + e.getMessage()); 1847 } 1848 } 1849 } 1850 } 1851 1852 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1853 1854 // Gross hack for now: we know this file doesn't contain any 1855 // code, so don't dexopt it to avoid the resulting log spew. 1856 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1857 1858 // Gross hack for now: we know this file is only part of 1859 // the boot class path for art, so don't dexopt it to 1860 // avoid the resulting log spew. 1861 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1862 1863 /** 1864 * And there are a number of commands implemented in Java, which 1865 * we currently need to do the dexopt on so that they can be 1866 * run from a non-root shell. 1867 */ 1868 String[] frameworkFiles = frameworkDir.list(); 1869 if (frameworkFiles != null) { 1870 // TODO: We could compile these only for the most preferred ABI. We should 1871 // first double check that the dex files for these commands are not referenced 1872 // by other system apps. 1873 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1874 for (int i=0; i<frameworkFiles.length; i++) { 1875 File libPath = new File(frameworkDir, frameworkFiles[i]); 1876 String path = libPath.getPath(); 1877 // Skip the file if we already did it. 1878 if (alreadyDexOpted.contains(path)) { 1879 continue; 1880 } 1881 // Skip the file if it is not a type we want to dexopt. 1882 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1883 continue; 1884 } 1885 try { 1886 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1887 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1888 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1889 } 1890 } catch (FileNotFoundException e) { 1891 Slog.w(TAG, "Jar not found: " + path); 1892 } catch (IOException e) { 1893 Slog.w(TAG, "Exception reading jar: " + path, e); 1894 } 1895 } 1896 } 1897 } 1898 1899 // Collect vendor overlay packages. 1900 // (Do this before scanning any apps.) 1901 // For security and version matching reason, only consider 1902 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1903 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1904 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1905 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1906 1907 // Find base frameworks (resource packages without code). 1908 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1909 | PackageParser.PARSE_IS_SYSTEM_DIR 1910 | PackageParser.PARSE_IS_PRIVILEGED, 1911 scanFlags | SCAN_NO_DEX, 0); 1912 1913 // Collected privileged system packages. 1914 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1915 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1916 | PackageParser.PARSE_IS_SYSTEM_DIR 1917 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1918 1919 // Collect ordinary system packages. 1920 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1921 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1922 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1923 1924 // Collect all vendor packages. 1925 File vendorAppDir = new File("/vendor/app"); 1926 try { 1927 vendorAppDir = vendorAppDir.getCanonicalFile(); 1928 } catch (IOException e) { 1929 // failed to look up canonical path, continue with original one 1930 } 1931 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 // Collect all OEM packages. 1935 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1936 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1937 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1938 1939 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1940 mInstaller.moveFiles(); 1941 1942 // Prune any system packages that no longer exist. 1943 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1944 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1945 if (!mOnlyCore) { 1946 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1947 while (psit.hasNext()) { 1948 PackageSetting ps = psit.next(); 1949 1950 /* 1951 * If this is not a system app, it can't be a 1952 * disable system app. 1953 */ 1954 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1955 continue; 1956 } 1957 1958 /* 1959 * If the package is scanned, it's not erased. 1960 */ 1961 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1962 if (scannedPkg != null) { 1963 /* 1964 * If the system app is both scanned and in the 1965 * disabled packages list, then it must have been 1966 * added via OTA. Remove it from the currently 1967 * scanned package so the previously user-installed 1968 * application can be scanned. 1969 */ 1970 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1971 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1972 + ps.name + "; removing system app. Last known codePath=" 1973 + ps.codePathString + ", installStatus=" + ps.installStatus 1974 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1975 + scannedPkg.mVersionCode); 1976 removePackageLI(ps, true); 1977 expectingBetter.put(ps.name, ps.codePath); 1978 } 1979 1980 continue; 1981 } 1982 1983 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1984 psit.remove(); 1985 logCriticalInfo(Log.WARN, "System package " + ps.name 1986 + " no longer exists; wiping its data"); 1987 removeDataDirsLI(null, ps.name); 1988 } else { 1989 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1990 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1991 possiblyDeletedUpdatedSystemApps.add(ps.name); 1992 } 1993 } 1994 } 1995 } 1996 1997 //look for any incomplete package installations 1998 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1999 //clean up list 2000 for(int i = 0; i < deletePkgsList.size(); i++) { 2001 //clean up here 2002 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2003 } 2004 //delete tmp files 2005 deleteTempPackageFiles(); 2006 2007 // Remove any shared userIDs that have no associated packages 2008 mSettings.pruneSharedUsersLPw(); 2009 2010 if (!mOnlyCore) { 2011 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2012 SystemClock.uptimeMillis()); 2013 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2014 2015 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2016 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2017 2018 /** 2019 * Remove disable package settings for any updated system 2020 * apps that were removed via an OTA. If they're not a 2021 * previously-updated app, remove them completely. 2022 * Otherwise, just revoke their system-level permissions. 2023 */ 2024 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2025 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2026 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2027 2028 String msg; 2029 if (deletedPkg == null) { 2030 msg = "Updated system package " + deletedAppName 2031 + " no longer exists; wiping its data"; 2032 removeDataDirsLI(null, deletedAppName); 2033 } else { 2034 msg = "Updated system app + " + deletedAppName 2035 + " no longer present; removing system privileges for " 2036 + deletedAppName; 2037 2038 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2039 2040 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2041 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2042 } 2043 logCriticalInfo(Log.WARN, msg); 2044 } 2045 2046 /** 2047 * Make sure all system apps that we expected to appear on 2048 * the userdata partition actually showed up. If they never 2049 * appeared, crawl back and revive the system version. 2050 */ 2051 for (int i = 0; i < expectingBetter.size(); i++) { 2052 final String packageName = expectingBetter.keyAt(i); 2053 if (!mPackages.containsKey(packageName)) { 2054 final File scanFile = expectingBetter.valueAt(i); 2055 2056 logCriticalInfo(Log.WARN, "Expected better " + packageName 2057 + " but never showed up; reverting to system"); 2058 2059 final int reparseFlags; 2060 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2061 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2062 | PackageParser.PARSE_IS_SYSTEM_DIR 2063 | PackageParser.PARSE_IS_PRIVILEGED; 2064 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2065 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2066 | PackageParser.PARSE_IS_SYSTEM_DIR; 2067 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2068 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR; 2070 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2071 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2072 | PackageParser.PARSE_IS_SYSTEM_DIR; 2073 } else { 2074 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2075 continue; 2076 } 2077 2078 mSettings.enableSystemPackageLPw(packageName); 2079 2080 try { 2081 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2082 } catch (PackageManagerException e) { 2083 Slog.e(TAG, "Failed to parse original system package: " 2084 + e.getMessage()); 2085 } 2086 } 2087 } 2088 } 2089 2090 // Now that we know all of the shared libraries, update all clients to have 2091 // the correct library paths. 2092 updateAllSharedLibrariesLPw(); 2093 2094 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2095 // NOTE: We ignore potential failures here during a system scan (like 2096 // the rest of the commands above) because there's precious little we 2097 // can do about it. A settings error is reported, though. 2098 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2099 false /* force dexopt */, false /* defer dexopt */); 2100 } 2101 2102 // Now that we know all the packages we are keeping, 2103 // read and update their last usage times. 2104 mPackageUsage.readLP(); 2105 2106 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2107 SystemClock.uptimeMillis()); 2108 Slog.i(TAG, "Time to scan packages: " 2109 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2110 + " seconds"); 2111 2112 // If the platform SDK has changed since the last time we booted, 2113 // we need to re-grant app permission to catch any new ones that 2114 // appear. This is really a hack, and means that apps can in some 2115 // cases get permissions that the user didn't initially explicitly 2116 // allow... it would be nice to have some better way to handle 2117 // this situation. 2118 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2119 != mSdkVersion; 2120 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2121 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2122 + "; regranting permissions for internal storage"); 2123 mSettings.mInternalSdkPlatform = mSdkVersion; 2124 2125 // For now runtime permissions are toggled via a system property. 2126 if (!RUNTIME_PERMISSIONS_ENABLED) { 2127 // Remove the runtime permissions state if the feature 2128 // was disabled by flipping the system property. 2129 mSettings.deleteRuntimePermissionsFiles(); 2130 } 2131 2132 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2133 | (regrantPermissions 2134 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2135 : 0)); 2136 2137 // If this is the first boot, and it is a normal boot, then 2138 // we need to initialize the default preferred apps. 2139 if (!mRestoredSettings && !onlyCore) { 2140 mSettings.readDefaultPreferredAppsLPw(this, 0); 2141 } 2142 2143 // If this is first boot after an OTA, and a normal boot, then 2144 // we need to clear code cache directories. 2145 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2146 if (mIsUpgrade && !onlyCore) { 2147 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2148 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2149 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2150 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2151 } 2152 mSettings.mFingerprint = Build.FINGERPRINT; 2153 } 2154 2155 // All the changes are done during package scanning. 2156 mSettings.updateInternalDatabaseVersion(); 2157 2158 // can downgrade to reader 2159 mSettings.writeLPr(); 2160 2161 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2162 SystemClock.uptimeMillis()); 2163 2164 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2165 2166 mInstallerService = new PackageInstallerService(context, this); 2167 2168 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2169 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2170 mIntentFilterVerifierComponent); 2171 2172 primeDomainVerificationsLPw(false); 2173 2174 } // synchronized (mPackages) 2175 } // synchronized (mInstallLock) 2176 2177 // Now after opening every single application zip, make sure they 2178 // are all flushed. Not really needed, but keeps things nice and 2179 // tidy. 2180 Runtime.getRuntime().gc(); 2181 } 2182 2183 @Override 2184 public boolean isFirstBoot() { 2185 return !mRestoredSettings; 2186 } 2187 2188 @Override 2189 public boolean isOnlyCoreApps() { 2190 return mOnlyCore; 2191 } 2192 2193 @Override 2194 public boolean isUpgrade() { 2195 return mIsUpgrade; 2196 } 2197 2198 private String getRequiredVerifierLPr() { 2199 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2200 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2201 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2202 2203 String requiredVerifier = null; 2204 2205 final int N = receivers.size(); 2206 for (int i = 0; i < N; i++) { 2207 final ResolveInfo info = receivers.get(i); 2208 2209 if (info.activityInfo == null) { 2210 continue; 2211 } 2212 2213 final String packageName = info.activityInfo.packageName; 2214 2215 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2216 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2217 continue; 2218 } 2219 2220 if (requiredVerifier != null) { 2221 throw new RuntimeException("There can be only one required verifier"); 2222 } 2223 2224 requiredVerifier = packageName; 2225 } 2226 2227 return requiredVerifier; 2228 } 2229 2230 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2231 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2232 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2233 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2234 2235 ComponentName verifierComponentName = null; 2236 2237 int priority = -1000; 2238 final int N = receivers.size(); 2239 for (int i = 0; i < N; i++) { 2240 final ResolveInfo info = receivers.get(i); 2241 2242 if (info.activityInfo == null) { 2243 continue; 2244 } 2245 2246 final String packageName = info.activityInfo.packageName; 2247 2248 final PackageSetting ps = mSettings.mPackages.get(packageName); 2249 if (ps == null) { 2250 continue; 2251 } 2252 2253 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2254 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2255 continue; 2256 } 2257 2258 // Select the IntentFilterVerifier with the highest priority 2259 if (priority < info.priority) { 2260 priority = info.priority; 2261 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2262 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2263 " with priority: " + info.priority); 2264 } 2265 } 2266 2267 return verifierComponentName; 2268 } 2269 2270 private void primeDomainVerificationsLPw(boolean logging) { 2271 Slog.d(TAG, "Start priming domain verification"); 2272 boolean updated = false; 2273 ArrayList<String> allHosts = new ArrayList<>(); 2274 for (PackageParser.Package pkg : mPackages.values()) { 2275 final String packageName = pkg.packageName; 2276 if (!hasDomainURLs(pkg)) { 2277 if (logging) { 2278 Slog.d(TAG, "No priming domain verifications for " + 2279 "package with no domain URLs: " + packageName); 2280 } 2281 continue; 2282 } 2283 if (!pkg.isSystemApp()) { 2284 if (logging) { 2285 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2286 packageName); 2287 } 2288 continue; 2289 } 2290 for (PackageParser.Activity a : pkg.activities) { 2291 for (ActivityIntentInfo filter : a.intents) { 2292 if (hasValidDomains(filter, false)) { 2293 allHosts.addAll(filter.getHostsList()); 2294 } 2295 } 2296 } 2297 if (allHosts.size() == 0) { 2298 allHosts.add("*"); 2299 } 2300 IntentFilterVerificationInfo ivi = 2301 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2302 if (ivi != null) { 2303 // We will always log this 2304 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2305 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2306 updated = true; 2307 } 2308 else { 2309 if (logging) { 2310 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2311 } 2312 } 2313 allHosts.clear(); 2314 } 2315 if (updated) { 2316 scheduleWriteSettingsLocked(); 2317 } 2318 Slog.d(TAG, "End priming domain verification"); 2319 } 2320 2321 @Override 2322 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2323 throws RemoteException { 2324 try { 2325 return super.onTransact(code, data, reply, flags); 2326 } catch (RuntimeException e) { 2327 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2328 Slog.wtf(TAG, "Package Manager Crash", e); 2329 } 2330 throw e; 2331 } 2332 } 2333 2334 void cleanupInstallFailedPackage(PackageSetting ps) { 2335 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2336 2337 removeDataDirsLI(ps.volumeUuid, ps.name); 2338 if (ps.codePath != null) { 2339 if (ps.codePath.isDirectory()) { 2340 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2341 } else { 2342 ps.codePath.delete(); 2343 } 2344 } 2345 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2346 if (ps.resourcePath.isDirectory()) { 2347 FileUtils.deleteContents(ps.resourcePath); 2348 } 2349 ps.resourcePath.delete(); 2350 } 2351 mSettings.removePackageLPw(ps.name); 2352 } 2353 2354 static int[] appendInts(int[] cur, int[] add) { 2355 if (add == null) return cur; 2356 if (cur == null) return add; 2357 final int N = add.length; 2358 for (int i=0; i<N; i++) { 2359 cur = appendInt(cur, add[i]); 2360 } 2361 return cur; 2362 } 2363 2364 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2365 if (!sUserManager.exists(userId)) return null; 2366 final PackageSetting ps = (PackageSetting) p.mExtras; 2367 if (ps == null) { 2368 return null; 2369 } 2370 2371 final PermissionsState permissionsState = ps.getPermissionsState(); 2372 2373 final int[] gids = permissionsState.computeGids(userId); 2374 final Set<String> permissions = permissionsState.getPermissions(userId); 2375 final PackageUserState state = ps.readUserState(userId); 2376 2377 return PackageParser.generatePackageInfo(p, gids, flags, 2378 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2379 } 2380 2381 @Override 2382 public boolean isPackageFrozen(String packageName) { 2383 synchronized (mPackages) { 2384 final PackageSetting ps = mSettings.mPackages.get(packageName); 2385 if (ps != null) { 2386 return ps.frozen; 2387 } 2388 } 2389 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2390 return true; 2391 } 2392 2393 @Override 2394 public boolean isPackageAvailable(String packageName, int userId) { 2395 if (!sUserManager.exists(userId)) return false; 2396 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2397 synchronized (mPackages) { 2398 PackageParser.Package p = mPackages.get(packageName); 2399 if (p != null) { 2400 final PackageSetting ps = (PackageSetting) p.mExtras; 2401 if (ps != null) { 2402 final PackageUserState state = ps.readUserState(userId); 2403 if (state != null) { 2404 return PackageParser.isAvailable(state); 2405 } 2406 } 2407 } 2408 } 2409 return false; 2410 } 2411 2412 @Override 2413 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2414 if (!sUserManager.exists(userId)) return null; 2415 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2416 // reader 2417 synchronized (mPackages) { 2418 PackageParser.Package p = mPackages.get(packageName); 2419 if (DEBUG_PACKAGE_INFO) 2420 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2421 if (p != null) { 2422 return generatePackageInfo(p, flags, userId); 2423 } 2424 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2425 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2426 } 2427 } 2428 return null; 2429 } 2430 2431 @Override 2432 public String[] currentToCanonicalPackageNames(String[] names) { 2433 String[] out = new String[names.length]; 2434 // reader 2435 synchronized (mPackages) { 2436 for (int i=names.length-1; i>=0; i--) { 2437 PackageSetting ps = mSettings.mPackages.get(names[i]); 2438 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2439 } 2440 } 2441 return out; 2442 } 2443 2444 @Override 2445 public String[] canonicalToCurrentPackageNames(String[] names) { 2446 String[] out = new String[names.length]; 2447 // reader 2448 synchronized (mPackages) { 2449 for (int i=names.length-1; i>=0; i--) { 2450 String cur = mSettings.mRenamedPackages.get(names[i]); 2451 out[i] = cur != null ? cur : names[i]; 2452 } 2453 } 2454 return out; 2455 } 2456 2457 @Override 2458 public int getPackageUid(String packageName, int userId) { 2459 if (!sUserManager.exists(userId)) return -1; 2460 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2461 2462 // reader 2463 synchronized (mPackages) { 2464 PackageParser.Package p = mPackages.get(packageName); 2465 if(p != null) { 2466 return UserHandle.getUid(userId, p.applicationInfo.uid); 2467 } 2468 PackageSetting ps = mSettings.mPackages.get(packageName); 2469 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2470 return -1; 2471 } 2472 p = ps.pkg; 2473 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2474 } 2475 } 2476 2477 @Override 2478 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2479 if (!sUserManager.exists(userId)) { 2480 return null; 2481 } 2482 2483 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2484 "getPackageGids"); 2485 2486 // reader 2487 synchronized (mPackages) { 2488 PackageParser.Package p = mPackages.get(packageName); 2489 if (DEBUG_PACKAGE_INFO) { 2490 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2491 } 2492 if (p != null) { 2493 PackageSetting ps = (PackageSetting) p.mExtras; 2494 return ps.getPermissionsState().computeGids(userId); 2495 } 2496 } 2497 2498 return null; 2499 } 2500 2501 static PermissionInfo generatePermissionInfo( 2502 BasePermission bp, int flags) { 2503 if (bp.perm != null) { 2504 return PackageParser.generatePermissionInfo(bp.perm, flags); 2505 } 2506 PermissionInfo pi = new PermissionInfo(); 2507 pi.name = bp.name; 2508 pi.packageName = bp.sourcePackage; 2509 pi.nonLocalizedLabel = bp.name; 2510 pi.protectionLevel = bp.protectionLevel; 2511 return pi; 2512 } 2513 2514 @Override 2515 public PermissionInfo getPermissionInfo(String name, int flags) { 2516 // reader 2517 synchronized (mPackages) { 2518 final BasePermission p = mSettings.mPermissions.get(name); 2519 if (p != null) { 2520 return generatePermissionInfo(p, flags); 2521 } 2522 return null; 2523 } 2524 } 2525 2526 @Override 2527 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2528 // reader 2529 synchronized (mPackages) { 2530 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2531 for (BasePermission p : mSettings.mPermissions.values()) { 2532 if (group == null) { 2533 if (p.perm == null || p.perm.info.group == null) { 2534 out.add(generatePermissionInfo(p, flags)); 2535 } 2536 } else { 2537 if (p.perm != null && group.equals(p.perm.info.group)) { 2538 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2539 } 2540 } 2541 } 2542 2543 if (out.size() > 0) { 2544 return out; 2545 } 2546 return mPermissionGroups.containsKey(group) ? out : null; 2547 } 2548 } 2549 2550 @Override 2551 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2552 // reader 2553 synchronized (mPackages) { 2554 return PackageParser.generatePermissionGroupInfo( 2555 mPermissionGroups.get(name), flags); 2556 } 2557 } 2558 2559 @Override 2560 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2561 // reader 2562 synchronized (mPackages) { 2563 final int N = mPermissionGroups.size(); 2564 ArrayList<PermissionGroupInfo> out 2565 = new ArrayList<PermissionGroupInfo>(N); 2566 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2567 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2568 } 2569 return out; 2570 } 2571 } 2572 2573 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2574 int userId) { 2575 if (!sUserManager.exists(userId)) return null; 2576 PackageSetting ps = mSettings.mPackages.get(packageName); 2577 if (ps != null) { 2578 if (ps.pkg == null) { 2579 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2580 flags, userId); 2581 if (pInfo != null) { 2582 return pInfo.applicationInfo; 2583 } 2584 return null; 2585 } 2586 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2587 ps.readUserState(userId), userId); 2588 } 2589 return null; 2590 } 2591 2592 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2593 int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 PackageSetting ps = mSettings.mPackages.get(packageName); 2596 if (ps != null) { 2597 PackageParser.Package pkg = ps.pkg; 2598 if (pkg == null) { 2599 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2600 return null; 2601 } 2602 // Only data remains, so we aren't worried about code paths 2603 pkg = new PackageParser.Package(packageName); 2604 pkg.applicationInfo.packageName = packageName; 2605 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2606 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2607 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2608 packageName, userId).getAbsolutePath(); 2609 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2610 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2611 } 2612 return generatePackageInfo(pkg, flags, userId); 2613 } 2614 return null; 2615 } 2616 2617 @Override 2618 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2619 if (!sUserManager.exists(userId)) return null; 2620 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2621 // writer 2622 synchronized (mPackages) { 2623 PackageParser.Package p = mPackages.get(packageName); 2624 if (DEBUG_PACKAGE_INFO) Log.v( 2625 TAG, "getApplicationInfo " + packageName 2626 + ": " + p); 2627 if (p != null) { 2628 PackageSetting ps = mSettings.mPackages.get(packageName); 2629 if (ps == null) return null; 2630 // Note: isEnabledLP() does not apply here - always return info 2631 return PackageParser.generateApplicationInfo( 2632 p, flags, ps.readUserState(userId), userId); 2633 } 2634 if ("android".equals(packageName)||"system".equals(packageName)) { 2635 return mAndroidApplication; 2636 } 2637 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2638 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2639 } 2640 } 2641 return null; 2642 } 2643 2644 @Override 2645 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2646 final IPackageDataObserver observer) { 2647 mContext.enforceCallingOrSelfPermission( 2648 android.Manifest.permission.CLEAR_APP_CACHE, null); 2649 // Queue up an async operation since clearing cache may take a little while. 2650 mHandler.post(new Runnable() { 2651 public void run() { 2652 mHandler.removeCallbacks(this); 2653 int retCode = -1; 2654 synchronized (mInstallLock) { 2655 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2656 if (retCode < 0) { 2657 Slog.w(TAG, "Couldn't clear application caches"); 2658 } 2659 } 2660 if (observer != null) { 2661 try { 2662 observer.onRemoveCompleted(null, (retCode >= 0)); 2663 } catch (RemoteException e) { 2664 Slog.w(TAG, "RemoveException when invoking call back"); 2665 } 2666 } 2667 } 2668 }); 2669 } 2670 2671 @Override 2672 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2673 final IntentSender pi) { 2674 mContext.enforceCallingOrSelfPermission( 2675 android.Manifest.permission.CLEAR_APP_CACHE, null); 2676 // Queue up an async operation since clearing cache may take a little while. 2677 mHandler.post(new Runnable() { 2678 public void run() { 2679 mHandler.removeCallbacks(this); 2680 int retCode = -1; 2681 synchronized (mInstallLock) { 2682 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2683 if (retCode < 0) { 2684 Slog.w(TAG, "Couldn't clear application caches"); 2685 } 2686 } 2687 if(pi != null) { 2688 try { 2689 // Callback via pending intent 2690 int code = (retCode >= 0) ? 1 : 0; 2691 pi.sendIntent(null, code, null, 2692 null, null); 2693 } catch (SendIntentException e1) { 2694 Slog.i(TAG, "Failed to send pending intent"); 2695 } 2696 } 2697 } 2698 }); 2699 } 2700 2701 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2702 synchronized (mInstallLock) { 2703 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2704 throw new IOException("Failed to free enough space"); 2705 } 2706 } 2707 } 2708 2709 @Override 2710 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2711 if (!sUserManager.exists(userId)) return null; 2712 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2713 synchronized (mPackages) { 2714 PackageParser.Activity a = mActivities.mActivities.get(component); 2715 2716 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2717 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2718 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2719 if (ps == null) return null; 2720 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2721 userId); 2722 } 2723 if (mResolveComponentName.equals(component)) { 2724 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2725 new PackageUserState(), userId); 2726 } 2727 } 2728 return null; 2729 } 2730 2731 @Override 2732 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2733 String resolvedType) { 2734 synchronized (mPackages) { 2735 PackageParser.Activity a = mActivities.mActivities.get(component); 2736 if (a == null) { 2737 return false; 2738 } 2739 for (int i=0; i<a.intents.size(); i++) { 2740 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2741 intent.getData(), intent.getCategories(), TAG) >= 0) { 2742 return true; 2743 } 2744 } 2745 return false; 2746 } 2747 } 2748 2749 @Override 2750 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2751 if (!sUserManager.exists(userId)) return null; 2752 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2753 synchronized (mPackages) { 2754 PackageParser.Activity a = mReceivers.mActivities.get(component); 2755 if (DEBUG_PACKAGE_INFO) Log.v( 2756 TAG, "getReceiverInfo " + component + ": " + a); 2757 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2758 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2759 if (ps == null) return null; 2760 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2761 userId); 2762 } 2763 } 2764 return null; 2765 } 2766 2767 @Override 2768 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2769 if (!sUserManager.exists(userId)) return null; 2770 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2771 synchronized (mPackages) { 2772 PackageParser.Service s = mServices.mServices.get(component); 2773 if (DEBUG_PACKAGE_INFO) Log.v( 2774 TAG, "getServiceInfo " + component + ": " + s); 2775 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2776 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2777 if (ps == null) return null; 2778 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2779 userId); 2780 } 2781 } 2782 return null; 2783 } 2784 2785 @Override 2786 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2787 if (!sUserManager.exists(userId)) return null; 2788 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2789 synchronized (mPackages) { 2790 PackageParser.Provider p = mProviders.mProviders.get(component); 2791 if (DEBUG_PACKAGE_INFO) Log.v( 2792 TAG, "getProviderInfo " + component + ": " + p); 2793 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2794 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2795 if (ps == null) return null; 2796 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2797 userId); 2798 } 2799 } 2800 return null; 2801 } 2802 2803 @Override 2804 public String[] getSystemSharedLibraryNames() { 2805 Set<String> libSet; 2806 synchronized (mPackages) { 2807 libSet = mSharedLibraries.keySet(); 2808 int size = libSet.size(); 2809 if (size > 0) { 2810 String[] libs = new String[size]; 2811 libSet.toArray(libs); 2812 return libs; 2813 } 2814 } 2815 return null; 2816 } 2817 2818 /** 2819 * @hide 2820 */ 2821 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2822 synchronized (mPackages) { 2823 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2824 if (lib != null && lib.apk != null) { 2825 return mPackages.get(lib.apk); 2826 } 2827 } 2828 return null; 2829 } 2830 2831 @Override 2832 public FeatureInfo[] getSystemAvailableFeatures() { 2833 Collection<FeatureInfo> featSet; 2834 synchronized (mPackages) { 2835 featSet = mAvailableFeatures.values(); 2836 int size = featSet.size(); 2837 if (size > 0) { 2838 FeatureInfo[] features = new FeatureInfo[size+1]; 2839 featSet.toArray(features); 2840 FeatureInfo fi = new FeatureInfo(); 2841 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2842 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2843 features[size] = fi; 2844 return features; 2845 } 2846 } 2847 return null; 2848 } 2849 2850 @Override 2851 public boolean hasSystemFeature(String name) { 2852 synchronized (mPackages) { 2853 return mAvailableFeatures.containsKey(name); 2854 } 2855 } 2856 2857 private void checkValidCaller(int uid, int userId) { 2858 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2859 return; 2860 2861 throw new SecurityException("Caller uid=" + uid 2862 + " is not privileged to communicate with user=" + userId); 2863 } 2864 2865 @Override 2866 public int checkPermission(String permName, String pkgName, int userId) { 2867 if (!sUserManager.exists(userId)) { 2868 return PackageManager.PERMISSION_DENIED; 2869 } 2870 2871 synchronized (mPackages) { 2872 final PackageParser.Package p = mPackages.get(pkgName); 2873 if (p != null && p.mExtras != null) { 2874 final PackageSetting ps = (PackageSetting) p.mExtras; 2875 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2876 return PackageManager.PERMISSION_GRANTED; 2877 } 2878 } 2879 } 2880 2881 return PackageManager.PERMISSION_DENIED; 2882 } 2883 2884 @Override 2885 public int checkUidPermission(String permName, int uid) { 2886 final int userId = UserHandle.getUserId(uid); 2887 2888 if (!sUserManager.exists(userId)) { 2889 return PackageManager.PERMISSION_DENIED; 2890 } 2891 2892 synchronized (mPackages) { 2893 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2894 if (obj != null) { 2895 final SettingBase ps = (SettingBase) obj; 2896 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2897 return PackageManager.PERMISSION_GRANTED; 2898 } 2899 } else { 2900 ArraySet<String> perms = mSystemPermissions.get(uid); 2901 if (perms != null && perms.contains(permName)) { 2902 return PackageManager.PERMISSION_GRANTED; 2903 } 2904 } 2905 } 2906 2907 return PackageManager.PERMISSION_DENIED; 2908 } 2909 2910 /** 2911 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2912 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2913 * @param checkShell TODO(yamasani): 2914 * @param message the message to log on security exception 2915 */ 2916 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2917 boolean checkShell, String message) { 2918 if (userId < 0) { 2919 throw new IllegalArgumentException("Invalid userId " + userId); 2920 } 2921 if (checkShell) { 2922 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2923 } 2924 if (userId == UserHandle.getUserId(callingUid)) return; 2925 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2926 if (requireFullPermission) { 2927 mContext.enforceCallingOrSelfPermission( 2928 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2929 } else { 2930 try { 2931 mContext.enforceCallingOrSelfPermission( 2932 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2933 } catch (SecurityException se) { 2934 mContext.enforceCallingOrSelfPermission( 2935 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2936 } 2937 } 2938 } 2939 } 2940 2941 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2942 if (callingUid == Process.SHELL_UID) { 2943 if (userHandle >= 0 2944 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2945 throw new SecurityException("Shell does not have permission to access user " 2946 + userHandle); 2947 } else if (userHandle < 0) { 2948 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2949 + Debug.getCallers(3)); 2950 } 2951 } 2952 } 2953 2954 private BasePermission findPermissionTreeLP(String permName) { 2955 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2956 if (permName.startsWith(bp.name) && 2957 permName.length() > bp.name.length() && 2958 permName.charAt(bp.name.length()) == '.') { 2959 return bp; 2960 } 2961 } 2962 return null; 2963 } 2964 2965 private BasePermission checkPermissionTreeLP(String permName) { 2966 if (permName != null) { 2967 BasePermission bp = findPermissionTreeLP(permName); 2968 if (bp != null) { 2969 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2970 return bp; 2971 } 2972 throw new SecurityException("Calling uid " 2973 + Binder.getCallingUid() 2974 + " is not allowed to add to permission tree " 2975 + bp.name + " owned by uid " + bp.uid); 2976 } 2977 } 2978 throw new SecurityException("No permission tree found for " + permName); 2979 } 2980 2981 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2982 if (s1 == null) { 2983 return s2 == null; 2984 } 2985 if (s2 == null) { 2986 return false; 2987 } 2988 if (s1.getClass() != s2.getClass()) { 2989 return false; 2990 } 2991 return s1.equals(s2); 2992 } 2993 2994 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2995 if (pi1.icon != pi2.icon) return false; 2996 if (pi1.logo != pi2.logo) return false; 2997 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2998 if (!compareStrings(pi1.name, pi2.name)) return false; 2999 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3000 // We'll take care of setting this one. 3001 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3002 // These are not currently stored in settings. 3003 //if (!compareStrings(pi1.group, pi2.group)) return false; 3004 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3005 //if (pi1.labelRes != pi2.labelRes) return false; 3006 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3007 return true; 3008 } 3009 3010 int permissionInfoFootprint(PermissionInfo info) { 3011 int size = info.name.length(); 3012 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3013 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3014 return size; 3015 } 3016 3017 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3018 int size = 0; 3019 for (BasePermission perm : mSettings.mPermissions.values()) { 3020 if (perm.uid == tree.uid) { 3021 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3022 } 3023 } 3024 return size; 3025 } 3026 3027 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3028 // We calculate the max size of permissions defined by this uid and throw 3029 // if that plus the size of 'info' would exceed our stated maximum. 3030 if (tree.uid != Process.SYSTEM_UID) { 3031 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3032 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3033 throw new SecurityException("Permission tree size cap exceeded"); 3034 } 3035 } 3036 } 3037 3038 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3039 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3040 throw new SecurityException("Label must be specified in permission"); 3041 } 3042 BasePermission tree = checkPermissionTreeLP(info.name); 3043 BasePermission bp = mSettings.mPermissions.get(info.name); 3044 boolean added = bp == null; 3045 boolean changed = true; 3046 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3047 if (added) { 3048 enforcePermissionCapLocked(info, tree); 3049 bp = new BasePermission(info.name, tree.sourcePackage, 3050 BasePermission.TYPE_DYNAMIC); 3051 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3052 throw new SecurityException( 3053 "Not allowed to modify non-dynamic permission " 3054 + info.name); 3055 } else { 3056 if (bp.protectionLevel == fixedLevel 3057 && bp.perm.owner.equals(tree.perm.owner) 3058 && bp.uid == tree.uid 3059 && comparePermissionInfos(bp.perm.info, info)) { 3060 changed = false; 3061 } 3062 } 3063 bp.protectionLevel = fixedLevel; 3064 info = new PermissionInfo(info); 3065 info.protectionLevel = fixedLevel; 3066 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3067 bp.perm.info.packageName = tree.perm.info.packageName; 3068 bp.uid = tree.uid; 3069 if (added) { 3070 mSettings.mPermissions.put(info.name, bp); 3071 } 3072 if (changed) { 3073 if (!async) { 3074 mSettings.writeLPr(); 3075 } else { 3076 scheduleWriteSettingsLocked(); 3077 } 3078 } 3079 return added; 3080 } 3081 3082 @Override 3083 public boolean addPermission(PermissionInfo info) { 3084 synchronized (mPackages) { 3085 return addPermissionLocked(info, false); 3086 } 3087 } 3088 3089 @Override 3090 public boolean addPermissionAsync(PermissionInfo info) { 3091 synchronized (mPackages) { 3092 return addPermissionLocked(info, true); 3093 } 3094 } 3095 3096 @Override 3097 public void removePermission(String name) { 3098 synchronized (mPackages) { 3099 checkPermissionTreeLP(name); 3100 BasePermission bp = mSettings.mPermissions.get(name); 3101 if (bp != null) { 3102 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3103 throw new SecurityException( 3104 "Not allowed to modify non-dynamic permission " 3105 + name); 3106 } 3107 mSettings.mPermissions.remove(name); 3108 mSettings.writeLPr(); 3109 } 3110 } 3111 } 3112 3113 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3114 BasePermission bp) { 3115 int index = pkg.requestedPermissions.indexOf(bp.name); 3116 if (index == -1) { 3117 throw new SecurityException("Package " + pkg.packageName 3118 + " has not requested permission " + bp.name); 3119 } 3120 if (!bp.isRuntime()) { 3121 throw new SecurityException("Permission " + bp.name 3122 + " is not a changeable permission type"); 3123 } 3124 } 3125 3126 @Override 3127 public boolean grantPermission(String packageName, String name, int userId) { 3128 if (!RUNTIME_PERMISSIONS_ENABLED) { 3129 return false; 3130 } 3131 3132 if (!sUserManager.exists(userId)) { 3133 return false; 3134 } 3135 3136 mContext.enforceCallingOrSelfPermission( 3137 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3138 "grantPermission"); 3139 3140 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3141 "grantPermission"); 3142 3143 boolean gidsChanged = false; 3144 final SettingBase sb; 3145 3146 synchronized (mPackages) { 3147 final PackageParser.Package pkg = mPackages.get(packageName); 3148 if (pkg == null) { 3149 throw new IllegalArgumentException("Unknown package: " + packageName); 3150 } 3151 3152 final BasePermission bp = mSettings.mPermissions.get(name); 3153 if (bp == null) { 3154 throw new IllegalArgumentException("Unknown permission: " + name); 3155 } 3156 3157 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3158 3159 sb = (SettingBase) pkg.mExtras; 3160 if (sb == null) { 3161 throw new IllegalArgumentException("Unknown package: " + packageName); 3162 } 3163 3164 final PermissionsState permissionsState = sb.getPermissionsState(); 3165 3166 final int result = permissionsState.grantRuntimePermission(bp, userId); 3167 switch (result) { 3168 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3169 return false; 3170 } 3171 3172 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3173 gidsChanged = true; 3174 } break; 3175 } 3176 3177 // Not critical if that is lost - app has to request again. 3178 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3179 } 3180 3181 if (gidsChanged) { 3182 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3183 } 3184 3185 return true; 3186 } 3187 3188 @Override 3189 public boolean revokePermission(String packageName, String name, int userId) { 3190 if (!RUNTIME_PERMISSIONS_ENABLED) { 3191 return false; 3192 } 3193 3194 if (!sUserManager.exists(userId)) { 3195 return false; 3196 } 3197 3198 mContext.enforceCallingOrSelfPermission( 3199 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3200 "revokePermission"); 3201 3202 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3203 "revokePermission"); 3204 3205 final SettingBase sb; 3206 3207 synchronized (mPackages) { 3208 final PackageParser.Package pkg = mPackages.get(packageName); 3209 if (pkg == null) { 3210 throw new IllegalArgumentException("Unknown package: " + packageName); 3211 } 3212 3213 final BasePermission bp = mSettings.mPermissions.get(name); 3214 if (bp == null) { 3215 throw new IllegalArgumentException("Unknown permission: " + name); 3216 } 3217 3218 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3219 3220 sb = (SettingBase) pkg.mExtras; 3221 if (sb == null) { 3222 throw new IllegalArgumentException("Unknown package: " + packageName); 3223 } 3224 3225 final PermissionsState permissionsState = sb.getPermissionsState(); 3226 3227 if (permissionsState.revokeRuntimePermission(bp, userId) == 3228 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3229 return false; 3230 } 3231 3232 // Critical, after this call all should never have the permission. 3233 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3234 } 3235 3236 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3237 3238 return true; 3239 } 3240 3241 @Override 3242 public boolean isProtectedBroadcast(String actionName) { 3243 synchronized (mPackages) { 3244 return mProtectedBroadcasts.contains(actionName); 3245 } 3246 } 3247 3248 @Override 3249 public int checkSignatures(String pkg1, String pkg2) { 3250 synchronized (mPackages) { 3251 final PackageParser.Package p1 = mPackages.get(pkg1); 3252 final PackageParser.Package p2 = mPackages.get(pkg2); 3253 if (p1 == null || p1.mExtras == null 3254 || p2 == null || p2.mExtras == null) { 3255 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3256 } 3257 return compareSignatures(p1.mSignatures, p2.mSignatures); 3258 } 3259 } 3260 3261 @Override 3262 public int checkUidSignatures(int uid1, int uid2) { 3263 // Map to base uids. 3264 uid1 = UserHandle.getAppId(uid1); 3265 uid2 = UserHandle.getAppId(uid2); 3266 // reader 3267 synchronized (mPackages) { 3268 Signature[] s1; 3269 Signature[] s2; 3270 Object obj = mSettings.getUserIdLPr(uid1); 3271 if (obj != null) { 3272 if (obj instanceof SharedUserSetting) { 3273 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3274 } else if (obj instanceof PackageSetting) { 3275 s1 = ((PackageSetting)obj).signatures.mSignatures; 3276 } else { 3277 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3278 } 3279 } else { 3280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3281 } 3282 obj = mSettings.getUserIdLPr(uid2); 3283 if (obj != null) { 3284 if (obj instanceof SharedUserSetting) { 3285 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3286 } else if (obj instanceof PackageSetting) { 3287 s2 = ((PackageSetting)obj).signatures.mSignatures; 3288 } else { 3289 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3290 } 3291 } else { 3292 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3293 } 3294 return compareSignatures(s1, s2); 3295 } 3296 } 3297 3298 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3299 final long identity = Binder.clearCallingIdentity(); 3300 try { 3301 if (sb instanceof SharedUserSetting) { 3302 SharedUserSetting sus = (SharedUserSetting) sb; 3303 final int packageCount = sus.packages.size(); 3304 for (int i = 0; i < packageCount; i++) { 3305 PackageSetting susPs = sus.packages.valueAt(i); 3306 if (userId == UserHandle.USER_ALL) { 3307 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3308 } else { 3309 final int uid = UserHandle.getUid(userId, susPs.appId); 3310 killUid(uid, reason); 3311 } 3312 } 3313 } else if (sb instanceof PackageSetting) { 3314 PackageSetting ps = (PackageSetting) sb; 3315 if (userId == UserHandle.USER_ALL) { 3316 killApplication(ps.pkg.packageName, ps.appId, reason); 3317 } else { 3318 final int uid = UserHandle.getUid(userId, ps.appId); 3319 killUid(uid, reason); 3320 } 3321 } 3322 } finally { 3323 Binder.restoreCallingIdentity(identity); 3324 } 3325 } 3326 3327 private static void killUid(int uid, String reason) { 3328 IActivityManager am = ActivityManagerNative.getDefault(); 3329 if (am != null) { 3330 try { 3331 am.killUid(uid, reason); 3332 } catch (RemoteException e) { 3333 /* ignore - same process */ 3334 } 3335 } 3336 } 3337 3338 /** 3339 * Compares two sets of signatures. Returns: 3340 * <br /> 3341 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3342 * <br /> 3343 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3344 * <br /> 3345 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3346 * <br /> 3347 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3348 * <br /> 3349 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3350 */ 3351 static int compareSignatures(Signature[] s1, Signature[] s2) { 3352 if (s1 == null) { 3353 return s2 == null 3354 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3355 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3356 } 3357 3358 if (s2 == null) { 3359 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3360 } 3361 3362 if (s1.length != s2.length) { 3363 return PackageManager.SIGNATURE_NO_MATCH; 3364 } 3365 3366 // Since both signature sets are of size 1, we can compare without HashSets. 3367 if (s1.length == 1) { 3368 return s1[0].equals(s2[0]) ? 3369 PackageManager.SIGNATURE_MATCH : 3370 PackageManager.SIGNATURE_NO_MATCH; 3371 } 3372 3373 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3374 for (Signature sig : s1) { 3375 set1.add(sig); 3376 } 3377 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3378 for (Signature sig : s2) { 3379 set2.add(sig); 3380 } 3381 // Make sure s2 contains all signatures in s1. 3382 if (set1.equals(set2)) { 3383 return PackageManager.SIGNATURE_MATCH; 3384 } 3385 return PackageManager.SIGNATURE_NO_MATCH; 3386 } 3387 3388 /** 3389 * If the database version for this type of package (internal storage or 3390 * external storage) is less than the version where package signatures 3391 * were updated, return true. 3392 */ 3393 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3394 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3395 DatabaseVersion.SIGNATURE_END_ENTITY)) 3396 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3397 DatabaseVersion.SIGNATURE_END_ENTITY)); 3398 } 3399 3400 /** 3401 * Used for backward compatibility to make sure any packages with 3402 * certificate chains get upgraded to the new style. {@code existingSigs} 3403 * will be in the old format (since they were stored on disk from before the 3404 * system upgrade) and {@code scannedSigs} will be in the newer format. 3405 */ 3406 private int compareSignaturesCompat(PackageSignatures existingSigs, 3407 PackageParser.Package scannedPkg) { 3408 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3409 return PackageManager.SIGNATURE_NO_MATCH; 3410 } 3411 3412 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3413 for (Signature sig : existingSigs.mSignatures) { 3414 existingSet.add(sig); 3415 } 3416 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3417 for (Signature sig : scannedPkg.mSignatures) { 3418 try { 3419 Signature[] chainSignatures = sig.getChainSignatures(); 3420 for (Signature chainSig : chainSignatures) { 3421 scannedCompatSet.add(chainSig); 3422 } 3423 } catch (CertificateEncodingException e) { 3424 scannedCompatSet.add(sig); 3425 } 3426 } 3427 /* 3428 * Make sure the expanded scanned set contains all signatures in the 3429 * existing one. 3430 */ 3431 if (scannedCompatSet.equals(existingSet)) { 3432 // Migrate the old signatures to the new scheme. 3433 existingSigs.assignSignatures(scannedPkg.mSignatures); 3434 // The new KeySets will be re-added later in the scanning process. 3435 synchronized (mPackages) { 3436 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3437 } 3438 return PackageManager.SIGNATURE_MATCH; 3439 } 3440 return PackageManager.SIGNATURE_NO_MATCH; 3441 } 3442 3443 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3444 if (isExternal(scannedPkg)) { 3445 return mSettings.isExternalDatabaseVersionOlderThan( 3446 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3447 } else { 3448 return mSettings.isInternalDatabaseVersionOlderThan( 3449 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3450 } 3451 } 3452 3453 private int compareSignaturesRecover(PackageSignatures existingSigs, 3454 PackageParser.Package scannedPkg) { 3455 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3456 return PackageManager.SIGNATURE_NO_MATCH; 3457 } 3458 3459 String msg = null; 3460 try { 3461 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3462 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3463 + scannedPkg.packageName); 3464 return PackageManager.SIGNATURE_MATCH; 3465 } 3466 } catch (CertificateException e) { 3467 msg = e.getMessage(); 3468 } 3469 3470 logCriticalInfo(Log.INFO, 3471 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3472 return PackageManager.SIGNATURE_NO_MATCH; 3473 } 3474 3475 @Override 3476 public String[] getPackagesForUid(int uid) { 3477 uid = UserHandle.getAppId(uid); 3478 // reader 3479 synchronized (mPackages) { 3480 Object obj = mSettings.getUserIdLPr(uid); 3481 if (obj instanceof SharedUserSetting) { 3482 final SharedUserSetting sus = (SharedUserSetting) obj; 3483 final int N = sus.packages.size(); 3484 final String[] res = new String[N]; 3485 final Iterator<PackageSetting> it = sus.packages.iterator(); 3486 int i = 0; 3487 while (it.hasNext()) { 3488 res[i++] = it.next().name; 3489 } 3490 return res; 3491 } else if (obj instanceof PackageSetting) { 3492 final PackageSetting ps = (PackageSetting) obj; 3493 return new String[] { ps.name }; 3494 } 3495 } 3496 return null; 3497 } 3498 3499 @Override 3500 public String getNameForUid(int uid) { 3501 // reader 3502 synchronized (mPackages) { 3503 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3504 if (obj instanceof SharedUserSetting) { 3505 final SharedUserSetting sus = (SharedUserSetting) obj; 3506 return sus.name + ":" + sus.userId; 3507 } else if (obj instanceof PackageSetting) { 3508 final PackageSetting ps = (PackageSetting) obj; 3509 return ps.name; 3510 } 3511 } 3512 return null; 3513 } 3514 3515 @Override 3516 public int getUidForSharedUser(String sharedUserName) { 3517 if(sharedUserName == null) { 3518 return -1; 3519 } 3520 // reader 3521 synchronized (mPackages) { 3522 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3523 if (suid == null) { 3524 return -1; 3525 } 3526 return suid.userId; 3527 } 3528 } 3529 3530 @Override 3531 public int getFlagsForUid(int uid) { 3532 synchronized (mPackages) { 3533 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3534 if (obj instanceof SharedUserSetting) { 3535 final SharedUserSetting sus = (SharedUserSetting) obj; 3536 return sus.pkgFlags; 3537 } else if (obj instanceof PackageSetting) { 3538 final PackageSetting ps = (PackageSetting) obj; 3539 return ps.pkgFlags; 3540 } 3541 } 3542 return 0; 3543 } 3544 3545 @Override 3546 public int getPrivateFlagsForUid(int uid) { 3547 synchronized (mPackages) { 3548 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3549 if (obj instanceof SharedUserSetting) { 3550 final SharedUserSetting sus = (SharedUserSetting) obj; 3551 return sus.pkgPrivateFlags; 3552 } else if (obj instanceof PackageSetting) { 3553 final PackageSetting ps = (PackageSetting) obj; 3554 return ps.pkgPrivateFlags; 3555 } 3556 } 3557 return 0; 3558 } 3559 3560 @Override 3561 public boolean isUidPrivileged(int uid) { 3562 uid = UserHandle.getAppId(uid); 3563 // reader 3564 synchronized (mPackages) { 3565 Object obj = mSettings.getUserIdLPr(uid); 3566 if (obj instanceof SharedUserSetting) { 3567 final SharedUserSetting sus = (SharedUserSetting) obj; 3568 final Iterator<PackageSetting> it = sus.packages.iterator(); 3569 while (it.hasNext()) { 3570 if (it.next().isPrivileged()) { 3571 return true; 3572 } 3573 } 3574 } else if (obj instanceof PackageSetting) { 3575 final PackageSetting ps = (PackageSetting) obj; 3576 return ps.isPrivileged(); 3577 } 3578 } 3579 return false; 3580 } 3581 3582 @Override 3583 public String[] getAppOpPermissionPackages(String permissionName) { 3584 synchronized (mPackages) { 3585 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3586 if (pkgs == null) { 3587 return null; 3588 } 3589 return pkgs.toArray(new String[pkgs.size()]); 3590 } 3591 } 3592 3593 @Override 3594 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3595 int flags, int userId) { 3596 if (!sUserManager.exists(userId)) return null; 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3598 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3599 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3600 } 3601 3602 @Override 3603 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3604 IntentFilter filter, int match, ComponentName activity) { 3605 final int userId = UserHandle.getCallingUserId(); 3606 if (DEBUG_PREFERRED) { 3607 Log.v(TAG, "setLastChosenActivity intent=" + intent 3608 + " resolvedType=" + resolvedType 3609 + " flags=" + flags 3610 + " filter=" + filter 3611 + " match=" + match 3612 + " activity=" + activity); 3613 filter.dump(new PrintStreamPrinter(System.out), " "); 3614 } 3615 intent.setComponent(null); 3616 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3617 // Find any earlier preferred or last chosen entries and nuke them 3618 findPreferredActivity(intent, resolvedType, 3619 flags, query, 0, false, true, false, userId); 3620 // Add the new activity as the last chosen for this filter 3621 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3622 "Setting last chosen"); 3623 } 3624 3625 @Override 3626 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3627 final int userId = UserHandle.getCallingUserId(); 3628 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3629 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3630 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3631 false, false, false, userId); 3632 } 3633 3634 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3635 int flags, List<ResolveInfo> query, int userId) { 3636 if (query != null) { 3637 final int N = query.size(); 3638 if (N == 1) { 3639 return query.get(0); 3640 } else if (N > 1) { 3641 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3642 // If there is more than one activity with the same priority, 3643 // then let the user decide between them. 3644 ResolveInfo r0 = query.get(0); 3645 ResolveInfo r1 = query.get(1); 3646 if (DEBUG_INTENT_MATCHING || debug) { 3647 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3648 + r1.activityInfo.name + "=" + r1.priority); 3649 } 3650 // If the first activity has a higher priority, or a different 3651 // default, then it is always desireable to pick it. 3652 if (r0.priority != r1.priority 3653 || r0.preferredOrder != r1.preferredOrder 3654 || r0.isDefault != r1.isDefault) { 3655 return query.get(0); 3656 } 3657 // If we have saved a preference for a preferred activity for 3658 // this Intent, use that. 3659 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3660 flags, query, r0.priority, true, false, debug, userId); 3661 if (ri != null) { 3662 return ri; 3663 } 3664 if (userId != 0) { 3665 ri = new ResolveInfo(mResolveInfo); 3666 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3667 ri.activityInfo.applicationInfo = new ApplicationInfo( 3668 ri.activityInfo.applicationInfo); 3669 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3670 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3671 return ri; 3672 } 3673 return mResolveInfo; 3674 } 3675 } 3676 return null; 3677 } 3678 3679 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3680 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3681 final int N = query.size(); 3682 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3683 .get(userId); 3684 // Get the list of persistent preferred activities that handle the intent 3685 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3686 List<PersistentPreferredActivity> pprefs = ppir != null 3687 ? ppir.queryIntent(intent, resolvedType, 3688 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3689 : null; 3690 if (pprefs != null && pprefs.size() > 0) { 3691 final int M = pprefs.size(); 3692 for (int i=0; i<M; i++) { 3693 final PersistentPreferredActivity ppa = pprefs.get(i); 3694 if (DEBUG_PREFERRED || debug) { 3695 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3696 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3697 + "\n component=" + ppa.mComponent); 3698 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3699 } 3700 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3701 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3702 if (DEBUG_PREFERRED || debug) { 3703 Slog.v(TAG, "Found persistent preferred activity:"); 3704 if (ai != null) { 3705 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3706 } else { 3707 Slog.v(TAG, " null"); 3708 } 3709 } 3710 if (ai == null) { 3711 // This previously registered persistent preferred activity 3712 // component is no longer known. Ignore it and do NOT remove it. 3713 continue; 3714 } 3715 for (int j=0; j<N; j++) { 3716 final ResolveInfo ri = query.get(j); 3717 if (!ri.activityInfo.applicationInfo.packageName 3718 .equals(ai.applicationInfo.packageName)) { 3719 continue; 3720 } 3721 if (!ri.activityInfo.name.equals(ai.name)) { 3722 continue; 3723 } 3724 // Found a persistent preference that can handle the intent. 3725 if (DEBUG_PREFERRED || debug) { 3726 Slog.v(TAG, "Returning persistent preferred activity: " + 3727 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3728 } 3729 return ri; 3730 } 3731 } 3732 } 3733 return null; 3734 } 3735 3736 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3737 List<ResolveInfo> query, int priority, boolean always, 3738 boolean removeMatches, boolean debug, int userId) { 3739 if (!sUserManager.exists(userId)) return null; 3740 // writer 3741 synchronized (mPackages) { 3742 if (intent.getSelector() != null) { 3743 intent = intent.getSelector(); 3744 } 3745 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3746 3747 // Try to find a matching persistent preferred activity. 3748 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3749 debug, userId); 3750 3751 // If a persistent preferred activity matched, use it. 3752 if (pri != null) { 3753 return pri; 3754 } 3755 3756 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3757 // Get the list of preferred activities that handle the intent 3758 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3759 List<PreferredActivity> prefs = pir != null 3760 ? pir.queryIntent(intent, resolvedType, 3761 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3762 : null; 3763 if (prefs != null && prefs.size() > 0) { 3764 boolean changed = false; 3765 try { 3766 // First figure out how good the original match set is. 3767 // We will only allow preferred activities that came 3768 // from the same match quality. 3769 int match = 0; 3770 3771 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3772 3773 final int N = query.size(); 3774 for (int j=0; j<N; j++) { 3775 final ResolveInfo ri = query.get(j); 3776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3777 + ": 0x" + Integer.toHexString(match)); 3778 if (ri.match > match) { 3779 match = ri.match; 3780 } 3781 } 3782 3783 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3784 + Integer.toHexString(match)); 3785 3786 match &= IntentFilter.MATCH_CATEGORY_MASK; 3787 final int M = prefs.size(); 3788 for (int i=0; i<M; i++) { 3789 final PreferredActivity pa = prefs.get(i); 3790 if (DEBUG_PREFERRED || debug) { 3791 Slog.v(TAG, "Checking PreferredActivity ds=" 3792 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3793 + "\n component=" + pa.mPref.mComponent); 3794 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3795 } 3796 if (pa.mPref.mMatch != match) { 3797 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3798 + Integer.toHexString(pa.mPref.mMatch)); 3799 continue; 3800 } 3801 // If it's not an "always" type preferred activity and that's what we're 3802 // looking for, skip it. 3803 if (always && !pa.mPref.mAlways) { 3804 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3805 continue; 3806 } 3807 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3808 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3809 if (DEBUG_PREFERRED || debug) { 3810 Slog.v(TAG, "Found preferred activity:"); 3811 if (ai != null) { 3812 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3813 } else { 3814 Slog.v(TAG, " null"); 3815 } 3816 } 3817 if (ai == null) { 3818 // This previously registered preferred activity 3819 // component is no longer known. Most likely an update 3820 // to the app was installed and in the new version this 3821 // component no longer exists. Clean it up by removing 3822 // it from the preferred activities list, and skip it. 3823 Slog.w(TAG, "Removing dangling preferred activity: " 3824 + pa.mPref.mComponent); 3825 pir.removeFilter(pa); 3826 changed = true; 3827 continue; 3828 } 3829 for (int j=0; j<N; j++) { 3830 final ResolveInfo ri = query.get(j); 3831 if (!ri.activityInfo.applicationInfo.packageName 3832 .equals(ai.applicationInfo.packageName)) { 3833 continue; 3834 } 3835 if (!ri.activityInfo.name.equals(ai.name)) { 3836 continue; 3837 } 3838 3839 if (removeMatches) { 3840 pir.removeFilter(pa); 3841 changed = true; 3842 if (DEBUG_PREFERRED) { 3843 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3844 } 3845 break; 3846 } 3847 3848 // Okay we found a previously set preferred or last chosen app. 3849 // If the result set is different from when this 3850 // was created, we need to clear it and re-ask the 3851 // user their preference, if we're looking for an "always" type entry. 3852 if (always && !pa.mPref.sameSet(query)) { 3853 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3854 + intent + " type " + resolvedType); 3855 if (DEBUG_PREFERRED) { 3856 Slog.v(TAG, "Removing preferred activity since set changed " 3857 + pa.mPref.mComponent); 3858 } 3859 pir.removeFilter(pa); 3860 // Re-add the filter as a "last chosen" entry (!always) 3861 PreferredActivity lastChosen = new PreferredActivity( 3862 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3863 pir.addFilter(lastChosen); 3864 changed = true; 3865 return null; 3866 } 3867 3868 // Yay! Either the set matched or we're looking for the last chosen 3869 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3870 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3871 return ri; 3872 } 3873 } 3874 } finally { 3875 if (changed) { 3876 if (DEBUG_PREFERRED) { 3877 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3878 } 3879 scheduleWritePackageRestrictionsLocked(userId); 3880 } 3881 } 3882 } 3883 } 3884 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3885 return null; 3886 } 3887 3888 /* 3889 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3890 */ 3891 @Override 3892 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3893 int targetUserId) { 3894 mContext.enforceCallingOrSelfPermission( 3895 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3896 List<CrossProfileIntentFilter> matches = 3897 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3898 if (matches != null) { 3899 int size = matches.size(); 3900 for (int i = 0; i < size; i++) { 3901 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3902 } 3903 } 3904 return false; 3905 } 3906 3907 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3908 String resolvedType, int userId) { 3909 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3910 if (resolver != null) { 3911 return resolver.queryIntent(intent, resolvedType, false, userId); 3912 } 3913 return null; 3914 } 3915 3916 @Override 3917 public List<ResolveInfo> queryIntentActivities(Intent intent, 3918 String resolvedType, int flags, int userId) { 3919 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3920 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3921 ComponentName comp = intent.getComponent(); 3922 if (comp == null) { 3923 if (intent.getSelector() != null) { 3924 intent = intent.getSelector(); 3925 comp = intent.getComponent(); 3926 } 3927 } 3928 3929 if (comp != null) { 3930 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3931 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3932 if (ai != null) { 3933 final ResolveInfo ri = new ResolveInfo(); 3934 ri.activityInfo = ai; 3935 list.add(ri); 3936 } 3937 return list; 3938 } 3939 3940 // reader 3941 synchronized (mPackages) { 3942 final String pkgName = intent.getPackage(); 3943 if (pkgName == null) { 3944 List<CrossProfileIntentFilter> matchingFilters = 3945 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3946 // Check for results that need to skip the current profile. 3947 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3948 resolvedType, flags, userId); 3949 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3950 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3951 result.add(resolveInfo); 3952 return filterIfNotPrimaryUser(result, userId); 3953 } 3954 3955 // Check for results in the current profile. 3956 List<ResolveInfo> result = mActivities.queryIntent( 3957 intent, resolvedType, flags, userId); 3958 3959 // Check for cross profile results. 3960 resolveInfo = queryCrossProfileIntents( 3961 matchingFilters, intent, resolvedType, flags, userId); 3962 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3963 result.add(resolveInfo); 3964 Collections.sort(result, mResolvePrioritySorter); 3965 } 3966 result = filterIfNotPrimaryUser(result, userId); 3967 if (result.size() > 1 && hasWebURI(intent)) { 3968 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3969 } 3970 return result; 3971 } 3972 final PackageParser.Package pkg = mPackages.get(pkgName); 3973 if (pkg != null) { 3974 return filterIfNotPrimaryUser( 3975 mActivities.queryIntentForPackage( 3976 intent, resolvedType, flags, pkg.activities, userId), 3977 userId); 3978 } 3979 return new ArrayList<ResolveInfo>(); 3980 } 3981 } 3982 3983 private boolean isUserEnabled(int userId) { 3984 long callingId = Binder.clearCallingIdentity(); 3985 try { 3986 UserInfo userInfo = sUserManager.getUserInfo(userId); 3987 return userInfo != null && userInfo.isEnabled(); 3988 } finally { 3989 Binder.restoreCallingIdentity(callingId); 3990 } 3991 } 3992 3993 /** 3994 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3995 * 3996 * @return filtered list 3997 */ 3998 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3999 if (userId == UserHandle.USER_OWNER) { 4000 return resolveInfos; 4001 } 4002 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4003 ResolveInfo info = resolveInfos.get(i); 4004 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4005 resolveInfos.remove(i); 4006 } 4007 } 4008 return resolveInfos; 4009 } 4010 4011 private static boolean hasWebURI(Intent intent) { 4012 if (intent.getData() == null) { 4013 return false; 4014 } 4015 final String scheme = intent.getScheme(); 4016 if (TextUtils.isEmpty(scheme)) { 4017 return false; 4018 } 4019 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4020 } 4021 4022 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4023 int flags, List<ResolveInfo> candidates) { 4024 if (DEBUG_PREFERRED) { 4025 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4026 candidates.size()); 4027 } 4028 4029 final int userId = UserHandle.getCallingUserId(); 4030 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4031 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4032 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4033 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4034 4035 synchronized (mPackages) { 4036 final int count = candidates.size(); 4037 // First, try to use the domain prefered App 4038 for (int n=0; n<count; n++) { 4039 ResolveInfo info = candidates.get(n); 4040 String packageName = info.activityInfo.packageName; 4041 PackageSetting ps = mSettings.mPackages.get(packageName); 4042 if (ps != null) { 4043 // Add to the special match all list (Browser use case) 4044 if (info.handleAllWebDataURI) { 4045 matchAllList.add(info); 4046 continue; 4047 } 4048 // Try to get the status from User settings first 4049 int status = getDomainVerificationStatusLPr(ps, userId); 4050 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4051 result.add(info); 4052 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4053 neverList.add(info); 4054 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4055 undefinedList.add(info); 4056 } 4057 } 4058 } 4059 // If there is nothing selected, add all candidates and remove the ones that the User 4060 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4061 // also remove any Browser Apps ones. 4062 // If there is still none after this pass, add all undefined one and Browser Apps and 4063 // let the User decide with the Disambiguation dialog if there are several ones. 4064 if (result.size() == 0) { 4065 result.addAll(candidates); 4066 } 4067 result.removeAll(neverList); 4068 result.removeAll(matchAllList); 4069 if (result.size() == 0) { 4070 result.addAll(undefinedList); 4071 if ((flags & MATCH_ALL) != 0) { 4072 result.addAll(matchAllList); 4073 } else { 4074 // Try to add the Default Browser if we can 4075 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4076 UserHandle.myUserId()); 4077 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4078 boolean defaultBrowserFound = false; 4079 final int browserCount = matchAllList.size(); 4080 for (int n=0; n<browserCount; n++) { 4081 ResolveInfo browser = matchAllList.get(n); 4082 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4083 result.add(browser); 4084 defaultBrowserFound = true; 4085 break; 4086 } 4087 } 4088 if (!defaultBrowserFound) { 4089 result.addAll(matchAllList); 4090 } 4091 } else { 4092 result.addAll(matchAllList); 4093 } 4094 } 4095 } 4096 } 4097 if (DEBUG_PREFERRED) { 4098 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4099 result.size()); 4100 } 4101 return result; 4102 } 4103 4104 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4105 int status = ps.getDomainVerificationStatusForUser(userId); 4106 // if none available, get the master status 4107 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4108 if (ps.getIntentFilterVerificationInfo() != null) { 4109 status = ps.getIntentFilterVerificationInfo().getStatus(); 4110 } 4111 } 4112 return status; 4113 } 4114 4115 private ResolveInfo querySkipCurrentProfileIntents( 4116 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4117 int flags, int sourceUserId) { 4118 if (matchingFilters != null) { 4119 int size = matchingFilters.size(); 4120 for (int i = 0; i < size; i ++) { 4121 CrossProfileIntentFilter filter = matchingFilters.get(i); 4122 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4123 // Checking if there are activities in the target user that can handle the 4124 // intent. 4125 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4126 flags, sourceUserId); 4127 if (resolveInfo != null) { 4128 return resolveInfo; 4129 } 4130 } 4131 } 4132 } 4133 return null; 4134 } 4135 4136 // Return matching ResolveInfo if any for skip current profile intent filters. 4137 private ResolveInfo queryCrossProfileIntents( 4138 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4139 int flags, int sourceUserId) { 4140 if (matchingFilters != null) { 4141 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4142 // match the same intent. For performance reasons, it is better not to 4143 // run queryIntent twice for the same userId 4144 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4145 int size = matchingFilters.size(); 4146 for (int i = 0; i < size; i++) { 4147 CrossProfileIntentFilter filter = matchingFilters.get(i); 4148 int targetUserId = filter.getTargetUserId(); 4149 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4150 && !alreadyTriedUserIds.get(targetUserId)) { 4151 // Checking if there are activities in the target user that can handle the 4152 // intent. 4153 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4154 flags, sourceUserId); 4155 if (resolveInfo != null) return resolveInfo; 4156 alreadyTriedUserIds.put(targetUserId, true); 4157 } 4158 } 4159 } 4160 return null; 4161 } 4162 4163 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4164 String resolvedType, int flags, int sourceUserId) { 4165 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4166 resolvedType, flags, filter.getTargetUserId()); 4167 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4168 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4169 } 4170 return null; 4171 } 4172 4173 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4174 int sourceUserId, int targetUserId) { 4175 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4176 String className; 4177 if (targetUserId == UserHandle.USER_OWNER) { 4178 className = FORWARD_INTENT_TO_USER_OWNER; 4179 } else { 4180 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4181 } 4182 ComponentName forwardingActivityComponentName = new ComponentName( 4183 mAndroidApplication.packageName, className); 4184 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4185 sourceUserId); 4186 if (targetUserId == UserHandle.USER_OWNER) { 4187 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4188 forwardingResolveInfo.noResourceId = true; 4189 } 4190 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4191 forwardingResolveInfo.priority = 0; 4192 forwardingResolveInfo.preferredOrder = 0; 4193 forwardingResolveInfo.match = 0; 4194 forwardingResolveInfo.isDefault = true; 4195 forwardingResolveInfo.filter = filter; 4196 forwardingResolveInfo.targetUserId = targetUserId; 4197 return forwardingResolveInfo; 4198 } 4199 4200 @Override 4201 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4202 Intent[] specifics, String[] specificTypes, Intent intent, 4203 String resolvedType, int flags, int userId) { 4204 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4205 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4206 false, "query intent activity options"); 4207 final String resultsAction = intent.getAction(); 4208 4209 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4210 | PackageManager.GET_RESOLVED_FILTER, userId); 4211 4212 if (DEBUG_INTENT_MATCHING) { 4213 Log.v(TAG, "Query " + intent + ": " + results); 4214 } 4215 4216 int specificsPos = 0; 4217 int N; 4218 4219 // todo: note that the algorithm used here is O(N^2). This 4220 // isn't a problem in our current environment, but if we start running 4221 // into situations where we have more than 5 or 10 matches then this 4222 // should probably be changed to something smarter... 4223 4224 // First we go through and resolve each of the specific items 4225 // that were supplied, taking care of removing any corresponding 4226 // duplicate items in the generic resolve list. 4227 if (specifics != null) { 4228 for (int i=0; i<specifics.length; i++) { 4229 final Intent sintent = specifics[i]; 4230 if (sintent == null) { 4231 continue; 4232 } 4233 4234 if (DEBUG_INTENT_MATCHING) { 4235 Log.v(TAG, "Specific #" + i + ": " + sintent); 4236 } 4237 4238 String action = sintent.getAction(); 4239 if (resultsAction != null && resultsAction.equals(action)) { 4240 // If this action was explicitly requested, then don't 4241 // remove things that have it. 4242 action = null; 4243 } 4244 4245 ResolveInfo ri = null; 4246 ActivityInfo ai = null; 4247 4248 ComponentName comp = sintent.getComponent(); 4249 if (comp == null) { 4250 ri = resolveIntent( 4251 sintent, 4252 specificTypes != null ? specificTypes[i] : null, 4253 flags, userId); 4254 if (ri == null) { 4255 continue; 4256 } 4257 if (ri == mResolveInfo) { 4258 // ACK! Must do something better with this. 4259 } 4260 ai = ri.activityInfo; 4261 comp = new ComponentName(ai.applicationInfo.packageName, 4262 ai.name); 4263 } else { 4264 ai = getActivityInfo(comp, flags, userId); 4265 if (ai == null) { 4266 continue; 4267 } 4268 } 4269 4270 // Look for any generic query activities that are duplicates 4271 // of this specific one, and remove them from the results. 4272 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4273 N = results.size(); 4274 int j; 4275 for (j=specificsPos; j<N; j++) { 4276 ResolveInfo sri = results.get(j); 4277 if ((sri.activityInfo.name.equals(comp.getClassName()) 4278 && sri.activityInfo.applicationInfo.packageName.equals( 4279 comp.getPackageName())) 4280 || (action != null && sri.filter.matchAction(action))) { 4281 results.remove(j); 4282 if (DEBUG_INTENT_MATCHING) Log.v( 4283 TAG, "Removing duplicate item from " + j 4284 + " due to specific " + specificsPos); 4285 if (ri == null) { 4286 ri = sri; 4287 } 4288 j--; 4289 N--; 4290 } 4291 } 4292 4293 // Add this specific item to its proper place. 4294 if (ri == null) { 4295 ri = new ResolveInfo(); 4296 ri.activityInfo = ai; 4297 } 4298 results.add(specificsPos, ri); 4299 ri.specificIndex = i; 4300 specificsPos++; 4301 } 4302 } 4303 4304 // Now we go through the remaining generic results and remove any 4305 // duplicate actions that are found here. 4306 N = results.size(); 4307 for (int i=specificsPos; i<N-1; i++) { 4308 final ResolveInfo rii = results.get(i); 4309 if (rii.filter == null) { 4310 continue; 4311 } 4312 4313 // Iterate over all of the actions of this result's intent 4314 // filter... typically this should be just one. 4315 final Iterator<String> it = rii.filter.actionsIterator(); 4316 if (it == null) { 4317 continue; 4318 } 4319 while (it.hasNext()) { 4320 final String action = it.next(); 4321 if (resultsAction != null && resultsAction.equals(action)) { 4322 // If this action was explicitly requested, then don't 4323 // remove things that have it. 4324 continue; 4325 } 4326 for (int j=i+1; j<N; j++) { 4327 final ResolveInfo rij = results.get(j); 4328 if (rij.filter != null && rij.filter.hasAction(action)) { 4329 results.remove(j); 4330 if (DEBUG_INTENT_MATCHING) Log.v( 4331 TAG, "Removing duplicate item from " + j 4332 + " due to action " + action + " at " + i); 4333 j--; 4334 N--; 4335 } 4336 } 4337 } 4338 4339 // If the caller didn't request filter information, drop it now 4340 // so we don't have to marshall/unmarshall it. 4341 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4342 rii.filter = null; 4343 } 4344 } 4345 4346 // Filter out the caller activity if so requested. 4347 if (caller != null) { 4348 N = results.size(); 4349 for (int i=0; i<N; i++) { 4350 ActivityInfo ainfo = results.get(i).activityInfo; 4351 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4352 && caller.getClassName().equals(ainfo.name)) { 4353 results.remove(i); 4354 break; 4355 } 4356 } 4357 } 4358 4359 // If the caller didn't request filter information, 4360 // drop them now so we don't have to 4361 // marshall/unmarshall it. 4362 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4363 N = results.size(); 4364 for (int i=0; i<N; i++) { 4365 results.get(i).filter = null; 4366 } 4367 } 4368 4369 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4370 return results; 4371 } 4372 4373 @Override 4374 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4375 int userId) { 4376 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4377 ComponentName comp = intent.getComponent(); 4378 if (comp == null) { 4379 if (intent.getSelector() != null) { 4380 intent = intent.getSelector(); 4381 comp = intent.getComponent(); 4382 } 4383 } 4384 if (comp != null) { 4385 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4386 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4387 if (ai != null) { 4388 ResolveInfo ri = new ResolveInfo(); 4389 ri.activityInfo = ai; 4390 list.add(ri); 4391 } 4392 return list; 4393 } 4394 4395 // reader 4396 synchronized (mPackages) { 4397 String pkgName = intent.getPackage(); 4398 if (pkgName == null) { 4399 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4400 } 4401 final PackageParser.Package pkg = mPackages.get(pkgName); 4402 if (pkg != null) { 4403 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4404 userId); 4405 } 4406 return null; 4407 } 4408 } 4409 4410 @Override 4411 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4412 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4413 if (!sUserManager.exists(userId)) return null; 4414 if (query != null) { 4415 if (query.size() >= 1) { 4416 // If there is more than one service with the same priority, 4417 // just arbitrarily pick the first one. 4418 return query.get(0); 4419 } 4420 } 4421 return null; 4422 } 4423 4424 @Override 4425 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4426 int userId) { 4427 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4428 ComponentName comp = intent.getComponent(); 4429 if (comp == null) { 4430 if (intent.getSelector() != null) { 4431 intent = intent.getSelector(); 4432 comp = intent.getComponent(); 4433 } 4434 } 4435 if (comp != null) { 4436 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4437 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4438 if (si != null) { 4439 final ResolveInfo ri = new ResolveInfo(); 4440 ri.serviceInfo = si; 4441 list.add(ri); 4442 } 4443 return list; 4444 } 4445 4446 // reader 4447 synchronized (mPackages) { 4448 String pkgName = intent.getPackage(); 4449 if (pkgName == null) { 4450 return mServices.queryIntent(intent, resolvedType, flags, userId); 4451 } 4452 final PackageParser.Package pkg = mPackages.get(pkgName); 4453 if (pkg != null) { 4454 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4455 userId); 4456 } 4457 return null; 4458 } 4459 } 4460 4461 @Override 4462 public List<ResolveInfo> queryIntentContentProviders( 4463 Intent intent, String resolvedType, int flags, int userId) { 4464 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4465 ComponentName comp = intent.getComponent(); 4466 if (comp == null) { 4467 if (intent.getSelector() != null) { 4468 intent = intent.getSelector(); 4469 comp = intent.getComponent(); 4470 } 4471 } 4472 if (comp != null) { 4473 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4474 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4475 if (pi != null) { 4476 final ResolveInfo ri = new ResolveInfo(); 4477 ri.providerInfo = pi; 4478 list.add(ri); 4479 } 4480 return list; 4481 } 4482 4483 // reader 4484 synchronized (mPackages) { 4485 String pkgName = intent.getPackage(); 4486 if (pkgName == null) { 4487 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4488 } 4489 final PackageParser.Package pkg = mPackages.get(pkgName); 4490 if (pkg != null) { 4491 return mProviders.queryIntentForPackage( 4492 intent, resolvedType, flags, pkg.providers, userId); 4493 } 4494 return null; 4495 } 4496 } 4497 4498 @Override 4499 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4500 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4501 4502 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4503 4504 // writer 4505 synchronized (mPackages) { 4506 ArrayList<PackageInfo> list; 4507 if (listUninstalled) { 4508 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4509 for (PackageSetting ps : mSettings.mPackages.values()) { 4510 PackageInfo pi; 4511 if (ps.pkg != null) { 4512 pi = generatePackageInfo(ps.pkg, flags, userId); 4513 } else { 4514 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4515 } 4516 if (pi != null) { 4517 list.add(pi); 4518 } 4519 } 4520 } else { 4521 list = new ArrayList<PackageInfo>(mPackages.size()); 4522 for (PackageParser.Package p : mPackages.values()) { 4523 PackageInfo pi = generatePackageInfo(p, flags, userId); 4524 if (pi != null) { 4525 list.add(pi); 4526 } 4527 } 4528 } 4529 4530 return new ParceledListSlice<PackageInfo>(list); 4531 } 4532 } 4533 4534 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4535 String[] permissions, boolean[] tmp, int flags, int userId) { 4536 int numMatch = 0; 4537 final PermissionsState permissionsState = ps.getPermissionsState(); 4538 for (int i=0; i<permissions.length; i++) { 4539 final String permission = permissions[i]; 4540 if (permissionsState.hasPermission(permission, userId)) { 4541 tmp[i] = true; 4542 numMatch++; 4543 } else { 4544 tmp[i] = false; 4545 } 4546 } 4547 if (numMatch == 0) { 4548 return; 4549 } 4550 PackageInfo pi; 4551 if (ps.pkg != null) { 4552 pi = generatePackageInfo(ps.pkg, flags, userId); 4553 } else { 4554 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4555 } 4556 // The above might return null in cases of uninstalled apps or install-state 4557 // skew across users/profiles. 4558 if (pi != null) { 4559 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4560 if (numMatch == permissions.length) { 4561 pi.requestedPermissions = permissions; 4562 } else { 4563 pi.requestedPermissions = new String[numMatch]; 4564 numMatch = 0; 4565 for (int i=0; i<permissions.length; i++) { 4566 if (tmp[i]) { 4567 pi.requestedPermissions[numMatch] = permissions[i]; 4568 numMatch++; 4569 } 4570 } 4571 } 4572 } 4573 list.add(pi); 4574 } 4575 } 4576 4577 @Override 4578 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4579 String[] permissions, int flags, int userId) { 4580 if (!sUserManager.exists(userId)) return null; 4581 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4582 4583 // writer 4584 synchronized (mPackages) { 4585 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4586 boolean[] tmpBools = new boolean[permissions.length]; 4587 if (listUninstalled) { 4588 for (PackageSetting ps : mSettings.mPackages.values()) { 4589 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4590 } 4591 } else { 4592 for (PackageParser.Package pkg : mPackages.values()) { 4593 PackageSetting ps = (PackageSetting)pkg.mExtras; 4594 if (ps != null) { 4595 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4596 userId); 4597 } 4598 } 4599 } 4600 4601 return new ParceledListSlice<PackageInfo>(list); 4602 } 4603 } 4604 4605 @Override 4606 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4607 if (!sUserManager.exists(userId)) return null; 4608 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4609 4610 // writer 4611 synchronized (mPackages) { 4612 ArrayList<ApplicationInfo> list; 4613 if (listUninstalled) { 4614 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4615 for (PackageSetting ps : mSettings.mPackages.values()) { 4616 ApplicationInfo ai; 4617 if (ps.pkg != null) { 4618 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4619 ps.readUserState(userId), userId); 4620 } else { 4621 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4622 } 4623 if (ai != null) { 4624 list.add(ai); 4625 } 4626 } 4627 } else { 4628 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4629 for (PackageParser.Package p : mPackages.values()) { 4630 if (p.mExtras != null) { 4631 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4632 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4633 if (ai != null) { 4634 list.add(ai); 4635 } 4636 } 4637 } 4638 } 4639 4640 return new ParceledListSlice<ApplicationInfo>(list); 4641 } 4642 } 4643 4644 public List<ApplicationInfo> getPersistentApplications(int flags) { 4645 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4646 4647 // reader 4648 synchronized (mPackages) { 4649 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4650 final int userId = UserHandle.getCallingUserId(); 4651 while (i.hasNext()) { 4652 final PackageParser.Package p = i.next(); 4653 if (p.applicationInfo != null 4654 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4655 && (!mSafeMode || isSystemApp(p))) { 4656 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4657 if (ps != null) { 4658 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4659 ps.readUserState(userId), userId); 4660 if (ai != null) { 4661 finalList.add(ai); 4662 } 4663 } 4664 } 4665 } 4666 } 4667 4668 return finalList; 4669 } 4670 4671 @Override 4672 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4673 if (!sUserManager.exists(userId)) return null; 4674 // reader 4675 synchronized (mPackages) { 4676 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4677 PackageSetting ps = provider != null 4678 ? mSettings.mPackages.get(provider.owner.packageName) 4679 : null; 4680 return ps != null 4681 && mSettings.isEnabledLPr(provider.info, flags, userId) 4682 && (!mSafeMode || (provider.info.applicationInfo.flags 4683 &ApplicationInfo.FLAG_SYSTEM) != 0) 4684 ? PackageParser.generateProviderInfo(provider, flags, 4685 ps.readUserState(userId), userId) 4686 : null; 4687 } 4688 } 4689 4690 /** 4691 * @deprecated 4692 */ 4693 @Deprecated 4694 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4695 // reader 4696 synchronized (mPackages) { 4697 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4698 .entrySet().iterator(); 4699 final int userId = UserHandle.getCallingUserId(); 4700 while (i.hasNext()) { 4701 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4702 PackageParser.Provider p = entry.getValue(); 4703 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4704 4705 if (ps != null && p.syncable 4706 && (!mSafeMode || (p.info.applicationInfo.flags 4707 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4708 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4709 ps.readUserState(userId), userId); 4710 if (info != null) { 4711 outNames.add(entry.getKey()); 4712 outInfo.add(info); 4713 } 4714 } 4715 } 4716 } 4717 } 4718 4719 @Override 4720 public List<ProviderInfo> queryContentProviders(String processName, 4721 int uid, int flags) { 4722 ArrayList<ProviderInfo> finalList = null; 4723 // reader 4724 synchronized (mPackages) { 4725 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4726 final int userId = processName != null ? 4727 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4728 while (i.hasNext()) { 4729 final PackageParser.Provider p = i.next(); 4730 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4731 if (ps != null && p.info.authority != null 4732 && (processName == null 4733 || (p.info.processName.equals(processName) 4734 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4735 && mSettings.isEnabledLPr(p.info, flags, userId) 4736 && (!mSafeMode 4737 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4738 if (finalList == null) { 4739 finalList = new ArrayList<ProviderInfo>(3); 4740 } 4741 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4742 ps.readUserState(userId), userId); 4743 if (info != null) { 4744 finalList.add(info); 4745 } 4746 } 4747 } 4748 } 4749 4750 if (finalList != null) { 4751 Collections.sort(finalList, mProviderInitOrderSorter); 4752 } 4753 4754 return finalList; 4755 } 4756 4757 @Override 4758 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4759 int flags) { 4760 // reader 4761 synchronized (mPackages) { 4762 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4763 return PackageParser.generateInstrumentationInfo(i, flags); 4764 } 4765 } 4766 4767 @Override 4768 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4769 int flags) { 4770 ArrayList<InstrumentationInfo> finalList = 4771 new ArrayList<InstrumentationInfo>(); 4772 4773 // reader 4774 synchronized (mPackages) { 4775 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4776 while (i.hasNext()) { 4777 final PackageParser.Instrumentation p = i.next(); 4778 if (targetPackage == null 4779 || targetPackage.equals(p.info.targetPackage)) { 4780 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4781 flags); 4782 if (ii != null) { 4783 finalList.add(ii); 4784 } 4785 } 4786 } 4787 } 4788 4789 return finalList; 4790 } 4791 4792 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4793 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4794 if (overlays == null) { 4795 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4796 return; 4797 } 4798 for (PackageParser.Package opkg : overlays.values()) { 4799 // Not much to do if idmap fails: we already logged the error 4800 // and we certainly don't want to abort installation of pkg simply 4801 // because an overlay didn't fit properly. For these reasons, 4802 // ignore the return value of createIdmapForPackagePairLI. 4803 createIdmapForPackagePairLI(pkg, opkg); 4804 } 4805 } 4806 4807 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4808 PackageParser.Package opkg) { 4809 if (!opkg.mTrustedOverlay) { 4810 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4811 opkg.baseCodePath + ": overlay not trusted"); 4812 return false; 4813 } 4814 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4815 if (overlaySet == null) { 4816 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4817 opkg.baseCodePath + " but target package has no known overlays"); 4818 return false; 4819 } 4820 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4821 // TODO: generate idmap for split APKs 4822 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4823 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4824 + opkg.baseCodePath); 4825 return false; 4826 } 4827 PackageParser.Package[] overlayArray = 4828 overlaySet.values().toArray(new PackageParser.Package[0]); 4829 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4830 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4831 return p1.mOverlayPriority - p2.mOverlayPriority; 4832 } 4833 }; 4834 Arrays.sort(overlayArray, cmp); 4835 4836 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4837 int i = 0; 4838 for (PackageParser.Package p : overlayArray) { 4839 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4840 } 4841 return true; 4842 } 4843 4844 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4845 final File[] files = dir.listFiles(); 4846 if (ArrayUtils.isEmpty(files)) { 4847 Log.d(TAG, "No files in app dir " + dir); 4848 return; 4849 } 4850 4851 if (DEBUG_PACKAGE_SCANNING) { 4852 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4853 + " flags=0x" + Integer.toHexString(parseFlags)); 4854 } 4855 4856 for (File file : files) { 4857 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4858 && !PackageInstallerService.isStageName(file.getName()); 4859 if (!isPackage) { 4860 // Ignore entries which are not packages 4861 continue; 4862 } 4863 try { 4864 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4865 scanFlags, currentTime, null); 4866 } catch (PackageManagerException e) { 4867 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4868 4869 // Delete invalid userdata apps 4870 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4871 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4872 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4873 if (file.isDirectory()) { 4874 mInstaller.rmPackageDir(file.getAbsolutePath()); 4875 } else { 4876 file.delete(); 4877 } 4878 } 4879 } 4880 } 4881 } 4882 4883 private static File getSettingsProblemFile() { 4884 File dataDir = Environment.getDataDirectory(); 4885 File systemDir = new File(dataDir, "system"); 4886 File fname = new File(systemDir, "uiderrors.txt"); 4887 return fname; 4888 } 4889 4890 static void reportSettingsProblem(int priority, String msg) { 4891 logCriticalInfo(priority, msg); 4892 } 4893 4894 static void logCriticalInfo(int priority, String msg) { 4895 Slog.println(priority, TAG, msg); 4896 EventLogTags.writePmCriticalInfo(msg); 4897 try { 4898 File fname = getSettingsProblemFile(); 4899 FileOutputStream out = new FileOutputStream(fname, true); 4900 PrintWriter pw = new FastPrintWriter(out); 4901 SimpleDateFormat formatter = new SimpleDateFormat(); 4902 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4903 pw.println(dateString + ": " + msg); 4904 pw.close(); 4905 FileUtils.setPermissions( 4906 fname.toString(), 4907 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4908 -1, -1); 4909 } catch (java.io.IOException e) { 4910 } 4911 } 4912 4913 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4914 PackageParser.Package pkg, File srcFile, int parseFlags) 4915 throws PackageManagerException { 4916 if (ps != null 4917 && ps.codePath.equals(srcFile) 4918 && ps.timeStamp == srcFile.lastModified() 4919 && !isCompatSignatureUpdateNeeded(pkg) 4920 && !isRecoverSignatureUpdateNeeded(pkg)) { 4921 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4922 if (ps.signatures.mSignatures != null 4923 && ps.signatures.mSignatures.length != 0 4924 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4925 // Optimization: reuse the existing cached certificates 4926 // if the package appears to be unchanged. 4927 pkg.mSignatures = ps.signatures.mSignatures; 4928 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4929 synchronized (mPackages) { 4930 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4931 } 4932 return; 4933 } 4934 4935 Slog.w(TAG, "PackageSetting for " + ps.name 4936 + " is missing signatures. Collecting certs again to recover them."); 4937 } else { 4938 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4939 } 4940 4941 try { 4942 pp.collectCertificates(pkg, parseFlags); 4943 pp.collectManifestDigest(pkg); 4944 } catch (PackageParserException e) { 4945 throw PackageManagerException.from(e); 4946 } 4947 } 4948 4949 /* 4950 * Scan a package and return the newly parsed package. 4951 * Returns null in case of errors and the error code is stored in mLastScanError 4952 */ 4953 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4954 long currentTime, UserHandle user) throws PackageManagerException { 4955 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4956 parseFlags |= mDefParseFlags; 4957 PackageParser pp = new PackageParser(); 4958 pp.setSeparateProcesses(mSeparateProcesses); 4959 pp.setOnlyCoreApps(mOnlyCore); 4960 pp.setDisplayMetrics(mMetrics); 4961 4962 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4963 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4964 } 4965 4966 final PackageParser.Package pkg; 4967 try { 4968 pkg = pp.parsePackage(scanFile, parseFlags); 4969 } catch (PackageParserException e) { 4970 throw PackageManagerException.from(e); 4971 } 4972 4973 PackageSetting ps = null; 4974 PackageSetting updatedPkg; 4975 // reader 4976 synchronized (mPackages) { 4977 // Look to see if we already know about this package. 4978 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4979 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4980 // This package has been renamed to its original name. Let's 4981 // use that. 4982 ps = mSettings.peekPackageLPr(oldName); 4983 } 4984 // If there was no original package, see one for the real package name. 4985 if (ps == null) { 4986 ps = mSettings.peekPackageLPr(pkg.packageName); 4987 } 4988 // Check to see if this package could be hiding/updating a system 4989 // package. Must look for it either under the original or real 4990 // package name depending on our state. 4991 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4992 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4993 } 4994 boolean updatedPkgBetter = false; 4995 // First check if this is a system package that may involve an update 4996 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4997 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4998 // it needs to drop FLAG_PRIVILEGED. 4999 if (locationIsPrivileged(scanFile)) { 5000 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5001 } else { 5002 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5003 } 5004 5005 if (ps != null && !ps.codePath.equals(scanFile)) { 5006 // The path has changed from what was last scanned... check the 5007 // version of the new path against what we have stored to determine 5008 // what to do. 5009 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5010 if (pkg.mVersionCode <= ps.versionCode) { 5011 // The system package has been updated and the code path does not match 5012 // Ignore entry. Skip it. 5013 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5014 + " ignored: updated version " + ps.versionCode 5015 + " better than this " + pkg.mVersionCode); 5016 if (!updatedPkg.codePath.equals(scanFile)) { 5017 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5018 + ps.name + " changing from " + updatedPkg.codePathString 5019 + " to " + scanFile); 5020 updatedPkg.codePath = scanFile; 5021 updatedPkg.codePathString = scanFile.toString(); 5022 updatedPkg.resourcePath = scanFile; 5023 updatedPkg.resourcePathString = scanFile.toString(); 5024 } 5025 updatedPkg.pkg = pkg; 5026 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5027 } else { 5028 // The current app on the system partition is better than 5029 // what we have updated to on the data partition; switch 5030 // back to the system partition version. 5031 // At this point, its safely assumed that package installation for 5032 // apps in system partition will go through. If not there won't be a working 5033 // version of the app 5034 // writer 5035 synchronized (mPackages) { 5036 // Just remove the loaded entries from package lists. 5037 mPackages.remove(ps.name); 5038 } 5039 5040 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5041 + " reverting from " + ps.codePathString 5042 + ": new version " + pkg.mVersionCode 5043 + " better than installed " + ps.versionCode); 5044 5045 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5046 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5047 getAppDexInstructionSets(ps)); 5048 synchronized (mInstallLock) { 5049 args.cleanUpResourcesLI(); 5050 } 5051 synchronized (mPackages) { 5052 mSettings.enableSystemPackageLPw(ps.name); 5053 } 5054 updatedPkgBetter = true; 5055 } 5056 } 5057 } 5058 5059 if (updatedPkg != null) { 5060 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5061 // initially 5062 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5063 5064 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5065 // flag set initially 5066 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5067 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5068 } 5069 } 5070 5071 // Verify certificates against what was last scanned 5072 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5073 5074 /* 5075 * A new system app appeared, but we already had a non-system one of the 5076 * same name installed earlier. 5077 */ 5078 boolean shouldHideSystemApp = false; 5079 if (updatedPkg == null && ps != null 5080 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5081 /* 5082 * Check to make sure the signatures match first. If they don't, 5083 * wipe the installed application and its data. 5084 */ 5085 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5086 != PackageManager.SIGNATURE_MATCH) { 5087 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5088 + " signatures don't match existing userdata copy; removing"); 5089 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5090 ps = null; 5091 } else { 5092 /* 5093 * If the newly-added system app is an older version than the 5094 * already installed version, hide it. It will be scanned later 5095 * and re-added like an update. 5096 */ 5097 if (pkg.mVersionCode <= ps.versionCode) { 5098 shouldHideSystemApp = true; 5099 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5100 + " but new version " + pkg.mVersionCode + " better than installed " 5101 + ps.versionCode + "; hiding system"); 5102 } else { 5103 /* 5104 * The newly found system app is a newer version that the 5105 * one previously installed. Simply remove the 5106 * already-installed application and replace it with our own 5107 * while keeping the application data. 5108 */ 5109 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5110 + " reverting from " + ps.codePathString + ": new version " 5111 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5112 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5113 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5114 getAppDexInstructionSets(ps)); 5115 synchronized (mInstallLock) { 5116 args.cleanUpResourcesLI(); 5117 } 5118 } 5119 } 5120 } 5121 5122 // The apk is forward locked (not public) if its code and resources 5123 // are kept in different files. (except for app in either system or 5124 // vendor path). 5125 // TODO grab this value from PackageSettings 5126 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5127 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5128 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5129 } 5130 } 5131 5132 // TODO: extend to support forward-locked splits 5133 String resourcePath = null; 5134 String baseResourcePath = null; 5135 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5136 if (ps != null && ps.resourcePathString != null) { 5137 resourcePath = ps.resourcePathString; 5138 baseResourcePath = ps.resourcePathString; 5139 } else { 5140 // Should not happen at all. Just log an error. 5141 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5142 } 5143 } else { 5144 resourcePath = pkg.codePath; 5145 baseResourcePath = pkg.baseCodePath; 5146 } 5147 5148 // Set application objects path explicitly. 5149 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5150 pkg.applicationInfo.setCodePath(pkg.codePath); 5151 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5152 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5153 pkg.applicationInfo.setResourcePath(resourcePath); 5154 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5155 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5156 5157 // Note that we invoke the following method only if we are about to unpack an application 5158 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5159 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5160 5161 /* 5162 * If the system app should be overridden by a previously installed 5163 * data, hide the system app now and let the /data/app scan pick it up 5164 * again. 5165 */ 5166 if (shouldHideSystemApp) { 5167 synchronized (mPackages) { 5168 /* 5169 * We have to grant systems permissions before we hide, because 5170 * grantPermissions will assume the package update is trying to 5171 * expand its permissions. 5172 */ 5173 grantPermissionsLPw(pkg, true, pkg.packageName); 5174 mSettings.disableSystemPackageLPw(pkg.packageName); 5175 } 5176 } 5177 5178 return scannedPkg; 5179 } 5180 5181 private static String fixProcessName(String defProcessName, 5182 String processName, int uid) { 5183 if (processName == null) { 5184 return defProcessName; 5185 } 5186 return processName; 5187 } 5188 5189 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5190 throws PackageManagerException { 5191 if (pkgSetting.signatures.mSignatures != null) { 5192 // Already existing package. Make sure signatures match 5193 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5194 == PackageManager.SIGNATURE_MATCH; 5195 if (!match) { 5196 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5197 == PackageManager.SIGNATURE_MATCH; 5198 } 5199 if (!match) { 5200 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5201 == PackageManager.SIGNATURE_MATCH; 5202 } 5203 if (!match) { 5204 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5205 + pkg.packageName + " signatures do not match the " 5206 + "previously installed version; ignoring!"); 5207 } 5208 } 5209 5210 // Check for shared user signatures 5211 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5212 // Already existing package. Make sure signatures match 5213 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5214 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5215 if (!match) { 5216 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5217 == PackageManager.SIGNATURE_MATCH; 5218 } 5219 if (!match) { 5220 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5221 == PackageManager.SIGNATURE_MATCH; 5222 } 5223 if (!match) { 5224 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5225 "Package " + pkg.packageName 5226 + " has no signatures that match those in shared user " 5227 + pkgSetting.sharedUser.name + "; ignoring!"); 5228 } 5229 } 5230 } 5231 5232 /** 5233 * Enforces that only the system UID or root's UID can call a method exposed 5234 * via Binder. 5235 * 5236 * @param message used as message if SecurityException is thrown 5237 * @throws SecurityException if the caller is not system or root 5238 */ 5239 private static final void enforceSystemOrRoot(String message) { 5240 final int uid = Binder.getCallingUid(); 5241 if (uid != Process.SYSTEM_UID && uid != 0) { 5242 throw new SecurityException(message); 5243 } 5244 } 5245 5246 @Override 5247 public void performBootDexOpt() { 5248 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5249 5250 // Before everything else, see whether we need to fstrim. 5251 try { 5252 IMountService ms = PackageHelper.getMountService(); 5253 if (ms != null) { 5254 final boolean isUpgrade = isUpgrade(); 5255 boolean doTrim = isUpgrade; 5256 if (doTrim) { 5257 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5258 } else { 5259 final long interval = android.provider.Settings.Global.getLong( 5260 mContext.getContentResolver(), 5261 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5262 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5263 if (interval > 0) { 5264 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5265 if (timeSinceLast > interval) { 5266 doTrim = true; 5267 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5268 + "; running immediately"); 5269 } 5270 } 5271 } 5272 if (doTrim) { 5273 if (!isFirstBoot()) { 5274 try { 5275 ActivityManagerNative.getDefault().showBootMessage( 5276 mContext.getResources().getString( 5277 R.string.android_upgrading_fstrim), true); 5278 } catch (RemoteException e) { 5279 } 5280 } 5281 ms.runMaintenance(); 5282 } 5283 } else { 5284 Slog.e(TAG, "Mount service unavailable!"); 5285 } 5286 } catch (RemoteException e) { 5287 // Can't happen; MountService is local 5288 } 5289 5290 final ArraySet<PackageParser.Package> pkgs; 5291 synchronized (mPackages) { 5292 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5293 } 5294 5295 if (pkgs != null) { 5296 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5297 // in case the device runs out of space. 5298 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5299 // Give priority to core apps. 5300 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5301 PackageParser.Package pkg = it.next(); 5302 if (pkg.coreApp) { 5303 if (DEBUG_DEXOPT) { 5304 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5305 } 5306 sortedPkgs.add(pkg); 5307 it.remove(); 5308 } 5309 } 5310 // Give priority to system apps that listen for pre boot complete. 5311 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5312 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5313 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5314 PackageParser.Package pkg = it.next(); 5315 if (pkgNames.contains(pkg.packageName)) { 5316 if (DEBUG_DEXOPT) { 5317 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5318 } 5319 sortedPkgs.add(pkg); 5320 it.remove(); 5321 } 5322 } 5323 // Give priority to system apps. 5324 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5325 PackageParser.Package pkg = it.next(); 5326 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5327 if (DEBUG_DEXOPT) { 5328 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5329 } 5330 sortedPkgs.add(pkg); 5331 it.remove(); 5332 } 5333 } 5334 // Give priority to updated system apps. 5335 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5336 PackageParser.Package pkg = it.next(); 5337 if (pkg.isUpdatedSystemApp()) { 5338 if (DEBUG_DEXOPT) { 5339 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5340 } 5341 sortedPkgs.add(pkg); 5342 it.remove(); 5343 } 5344 } 5345 // Give priority to apps that listen for boot complete. 5346 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5347 pkgNames = getPackageNamesForIntent(intent); 5348 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5349 PackageParser.Package pkg = it.next(); 5350 if (pkgNames.contains(pkg.packageName)) { 5351 if (DEBUG_DEXOPT) { 5352 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5353 } 5354 sortedPkgs.add(pkg); 5355 it.remove(); 5356 } 5357 } 5358 // Filter out packages that aren't recently used. 5359 filterRecentlyUsedApps(pkgs); 5360 // Add all remaining apps. 5361 for (PackageParser.Package pkg : pkgs) { 5362 if (DEBUG_DEXOPT) { 5363 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5364 } 5365 sortedPkgs.add(pkg); 5366 } 5367 5368 // If we want to be lazy, filter everything that wasn't recently used. 5369 if (mLazyDexOpt) { 5370 filterRecentlyUsedApps(sortedPkgs); 5371 } 5372 5373 int i = 0; 5374 int total = sortedPkgs.size(); 5375 File dataDir = Environment.getDataDirectory(); 5376 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5377 if (lowThreshold == 0) { 5378 throw new IllegalStateException("Invalid low memory threshold"); 5379 } 5380 for (PackageParser.Package pkg : sortedPkgs) { 5381 long usableSpace = dataDir.getUsableSpace(); 5382 if (usableSpace < lowThreshold) { 5383 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5384 break; 5385 } 5386 performBootDexOpt(pkg, ++i, total); 5387 } 5388 } 5389 } 5390 5391 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5392 // Filter out packages that aren't recently used. 5393 // 5394 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5395 // should do a full dexopt. 5396 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5397 int total = pkgs.size(); 5398 int skipped = 0; 5399 long now = System.currentTimeMillis(); 5400 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5401 PackageParser.Package pkg = i.next(); 5402 long then = pkg.mLastPackageUsageTimeInMills; 5403 if (then + mDexOptLRUThresholdInMills < now) { 5404 if (DEBUG_DEXOPT) { 5405 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5406 ((then == 0) ? "never" : new Date(then))); 5407 } 5408 i.remove(); 5409 skipped++; 5410 } 5411 } 5412 if (DEBUG_DEXOPT) { 5413 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5414 } 5415 } 5416 } 5417 5418 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5419 List<ResolveInfo> ris = null; 5420 try { 5421 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5422 intent, null, 0, UserHandle.USER_OWNER); 5423 } catch (RemoteException e) { 5424 } 5425 ArraySet<String> pkgNames = new ArraySet<String>(); 5426 if (ris != null) { 5427 for (ResolveInfo ri : ris) { 5428 pkgNames.add(ri.activityInfo.packageName); 5429 } 5430 } 5431 return pkgNames; 5432 } 5433 5434 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5435 if (DEBUG_DEXOPT) { 5436 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5437 } 5438 if (!isFirstBoot()) { 5439 try { 5440 ActivityManagerNative.getDefault().showBootMessage( 5441 mContext.getResources().getString(R.string.android_upgrading_apk, 5442 curr, total), true); 5443 } catch (RemoteException e) { 5444 } 5445 } 5446 PackageParser.Package p = pkg; 5447 synchronized (mInstallLock) { 5448 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5449 false /* force dex */, false /* defer */, true /* include dependencies */); 5450 } 5451 } 5452 5453 @Override 5454 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5455 return performDexOpt(packageName, instructionSet, false); 5456 } 5457 5458 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5459 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5460 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5461 if (!dexopt && !updateUsage) { 5462 // We aren't going to dexopt or update usage, so bail early. 5463 return false; 5464 } 5465 PackageParser.Package p; 5466 final String targetInstructionSet; 5467 synchronized (mPackages) { 5468 p = mPackages.get(packageName); 5469 if (p == null) { 5470 return false; 5471 } 5472 if (updateUsage) { 5473 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5474 } 5475 mPackageUsage.write(false); 5476 if (!dexopt) { 5477 // We aren't going to dexopt, so bail early. 5478 return false; 5479 } 5480 5481 targetInstructionSet = instructionSet != null ? instructionSet : 5482 getPrimaryInstructionSet(p.applicationInfo); 5483 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5484 return false; 5485 } 5486 } 5487 5488 synchronized (mInstallLock) { 5489 final String[] instructionSets = new String[] { targetInstructionSet }; 5490 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5491 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5492 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5493 } 5494 } 5495 5496 public ArraySet<String> getPackagesThatNeedDexOpt() { 5497 ArraySet<String> pkgs = null; 5498 synchronized (mPackages) { 5499 for (PackageParser.Package p : mPackages.values()) { 5500 if (DEBUG_DEXOPT) { 5501 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5502 } 5503 if (!p.mDexOptPerformed.isEmpty()) { 5504 continue; 5505 } 5506 if (pkgs == null) { 5507 pkgs = new ArraySet<String>(); 5508 } 5509 pkgs.add(p.packageName); 5510 } 5511 } 5512 return pkgs; 5513 } 5514 5515 public void shutdown() { 5516 mPackageUsage.write(true); 5517 } 5518 5519 @Override 5520 public void forceDexOpt(String packageName) { 5521 enforceSystemOrRoot("forceDexOpt"); 5522 5523 PackageParser.Package pkg; 5524 synchronized (mPackages) { 5525 pkg = mPackages.get(packageName); 5526 if (pkg == null) { 5527 throw new IllegalArgumentException("Missing package: " + packageName); 5528 } 5529 } 5530 5531 synchronized (mInstallLock) { 5532 final String[] instructionSets = new String[] { 5533 getPrimaryInstructionSet(pkg.applicationInfo) }; 5534 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5535 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5536 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5537 throw new IllegalStateException("Failed to dexopt: " + res); 5538 } 5539 } 5540 } 5541 5542 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5543 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5544 Slog.w(TAG, "Unable to update from " + oldPkg.name 5545 + " to " + newPkg.packageName 5546 + ": old package not in system partition"); 5547 return false; 5548 } else if (mPackages.get(oldPkg.name) != null) { 5549 Slog.w(TAG, "Unable to update from " + oldPkg.name 5550 + " to " + newPkg.packageName 5551 + ": old package still exists"); 5552 return false; 5553 } 5554 return true; 5555 } 5556 5557 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5558 int[] users = sUserManager.getUserIds(); 5559 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5560 if (res < 0) { 5561 return res; 5562 } 5563 for (int user : users) { 5564 if (user != 0) { 5565 res = mInstaller.createUserData(volumeUuid, packageName, 5566 UserHandle.getUid(user, uid), user, seinfo); 5567 if (res < 0) { 5568 return res; 5569 } 5570 } 5571 } 5572 return res; 5573 } 5574 5575 private int removeDataDirsLI(String volumeUuid, String packageName) { 5576 int[] users = sUserManager.getUserIds(); 5577 int res = 0; 5578 for (int user : users) { 5579 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5580 if (resInner < 0) { 5581 res = resInner; 5582 } 5583 } 5584 5585 return res; 5586 } 5587 5588 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5589 int[] users = sUserManager.getUserIds(); 5590 int res = 0; 5591 for (int user : users) { 5592 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5593 if (resInner < 0) { 5594 res = resInner; 5595 } 5596 } 5597 return res; 5598 } 5599 5600 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5601 PackageParser.Package changingLib) { 5602 if (file.path != null) { 5603 usesLibraryFiles.add(file.path); 5604 return; 5605 } 5606 PackageParser.Package p = mPackages.get(file.apk); 5607 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5608 // If we are doing this while in the middle of updating a library apk, 5609 // then we need to make sure to use that new apk for determining the 5610 // dependencies here. (We haven't yet finished committing the new apk 5611 // to the package manager state.) 5612 if (p == null || p.packageName.equals(changingLib.packageName)) { 5613 p = changingLib; 5614 } 5615 } 5616 if (p != null) { 5617 usesLibraryFiles.addAll(p.getAllCodePaths()); 5618 } 5619 } 5620 5621 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5622 PackageParser.Package changingLib) throws PackageManagerException { 5623 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5624 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5625 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5626 for (int i=0; i<N; i++) { 5627 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5628 if (file == null) { 5629 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5630 "Package " + pkg.packageName + " requires unavailable shared library " 5631 + pkg.usesLibraries.get(i) + "; failing!"); 5632 } 5633 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5634 } 5635 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5636 for (int i=0; i<N; i++) { 5637 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5638 if (file == null) { 5639 Slog.w(TAG, "Package " + pkg.packageName 5640 + " desires unavailable shared library " 5641 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5642 } else { 5643 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5644 } 5645 } 5646 N = usesLibraryFiles.size(); 5647 if (N > 0) { 5648 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5649 } else { 5650 pkg.usesLibraryFiles = null; 5651 } 5652 } 5653 } 5654 5655 private static boolean hasString(List<String> list, List<String> which) { 5656 if (list == null) { 5657 return false; 5658 } 5659 for (int i=list.size()-1; i>=0; i--) { 5660 for (int j=which.size()-1; j>=0; j--) { 5661 if (which.get(j).equals(list.get(i))) { 5662 return true; 5663 } 5664 } 5665 } 5666 return false; 5667 } 5668 5669 private void updateAllSharedLibrariesLPw() { 5670 for (PackageParser.Package pkg : mPackages.values()) { 5671 try { 5672 updateSharedLibrariesLPw(pkg, null); 5673 } catch (PackageManagerException e) { 5674 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5675 } 5676 } 5677 } 5678 5679 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5680 PackageParser.Package changingPkg) { 5681 ArrayList<PackageParser.Package> res = null; 5682 for (PackageParser.Package pkg : mPackages.values()) { 5683 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5684 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5685 if (res == null) { 5686 res = new ArrayList<PackageParser.Package>(); 5687 } 5688 res.add(pkg); 5689 try { 5690 updateSharedLibrariesLPw(pkg, changingPkg); 5691 } catch (PackageManagerException e) { 5692 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5693 } 5694 } 5695 } 5696 return res; 5697 } 5698 5699 /** 5700 * Derive the value of the {@code cpuAbiOverride} based on the provided 5701 * value and an optional stored value from the package settings. 5702 */ 5703 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5704 String cpuAbiOverride = null; 5705 5706 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5707 cpuAbiOverride = null; 5708 } else if (abiOverride != null) { 5709 cpuAbiOverride = abiOverride; 5710 } else if (settings != null) { 5711 cpuAbiOverride = settings.cpuAbiOverrideString; 5712 } 5713 5714 return cpuAbiOverride; 5715 } 5716 5717 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5718 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5719 boolean success = false; 5720 try { 5721 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5722 currentTime, user); 5723 success = true; 5724 return res; 5725 } finally { 5726 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5727 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5728 } 5729 } 5730 } 5731 5732 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5733 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5734 final File scanFile = new File(pkg.codePath); 5735 if (pkg.applicationInfo.getCodePath() == null || 5736 pkg.applicationInfo.getResourcePath() == null) { 5737 // Bail out. The resource and code paths haven't been set. 5738 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5739 "Code and resource paths haven't been set correctly"); 5740 } 5741 5742 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5743 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5744 } else { 5745 // Only allow system apps to be flagged as core apps. 5746 pkg.coreApp = false; 5747 } 5748 5749 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5750 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5751 } 5752 5753 if (mCustomResolverComponentName != null && 5754 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5755 setUpCustomResolverActivity(pkg); 5756 } 5757 5758 if (pkg.packageName.equals("android")) { 5759 synchronized (mPackages) { 5760 if (mAndroidApplication != null) { 5761 Slog.w(TAG, "*************************************************"); 5762 Slog.w(TAG, "Core android package being redefined. Skipping."); 5763 Slog.w(TAG, " file=" + scanFile); 5764 Slog.w(TAG, "*************************************************"); 5765 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5766 "Core android package being redefined. Skipping."); 5767 } 5768 5769 // Set up information for our fall-back user intent resolution activity. 5770 mPlatformPackage = pkg; 5771 pkg.mVersionCode = mSdkVersion; 5772 mAndroidApplication = pkg.applicationInfo; 5773 5774 if (!mResolverReplaced) { 5775 mResolveActivity.applicationInfo = mAndroidApplication; 5776 mResolveActivity.name = ResolverActivity.class.getName(); 5777 mResolveActivity.packageName = mAndroidApplication.packageName; 5778 mResolveActivity.processName = "system:ui"; 5779 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5780 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5781 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5782 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5783 mResolveActivity.exported = true; 5784 mResolveActivity.enabled = true; 5785 mResolveInfo.activityInfo = mResolveActivity; 5786 mResolveInfo.priority = 0; 5787 mResolveInfo.preferredOrder = 0; 5788 mResolveInfo.match = 0; 5789 mResolveComponentName = new ComponentName( 5790 mAndroidApplication.packageName, mResolveActivity.name); 5791 } 5792 } 5793 } 5794 5795 if (DEBUG_PACKAGE_SCANNING) { 5796 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5797 Log.d(TAG, "Scanning package " + pkg.packageName); 5798 } 5799 5800 if (mPackages.containsKey(pkg.packageName) 5801 || mSharedLibraries.containsKey(pkg.packageName)) { 5802 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5803 "Application package " + pkg.packageName 5804 + " already installed. Skipping duplicate."); 5805 } 5806 5807 // If we're only installing presumed-existing packages, require that the 5808 // scanned APK is both already known and at the path previously established 5809 // for it. Previously unknown packages we pick up normally, but if we have an 5810 // a priori expectation about this package's install presence, enforce it. 5811 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5812 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5813 if (known != null) { 5814 if (DEBUG_PACKAGE_SCANNING) { 5815 Log.d(TAG, "Examining " + pkg.codePath 5816 + " and requiring known paths " + known.codePathString 5817 + " & " + known.resourcePathString); 5818 } 5819 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5820 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5821 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5822 "Application package " + pkg.packageName 5823 + " found at " + pkg.applicationInfo.getCodePath() 5824 + " but expected at " + known.codePathString + "; ignoring."); 5825 } 5826 } 5827 } 5828 5829 // Initialize package source and resource directories 5830 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5831 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5832 5833 SharedUserSetting suid = null; 5834 PackageSetting pkgSetting = null; 5835 5836 if (!isSystemApp(pkg)) { 5837 // Only system apps can use these features. 5838 pkg.mOriginalPackages = null; 5839 pkg.mRealPackage = null; 5840 pkg.mAdoptPermissions = null; 5841 } 5842 5843 // writer 5844 synchronized (mPackages) { 5845 if (pkg.mSharedUserId != null) { 5846 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5847 if (suid == null) { 5848 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5849 "Creating application package " + pkg.packageName 5850 + " for shared user failed"); 5851 } 5852 if (DEBUG_PACKAGE_SCANNING) { 5853 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5854 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5855 + "): packages=" + suid.packages); 5856 } 5857 } 5858 5859 // Check if we are renaming from an original package name. 5860 PackageSetting origPackage = null; 5861 String realName = null; 5862 if (pkg.mOriginalPackages != null) { 5863 // This package may need to be renamed to a previously 5864 // installed name. Let's check on that... 5865 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5866 if (pkg.mOriginalPackages.contains(renamed)) { 5867 // This package had originally been installed as the 5868 // original name, and we have already taken care of 5869 // transitioning to the new one. Just update the new 5870 // one to continue using the old name. 5871 realName = pkg.mRealPackage; 5872 if (!pkg.packageName.equals(renamed)) { 5873 // Callers into this function may have already taken 5874 // care of renaming the package; only do it here if 5875 // it is not already done. 5876 pkg.setPackageName(renamed); 5877 } 5878 5879 } else { 5880 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5881 if ((origPackage = mSettings.peekPackageLPr( 5882 pkg.mOriginalPackages.get(i))) != null) { 5883 // We do have the package already installed under its 5884 // original name... should we use it? 5885 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5886 // New package is not compatible with original. 5887 origPackage = null; 5888 continue; 5889 } else if (origPackage.sharedUser != null) { 5890 // Make sure uid is compatible between packages. 5891 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5892 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5893 + " to " + pkg.packageName + ": old uid " 5894 + origPackage.sharedUser.name 5895 + " differs from " + pkg.mSharedUserId); 5896 origPackage = null; 5897 continue; 5898 } 5899 } else { 5900 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5901 + pkg.packageName + " to old name " + origPackage.name); 5902 } 5903 break; 5904 } 5905 } 5906 } 5907 } 5908 5909 if (mTransferedPackages.contains(pkg.packageName)) { 5910 Slog.w(TAG, "Package " + pkg.packageName 5911 + " was transferred to another, but its .apk remains"); 5912 } 5913 5914 // Just create the setting, don't add it yet. For already existing packages 5915 // the PkgSetting exists already and doesn't have to be created. 5916 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5917 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5918 pkg.applicationInfo.primaryCpuAbi, 5919 pkg.applicationInfo.secondaryCpuAbi, 5920 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5921 user, false); 5922 if (pkgSetting == null) { 5923 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5924 "Creating application package " + pkg.packageName + " failed"); 5925 } 5926 5927 if (pkgSetting.origPackage != null) { 5928 // If we are first transitioning from an original package, 5929 // fix up the new package's name now. We need to do this after 5930 // looking up the package under its new name, so getPackageLP 5931 // can take care of fiddling things correctly. 5932 pkg.setPackageName(origPackage.name); 5933 5934 // File a report about this. 5935 String msg = "New package " + pkgSetting.realName 5936 + " renamed to replace old package " + pkgSetting.name; 5937 reportSettingsProblem(Log.WARN, msg); 5938 5939 // Make a note of it. 5940 mTransferedPackages.add(origPackage.name); 5941 5942 // No longer need to retain this. 5943 pkgSetting.origPackage = null; 5944 } 5945 5946 if (realName != null) { 5947 // Make a note of it. 5948 mTransferedPackages.add(pkg.packageName); 5949 } 5950 5951 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5952 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5953 } 5954 5955 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5956 // Check all shared libraries and map to their actual file path. 5957 // We only do this here for apps not on a system dir, because those 5958 // are the only ones that can fail an install due to this. We 5959 // will take care of the system apps by updating all of their 5960 // library paths after the scan is done. 5961 updateSharedLibrariesLPw(pkg, null); 5962 } 5963 5964 if (mFoundPolicyFile) { 5965 SELinuxMMAC.assignSeinfoValue(pkg); 5966 } 5967 5968 pkg.applicationInfo.uid = pkgSetting.appId; 5969 pkg.mExtras = pkgSetting; 5970 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5971 try { 5972 verifySignaturesLP(pkgSetting, pkg); 5973 // We just determined the app is signed correctly, so bring 5974 // over the latest parsed certs. 5975 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5976 } catch (PackageManagerException e) { 5977 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5978 throw e; 5979 } 5980 // The signature has changed, but this package is in the system 5981 // image... let's recover! 5982 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5983 // However... if this package is part of a shared user, but it 5984 // doesn't match the signature of the shared user, let's fail. 5985 // What this means is that you can't change the signatures 5986 // associated with an overall shared user, which doesn't seem all 5987 // that unreasonable. 5988 if (pkgSetting.sharedUser != null) { 5989 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5990 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5991 throw new PackageManagerException( 5992 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5993 "Signature mismatch for shared user : " 5994 + pkgSetting.sharedUser); 5995 } 5996 } 5997 // File a report about this. 5998 String msg = "System package " + pkg.packageName 5999 + " signature changed; retaining data."; 6000 reportSettingsProblem(Log.WARN, msg); 6001 } 6002 } else { 6003 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6004 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6005 + pkg.packageName + " upgrade keys do not match the " 6006 + "previously installed version"); 6007 } else { 6008 // We just determined the app is signed correctly, so bring 6009 // over the latest parsed certs. 6010 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6011 } 6012 } 6013 // Verify that this new package doesn't have any content providers 6014 // that conflict with existing packages. Only do this if the 6015 // package isn't already installed, since we don't want to break 6016 // things that are installed. 6017 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6018 final int N = pkg.providers.size(); 6019 int i; 6020 for (i=0; i<N; i++) { 6021 PackageParser.Provider p = pkg.providers.get(i); 6022 if (p.info.authority != null) { 6023 String names[] = p.info.authority.split(";"); 6024 for (int j = 0; j < names.length; j++) { 6025 if (mProvidersByAuthority.containsKey(names[j])) { 6026 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6027 final String otherPackageName = 6028 ((other != null && other.getComponentName() != null) ? 6029 other.getComponentName().getPackageName() : "?"); 6030 throw new PackageManagerException( 6031 INSTALL_FAILED_CONFLICTING_PROVIDER, 6032 "Can't install because provider name " + names[j] 6033 + " (in package " + pkg.applicationInfo.packageName 6034 + ") is already used by " + otherPackageName); 6035 } 6036 } 6037 } 6038 } 6039 } 6040 6041 if (pkg.mAdoptPermissions != null) { 6042 // This package wants to adopt ownership of permissions from 6043 // another package. 6044 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6045 final String origName = pkg.mAdoptPermissions.get(i); 6046 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6047 if (orig != null) { 6048 if (verifyPackageUpdateLPr(orig, pkg)) { 6049 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6050 + pkg.packageName); 6051 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6052 } 6053 } 6054 } 6055 } 6056 } 6057 6058 final String pkgName = pkg.packageName; 6059 6060 final long scanFileTime = scanFile.lastModified(); 6061 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6062 pkg.applicationInfo.processName = fixProcessName( 6063 pkg.applicationInfo.packageName, 6064 pkg.applicationInfo.processName, 6065 pkg.applicationInfo.uid); 6066 6067 File dataPath; 6068 if (mPlatformPackage == pkg) { 6069 // The system package is special. 6070 dataPath = new File(Environment.getDataDirectory(), "system"); 6071 6072 pkg.applicationInfo.dataDir = dataPath.getPath(); 6073 6074 } else { 6075 // This is a normal package, need to make its data directory. 6076 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6077 UserHandle.USER_OWNER); 6078 6079 boolean uidError = false; 6080 if (dataPath.exists()) { 6081 int currentUid = 0; 6082 try { 6083 StructStat stat = Os.stat(dataPath.getPath()); 6084 currentUid = stat.st_uid; 6085 } catch (ErrnoException e) { 6086 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6087 } 6088 6089 // If we have mismatched owners for the data path, we have a problem. 6090 if (currentUid != pkg.applicationInfo.uid) { 6091 boolean recovered = false; 6092 if (currentUid == 0) { 6093 // The directory somehow became owned by root. Wow. 6094 // This is probably because the system was stopped while 6095 // installd was in the middle of messing with its libs 6096 // directory. Ask installd to fix that. 6097 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6098 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6099 if (ret >= 0) { 6100 recovered = true; 6101 String msg = "Package " + pkg.packageName 6102 + " unexpectedly changed to uid 0; recovered to " + 6103 + pkg.applicationInfo.uid; 6104 reportSettingsProblem(Log.WARN, msg); 6105 } 6106 } 6107 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6108 || (scanFlags&SCAN_BOOTING) != 0)) { 6109 // If this is a system app, we can at least delete its 6110 // current data so the application will still work. 6111 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6112 if (ret >= 0) { 6113 // TODO: Kill the processes first 6114 // Old data gone! 6115 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6116 ? "System package " : "Third party package "; 6117 String msg = prefix + pkg.packageName 6118 + " has changed from uid: " 6119 + currentUid + " to " 6120 + pkg.applicationInfo.uid + "; old data erased"; 6121 reportSettingsProblem(Log.WARN, msg); 6122 recovered = true; 6123 6124 // And now re-install the app. 6125 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6126 pkg.applicationInfo.seinfo); 6127 if (ret == -1) { 6128 // Ack should not happen! 6129 msg = prefix + pkg.packageName 6130 + " could not have data directory re-created after delete."; 6131 reportSettingsProblem(Log.WARN, msg); 6132 throw new PackageManagerException( 6133 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6134 } 6135 } 6136 if (!recovered) { 6137 mHasSystemUidErrors = true; 6138 } 6139 } else if (!recovered) { 6140 // If we allow this install to proceed, we will be broken. 6141 // Abort, abort! 6142 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6143 "scanPackageLI"); 6144 } 6145 if (!recovered) { 6146 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6147 + pkg.applicationInfo.uid + "/fs_" 6148 + currentUid; 6149 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6150 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6151 String msg = "Package " + pkg.packageName 6152 + " has mismatched uid: " 6153 + currentUid + " on disk, " 6154 + pkg.applicationInfo.uid + " in settings"; 6155 // writer 6156 synchronized (mPackages) { 6157 mSettings.mReadMessages.append(msg); 6158 mSettings.mReadMessages.append('\n'); 6159 uidError = true; 6160 if (!pkgSetting.uidError) { 6161 reportSettingsProblem(Log.ERROR, msg); 6162 } 6163 } 6164 } 6165 } 6166 pkg.applicationInfo.dataDir = dataPath.getPath(); 6167 if (mShouldRestoreconData) { 6168 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6169 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6170 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6171 } 6172 } else { 6173 if (DEBUG_PACKAGE_SCANNING) { 6174 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6175 Log.v(TAG, "Want this data dir: " + dataPath); 6176 } 6177 //invoke installer to do the actual installation 6178 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6179 pkg.applicationInfo.seinfo); 6180 if (ret < 0) { 6181 // Error from installer 6182 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6183 "Unable to create data dirs [errorCode=" + ret + "]"); 6184 } 6185 6186 if (dataPath.exists()) { 6187 pkg.applicationInfo.dataDir = dataPath.getPath(); 6188 } else { 6189 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6190 pkg.applicationInfo.dataDir = null; 6191 } 6192 } 6193 6194 pkgSetting.uidError = uidError; 6195 } 6196 6197 final String path = scanFile.getPath(); 6198 final String codePath = pkg.applicationInfo.getCodePath(); 6199 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6200 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6201 setBundledAppAbisAndRoots(pkg, pkgSetting); 6202 6203 // If we haven't found any native libraries for the app, check if it has 6204 // renderscript code. We'll need to force the app to 32 bit if it has 6205 // renderscript bitcode. 6206 if (pkg.applicationInfo.primaryCpuAbi == null 6207 && pkg.applicationInfo.secondaryCpuAbi == null 6208 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6209 NativeLibraryHelper.Handle handle = null; 6210 try { 6211 handle = NativeLibraryHelper.Handle.create(scanFile); 6212 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6213 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6214 } 6215 } catch (IOException ioe) { 6216 Slog.w(TAG, "Error scanning system app : " + ioe); 6217 } finally { 6218 IoUtils.closeQuietly(handle); 6219 } 6220 } 6221 6222 setNativeLibraryPaths(pkg); 6223 } else { 6224 // TODO: We can probably be smarter about this stuff. For installed apps, 6225 // we can calculate this information at install time once and for all. For 6226 // system apps, we can probably assume that this information doesn't change 6227 // after the first boot scan. As things stand, we do lots of unnecessary work. 6228 6229 // Give ourselves some initial paths; we'll come back for another 6230 // pass once we've determined ABI below. 6231 setNativeLibraryPaths(pkg); 6232 6233 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6234 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6235 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6236 6237 NativeLibraryHelper.Handle handle = null; 6238 try { 6239 handle = NativeLibraryHelper.Handle.create(scanFile); 6240 // TODO(multiArch): This can be null for apps that didn't go through the 6241 // usual installation process. We can calculate it again, like we 6242 // do during install time. 6243 // 6244 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6245 // unnecessary. 6246 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6247 6248 // Null out the abis so that they can be recalculated. 6249 pkg.applicationInfo.primaryCpuAbi = null; 6250 pkg.applicationInfo.secondaryCpuAbi = null; 6251 if (isMultiArch(pkg.applicationInfo)) { 6252 // Warn if we've set an abiOverride for multi-lib packages.. 6253 // By definition, we need to copy both 32 and 64 bit libraries for 6254 // such packages. 6255 if (pkg.cpuAbiOverride != null 6256 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6257 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6258 } 6259 6260 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6261 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6262 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6263 if (isAsec) { 6264 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6265 } else { 6266 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6267 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6268 useIsaSpecificSubdirs); 6269 } 6270 } 6271 6272 maybeThrowExceptionForMultiArchCopy( 6273 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6274 6275 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6276 if (isAsec) { 6277 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6278 } else { 6279 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6280 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6281 useIsaSpecificSubdirs); 6282 } 6283 } 6284 6285 maybeThrowExceptionForMultiArchCopy( 6286 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6287 6288 if (abi64 >= 0) { 6289 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6290 } 6291 6292 if (abi32 >= 0) { 6293 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6294 if (abi64 >= 0) { 6295 pkg.applicationInfo.secondaryCpuAbi = abi; 6296 } else { 6297 pkg.applicationInfo.primaryCpuAbi = abi; 6298 } 6299 } 6300 } else { 6301 String[] abiList = (cpuAbiOverride != null) ? 6302 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6303 6304 // Enable gross and lame hacks for apps that are built with old 6305 // SDK tools. We must scan their APKs for renderscript bitcode and 6306 // not launch them if it's present. Don't bother checking on devices 6307 // that don't have 64 bit support. 6308 boolean needsRenderScriptOverride = false; 6309 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6310 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6311 abiList = Build.SUPPORTED_32_BIT_ABIS; 6312 needsRenderScriptOverride = true; 6313 } 6314 6315 final int copyRet; 6316 if (isAsec) { 6317 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6318 } else { 6319 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6320 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6321 } 6322 6323 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6324 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6325 "Error unpackaging native libs for app, errorCode=" + copyRet); 6326 } 6327 6328 if (copyRet >= 0) { 6329 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6330 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6331 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6332 } else if (needsRenderScriptOverride) { 6333 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6334 } 6335 } 6336 } catch (IOException ioe) { 6337 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6338 } finally { 6339 IoUtils.closeQuietly(handle); 6340 } 6341 6342 // Now that we've calculated the ABIs and determined if it's an internal app, 6343 // we will go ahead and populate the nativeLibraryPath. 6344 setNativeLibraryPaths(pkg); 6345 6346 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6347 final int[] userIds = sUserManager.getUserIds(); 6348 synchronized (mInstallLock) { 6349 // Create a native library symlink only if we have native libraries 6350 // and if the native libraries are 32 bit libraries. We do not provide 6351 // this symlink for 64 bit libraries. 6352 if (pkg.applicationInfo.primaryCpuAbi != null && 6353 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6354 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6355 for (int userId : userIds) { 6356 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6357 nativeLibPath, userId) < 0) { 6358 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6359 "Failed linking native library dir (user=" + userId + ")"); 6360 } 6361 } 6362 } 6363 } 6364 } 6365 6366 // This is a special case for the "system" package, where the ABI is 6367 // dictated by the zygote configuration (and init.rc). We should keep track 6368 // of this ABI so that we can deal with "normal" applications that run under 6369 // the same UID correctly. 6370 if (mPlatformPackage == pkg) { 6371 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6372 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6373 } 6374 6375 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6376 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6377 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6378 // Copy the derived override back to the parsed package, so that we can 6379 // update the package settings accordingly. 6380 pkg.cpuAbiOverride = cpuAbiOverride; 6381 6382 if (DEBUG_ABI_SELECTION) { 6383 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6384 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6385 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6386 } 6387 6388 // Push the derived path down into PackageSettings so we know what to 6389 // clean up at uninstall time. 6390 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6391 6392 if (DEBUG_ABI_SELECTION) { 6393 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6394 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6395 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6396 } 6397 6398 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6399 // We don't do this here during boot because we can do it all 6400 // at once after scanning all existing packages. 6401 // 6402 // We also do this *before* we perform dexopt on this package, so that 6403 // we can avoid redundant dexopts, and also to make sure we've got the 6404 // code and package path correct. 6405 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6406 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6407 } 6408 6409 if ((scanFlags & SCAN_NO_DEX) == 0) { 6410 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6411 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6412 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6413 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6414 } 6415 } 6416 if (mFactoryTest && pkg.requestedPermissions.contains( 6417 android.Manifest.permission.FACTORY_TEST)) { 6418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6419 } 6420 6421 ArrayList<PackageParser.Package> clientLibPkgs = null; 6422 6423 // writer 6424 synchronized (mPackages) { 6425 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6426 // Only system apps can add new shared libraries. 6427 if (pkg.libraryNames != null) { 6428 for (int i=0; i<pkg.libraryNames.size(); i++) { 6429 String name = pkg.libraryNames.get(i); 6430 boolean allowed = false; 6431 if (pkg.isUpdatedSystemApp()) { 6432 // New library entries can only be added through the 6433 // system image. This is important to get rid of a lot 6434 // of nasty edge cases: for example if we allowed a non- 6435 // system update of the app to add a library, then uninstalling 6436 // the update would make the library go away, and assumptions 6437 // we made such as through app install filtering would now 6438 // have allowed apps on the device which aren't compatible 6439 // with it. Better to just have the restriction here, be 6440 // conservative, and create many fewer cases that can negatively 6441 // impact the user experience. 6442 final PackageSetting sysPs = mSettings 6443 .getDisabledSystemPkgLPr(pkg.packageName); 6444 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6445 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6446 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6447 allowed = true; 6448 allowed = true; 6449 break; 6450 } 6451 } 6452 } 6453 } else { 6454 allowed = true; 6455 } 6456 if (allowed) { 6457 if (!mSharedLibraries.containsKey(name)) { 6458 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6459 } else if (!name.equals(pkg.packageName)) { 6460 Slog.w(TAG, "Package " + pkg.packageName + " library " 6461 + name + " already exists; skipping"); 6462 } 6463 } else { 6464 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6465 + name + " that is not declared on system image; skipping"); 6466 } 6467 } 6468 if ((scanFlags&SCAN_BOOTING) == 0) { 6469 // If we are not booting, we need to update any applications 6470 // that are clients of our shared library. If we are booting, 6471 // this will all be done once the scan is complete. 6472 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6473 } 6474 } 6475 } 6476 } 6477 6478 // We also need to dexopt any apps that are dependent on this library. Note that 6479 // if these fail, we should abort the install since installing the library will 6480 // result in some apps being broken. 6481 if (clientLibPkgs != null) { 6482 if ((scanFlags & SCAN_NO_DEX) == 0) { 6483 for (int i = 0; i < clientLibPkgs.size(); i++) { 6484 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6485 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6486 null /* instruction sets */, forceDex, 6487 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6488 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6489 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6490 "scanPackageLI failed to dexopt clientLibPkgs"); 6491 } 6492 } 6493 } 6494 } 6495 6496 // Also need to kill any apps that are dependent on the library. 6497 if (clientLibPkgs != null) { 6498 for (int i=0; i<clientLibPkgs.size(); i++) { 6499 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6500 killApplication(clientPkg.applicationInfo.packageName, 6501 clientPkg.applicationInfo.uid, "update lib"); 6502 } 6503 } 6504 6505 // writer 6506 synchronized (mPackages) { 6507 // We don't expect installation to fail beyond this point 6508 6509 // Add the new setting to mSettings 6510 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6511 // Add the new setting to mPackages 6512 mPackages.put(pkg.applicationInfo.packageName, pkg); 6513 // Make sure we don't accidentally delete its data. 6514 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6515 while (iter.hasNext()) { 6516 PackageCleanItem item = iter.next(); 6517 if (pkgName.equals(item.packageName)) { 6518 iter.remove(); 6519 } 6520 } 6521 6522 // Take care of first install / last update times. 6523 if (currentTime != 0) { 6524 if (pkgSetting.firstInstallTime == 0) { 6525 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6526 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6527 pkgSetting.lastUpdateTime = currentTime; 6528 } 6529 } else if (pkgSetting.firstInstallTime == 0) { 6530 // We need *something*. Take time time stamp of the file. 6531 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6532 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6533 if (scanFileTime != pkgSetting.timeStamp) { 6534 // A package on the system image has changed; consider this 6535 // to be an update. 6536 pkgSetting.lastUpdateTime = scanFileTime; 6537 } 6538 } 6539 6540 // Add the package's KeySets to the global KeySetManagerService 6541 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6542 try { 6543 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6544 if (pkg.mKeySetMapping != null) { 6545 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6546 if (pkg.mUpgradeKeySets != null) { 6547 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6548 } 6549 } 6550 } catch (NullPointerException e) { 6551 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6552 } catch (IllegalArgumentException e) { 6553 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6554 } 6555 6556 int N = pkg.providers.size(); 6557 StringBuilder r = null; 6558 int i; 6559 for (i=0; i<N; i++) { 6560 PackageParser.Provider p = pkg.providers.get(i); 6561 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6562 p.info.processName, pkg.applicationInfo.uid); 6563 mProviders.addProvider(p); 6564 p.syncable = p.info.isSyncable; 6565 if (p.info.authority != null) { 6566 String names[] = p.info.authority.split(";"); 6567 p.info.authority = null; 6568 for (int j = 0; j < names.length; j++) { 6569 if (j == 1 && p.syncable) { 6570 // We only want the first authority for a provider to possibly be 6571 // syncable, so if we already added this provider using a different 6572 // authority clear the syncable flag. We copy the provider before 6573 // changing it because the mProviders object contains a reference 6574 // to a provider that we don't want to change. 6575 // Only do this for the second authority since the resulting provider 6576 // object can be the same for all future authorities for this provider. 6577 p = new PackageParser.Provider(p); 6578 p.syncable = false; 6579 } 6580 if (!mProvidersByAuthority.containsKey(names[j])) { 6581 mProvidersByAuthority.put(names[j], p); 6582 if (p.info.authority == null) { 6583 p.info.authority = names[j]; 6584 } else { 6585 p.info.authority = p.info.authority + ";" + names[j]; 6586 } 6587 if (DEBUG_PACKAGE_SCANNING) { 6588 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6589 Log.d(TAG, "Registered content provider: " + names[j] 6590 + ", className = " + p.info.name + ", isSyncable = " 6591 + p.info.isSyncable); 6592 } 6593 } else { 6594 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6595 Slog.w(TAG, "Skipping provider name " + names[j] + 6596 " (in package " + pkg.applicationInfo.packageName + 6597 "): name already used by " 6598 + ((other != null && other.getComponentName() != null) 6599 ? other.getComponentName().getPackageName() : "?")); 6600 } 6601 } 6602 } 6603 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6604 if (r == null) { 6605 r = new StringBuilder(256); 6606 } else { 6607 r.append(' '); 6608 } 6609 r.append(p.info.name); 6610 } 6611 } 6612 if (r != null) { 6613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6614 } 6615 6616 N = pkg.services.size(); 6617 r = null; 6618 for (i=0; i<N; i++) { 6619 PackageParser.Service s = pkg.services.get(i); 6620 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6621 s.info.processName, pkg.applicationInfo.uid); 6622 mServices.addService(s); 6623 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6624 if (r == null) { 6625 r = new StringBuilder(256); 6626 } else { 6627 r.append(' '); 6628 } 6629 r.append(s.info.name); 6630 } 6631 } 6632 if (r != null) { 6633 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6634 } 6635 6636 N = pkg.receivers.size(); 6637 r = null; 6638 for (i=0; i<N; i++) { 6639 PackageParser.Activity a = pkg.receivers.get(i); 6640 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6641 a.info.processName, pkg.applicationInfo.uid); 6642 mReceivers.addActivity(a, "receiver"); 6643 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6644 if (r == null) { 6645 r = new StringBuilder(256); 6646 } else { 6647 r.append(' '); 6648 } 6649 r.append(a.info.name); 6650 } 6651 } 6652 if (r != null) { 6653 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6654 } 6655 6656 N = pkg.activities.size(); 6657 r = null; 6658 for (i=0; i<N; i++) { 6659 PackageParser.Activity a = pkg.activities.get(i); 6660 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6661 a.info.processName, pkg.applicationInfo.uid); 6662 mActivities.addActivity(a, "activity"); 6663 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6664 if (r == null) { 6665 r = new StringBuilder(256); 6666 } else { 6667 r.append(' '); 6668 } 6669 r.append(a.info.name); 6670 } 6671 } 6672 if (r != null) { 6673 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6674 } 6675 6676 N = pkg.permissionGroups.size(); 6677 r = null; 6678 for (i=0; i<N; i++) { 6679 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6680 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6681 if (cur == null) { 6682 mPermissionGroups.put(pg.info.name, pg); 6683 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6684 if (r == null) { 6685 r = new StringBuilder(256); 6686 } else { 6687 r.append(' '); 6688 } 6689 r.append(pg.info.name); 6690 } 6691 } else { 6692 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6693 + pg.info.packageName + " ignored: original from " 6694 + cur.info.packageName); 6695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6696 if (r == null) { 6697 r = new StringBuilder(256); 6698 } else { 6699 r.append(' '); 6700 } 6701 r.append("DUP:"); 6702 r.append(pg.info.name); 6703 } 6704 } 6705 } 6706 if (r != null) { 6707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6708 } 6709 6710 N = pkg.permissions.size(); 6711 r = null; 6712 for (i=0; i<N; i++) { 6713 PackageParser.Permission p = pkg.permissions.get(i); 6714 6715 // Now that permission groups have a special meaning, we ignore permission 6716 // groups for legacy apps to prevent unexpected behavior. In particular, 6717 // permissions for one app being granted to someone just becuase they happen 6718 // to be in a group defined by another app (before this had no implications). 6719 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6720 p.group = mPermissionGroups.get(p.info.group); 6721 // Warn for a permission in an unknown group. 6722 if (p.info.group != null && p.group == null) { 6723 Slog.w(TAG, "Permission " + p.info.name + " from package " 6724 + p.info.packageName + " in an unknown group " + p.info.group); 6725 } 6726 } 6727 6728 ArrayMap<String, BasePermission> permissionMap = 6729 p.tree ? mSettings.mPermissionTrees 6730 : mSettings.mPermissions; 6731 BasePermission bp = permissionMap.get(p.info.name); 6732 6733 // Allow system apps to redefine non-system permissions 6734 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6735 final boolean currentOwnerIsSystem = (bp.perm != null 6736 && isSystemApp(bp.perm.owner)); 6737 if (isSystemApp(p.owner)) { 6738 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6739 // It's a built-in permission and no owner, take ownership now 6740 bp.packageSetting = pkgSetting; 6741 bp.perm = p; 6742 bp.uid = pkg.applicationInfo.uid; 6743 bp.sourcePackage = p.info.packageName; 6744 } else if (!currentOwnerIsSystem) { 6745 String msg = "New decl " + p.owner + " of permission " 6746 + p.info.name + " is system; overriding " + bp.sourcePackage; 6747 reportSettingsProblem(Log.WARN, msg); 6748 bp = null; 6749 } 6750 } 6751 } 6752 6753 if (bp == null) { 6754 bp = new BasePermission(p.info.name, p.info.packageName, 6755 BasePermission.TYPE_NORMAL); 6756 permissionMap.put(p.info.name, bp); 6757 } 6758 6759 if (bp.perm == null) { 6760 if (bp.sourcePackage == null 6761 || bp.sourcePackage.equals(p.info.packageName)) { 6762 BasePermission tree = findPermissionTreeLP(p.info.name); 6763 if (tree == null 6764 || tree.sourcePackage.equals(p.info.packageName)) { 6765 bp.packageSetting = pkgSetting; 6766 bp.perm = p; 6767 bp.uid = pkg.applicationInfo.uid; 6768 bp.sourcePackage = p.info.packageName; 6769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6770 if (r == null) { 6771 r = new StringBuilder(256); 6772 } else { 6773 r.append(' '); 6774 } 6775 r.append(p.info.name); 6776 } 6777 } else { 6778 Slog.w(TAG, "Permission " + p.info.name + " from package " 6779 + p.info.packageName + " ignored: base tree " 6780 + tree.name + " is from package " 6781 + tree.sourcePackage); 6782 } 6783 } else { 6784 Slog.w(TAG, "Permission " + p.info.name + " from package " 6785 + p.info.packageName + " ignored: original from " 6786 + bp.sourcePackage); 6787 } 6788 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6789 if (r == null) { 6790 r = new StringBuilder(256); 6791 } else { 6792 r.append(' '); 6793 } 6794 r.append("DUP:"); 6795 r.append(p.info.name); 6796 } 6797 if (bp.perm == p) { 6798 bp.protectionLevel = p.info.protectionLevel; 6799 } 6800 } 6801 6802 if (r != null) { 6803 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6804 } 6805 6806 N = pkg.instrumentation.size(); 6807 r = null; 6808 for (i=0; i<N; i++) { 6809 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6810 a.info.packageName = pkg.applicationInfo.packageName; 6811 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6812 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6813 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6814 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6815 a.info.dataDir = pkg.applicationInfo.dataDir; 6816 6817 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6818 // need other information about the application, like the ABI and what not ? 6819 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6820 mInstrumentation.put(a.getComponentName(), a); 6821 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6822 if (r == null) { 6823 r = new StringBuilder(256); 6824 } else { 6825 r.append(' '); 6826 } 6827 r.append(a.info.name); 6828 } 6829 } 6830 if (r != null) { 6831 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6832 } 6833 6834 if (pkg.protectedBroadcasts != null) { 6835 N = pkg.protectedBroadcasts.size(); 6836 for (i=0; i<N; i++) { 6837 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6838 } 6839 } 6840 6841 pkgSetting.setTimeStamp(scanFileTime); 6842 6843 // Create idmap files for pairs of (packages, overlay packages). 6844 // Note: "android", ie framework-res.apk, is handled by native layers. 6845 if (pkg.mOverlayTarget != null) { 6846 // This is an overlay package. 6847 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6848 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6849 mOverlays.put(pkg.mOverlayTarget, 6850 new ArrayMap<String, PackageParser.Package>()); 6851 } 6852 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6853 map.put(pkg.packageName, pkg); 6854 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6855 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6856 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6857 "scanPackageLI failed to createIdmap"); 6858 } 6859 } 6860 } else if (mOverlays.containsKey(pkg.packageName) && 6861 !pkg.packageName.equals("android")) { 6862 // This is a regular package, with one or more known overlay packages. 6863 createIdmapsForPackageLI(pkg); 6864 } 6865 } 6866 6867 return pkg; 6868 } 6869 6870 /** 6871 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6872 * i.e, so that all packages can be run inside a single process if required. 6873 * 6874 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6875 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6876 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6877 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6878 * updating a package that belongs to a shared user. 6879 * 6880 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6881 * adds unnecessary complexity. 6882 */ 6883 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6884 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6885 String requiredInstructionSet = null; 6886 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6887 requiredInstructionSet = VMRuntime.getInstructionSet( 6888 scannedPackage.applicationInfo.primaryCpuAbi); 6889 } 6890 6891 PackageSetting requirer = null; 6892 for (PackageSetting ps : packagesForUser) { 6893 // If packagesForUser contains scannedPackage, we skip it. This will happen 6894 // when scannedPackage is an update of an existing package. Without this check, 6895 // we will never be able to change the ABI of any package belonging to a shared 6896 // user, even if it's compatible with other packages. 6897 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6898 if (ps.primaryCpuAbiString == null) { 6899 continue; 6900 } 6901 6902 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6903 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6904 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6905 // this but there's not much we can do. 6906 String errorMessage = "Instruction set mismatch, " 6907 + ((requirer == null) ? "[caller]" : requirer) 6908 + " requires " + requiredInstructionSet + " whereas " + ps 6909 + " requires " + instructionSet; 6910 Slog.w(TAG, errorMessage); 6911 } 6912 6913 if (requiredInstructionSet == null) { 6914 requiredInstructionSet = instructionSet; 6915 requirer = ps; 6916 } 6917 } 6918 } 6919 6920 if (requiredInstructionSet != null) { 6921 String adjustedAbi; 6922 if (requirer != null) { 6923 // requirer != null implies that either scannedPackage was null or that scannedPackage 6924 // did not require an ABI, in which case we have to adjust scannedPackage to match 6925 // the ABI of the set (which is the same as requirer's ABI) 6926 adjustedAbi = requirer.primaryCpuAbiString; 6927 if (scannedPackage != null) { 6928 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6929 } 6930 } else { 6931 // requirer == null implies that we're updating all ABIs in the set to 6932 // match scannedPackage. 6933 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6934 } 6935 6936 for (PackageSetting ps : packagesForUser) { 6937 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6938 if (ps.primaryCpuAbiString != null) { 6939 continue; 6940 } 6941 6942 ps.primaryCpuAbiString = adjustedAbi; 6943 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6944 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6945 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6946 6947 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6948 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6949 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6950 ps.primaryCpuAbiString = null; 6951 ps.pkg.applicationInfo.primaryCpuAbi = null; 6952 return; 6953 } else { 6954 mInstaller.rmdex(ps.codePathString, 6955 getDexCodeInstructionSet(getPreferredInstructionSet())); 6956 } 6957 } 6958 } 6959 } 6960 } 6961 } 6962 6963 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6964 synchronized (mPackages) { 6965 mResolverReplaced = true; 6966 // Set up information for custom user intent resolution activity. 6967 mResolveActivity.applicationInfo = pkg.applicationInfo; 6968 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6969 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6970 mResolveActivity.processName = pkg.applicationInfo.packageName; 6971 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6972 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6973 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6974 mResolveActivity.theme = 0; 6975 mResolveActivity.exported = true; 6976 mResolveActivity.enabled = true; 6977 mResolveInfo.activityInfo = mResolveActivity; 6978 mResolveInfo.priority = 0; 6979 mResolveInfo.preferredOrder = 0; 6980 mResolveInfo.match = 0; 6981 mResolveComponentName = mCustomResolverComponentName; 6982 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6983 mResolveComponentName); 6984 } 6985 } 6986 6987 private static String calculateBundledApkRoot(final String codePathString) { 6988 final File codePath = new File(codePathString); 6989 final File codeRoot; 6990 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6991 codeRoot = Environment.getRootDirectory(); 6992 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6993 codeRoot = Environment.getOemDirectory(); 6994 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6995 codeRoot = Environment.getVendorDirectory(); 6996 } else { 6997 // Unrecognized code path; take its top real segment as the apk root: 6998 // e.g. /something/app/blah.apk => /something 6999 try { 7000 File f = codePath.getCanonicalFile(); 7001 File parent = f.getParentFile(); // non-null because codePath is a file 7002 File tmp; 7003 while ((tmp = parent.getParentFile()) != null) { 7004 f = parent; 7005 parent = tmp; 7006 } 7007 codeRoot = f; 7008 Slog.w(TAG, "Unrecognized code path " 7009 + codePath + " - using " + codeRoot); 7010 } catch (IOException e) { 7011 // Can't canonicalize the code path -- shenanigans? 7012 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7013 return Environment.getRootDirectory().getPath(); 7014 } 7015 } 7016 return codeRoot.getPath(); 7017 } 7018 7019 /** 7020 * Derive and set the location of native libraries for the given package, 7021 * which varies depending on where and how the package was installed. 7022 */ 7023 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7024 final ApplicationInfo info = pkg.applicationInfo; 7025 final String codePath = pkg.codePath; 7026 final File codeFile = new File(codePath); 7027 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7028 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7029 7030 info.nativeLibraryRootDir = null; 7031 info.nativeLibraryRootRequiresIsa = false; 7032 info.nativeLibraryDir = null; 7033 info.secondaryNativeLibraryDir = null; 7034 7035 if (isApkFile(codeFile)) { 7036 // Monolithic install 7037 if (bundledApp) { 7038 // If "/system/lib64/apkname" exists, assume that is the per-package 7039 // native library directory to use; otherwise use "/system/lib/apkname". 7040 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7041 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7042 getPrimaryInstructionSet(info)); 7043 7044 // This is a bundled system app so choose the path based on the ABI. 7045 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7046 // is just the default path. 7047 final String apkName = deriveCodePathName(codePath); 7048 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7049 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7050 apkName).getAbsolutePath(); 7051 7052 if (info.secondaryCpuAbi != null) { 7053 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7054 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7055 secondaryLibDir, apkName).getAbsolutePath(); 7056 } 7057 } else if (asecApp) { 7058 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7059 .getAbsolutePath(); 7060 } else { 7061 final String apkName = deriveCodePathName(codePath); 7062 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7063 .getAbsolutePath(); 7064 } 7065 7066 info.nativeLibraryRootRequiresIsa = false; 7067 info.nativeLibraryDir = info.nativeLibraryRootDir; 7068 } else { 7069 // Cluster install 7070 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7071 info.nativeLibraryRootRequiresIsa = true; 7072 7073 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7074 getPrimaryInstructionSet(info)).getAbsolutePath(); 7075 7076 if (info.secondaryCpuAbi != null) { 7077 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7078 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7079 } 7080 } 7081 } 7082 7083 /** 7084 * Calculate the abis and roots for a bundled app. These can uniquely 7085 * be determined from the contents of the system partition, i.e whether 7086 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7087 * of this information, and instead assume that the system was built 7088 * sensibly. 7089 */ 7090 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7091 PackageSetting pkgSetting) { 7092 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7093 7094 // If "/system/lib64/apkname" exists, assume that is the per-package 7095 // native library directory to use; otherwise use "/system/lib/apkname". 7096 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7097 setBundledAppAbi(pkg, apkRoot, apkName); 7098 // pkgSetting might be null during rescan following uninstall of updates 7099 // to a bundled app, so accommodate that possibility. The settings in 7100 // that case will be established later from the parsed package. 7101 // 7102 // If the settings aren't null, sync them up with what we've just derived. 7103 // note that apkRoot isn't stored in the package settings. 7104 if (pkgSetting != null) { 7105 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7106 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7107 } 7108 } 7109 7110 /** 7111 * Deduces the ABI of a bundled app and sets the relevant fields on the 7112 * parsed pkg object. 7113 * 7114 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7115 * under which system libraries are installed. 7116 * @param apkName the name of the installed package. 7117 */ 7118 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7119 final File codeFile = new File(pkg.codePath); 7120 7121 final boolean has64BitLibs; 7122 final boolean has32BitLibs; 7123 if (isApkFile(codeFile)) { 7124 // Monolithic install 7125 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7126 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7127 } else { 7128 // Cluster install 7129 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7130 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7131 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7132 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7133 has64BitLibs = (new File(rootDir, isa)).exists(); 7134 } else { 7135 has64BitLibs = false; 7136 } 7137 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7138 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7139 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7140 has32BitLibs = (new File(rootDir, isa)).exists(); 7141 } else { 7142 has32BitLibs = false; 7143 } 7144 } 7145 7146 if (has64BitLibs && !has32BitLibs) { 7147 // The package has 64 bit libs, but not 32 bit libs. Its primary 7148 // ABI should be 64 bit. We can safely assume here that the bundled 7149 // native libraries correspond to the most preferred ABI in the list. 7150 7151 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7152 pkg.applicationInfo.secondaryCpuAbi = null; 7153 } else if (has32BitLibs && !has64BitLibs) { 7154 // The package has 32 bit libs but not 64 bit libs. Its primary 7155 // ABI should be 32 bit. 7156 7157 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7158 pkg.applicationInfo.secondaryCpuAbi = null; 7159 } else if (has32BitLibs && has64BitLibs) { 7160 // The application has both 64 and 32 bit bundled libraries. We check 7161 // here that the app declares multiArch support, and warn if it doesn't. 7162 // 7163 // We will be lenient here and record both ABIs. The primary will be the 7164 // ABI that's higher on the list, i.e, a device that's configured to prefer 7165 // 64 bit apps will see a 64 bit primary ABI, 7166 7167 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7168 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7169 } 7170 7171 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7172 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7173 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7174 } else { 7175 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7176 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7177 } 7178 } else { 7179 pkg.applicationInfo.primaryCpuAbi = null; 7180 pkg.applicationInfo.secondaryCpuAbi = null; 7181 } 7182 } 7183 7184 private void killApplication(String pkgName, int appId, String reason) { 7185 // Request the ActivityManager to kill the process(only for existing packages) 7186 // so that we do not end up in a confused state while the user is still using the older 7187 // version of the application while the new one gets installed. 7188 IActivityManager am = ActivityManagerNative.getDefault(); 7189 if (am != null) { 7190 try { 7191 am.killApplicationWithAppId(pkgName, appId, reason); 7192 } catch (RemoteException e) { 7193 } 7194 } 7195 } 7196 7197 void removePackageLI(PackageSetting ps, boolean chatty) { 7198 if (DEBUG_INSTALL) { 7199 if (chatty) 7200 Log.d(TAG, "Removing package " + ps.name); 7201 } 7202 7203 // writer 7204 synchronized (mPackages) { 7205 mPackages.remove(ps.name); 7206 final PackageParser.Package pkg = ps.pkg; 7207 if (pkg != null) { 7208 cleanPackageDataStructuresLILPw(pkg, chatty); 7209 } 7210 } 7211 } 7212 7213 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7214 if (DEBUG_INSTALL) { 7215 if (chatty) 7216 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7217 } 7218 7219 // writer 7220 synchronized (mPackages) { 7221 mPackages.remove(pkg.applicationInfo.packageName); 7222 cleanPackageDataStructuresLILPw(pkg, chatty); 7223 } 7224 } 7225 7226 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7227 int N = pkg.providers.size(); 7228 StringBuilder r = null; 7229 int i; 7230 for (i=0; i<N; i++) { 7231 PackageParser.Provider p = pkg.providers.get(i); 7232 mProviders.removeProvider(p); 7233 if (p.info.authority == null) { 7234 7235 /* There was another ContentProvider with this authority when 7236 * this app was installed so this authority is null, 7237 * Ignore it as we don't have to unregister the provider. 7238 */ 7239 continue; 7240 } 7241 String names[] = p.info.authority.split(";"); 7242 for (int j = 0; j < names.length; j++) { 7243 if (mProvidersByAuthority.get(names[j]) == p) { 7244 mProvidersByAuthority.remove(names[j]); 7245 if (DEBUG_REMOVE) { 7246 if (chatty) 7247 Log.d(TAG, "Unregistered content provider: " + names[j] 7248 + ", className = " + p.info.name + ", isSyncable = " 7249 + p.info.isSyncable); 7250 } 7251 } 7252 } 7253 if (DEBUG_REMOVE && chatty) { 7254 if (r == null) { 7255 r = new StringBuilder(256); 7256 } else { 7257 r.append(' '); 7258 } 7259 r.append(p.info.name); 7260 } 7261 } 7262 if (r != null) { 7263 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7264 } 7265 7266 N = pkg.services.size(); 7267 r = null; 7268 for (i=0; i<N; i++) { 7269 PackageParser.Service s = pkg.services.get(i); 7270 mServices.removeService(s); 7271 if (chatty) { 7272 if (r == null) { 7273 r = new StringBuilder(256); 7274 } else { 7275 r.append(' '); 7276 } 7277 r.append(s.info.name); 7278 } 7279 } 7280 if (r != null) { 7281 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7282 } 7283 7284 N = pkg.receivers.size(); 7285 r = null; 7286 for (i=0; i<N; i++) { 7287 PackageParser.Activity a = pkg.receivers.get(i); 7288 mReceivers.removeActivity(a, "receiver"); 7289 if (DEBUG_REMOVE && chatty) { 7290 if (r == null) { 7291 r = new StringBuilder(256); 7292 } else { 7293 r.append(' '); 7294 } 7295 r.append(a.info.name); 7296 } 7297 } 7298 if (r != null) { 7299 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7300 } 7301 7302 N = pkg.activities.size(); 7303 r = null; 7304 for (i=0; i<N; i++) { 7305 PackageParser.Activity a = pkg.activities.get(i); 7306 mActivities.removeActivity(a, "activity"); 7307 if (DEBUG_REMOVE && chatty) { 7308 if (r == null) { 7309 r = new StringBuilder(256); 7310 } else { 7311 r.append(' '); 7312 } 7313 r.append(a.info.name); 7314 } 7315 } 7316 if (r != null) { 7317 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7318 } 7319 7320 N = pkg.permissions.size(); 7321 r = null; 7322 for (i=0; i<N; i++) { 7323 PackageParser.Permission p = pkg.permissions.get(i); 7324 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7325 if (bp == null) { 7326 bp = mSettings.mPermissionTrees.get(p.info.name); 7327 } 7328 if (bp != null && bp.perm == p) { 7329 bp.perm = null; 7330 if (DEBUG_REMOVE && chatty) { 7331 if (r == null) { 7332 r = new StringBuilder(256); 7333 } else { 7334 r.append(' '); 7335 } 7336 r.append(p.info.name); 7337 } 7338 } 7339 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7340 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7341 if (appOpPerms != null) { 7342 appOpPerms.remove(pkg.packageName); 7343 } 7344 } 7345 } 7346 if (r != null) { 7347 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7348 } 7349 7350 N = pkg.requestedPermissions.size(); 7351 r = null; 7352 for (i=0; i<N; i++) { 7353 String perm = pkg.requestedPermissions.get(i); 7354 BasePermission bp = mSettings.mPermissions.get(perm); 7355 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7356 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7357 if (appOpPerms != null) { 7358 appOpPerms.remove(pkg.packageName); 7359 if (appOpPerms.isEmpty()) { 7360 mAppOpPermissionPackages.remove(perm); 7361 } 7362 } 7363 } 7364 } 7365 if (r != null) { 7366 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7367 } 7368 7369 N = pkg.instrumentation.size(); 7370 r = null; 7371 for (i=0; i<N; i++) { 7372 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7373 mInstrumentation.remove(a.getComponentName()); 7374 if (DEBUG_REMOVE && chatty) { 7375 if (r == null) { 7376 r = new StringBuilder(256); 7377 } else { 7378 r.append(' '); 7379 } 7380 r.append(a.info.name); 7381 } 7382 } 7383 if (r != null) { 7384 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7385 } 7386 7387 r = null; 7388 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7389 // Only system apps can hold shared libraries. 7390 if (pkg.libraryNames != null) { 7391 for (i=0; i<pkg.libraryNames.size(); i++) { 7392 String name = pkg.libraryNames.get(i); 7393 SharedLibraryEntry cur = mSharedLibraries.get(name); 7394 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7395 mSharedLibraries.remove(name); 7396 if (DEBUG_REMOVE && chatty) { 7397 if (r == null) { 7398 r = new StringBuilder(256); 7399 } else { 7400 r.append(' '); 7401 } 7402 r.append(name); 7403 } 7404 } 7405 } 7406 } 7407 } 7408 if (r != null) { 7409 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7410 } 7411 } 7412 7413 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7414 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7415 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7416 return true; 7417 } 7418 } 7419 return false; 7420 } 7421 7422 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7423 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7424 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7425 7426 private void updatePermissionsLPw(String changingPkg, 7427 PackageParser.Package pkgInfo, int flags) { 7428 // Make sure there are no dangling permission trees. 7429 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7430 while (it.hasNext()) { 7431 final BasePermission bp = it.next(); 7432 if (bp.packageSetting == null) { 7433 // We may not yet have parsed the package, so just see if 7434 // we still know about its settings. 7435 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7436 } 7437 if (bp.packageSetting == null) { 7438 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7439 + " from package " + bp.sourcePackage); 7440 it.remove(); 7441 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7442 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7443 Slog.i(TAG, "Removing old permission tree: " + bp.name 7444 + " from package " + bp.sourcePackage); 7445 flags |= UPDATE_PERMISSIONS_ALL; 7446 it.remove(); 7447 } 7448 } 7449 } 7450 7451 // Make sure all dynamic permissions have been assigned to a package, 7452 // and make sure there are no dangling permissions. 7453 it = mSettings.mPermissions.values().iterator(); 7454 while (it.hasNext()) { 7455 final BasePermission bp = it.next(); 7456 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7457 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7458 + bp.name + " pkg=" + bp.sourcePackage 7459 + " info=" + bp.pendingInfo); 7460 if (bp.packageSetting == null && bp.pendingInfo != null) { 7461 final BasePermission tree = findPermissionTreeLP(bp.name); 7462 if (tree != null && tree.perm != null) { 7463 bp.packageSetting = tree.packageSetting; 7464 bp.perm = new PackageParser.Permission(tree.perm.owner, 7465 new PermissionInfo(bp.pendingInfo)); 7466 bp.perm.info.packageName = tree.perm.info.packageName; 7467 bp.perm.info.name = bp.name; 7468 bp.uid = tree.uid; 7469 } 7470 } 7471 } 7472 if (bp.packageSetting == null) { 7473 // We may not yet have parsed the package, so just see if 7474 // we still know about its settings. 7475 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7476 } 7477 if (bp.packageSetting == null) { 7478 Slog.w(TAG, "Removing dangling permission: " + bp.name 7479 + " from package " + bp.sourcePackage); 7480 it.remove(); 7481 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7482 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7483 Slog.i(TAG, "Removing old permission: " + bp.name 7484 + " from package " + bp.sourcePackage); 7485 flags |= UPDATE_PERMISSIONS_ALL; 7486 it.remove(); 7487 } 7488 } 7489 } 7490 7491 // Now update the permissions for all packages, in particular 7492 // replace the granted permissions of the system packages. 7493 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7494 for (PackageParser.Package pkg : mPackages.values()) { 7495 if (pkg != pkgInfo) { 7496 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7497 changingPkg); 7498 } 7499 } 7500 } 7501 7502 if (pkgInfo != null) { 7503 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7504 } 7505 } 7506 7507 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7508 String packageOfInterest) { 7509 // IMPORTANT: There are two types of permissions: install and runtime. 7510 // Install time permissions are granted when the app is installed to 7511 // all device users and users added in the future. Runtime permissions 7512 // are granted at runtime explicitly to specific users. Normal and signature 7513 // protected permissions are install time permissions. Dangerous permissions 7514 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7515 // otherwise they are runtime permissions. This function does not manage 7516 // runtime permissions except for the case an app targeting Lollipop MR1 7517 // being upgraded to target a newer SDK, in which case dangerous permissions 7518 // are transformed from install time to runtime ones. 7519 7520 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7521 if (ps == null) { 7522 return; 7523 } 7524 7525 PermissionsState permissionsState = ps.getPermissionsState(); 7526 PermissionsState origPermissions = permissionsState; 7527 7528 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7529 7530 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7531 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7532 7533 boolean changedInstallPermission = false; 7534 7535 if (replace) { 7536 ps.installPermissionsFixed = false; 7537 if (!ps.isSharedUser()) { 7538 origPermissions = new PermissionsState(permissionsState); 7539 permissionsState.reset(); 7540 } 7541 } 7542 7543 permissionsState.setGlobalGids(mGlobalGids); 7544 7545 final int N = pkg.requestedPermissions.size(); 7546 for (int i=0; i<N; i++) { 7547 final String name = pkg.requestedPermissions.get(i); 7548 final BasePermission bp = mSettings.mPermissions.get(name); 7549 7550 if (DEBUG_INSTALL) { 7551 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7552 } 7553 7554 if (bp == null || bp.packageSetting == null) { 7555 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7556 Slog.w(TAG, "Unknown permission " + name 7557 + " in package " + pkg.packageName); 7558 } 7559 continue; 7560 } 7561 7562 final String perm = bp.name; 7563 boolean allowedSig = false; 7564 int grant = GRANT_DENIED; 7565 7566 // Keep track of app op permissions. 7567 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7568 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7569 if (pkgs == null) { 7570 pkgs = new ArraySet<>(); 7571 mAppOpPermissionPackages.put(bp.name, pkgs); 7572 } 7573 pkgs.add(pkg.packageName); 7574 } 7575 7576 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7577 switch (level) { 7578 case PermissionInfo.PROTECTION_NORMAL: { 7579 // For all apps normal permissions are install time ones. 7580 grant = GRANT_INSTALL; 7581 } break; 7582 7583 case PermissionInfo.PROTECTION_DANGEROUS: { 7584 if (!RUNTIME_PERMISSIONS_ENABLED 7585 || pkg.applicationInfo.targetSdkVersion 7586 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7587 // For legacy apps dangerous permissions are install time ones. 7588 grant = GRANT_INSTALL; 7589 } else if (ps.isSystem()) { 7590 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7591 if (origPermissions.hasInstallPermission(bp.name)) { 7592 // If a system app had an install permission, then the app was 7593 // upgraded and we grant the permissions as runtime to all users. 7594 grant = GRANT_UPGRADE; 7595 upgradeUserIds = currentUserIds; 7596 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7597 // If users changed since the last permissions update for a 7598 // system app, we grant the permission as runtime to the new users. 7599 grant = GRANT_UPGRADE; 7600 upgradeUserIds = currentUserIds; 7601 for (int userId : updatedUserIds) { 7602 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7603 } 7604 } else { 7605 // Otherwise, we grant the permission as runtime if the app 7606 // already had it, i.e. we preserve runtime permissions. 7607 grant = GRANT_RUNTIME; 7608 } 7609 } else if (origPermissions.hasInstallPermission(bp.name)) { 7610 // For legacy apps that became modern, install becomes runtime. 7611 grant = GRANT_UPGRADE; 7612 upgradeUserIds = currentUserIds; 7613 } else if (replace) { 7614 // For upgraded modern apps keep runtime permissions unchanged. 7615 grant = GRANT_RUNTIME; 7616 } 7617 } break; 7618 7619 case PermissionInfo.PROTECTION_SIGNATURE: { 7620 // For all apps signature permissions are install time ones. 7621 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7622 if (allowedSig) { 7623 grant = GRANT_INSTALL; 7624 } 7625 } break; 7626 } 7627 7628 if (DEBUG_INSTALL) { 7629 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7630 } 7631 7632 if (grant != GRANT_DENIED) { 7633 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7634 // If this is an existing, non-system package, then 7635 // we can't add any new permissions to it. 7636 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7637 // Except... if this is a permission that was added 7638 // to the platform (note: need to only do this when 7639 // updating the platform). 7640 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7641 grant = GRANT_DENIED; 7642 } 7643 } 7644 } 7645 7646 switch (grant) { 7647 case GRANT_INSTALL: { 7648 // Grant an install permission. 7649 if (permissionsState.grantInstallPermission(bp) != 7650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7651 changedInstallPermission = true; 7652 } 7653 } break; 7654 7655 case GRANT_RUNTIME: { 7656 // Grant previously granted runtime permissions. 7657 for (int userId : UserManagerService.getInstance().getUserIds()) { 7658 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7659 if (permissionsState.grantRuntimePermission(bp, userId) == 7660 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7661 // If we cannot put the permission as it was, we have to write. 7662 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7663 changedRuntimePermissionUserIds, userId); 7664 } 7665 } 7666 } 7667 } break; 7668 7669 case GRANT_UPGRADE: { 7670 // Grant runtime permissions for a previously held install permission. 7671 permissionsState.revokeInstallPermission(bp); 7672 for (int userId : upgradeUserIds) { 7673 if (permissionsState.grantRuntimePermission(bp, userId) != 7674 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7675 // If we granted the permission, we have to write. 7676 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7677 changedRuntimePermissionUserIds, userId); 7678 } 7679 } 7680 } break; 7681 7682 default: { 7683 if (packageOfInterest == null 7684 || packageOfInterest.equals(pkg.packageName)) { 7685 Slog.w(TAG, "Not granting permission " + perm 7686 + " to package " + pkg.packageName 7687 + " because it was previously installed without"); 7688 } 7689 } break; 7690 } 7691 } else { 7692 if (permissionsState.revokeInstallPermission(bp) != 7693 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7694 changedInstallPermission = true; 7695 Slog.i(TAG, "Un-granting permission " + perm 7696 + " from package " + pkg.packageName 7697 + " (protectionLevel=" + bp.protectionLevel 7698 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7699 + ")"); 7700 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7701 // Don't print warning for app op permissions, since it is fine for them 7702 // not to be granted, there is a UI for the user to decide. 7703 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7704 Slog.w(TAG, "Not granting permission " + perm 7705 + " to package " + pkg.packageName 7706 + " (protectionLevel=" + bp.protectionLevel 7707 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7708 + ")"); 7709 } 7710 } 7711 } 7712 } 7713 7714 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7715 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7716 // This is the first that we have heard about this package, so the 7717 // permissions we have now selected are fixed until explicitly 7718 // changed. 7719 ps.installPermissionsFixed = true; 7720 } 7721 7722 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7723 7724 // Persist the runtime permissions state for users with changes. 7725 if (RUNTIME_PERMISSIONS_ENABLED) { 7726 for (int userId : changedRuntimePermissionUserIds) { 7727 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7728 } 7729 } 7730 } 7731 7732 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7733 boolean allowed = false; 7734 final int NP = PackageParser.NEW_PERMISSIONS.length; 7735 for (int ip=0; ip<NP; ip++) { 7736 final PackageParser.NewPermissionInfo npi 7737 = PackageParser.NEW_PERMISSIONS[ip]; 7738 if (npi.name.equals(perm) 7739 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7740 allowed = true; 7741 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7742 + pkg.packageName); 7743 break; 7744 } 7745 } 7746 return allowed; 7747 } 7748 7749 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7750 BasePermission bp, PermissionsState origPermissions) { 7751 boolean allowed; 7752 allowed = (compareSignatures( 7753 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7754 == PackageManager.SIGNATURE_MATCH) 7755 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7756 == PackageManager.SIGNATURE_MATCH); 7757 if (!allowed && (bp.protectionLevel 7758 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7759 if (isSystemApp(pkg)) { 7760 // For updated system applications, a system permission 7761 // is granted only if it had been defined by the original application. 7762 if (pkg.isUpdatedSystemApp()) { 7763 final PackageSetting sysPs = mSettings 7764 .getDisabledSystemPkgLPr(pkg.packageName); 7765 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7766 // If the original was granted this permission, we take 7767 // that grant decision as read and propagate it to the 7768 // update. 7769 if (sysPs.isPrivileged()) { 7770 allowed = true; 7771 } 7772 } else { 7773 // The system apk may have been updated with an older 7774 // version of the one on the data partition, but which 7775 // granted a new system permission that it didn't have 7776 // before. In this case we do want to allow the app to 7777 // now get the new permission if the ancestral apk is 7778 // privileged to get it. 7779 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7780 for (int j=0; 7781 j<sysPs.pkg.requestedPermissions.size(); j++) { 7782 if (perm.equals( 7783 sysPs.pkg.requestedPermissions.get(j))) { 7784 allowed = true; 7785 break; 7786 } 7787 } 7788 } 7789 } 7790 } else { 7791 allowed = isPrivilegedApp(pkg); 7792 } 7793 } 7794 } 7795 if (!allowed && (bp.protectionLevel 7796 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7797 // For development permissions, a development permission 7798 // is granted only if it was already granted. 7799 allowed = origPermissions.hasInstallPermission(perm); 7800 } 7801 return allowed; 7802 } 7803 7804 final class ActivityIntentResolver 7805 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7806 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7807 boolean defaultOnly, int userId) { 7808 if (!sUserManager.exists(userId)) return null; 7809 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7810 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7811 } 7812 7813 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7814 int userId) { 7815 if (!sUserManager.exists(userId)) return null; 7816 mFlags = flags; 7817 return super.queryIntent(intent, resolvedType, 7818 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7819 } 7820 7821 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7822 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7823 if (!sUserManager.exists(userId)) return null; 7824 if (packageActivities == null) { 7825 return null; 7826 } 7827 mFlags = flags; 7828 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7829 final int N = packageActivities.size(); 7830 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7831 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7832 7833 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7834 for (int i = 0; i < N; ++i) { 7835 intentFilters = packageActivities.get(i).intents; 7836 if (intentFilters != null && intentFilters.size() > 0) { 7837 PackageParser.ActivityIntentInfo[] array = 7838 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7839 intentFilters.toArray(array); 7840 listCut.add(array); 7841 } 7842 } 7843 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7844 } 7845 7846 public final void addActivity(PackageParser.Activity a, String type) { 7847 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7848 mActivities.put(a.getComponentName(), a); 7849 if (DEBUG_SHOW_INFO) 7850 Log.v( 7851 TAG, " " + type + " " + 7852 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7853 if (DEBUG_SHOW_INFO) 7854 Log.v(TAG, " Class=" + a.info.name); 7855 final int NI = a.intents.size(); 7856 for (int j=0; j<NI; j++) { 7857 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7858 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7859 intent.setPriority(0); 7860 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7861 + a.className + " with priority > 0, forcing to 0"); 7862 } 7863 if (DEBUG_SHOW_INFO) { 7864 Log.v(TAG, " IntentFilter:"); 7865 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7866 } 7867 if (!intent.debugCheck()) { 7868 Log.w(TAG, "==> For Activity " + a.info.name); 7869 } 7870 addFilter(intent); 7871 } 7872 } 7873 7874 public final void removeActivity(PackageParser.Activity a, String type) { 7875 mActivities.remove(a.getComponentName()); 7876 if (DEBUG_SHOW_INFO) { 7877 Log.v(TAG, " " + type + " " 7878 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7879 : a.info.name) + ":"); 7880 Log.v(TAG, " Class=" + a.info.name); 7881 } 7882 final int NI = a.intents.size(); 7883 for (int j=0; j<NI; j++) { 7884 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7885 if (DEBUG_SHOW_INFO) { 7886 Log.v(TAG, " IntentFilter:"); 7887 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7888 } 7889 removeFilter(intent); 7890 } 7891 } 7892 7893 @Override 7894 protected boolean allowFilterResult( 7895 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7896 ActivityInfo filterAi = filter.activity.info; 7897 for (int i=dest.size()-1; i>=0; i--) { 7898 ActivityInfo destAi = dest.get(i).activityInfo; 7899 if (destAi.name == filterAi.name 7900 && destAi.packageName == filterAi.packageName) { 7901 return false; 7902 } 7903 } 7904 return true; 7905 } 7906 7907 @Override 7908 protected ActivityIntentInfo[] newArray(int size) { 7909 return new ActivityIntentInfo[size]; 7910 } 7911 7912 @Override 7913 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7914 if (!sUserManager.exists(userId)) return true; 7915 PackageParser.Package p = filter.activity.owner; 7916 if (p != null) { 7917 PackageSetting ps = (PackageSetting)p.mExtras; 7918 if (ps != null) { 7919 // System apps are never considered stopped for purposes of 7920 // filtering, because there may be no way for the user to 7921 // actually re-launch them. 7922 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7923 && ps.getStopped(userId); 7924 } 7925 } 7926 return false; 7927 } 7928 7929 @Override 7930 protected boolean isPackageForFilter(String packageName, 7931 PackageParser.ActivityIntentInfo info) { 7932 return packageName.equals(info.activity.owner.packageName); 7933 } 7934 7935 @Override 7936 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7937 int match, int userId) { 7938 if (!sUserManager.exists(userId)) return null; 7939 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7940 return null; 7941 } 7942 final PackageParser.Activity activity = info.activity; 7943 if (mSafeMode && (activity.info.applicationInfo.flags 7944 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7945 return null; 7946 } 7947 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7948 if (ps == null) { 7949 return null; 7950 } 7951 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7952 ps.readUserState(userId), userId); 7953 if (ai == null) { 7954 return null; 7955 } 7956 final ResolveInfo res = new ResolveInfo(); 7957 res.activityInfo = ai; 7958 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7959 res.filter = info; 7960 } 7961 if (info != null) { 7962 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7963 } 7964 res.priority = info.getPriority(); 7965 res.preferredOrder = activity.owner.mPreferredOrder; 7966 //System.out.println("Result: " + res.activityInfo.className + 7967 // " = " + res.priority); 7968 res.match = match; 7969 res.isDefault = info.hasDefault; 7970 res.labelRes = info.labelRes; 7971 res.nonLocalizedLabel = info.nonLocalizedLabel; 7972 if (userNeedsBadging(userId)) { 7973 res.noResourceId = true; 7974 } else { 7975 res.icon = info.icon; 7976 } 7977 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7978 return res; 7979 } 7980 7981 @Override 7982 protected void sortResults(List<ResolveInfo> results) { 7983 Collections.sort(results, mResolvePrioritySorter); 7984 } 7985 7986 @Override 7987 protected void dumpFilter(PrintWriter out, String prefix, 7988 PackageParser.ActivityIntentInfo filter) { 7989 out.print(prefix); out.print( 7990 Integer.toHexString(System.identityHashCode(filter.activity))); 7991 out.print(' '); 7992 filter.activity.printComponentShortName(out); 7993 out.print(" filter "); 7994 out.println(Integer.toHexString(System.identityHashCode(filter))); 7995 } 7996 7997 @Override 7998 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7999 return filter.activity; 8000 } 8001 8002 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8003 PackageParser.Activity activity = (PackageParser.Activity)label; 8004 out.print(prefix); out.print( 8005 Integer.toHexString(System.identityHashCode(activity))); 8006 out.print(' '); 8007 activity.printComponentShortName(out); 8008 if (count > 1) { 8009 out.print(" ("); out.print(count); out.print(" filters)"); 8010 } 8011 out.println(); 8012 } 8013 8014// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8015// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8016// final List<ResolveInfo> retList = Lists.newArrayList(); 8017// while (i.hasNext()) { 8018// final ResolveInfo resolveInfo = i.next(); 8019// if (isEnabledLP(resolveInfo.activityInfo)) { 8020// retList.add(resolveInfo); 8021// } 8022// } 8023// return retList; 8024// } 8025 8026 // Keys are String (activity class name), values are Activity. 8027 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8028 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8029 private int mFlags; 8030 } 8031 8032 private final class ServiceIntentResolver 8033 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8034 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8035 boolean defaultOnly, int userId) { 8036 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8037 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8038 } 8039 8040 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8041 int userId) { 8042 if (!sUserManager.exists(userId)) return null; 8043 mFlags = flags; 8044 return super.queryIntent(intent, resolvedType, 8045 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8046 } 8047 8048 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8049 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8050 if (!sUserManager.exists(userId)) return null; 8051 if (packageServices == null) { 8052 return null; 8053 } 8054 mFlags = flags; 8055 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8056 final int N = packageServices.size(); 8057 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8058 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8059 8060 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8061 for (int i = 0; i < N; ++i) { 8062 intentFilters = packageServices.get(i).intents; 8063 if (intentFilters != null && intentFilters.size() > 0) { 8064 PackageParser.ServiceIntentInfo[] array = 8065 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8066 intentFilters.toArray(array); 8067 listCut.add(array); 8068 } 8069 } 8070 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8071 } 8072 8073 public final void addService(PackageParser.Service s) { 8074 mServices.put(s.getComponentName(), s); 8075 if (DEBUG_SHOW_INFO) { 8076 Log.v(TAG, " " 8077 + (s.info.nonLocalizedLabel != null 8078 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8079 Log.v(TAG, " Class=" + s.info.name); 8080 } 8081 final int NI = s.intents.size(); 8082 int j; 8083 for (j=0; j<NI; j++) { 8084 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8085 if (DEBUG_SHOW_INFO) { 8086 Log.v(TAG, " IntentFilter:"); 8087 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8088 } 8089 if (!intent.debugCheck()) { 8090 Log.w(TAG, "==> For Service " + s.info.name); 8091 } 8092 addFilter(intent); 8093 } 8094 } 8095 8096 public final void removeService(PackageParser.Service s) { 8097 mServices.remove(s.getComponentName()); 8098 if (DEBUG_SHOW_INFO) { 8099 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8100 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8101 Log.v(TAG, " Class=" + s.info.name); 8102 } 8103 final int NI = s.intents.size(); 8104 int j; 8105 for (j=0; j<NI; j++) { 8106 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8107 if (DEBUG_SHOW_INFO) { 8108 Log.v(TAG, " IntentFilter:"); 8109 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8110 } 8111 removeFilter(intent); 8112 } 8113 } 8114 8115 @Override 8116 protected boolean allowFilterResult( 8117 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8118 ServiceInfo filterSi = filter.service.info; 8119 for (int i=dest.size()-1; i>=0; i--) { 8120 ServiceInfo destAi = dest.get(i).serviceInfo; 8121 if (destAi.name == filterSi.name 8122 && destAi.packageName == filterSi.packageName) { 8123 return false; 8124 } 8125 } 8126 return true; 8127 } 8128 8129 @Override 8130 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8131 return new PackageParser.ServiceIntentInfo[size]; 8132 } 8133 8134 @Override 8135 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8136 if (!sUserManager.exists(userId)) return true; 8137 PackageParser.Package p = filter.service.owner; 8138 if (p != null) { 8139 PackageSetting ps = (PackageSetting)p.mExtras; 8140 if (ps != null) { 8141 // System apps are never considered stopped for purposes of 8142 // filtering, because there may be no way for the user to 8143 // actually re-launch them. 8144 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8145 && ps.getStopped(userId); 8146 } 8147 } 8148 return false; 8149 } 8150 8151 @Override 8152 protected boolean isPackageForFilter(String packageName, 8153 PackageParser.ServiceIntentInfo info) { 8154 return packageName.equals(info.service.owner.packageName); 8155 } 8156 8157 @Override 8158 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8159 int match, int userId) { 8160 if (!sUserManager.exists(userId)) return null; 8161 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8162 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8163 return null; 8164 } 8165 final PackageParser.Service service = info.service; 8166 if (mSafeMode && (service.info.applicationInfo.flags 8167 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8168 return null; 8169 } 8170 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8171 if (ps == null) { 8172 return null; 8173 } 8174 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8175 ps.readUserState(userId), userId); 8176 if (si == null) { 8177 return null; 8178 } 8179 final ResolveInfo res = new ResolveInfo(); 8180 res.serviceInfo = si; 8181 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8182 res.filter = filter; 8183 } 8184 res.priority = info.getPriority(); 8185 res.preferredOrder = service.owner.mPreferredOrder; 8186 res.match = match; 8187 res.isDefault = info.hasDefault; 8188 res.labelRes = info.labelRes; 8189 res.nonLocalizedLabel = info.nonLocalizedLabel; 8190 res.icon = info.icon; 8191 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8192 return res; 8193 } 8194 8195 @Override 8196 protected void sortResults(List<ResolveInfo> results) { 8197 Collections.sort(results, mResolvePrioritySorter); 8198 } 8199 8200 @Override 8201 protected void dumpFilter(PrintWriter out, String prefix, 8202 PackageParser.ServiceIntentInfo filter) { 8203 out.print(prefix); out.print( 8204 Integer.toHexString(System.identityHashCode(filter.service))); 8205 out.print(' '); 8206 filter.service.printComponentShortName(out); 8207 out.print(" filter "); 8208 out.println(Integer.toHexString(System.identityHashCode(filter))); 8209 } 8210 8211 @Override 8212 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8213 return filter.service; 8214 } 8215 8216 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8217 PackageParser.Service service = (PackageParser.Service)label; 8218 out.print(prefix); out.print( 8219 Integer.toHexString(System.identityHashCode(service))); 8220 out.print(' '); 8221 service.printComponentShortName(out); 8222 if (count > 1) { 8223 out.print(" ("); out.print(count); out.print(" filters)"); 8224 } 8225 out.println(); 8226 } 8227 8228// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8229// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8230// final List<ResolveInfo> retList = Lists.newArrayList(); 8231// while (i.hasNext()) { 8232// final ResolveInfo resolveInfo = (ResolveInfo) i; 8233// if (isEnabledLP(resolveInfo.serviceInfo)) { 8234// retList.add(resolveInfo); 8235// } 8236// } 8237// return retList; 8238// } 8239 8240 // Keys are String (activity class name), values are Activity. 8241 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8242 = new ArrayMap<ComponentName, PackageParser.Service>(); 8243 private int mFlags; 8244 }; 8245 8246 private final class ProviderIntentResolver 8247 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8248 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8249 boolean defaultOnly, int userId) { 8250 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8251 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8252 } 8253 8254 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8255 int userId) { 8256 if (!sUserManager.exists(userId)) 8257 return null; 8258 mFlags = flags; 8259 return super.queryIntent(intent, resolvedType, 8260 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8261 } 8262 8263 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8264 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8265 if (!sUserManager.exists(userId)) 8266 return null; 8267 if (packageProviders == null) { 8268 return null; 8269 } 8270 mFlags = flags; 8271 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8272 final int N = packageProviders.size(); 8273 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8274 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8275 8276 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8277 for (int i = 0; i < N; ++i) { 8278 intentFilters = packageProviders.get(i).intents; 8279 if (intentFilters != null && intentFilters.size() > 0) { 8280 PackageParser.ProviderIntentInfo[] array = 8281 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8282 intentFilters.toArray(array); 8283 listCut.add(array); 8284 } 8285 } 8286 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8287 } 8288 8289 public final void addProvider(PackageParser.Provider p) { 8290 if (mProviders.containsKey(p.getComponentName())) { 8291 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8292 return; 8293 } 8294 8295 mProviders.put(p.getComponentName(), p); 8296 if (DEBUG_SHOW_INFO) { 8297 Log.v(TAG, " " 8298 + (p.info.nonLocalizedLabel != null 8299 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8300 Log.v(TAG, " Class=" + p.info.name); 8301 } 8302 final int NI = p.intents.size(); 8303 int j; 8304 for (j = 0; j < NI; j++) { 8305 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8306 if (DEBUG_SHOW_INFO) { 8307 Log.v(TAG, " IntentFilter:"); 8308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8309 } 8310 if (!intent.debugCheck()) { 8311 Log.w(TAG, "==> For Provider " + p.info.name); 8312 } 8313 addFilter(intent); 8314 } 8315 } 8316 8317 public final void removeProvider(PackageParser.Provider p) { 8318 mProviders.remove(p.getComponentName()); 8319 if (DEBUG_SHOW_INFO) { 8320 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8321 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8322 Log.v(TAG, " Class=" + p.info.name); 8323 } 8324 final int NI = p.intents.size(); 8325 int j; 8326 for (j = 0; j < NI; j++) { 8327 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8328 if (DEBUG_SHOW_INFO) { 8329 Log.v(TAG, " IntentFilter:"); 8330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8331 } 8332 removeFilter(intent); 8333 } 8334 } 8335 8336 @Override 8337 protected boolean allowFilterResult( 8338 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8339 ProviderInfo filterPi = filter.provider.info; 8340 for (int i = dest.size() - 1; i >= 0; i--) { 8341 ProviderInfo destPi = dest.get(i).providerInfo; 8342 if (destPi.name == filterPi.name 8343 && destPi.packageName == filterPi.packageName) { 8344 return false; 8345 } 8346 } 8347 return true; 8348 } 8349 8350 @Override 8351 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8352 return new PackageParser.ProviderIntentInfo[size]; 8353 } 8354 8355 @Override 8356 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8357 if (!sUserManager.exists(userId)) 8358 return true; 8359 PackageParser.Package p = filter.provider.owner; 8360 if (p != null) { 8361 PackageSetting ps = (PackageSetting) p.mExtras; 8362 if (ps != null) { 8363 // System apps are never considered stopped for purposes of 8364 // filtering, because there may be no way for the user to 8365 // actually re-launch them. 8366 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8367 && ps.getStopped(userId); 8368 } 8369 } 8370 return false; 8371 } 8372 8373 @Override 8374 protected boolean isPackageForFilter(String packageName, 8375 PackageParser.ProviderIntentInfo info) { 8376 return packageName.equals(info.provider.owner.packageName); 8377 } 8378 8379 @Override 8380 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8381 int match, int userId) { 8382 if (!sUserManager.exists(userId)) 8383 return null; 8384 final PackageParser.ProviderIntentInfo info = filter; 8385 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8386 return null; 8387 } 8388 final PackageParser.Provider provider = info.provider; 8389 if (mSafeMode && (provider.info.applicationInfo.flags 8390 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8391 return null; 8392 } 8393 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8394 if (ps == null) { 8395 return null; 8396 } 8397 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8398 ps.readUserState(userId), userId); 8399 if (pi == null) { 8400 return null; 8401 } 8402 final ResolveInfo res = new ResolveInfo(); 8403 res.providerInfo = pi; 8404 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8405 res.filter = filter; 8406 } 8407 res.priority = info.getPriority(); 8408 res.preferredOrder = provider.owner.mPreferredOrder; 8409 res.match = match; 8410 res.isDefault = info.hasDefault; 8411 res.labelRes = info.labelRes; 8412 res.nonLocalizedLabel = info.nonLocalizedLabel; 8413 res.icon = info.icon; 8414 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8415 return res; 8416 } 8417 8418 @Override 8419 protected void sortResults(List<ResolveInfo> results) { 8420 Collections.sort(results, mResolvePrioritySorter); 8421 } 8422 8423 @Override 8424 protected void dumpFilter(PrintWriter out, String prefix, 8425 PackageParser.ProviderIntentInfo filter) { 8426 out.print(prefix); 8427 out.print( 8428 Integer.toHexString(System.identityHashCode(filter.provider))); 8429 out.print(' '); 8430 filter.provider.printComponentShortName(out); 8431 out.print(" filter "); 8432 out.println(Integer.toHexString(System.identityHashCode(filter))); 8433 } 8434 8435 @Override 8436 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8437 return filter.provider; 8438 } 8439 8440 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8441 PackageParser.Provider provider = (PackageParser.Provider)label; 8442 out.print(prefix); out.print( 8443 Integer.toHexString(System.identityHashCode(provider))); 8444 out.print(' '); 8445 provider.printComponentShortName(out); 8446 if (count > 1) { 8447 out.print(" ("); out.print(count); out.print(" filters)"); 8448 } 8449 out.println(); 8450 } 8451 8452 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8453 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8454 private int mFlags; 8455 }; 8456 8457 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8458 new Comparator<ResolveInfo>() { 8459 public int compare(ResolveInfo r1, ResolveInfo r2) { 8460 int v1 = r1.priority; 8461 int v2 = r2.priority; 8462 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8463 if (v1 != v2) { 8464 return (v1 > v2) ? -1 : 1; 8465 } 8466 v1 = r1.preferredOrder; 8467 v2 = r2.preferredOrder; 8468 if (v1 != v2) { 8469 return (v1 > v2) ? -1 : 1; 8470 } 8471 if (r1.isDefault != r2.isDefault) { 8472 return r1.isDefault ? -1 : 1; 8473 } 8474 v1 = r1.match; 8475 v2 = r2.match; 8476 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8477 if (v1 != v2) { 8478 return (v1 > v2) ? -1 : 1; 8479 } 8480 if (r1.system != r2.system) { 8481 return r1.system ? -1 : 1; 8482 } 8483 return 0; 8484 } 8485 }; 8486 8487 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8488 new Comparator<ProviderInfo>() { 8489 public int compare(ProviderInfo p1, ProviderInfo p2) { 8490 final int v1 = p1.initOrder; 8491 final int v2 = p2.initOrder; 8492 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8493 } 8494 }; 8495 8496 static final void sendPackageBroadcast(String action, String pkg, 8497 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8498 int[] userIds) { 8499 IActivityManager am = ActivityManagerNative.getDefault(); 8500 if (am != null) { 8501 try { 8502 if (userIds == null) { 8503 userIds = am.getRunningUserIds(); 8504 } 8505 for (int id : userIds) { 8506 final Intent intent = new Intent(action, 8507 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8508 if (extras != null) { 8509 intent.putExtras(extras); 8510 } 8511 if (targetPkg != null) { 8512 intent.setPackage(targetPkg); 8513 } 8514 // Modify the UID when posting to other users 8515 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8516 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8517 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8518 intent.putExtra(Intent.EXTRA_UID, uid); 8519 } 8520 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8521 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8522 if (DEBUG_BROADCASTS) { 8523 RuntimeException here = new RuntimeException("here"); 8524 here.fillInStackTrace(); 8525 Slog.d(TAG, "Sending to user " + id + ": " 8526 + intent.toShortString(false, true, false, false) 8527 + " " + intent.getExtras(), here); 8528 } 8529 am.broadcastIntent(null, intent, null, finishedReceiver, 8530 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8531 finishedReceiver != null, false, id); 8532 } 8533 } catch (RemoteException ex) { 8534 } 8535 } 8536 } 8537 8538 /** 8539 * Check if the external storage media is available. This is true if there 8540 * is a mounted external storage medium or if the external storage is 8541 * emulated. 8542 */ 8543 private boolean isExternalMediaAvailable() { 8544 return mMediaMounted || Environment.isExternalStorageEmulated(); 8545 } 8546 8547 @Override 8548 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8549 // writer 8550 synchronized (mPackages) { 8551 if (!isExternalMediaAvailable()) { 8552 // If the external storage is no longer mounted at this point, 8553 // the caller may not have been able to delete all of this 8554 // packages files and can not delete any more. Bail. 8555 return null; 8556 } 8557 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8558 if (lastPackage != null) { 8559 pkgs.remove(lastPackage); 8560 } 8561 if (pkgs.size() > 0) { 8562 return pkgs.get(0); 8563 } 8564 } 8565 return null; 8566 } 8567 8568 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8569 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8570 userId, andCode ? 1 : 0, packageName); 8571 if (mSystemReady) { 8572 msg.sendToTarget(); 8573 } else { 8574 if (mPostSystemReadyMessages == null) { 8575 mPostSystemReadyMessages = new ArrayList<>(); 8576 } 8577 mPostSystemReadyMessages.add(msg); 8578 } 8579 } 8580 8581 void startCleaningPackages() { 8582 // reader 8583 synchronized (mPackages) { 8584 if (!isExternalMediaAvailable()) { 8585 return; 8586 } 8587 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8588 return; 8589 } 8590 } 8591 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8592 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8593 IActivityManager am = ActivityManagerNative.getDefault(); 8594 if (am != null) { 8595 try { 8596 am.startService(null, intent, null, UserHandle.USER_OWNER); 8597 } catch (RemoteException e) { 8598 } 8599 } 8600 } 8601 8602 @Override 8603 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8604 int installFlags, String installerPackageName, VerificationParams verificationParams, 8605 String packageAbiOverride) { 8606 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8607 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8608 } 8609 8610 @Override 8611 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8612 int installFlags, String installerPackageName, VerificationParams verificationParams, 8613 String packageAbiOverride, int userId) { 8614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8615 8616 final int callingUid = Binder.getCallingUid(); 8617 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8618 8619 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8620 try { 8621 if (observer != null) { 8622 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8623 } 8624 } catch (RemoteException re) { 8625 } 8626 return; 8627 } 8628 8629 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8630 installFlags |= PackageManager.INSTALL_FROM_ADB; 8631 8632 } else { 8633 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8634 // about installerPackageName. 8635 8636 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8637 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8638 } 8639 8640 UserHandle user; 8641 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8642 user = UserHandle.ALL; 8643 } else { 8644 user = new UserHandle(userId); 8645 } 8646 8647 // Only system components can circumvent runtime permissions when installing. 8648 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8649 && mContext.checkCallingOrSelfPermission(Manifest.permission 8650 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8651 throw new SecurityException("You need the " 8652 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8653 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8654 } 8655 8656 verificationParams.setInstallerUid(callingUid); 8657 8658 final File originFile = new File(originPath); 8659 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8660 8661 final Message msg = mHandler.obtainMessage(INIT_COPY); 8662 msg.obj = new InstallParams(origin, observer, installFlags, 8663 installerPackageName, null, verificationParams, user, packageAbiOverride); 8664 mHandler.sendMessage(msg); 8665 } 8666 8667 void installStage(String packageName, File stagedDir, String stagedCid, 8668 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8669 String installerPackageName, int installerUid, UserHandle user) { 8670 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8671 params.referrerUri, installerUid, null); 8672 8673 final OriginInfo origin; 8674 if (stagedDir != null) { 8675 origin = OriginInfo.fromStagedFile(stagedDir); 8676 } else { 8677 origin = OriginInfo.fromStagedContainer(stagedCid); 8678 } 8679 8680 final Message msg = mHandler.obtainMessage(INIT_COPY); 8681 msg.obj = new InstallParams(origin, observer, params.installFlags, 8682 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8683 mHandler.sendMessage(msg); 8684 } 8685 8686 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8687 Bundle extras = new Bundle(1); 8688 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8689 8690 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8691 packageName, extras, null, null, new int[] {userId}); 8692 try { 8693 IActivityManager am = ActivityManagerNative.getDefault(); 8694 final boolean isSystem = 8695 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8696 if (isSystem && am.isUserRunning(userId, false)) { 8697 // The just-installed/enabled app is bundled on the system, so presumed 8698 // to be able to run automatically without needing an explicit launch. 8699 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8700 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8701 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8702 .setPackage(packageName); 8703 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8704 android.app.AppOpsManager.OP_NONE, false, false, userId); 8705 } 8706 } catch (RemoteException e) { 8707 // shouldn't happen 8708 Slog.w(TAG, "Unable to bootstrap installed package", e); 8709 } 8710 } 8711 8712 @Override 8713 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8714 int userId) { 8715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8716 PackageSetting pkgSetting; 8717 final int uid = Binder.getCallingUid(); 8718 enforceCrossUserPermission(uid, userId, true, true, 8719 "setApplicationHiddenSetting for user " + userId); 8720 8721 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8722 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8723 return false; 8724 } 8725 8726 long callingId = Binder.clearCallingIdentity(); 8727 try { 8728 boolean sendAdded = false; 8729 boolean sendRemoved = false; 8730 // writer 8731 synchronized (mPackages) { 8732 pkgSetting = mSettings.mPackages.get(packageName); 8733 if (pkgSetting == null) { 8734 return false; 8735 } 8736 if (pkgSetting.getHidden(userId) != hidden) { 8737 pkgSetting.setHidden(hidden, userId); 8738 mSettings.writePackageRestrictionsLPr(userId); 8739 if (hidden) { 8740 sendRemoved = true; 8741 } else { 8742 sendAdded = true; 8743 } 8744 } 8745 } 8746 if (sendAdded) { 8747 sendPackageAddedForUser(packageName, pkgSetting, userId); 8748 return true; 8749 } 8750 if (sendRemoved) { 8751 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8752 "hiding pkg"); 8753 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8754 } 8755 } finally { 8756 Binder.restoreCallingIdentity(callingId); 8757 } 8758 return false; 8759 } 8760 8761 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8762 int userId) { 8763 final PackageRemovedInfo info = new PackageRemovedInfo(); 8764 info.removedPackage = packageName; 8765 info.removedUsers = new int[] {userId}; 8766 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8767 info.sendBroadcast(false, false, false); 8768 } 8769 8770 /** 8771 * Returns true if application is not found or there was an error. Otherwise it returns 8772 * the hidden state of the package for the given user. 8773 */ 8774 @Override 8775 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8777 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8778 false, "getApplicationHidden for user " + userId); 8779 PackageSetting pkgSetting; 8780 long callingId = Binder.clearCallingIdentity(); 8781 try { 8782 // writer 8783 synchronized (mPackages) { 8784 pkgSetting = mSettings.mPackages.get(packageName); 8785 if (pkgSetting == null) { 8786 return true; 8787 } 8788 return pkgSetting.getHidden(userId); 8789 } 8790 } finally { 8791 Binder.restoreCallingIdentity(callingId); 8792 } 8793 } 8794 8795 /** 8796 * @hide 8797 */ 8798 @Override 8799 public int installExistingPackageAsUser(String packageName, int userId) { 8800 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8801 null); 8802 PackageSetting pkgSetting; 8803 final int uid = Binder.getCallingUid(); 8804 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8805 + userId); 8806 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8807 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8808 } 8809 8810 long callingId = Binder.clearCallingIdentity(); 8811 try { 8812 boolean sendAdded = false; 8813 8814 // writer 8815 synchronized (mPackages) { 8816 pkgSetting = mSettings.mPackages.get(packageName); 8817 if (pkgSetting == null) { 8818 return PackageManager.INSTALL_FAILED_INVALID_URI; 8819 } 8820 if (!pkgSetting.getInstalled(userId)) { 8821 pkgSetting.setInstalled(true, userId); 8822 pkgSetting.setHidden(false, userId); 8823 mSettings.writePackageRestrictionsLPr(userId); 8824 sendAdded = true; 8825 } 8826 } 8827 8828 if (sendAdded) { 8829 sendPackageAddedForUser(packageName, pkgSetting, userId); 8830 } 8831 } finally { 8832 Binder.restoreCallingIdentity(callingId); 8833 } 8834 8835 return PackageManager.INSTALL_SUCCEEDED; 8836 } 8837 8838 boolean isUserRestricted(int userId, String restrictionKey) { 8839 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8840 if (restrictions.getBoolean(restrictionKey, false)) { 8841 Log.w(TAG, "User is restricted: " + restrictionKey); 8842 return true; 8843 } 8844 return false; 8845 } 8846 8847 @Override 8848 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8849 mContext.enforceCallingOrSelfPermission( 8850 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8851 "Only package verification agents can verify applications"); 8852 8853 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8854 final PackageVerificationResponse response = new PackageVerificationResponse( 8855 verificationCode, Binder.getCallingUid()); 8856 msg.arg1 = id; 8857 msg.obj = response; 8858 mHandler.sendMessage(msg); 8859 } 8860 8861 @Override 8862 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8863 long millisecondsToDelay) { 8864 mContext.enforceCallingOrSelfPermission( 8865 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8866 "Only package verification agents can extend verification timeouts"); 8867 8868 final PackageVerificationState state = mPendingVerification.get(id); 8869 final PackageVerificationResponse response = new PackageVerificationResponse( 8870 verificationCodeAtTimeout, Binder.getCallingUid()); 8871 8872 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8873 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8874 } 8875 if (millisecondsToDelay < 0) { 8876 millisecondsToDelay = 0; 8877 } 8878 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8879 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8880 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8881 } 8882 8883 if ((state != null) && !state.timeoutExtended()) { 8884 state.extendTimeout(); 8885 8886 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8887 msg.arg1 = id; 8888 msg.obj = response; 8889 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8890 } 8891 } 8892 8893 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8894 int verificationCode, UserHandle user) { 8895 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8896 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8897 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8898 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8899 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8900 8901 mContext.sendBroadcastAsUser(intent, user, 8902 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8903 } 8904 8905 private ComponentName matchComponentForVerifier(String packageName, 8906 List<ResolveInfo> receivers) { 8907 ActivityInfo targetReceiver = null; 8908 8909 final int NR = receivers.size(); 8910 for (int i = 0; i < NR; i++) { 8911 final ResolveInfo info = receivers.get(i); 8912 if (info.activityInfo == null) { 8913 continue; 8914 } 8915 8916 if (packageName.equals(info.activityInfo.packageName)) { 8917 targetReceiver = info.activityInfo; 8918 break; 8919 } 8920 } 8921 8922 if (targetReceiver == null) { 8923 return null; 8924 } 8925 8926 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8927 } 8928 8929 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8930 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8931 if (pkgInfo.verifiers.length == 0) { 8932 return null; 8933 } 8934 8935 final int N = pkgInfo.verifiers.length; 8936 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8937 for (int i = 0; i < N; i++) { 8938 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8939 8940 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8941 receivers); 8942 if (comp == null) { 8943 continue; 8944 } 8945 8946 final int verifierUid = getUidForVerifier(verifierInfo); 8947 if (verifierUid == -1) { 8948 continue; 8949 } 8950 8951 if (DEBUG_VERIFY) { 8952 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8953 + " with the correct signature"); 8954 } 8955 sufficientVerifiers.add(comp); 8956 verificationState.addSufficientVerifier(verifierUid); 8957 } 8958 8959 return sufficientVerifiers; 8960 } 8961 8962 private int getUidForVerifier(VerifierInfo verifierInfo) { 8963 synchronized (mPackages) { 8964 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8965 if (pkg == null) { 8966 return -1; 8967 } else if (pkg.mSignatures.length != 1) { 8968 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8969 + " has more than one signature; ignoring"); 8970 return -1; 8971 } 8972 8973 /* 8974 * If the public key of the package's signature does not match 8975 * our expected public key, then this is a different package and 8976 * we should skip. 8977 */ 8978 8979 final byte[] expectedPublicKey; 8980 try { 8981 final Signature verifierSig = pkg.mSignatures[0]; 8982 final PublicKey publicKey = verifierSig.getPublicKey(); 8983 expectedPublicKey = publicKey.getEncoded(); 8984 } catch (CertificateException e) { 8985 return -1; 8986 } 8987 8988 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8989 8990 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8991 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8992 + " does not have the expected public key; ignoring"); 8993 return -1; 8994 } 8995 8996 return pkg.applicationInfo.uid; 8997 } 8998 } 8999 9000 @Override 9001 public void finishPackageInstall(int token) { 9002 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9003 9004 if (DEBUG_INSTALL) { 9005 Slog.v(TAG, "BM finishing package install for " + token); 9006 } 9007 9008 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9009 mHandler.sendMessage(msg); 9010 } 9011 9012 /** 9013 * Get the verification agent timeout. 9014 * 9015 * @return verification timeout in milliseconds 9016 */ 9017 private long getVerificationTimeout() { 9018 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9019 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9020 DEFAULT_VERIFICATION_TIMEOUT); 9021 } 9022 9023 /** 9024 * Get the default verification agent response code. 9025 * 9026 * @return default verification response code 9027 */ 9028 private int getDefaultVerificationResponse() { 9029 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9030 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9031 DEFAULT_VERIFICATION_RESPONSE); 9032 } 9033 9034 /** 9035 * Check whether or not package verification has been enabled. 9036 * 9037 * @return true if verification should be performed 9038 */ 9039 private boolean isVerificationEnabled(int userId, int installFlags) { 9040 if (!DEFAULT_VERIFY_ENABLE) { 9041 return false; 9042 } 9043 9044 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9045 9046 // Check if installing from ADB 9047 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9048 // Do not run verification in a test harness environment 9049 if (ActivityManager.isRunningInTestHarness()) { 9050 return false; 9051 } 9052 if (ensureVerifyAppsEnabled) { 9053 return true; 9054 } 9055 // Check if the developer does not want package verification for ADB installs 9056 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9057 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9058 return false; 9059 } 9060 } 9061 9062 if (ensureVerifyAppsEnabled) { 9063 return true; 9064 } 9065 9066 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9067 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9068 } 9069 9070 @Override 9071 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9072 throws RemoteException { 9073 mContext.enforceCallingOrSelfPermission( 9074 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9075 "Only intentfilter verification agents can verify applications"); 9076 9077 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9078 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9079 Binder.getCallingUid(), verificationCode, failedDomains); 9080 msg.arg1 = id; 9081 msg.obj = response; 9082 mHandler.sendMessage(msg); 9083 } 9084 9085 @Override 9086 public int getIntentVerificationStatus(String packageName, int userId) { 9087 synchronized (mPackages) { 9088 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9089 } 9090 } 9091 9092 @Override 9093 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9094 boolean result = false; 9095 synchronized (mPackages) { 9096 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9097 } 9098 scheduleWritePackageRestrictionsLocked(userId); 9099 return result; 9100 } 9101 9102 @Override 9103 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9104 synchronized (mPackages) { 9105 return mSettings.getIntentFilterVerificationsLPr(packageName); 9106 } 9107 } 9108 9109 @Override 9110 public List<IntentFilter> getAllIntentFilters(String packageName) { 9111 if (TextUtils.isEmpty(packageName)) { 9112 return Collections.<IntentFilter>emptyList(); 9113 } 9114 synchronized (mPackages) { 9115 PackageParser.Package pkg = mPackages.get(packageName); 9116 if (pkg == null || pkg.activities == null) { 9117 return Collections.<IntentFilter>emptyList(); 9118 } 9119 final int count = pkg.activities.size(); 9120 ArrayList<IntentFilter> result = new ArrayList<>(); 9121 for (int n=0; n<count; n++) { 9122 PackageParser.Activity activity = pkg.activities.get(n); 9123 if (activity.intents != null || activity.intents.size() > 0) { 9124 result.addAll(activity.intents); 9125 } 9126 } 9127 return result; 9128 } 9129 } 9130 9131 @Override 9132 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9133 synchronized (mPackages) { 9134 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9135 } 9136 } 9137 9138 @Override 9139 public String getDefaultBrowserPackageName(int userId) { 9140 synchronized (mPackages) { 9141 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9142 } 9143 } 9144 9145 /** 9146 * Get the "allow unknown sources" setting. 9147 * 9148 * @return the current "allow unknown sources" setting 9149 */ 9150 private int getUnknownSourcesSettings() { 9151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9152 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9153 -1); 9154 } 9155 9156 @Override 9157 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9158 final int uid = Binder.getCallingUid(); 9159 // writer 9160 synchronized (mPackages) { 9161 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9162 if (targetPackageSetting == null) { 9163 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9164 } 9165 9166 PackageSetting installerPackageSetting; 9167 if (installerPackageName != null) { 9168 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9169 if (installerPackageSetting == null) { 9170 throw new IllegalArgumentException("Unknown installer package: " 9171 + installerPackageName); 9172 } 9173 } else { 9174 installerPackageSetting = null; 9175 } 9176 9177 Signature[] callerSignature; 9178 Object obj = mSettings.getUserIdLPr(uid); 9179 if (obj != null) { 9180 if (obj instanceof SharedUserSetting) { 9181 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9182 } else if (obj instanceof PackageSetting) { 9183 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9184 } else { 9185 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9186 } 9187 } else { 9188 throw new SecurityException("Unknown calling uid " + uid); 9189 } 9190 9191 // Verify: can't set installerPackageName to a package that is 9192 // not signed with the same cert as the caller. 9193 if (installerPackageSetting != null) { 9194 if (compareSignatures(callerSignature, 9195 installerPackageSetting.signatures.mSignatures) 9196 != PackageManager.SIGNATURE_MATCH) { 9197 throw new SecurityException( 9198 "Caller does not have same cert as new installer package " 9199 + installerPackageName); 9200 } 9201 } 9202 9203 // Verify: if target already has an installer package, it must 9204 // be signed with the same cert as the caller. 9205 if (targetPackageSetting.installerPackageName != null) { 9206 PackageSetting setting = mSettings.mPackages.get( 9207 targetPackageSetting.installerPackageName); 9208 // If the currently set package isn't valid, then it's always 9209 // okay to change it. 9210 if (setting != null) { 9211 if (compareSignatures(callerSignature, 9212 setting.signatures.mSignatures) 9213 != PackageManager.SIGNATURE_MATCH) { 9214 throw new SecurityException( 9215 "Caller does not have same cert as old installer package " 9216 + targetPackageSetting.installerPackageName); 9217 } 9218 } 9219 } 9220 9221 // Okay! 9222 targetPackageSetting.installerPackageName = installerPackageName; 9223 scheduleWriteSettingsLocked(); 9224 } 9225 } 9226 9227 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9228 // Queue up an async operation since the package installation may take a little while. 9229 mHandler.post(new Runnable() { 9230 public void run() { 9231 mHandler.removeCallbacks(this); 9232 // Result object to be returned 9233 PackageInstalledInfo res = new PackageInstalledInfo(); 9234 res.returnCode = currentStatus; 9235 res.uid = -1; 9236 res.pkg = null; 9237 res.removedInfo = new PackageRemovedInfo(); 9238 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9239 args.doPreInstall(res.returnCode); 9240 synchronized (mInstallLock) { 9241 installPackageLI(args, res); 9242 } 9243 args.doPostInstall(res.returnCode, res.uid); 9244 } 9245 9246 // A restore should be performed at this point if (a) the install 9247 // succeeded, (b) the operation is not an update, and (c) the new 9248 // package has not opted out of backup participation. 9249 final boolean update = res.removedInfo.removedPackage != null; 9250 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9251 boolean doRestore = !update 9252 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9253 9254 // Set up the post-install work request bookkeeping. This will be used 9255 // and cleaned up by the post-install event handling regardless of whether 9256 // there's a restore pass performed. Token values are >= 1. 9257 int token; 9258 if (mNextInstallToken < 0) mNextInstallToken = 1; 9259 token = mNextInstallToken++; 9260 9261 PostInstallData data = new PostInstallData(args, res); 9262 mRunningInstalls.put(token, data); 9263 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9264 9265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9266 // Pass responsibility to the Backup Manager. It will perform a 9267 // restore if appropriate, then pass responsibility back to the 9268 // Package Manager to run the post-install observer callbacks 9269 // and broadcasts. 9270 IBackupManager bm = IBackupManager.Stub.asInterface( 9271 ServiceManager.getService(Context.BACKUP_SERVICE)); 9272 if (bm != null) { 9273 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9274 + " to BM for possible restore"); 9275 try { 9276 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9277 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9278 } else { 9279 doRestore = false; 9280 } 9281 } catch (RemoteException e) { 9282 // can't happen; the backup manager is local 9283 } catch (Exception e) { 9284 Slog.e(TAG, "Exception trying to enqueue restore", e); 9285 doRestore = false; 9286 } 9287 } else { 9288 Slog.e(TAG, "Backup Manager not found!"); 9289 doRestore = false; 9290 } 9291 } 9292 9293 if (!doRestore) { 9294 // No restore possible, or the Backup Manager was mysteriously not 9295 // available -- just fire the post-install work request directly. 9296 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9297 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9298 mHandler.sendMessage(msg); 9299 } 9300 } 9301 }); 9302 } 9303 9304 private abstract class HandlerParams { 9305 private static final int MAX_RETRIES = 4; 9306 9307 /** 9308 * Number of times startCopy() has been attempted and had a non-fatal 9309 * error. 9310 */ 9311 private int mRetries = 0; 9312 9313 /** User handle for the user requesting the information or installation. */ 9314 private final UserHandle mUser; 9315 9316 HandlerParams(UserHandle user) { 9317 mUser = user; 9318 } 9319 9320 UserHandle getUser() { 9321 return mUser; 9322 } 9323 9324 final boolean startCopy() { 9325 boolean res; 9326 try { 9327 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9328 9329 if (++mRetries > MAX_RETRIES) { 9330 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9331 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9332 handleServiceError(); 9333 return false; 9334 } else { 9335 handleStartCopy(); 9336 res = true; 9337 } 9338 } catch (RemoteException e) { 9339 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9340 mHandler.sendEmptyMessage(MCS_RECONNECT); 9341 res = false; 9342 } 9343 handleReturnCode(); 9344 return res; 9345 } 9346 9347 final void serviceError() { 9348 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9349 handleServiceError(); 9350 handleReturnCode(); 9351 } 9352 9353 abstract void handleStartCopy() throws RemoteException; 9354 abstract void handleServiceError(); 9355 abstract void handleReturnCode(); 9356 } 9357 9358 class MeasureParams extends HandlerParams { 9359 private final PackageStats mStats; 9360 private boolean mSuccess; 9361 9362 private final IPackageStatsObserver mObserver; 9363 9364 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9365 super(new UserHandle(stats.userHandle)); 9366 mObserver = observer; 9367 mStats = stats; 9368 } 9369 9370 @Override 9371 public String toString() { 9372 return "MeasureParams{" 9373 + Integer.toHexString(System.identityHashCode(this)) 9374 + " " + mStats.packageName + "}"; 9375 } 9376 9377 @Override 9378 void handleStartCopy() throws RemoteException { 9379 synchronized (mInstallLock) { 9380 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9381 } 9382 9383 if (mSuccess) { 9384 final boolean mounted; 9385 if (Environment.isExternalStorageEmulated()) { 9386 mounted = true; 9387 } else { 9388 final String status = Environment.getExternalStorageState(); 9389 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9390 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9391 } 9392 9393 if (mounted) { 9394 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9395 9396 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9397 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9398 9399 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9400 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9401 9402 // Always subtract cache size, since it's a subdirectory 9403 mStats.externalDataSize -= mStats.externalCacheSize; 9404 9405 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9406 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9407 9408 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9409 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9410 } 9411 } 9412 } 9413 9414 @Override 9415 void handleReturnCode() { 9416 if (mObserver != null) { 9417 try { 9418 mObserver.onGetStatsCompleted(mStats, mSuccess); 9419 } catch (RemoteException e) { 9420 Slog.i(TAG, "Observer no longer exists."); 9421 } 9422 } 9423 } 9424 9425 @Override 9426 void handleServiceError() { 9427 Slog.e(TAG, "Could not measure application " + mStats.packageName 9428 + " external storage"); 9429 } 9430 } 9431 9432 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9433 throws RemoteException { 9434 long result = 0; 9435 for (File path : paths) { 9436 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9437 } 9438 return result; 9439 } 9440 9441 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9442 for (File path : paths) { 9443 try { 9444 mcs.clearDirectory(path.getAbsolutePath()); 9445 } catch (RemoteException e) { 9446 } 9447 } 9448 } 9449 9450 static class OriginInfo { 9451 /** 9452 * Location where install is coming from, before it has been 9453 * copied/renamed into place. This could be a single monolithic APK 9454 * file, or a cluster directory. This location may be untrusted. 9455 */ 9456 final File file; 9457 final String cid; 9458 9459 /** 9460 * Flag indicating that {@link #file} or {@link #cid} has already been 9461 * staged, meaning downstream users don't need to defensively copy the 9462 * contents. 9463 */ 9464 final boolean staged; 9465 9466 /** 9467 * Flag indicating that {@link #file} or {@link #cid} is an already 9468 * installed app that is being moved. 9469 */ 9470 final boolean existing; 9471 9472 final String resolvedPath; 9473 final File resolvedFile; 9474 9475 static OriginInfo fromNothing() { 9476 return new OriginInfo(null, null, false, false); 9477 } 9478 9479 static OriginInfo fromUntrustedFile(File file) { 9480 return new OriginInfo(file, null, false, false); 9481 } 9482 9483 static OriginInfo fromExistingFile(File file) { 9484 return new OriginInfo(file, null, false, true); 9485 } 9486 9487 static OriginInfo fromStagedFile(File file) { 9488 return new OriginInfo(file, null, true, false); 9489 } 9490 9491 static OriginInfo fromStagedContainer(String cid) { 9492 return new OriginInfo(null, cid, true, false); 9493 } 9494 9495 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9496 this.file = file; 9497 this.cid = cid; 9498 this.staged = staged; 9499 this.existing = existing; 9500 9501 if (cid != null) { 9502 resolvedPath = PackageHelper.getSdDir(cid); 9503 resolvedFile = new File(resolvedPath); 9504 } else if (file != null) { 9505 resolvedPath = file.getAbsolutePath(); 9506 resolvedFile = file; 9507 } else { 9508 resolvedPath = null; 9509 resolvedFile = null; 9510 } 9511 } 9512 } 9513 9514 class InstallParams extends HandlerParams { 9515 final OriginInfo origin; 9516 final IPackageInstallObserver2 observer; 9517 int installFlags; 9518 final String installerPackageName; 9519 final String volumeUuid; 9520 final VerificationParams verificationParams; 9521 private InstallArgs mArgs; 9522 private int mRet; 9523 final String packageAbiOverride; 9524 9525 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9526 String installerPackageName, String volumeUuid, 9527 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9528 super(user); 9529 this.origin = origin; 9530 this.observer = observer; 9531 this.installFlags = installFlags; 9532 this.installerPackageName = installerPackageName; 9533 this.volumeUuid = volumeUuid; 9534 this.verificationParams = verificationParams; 9535 this.packageAbiOverride = packageAbiOverride; 9536 } 9537 9538 @Override 9539 public String toString() { 9540 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9541 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9542 } 9543 9544 public ManifestDigest getManifestDigest() { 9545 if (verificationParams == null) { 9546 return null; 9547 } 9548 return verificationParams.getManifestDigest(); 9549 } 9550 9551 private int installLocationPolicy(PackageInfoLite pkgLite) { 9552 String packageName = pkgLite.packageName; 9553 int installLocation = pkgLite.installLocation; 9554 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9555 // reader 9556 synchronized (mPackages) { 9557 PackageParser.Package pkg = mPackages.get(packageName); 9558 if (pkg != null) { 9559 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9560 // Check for downgrading. 9561 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9562 try { 9563 checkDowngrade(pkg, pkgLite); 9564 } catch (PackageManagerException e) { 9565 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9566 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9567 } 9568 } 9569 // Check for updated system application. 9570 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9571 if (onSd) { 9572 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9573 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9574 } 9575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9576 } else { 9577 if (onSd) { 9578 // Install flag overrides everything. 9579 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9580 } 9581 // If current upgrade specifies particular preference 9582 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9583 // Application explicitly specified internal. 9584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9585 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9586 // App explictly prefers external. Let policy decide 9587 } else { 9588 // Prefer previous location 9589 if (isExternal(pkg)) { 9590 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9591 } 9592 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9593 } 9594 } 9595 } else { 9596 // Invalid install. Return error code 9597 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9598 } 9599 } 9600 } 9601 // All the special cases have been taken care of. 9602 // Return result based on recommended install location. 9603 if (onSd) { 9604 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9605 } 9606 return pkgLite.recommendedInstallLocation; 9607 } 9608 9609 /* 9610 * Invoke remote method to get package information and install 9611 * location values. Override install location based on default 9612 * policy if needed and then create install arguments based 9613 * on the install location. 9614 */ 9615 public void handleStartCopy() throws RemoteException { 9616 int ret = PackageManager.INSTALL_SUCCEEDED; 9617 9618 // If we're already staged, we've firmly committed to an install location 9619 if (origin.staged) { 9620 if (origin.file != null) { 9621 installFlags |= PackageManager.INSTALL_INTERNAL; 9622 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9623 } else if (origin.cid != null) { 9624 installFlags |= PackageManager.INSTALL_EXTERNAL; 9625 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9626 } else { 9627 throw new IllegalStateException("Invalid stage location"); 9628 } 9629 } 9630 9631 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9632 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9633 9634 PackageInfoLite pkgLite = null; 9635 9636 if (onInt && onSd) { 9637 // Check if both bits are set. 9638 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9640 } else { 9641 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9642 packageAbiOverride); 9643 9644 /* 9645 * If we have too little free space, try to free cache 9646 * before giving up. 9647 */ 9648 if (!origin.staged && pkgLite.recommendedInstallLocation 9649 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9650 // TODO: focus freeing disk space on the target device 9651 final StorageManager storage = StorageManager.from(mContext); 9652 final long lowThreshold = storage.getStorageLowBytes( 9653 Environment.getDataDirectory()); 9654 9655 final long sizeBytes = mContainerService.calculateInstalledSize( 9656 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9657 9658 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9659 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9660 installFlags, packageAbiOverride); 9661 } 9662 9663 /* 9664 * The cache free must have deleted the file we 9665 * downloaded to install. 9666 * 9667 * TODO: fix the "freeCache" call to not delete 9668 * the file we care about. 9669 */ 9670 if (pkgLite.recommendedInstallLocation 9671 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9672 pkgLite.recommendedInstallLocation 9673 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9674 } 9675 } 9676 } 9677 9678 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9679 int loc = pkgLite.recommendedInstallLocation; 9680 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9681 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9682 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9683 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9684 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9685 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9686 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9687 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9688 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9689 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9690 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9691 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9692 } else { 9693 // Override with defaults if needed. 9694 loc = installLocationPolicy(pkgLite); 9695 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9696 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9697 } else if (!onSd && !onInt) { 9698 // Override install location with flags 9699 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9700 // Set the flag to install on external media. 9701 installFlags |= PackageManager.INSTALL_EXTERNAL; 9702 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9703 } else { 9704 // Make sure the flag for installing on external 9705 // media is unset 9706 installFlags |= PackageManager.INSTALL_INTERNAL; 9707 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9708 } 9709 } 9710 } 9711 } 9712 9713 final InstallArgs args = createInstallArgs(this); 9714 mArgs = args; 9715 9716 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9717 /* 9718 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9719 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9720 */ 9721 int userIdentifier = getUser().getIdentifier(); 9722 if (userIdentifier == UserHandle.USER_ALL 9723 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9724 userIdentifier = UserHandle.USER_OWNER; 9725 } 9726 9727 /* 9728 * Determine if we have any installed package verifiers. If we 9729 * do, then we'll defer to them to verify the packages. 9730 */ 9731 final int requiredUid = mRequiredVerifierPackage == null ? -1 9732 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9733 if (!origin.existing && requiredUid != -1 9734 && isVerificationEnabled(userIdentifier, installFlags)) { 9735 final Intent verification = new Intent( 9736 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9737 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9738 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9739 PACKAGE_MIME_TYPE); 9740 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9741 9742 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9743 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9744 0 /* TODO: Which userId? */); 9745 9746 if (DEBUG_VERIFY) { 9747 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9748 + verification.toString() + " with " + pkgLite.verifiers.length 9749 + " optional verifiers"); 9750 } 9751 9752 final int verificationId = mPendingVerificationToken++; 9753 9754 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9755 9756 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9757 installerPackageName); 9758 9759 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9760 installFlags); 9761 9762 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9763 pkgLite.packageName); 9764 9765 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9766 pkgLite.versionCode); 9767 9768 if (verificationParams != null) { 9769 if (verificationParams.getVerificationURI() != null) { 9770 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9771 verificationParams.getVerificationURI()); 9772 } 9773 if (verificationParams.getOriginatingURI() != null) { 9774 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9775 verificationParams.getOriginatingURI()); 9776 } 9777 if (verificationParams.getReferrer() != null) { 9778 verification.putExtra(Intent.EXTRA_REFERRER, 9779 verificationParams.getReferrer()); 9780 } 9781 if (verificationParams.getOriginatingUid() >= 0) { 9782 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9783 verificationParams.getOriginatingUid()); 9784 } 9785 if (verificationParams.getInstallerUid() >= 0) { 9786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9787 verificationParams.getInstallerUid()); 9788 } 9789 } 9790 9791 final PackageVerificationState verificationState = new PackageVerificationState( 9792 requiredUid, args); 9793 9794 mPendingVerification.append(verificationId, verificationState); 9795 9796 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9797 receivers, verificationState); 9798 9799 /* 9800 * If any sufficient verifiers were listed in the package 9801 * manifest, attempt to ask them. 9802 */ 9803 if (sufficientVerifiers != null) { 9804 final int N = sufficientVerifiers.size(); 9805 if (N == 0) { 9806 Slog.i(TAG, "Additional verifiers required, but none installed."); 9807 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9808 } else { 9809 for (int i = 0; i < N; i++) { 9810 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9811 9812 final Intent sufficientIntent = new Intent(verification); 9813 sufficientIntent.setComponent(verifierComponent); 9814 9815 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9816 } 9817 } 9818 } 9819 9820 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9821 mRequiredVerifierPackage, receivers); 9822 if (ret == PackageManager.INSTALL_SUCCEEDED 9823 && mRequiredVerifierPackage != null) { 9824 /* 9825 * Send the intent to the required verification agent, 9826 * but only start the verification timeout after the 9827 * target BroadcastReceivers have run. 9828 */ 9829 verification.setComponent(requiredVerifierComponent); 9830 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9831 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9832 new BroadcastReceiver() { 9833 @Override 9834 public void onReceive(Context context, Intent intent) { 9835 final Message msg = mHandler 9836 .obtainMessage(CHECK_PENDING_VERIFICATION); 9837 msg.arg1 = verificationId; 9838 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9839 } 9840 }, null, 0, null, null); 9841 9842 /* 9843 * We don't want the copy to proceed until verification 9844 * succeeds, so null out this field. 9845 */ 9846 mArgs = null; 9847 } 9848 } else { 9849 /* 9850 * No package verification is enabled, so immediately start 9851 * the remote call to initiate copy using temporary file. 9852 */ 9853 ret = args.copyApk(mContainerService, true); 9854 } 9855 } 9856 9857 mRet = ret; 9858 } 9859 9860 @Override 9861 void handleReturnCode() { 9862 // If mArgs is null, then MCS couldn't be reached. When it 9863 // reconnects, it will try again to install. At that point, this 9864 // will succeed. 9865 if (mArgs != null) { 9866 processPendingInstall(mArgs, mRet); 9867 } 9868 } 9869 9870 @Override 9871 void handleServiceError() { 9872 mArgs = createInstallArgs(this); 9873 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9874 } 9875 9876 public boolean isForwardLocked() { 9877 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9878 } 9879 } 9880 9881 /** 9882 * Used during creation of InstallArgs 9883 * 9884 * @param installFlags package installation flags 9885 * @return true if should be installed on external storage 9886 */ 9887 private static boolean installOnExternalAsec(int installFlags) { 9888 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9889 return false; 9890 } 9891 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9892 return true; 9893 } 9894 return false; 9895 } 9896 9897 /** 9898 * Used during creation of InstallArgs 9899 * 9900 * @param installFlags package installation flags 9901 * @return true if should be installed as forward locked 9902 */ 9903 private static boolean installForwardLocked(int installFlags) { 9904 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9905 } 9906 9907 private InstallArgs createInstallArgs(InstallParams params) { 9908 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9909 return new AsecInstallArgs(params); 9910 } else { 9911 return new FileInstallArgs(params); 9912 } 9913 } 9914 9915 /** 9916 * Create args that describe an existing installed package. Typically used 9917 * when cleaning up old installs, or used as a move source. 9918 */ 9919 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9920 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9921 final boolean isInAsec; 9922 if (installOnExternalAsec(installFlags)) { 9923 /* Apps on SD card are always in ASEC containers. */ 9924 isInAsec = true; 9925 } else if (installForwardLocked(installFlags) 9926 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9927 /* 9928 * Forward-locked apps are only in ASEC containers if they're the 9929 * new style 9930 */ 9931 isInAsec = true; 9932 } else { 9933 isInAsec = false; 9934 } 9935 9936 if (isInAsec) { 9937 return new AsecInstallArgs(codePath, instructionSets, 9938 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9939 } else { 9940 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9941 instructionSets); 9942 } 9943 } 9944 9945 static abstract class InstallArgs { 9946 /** @see InstallParams#origin */ 9947 final OriginInfo origin; 9948 9949 final IPackageInstallObserver2 observer; 9950 // Always refers to PackageManager flags only 9951 final int installFlags; 9952 final String installerPackageName; 9953 final String volumeUuid; 9954 final ManifestDigest manifestDigest; 9955 final UserHandle user; 9956 final String abiOverride; 9957 9958 // The list of instruction sets supported by this app. This is currently 9959 // only used during the rmdex() phase to clean up resources. We can get rid of this 9960 // if we move dex files under the common app path. 9961 /* nullable */ String[] instructionSets; 9962 9963 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9964 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9965 UserHandle user, String[] instructionSets, String abiOverride) { 9966 this.origin = origin; 9967 this.installFlags = installFlags; 9968 this.observer = observer; 9969 this.installerPackageName = installerPackageName; 9970 this.volumeUuid = volumeUuid; 9971 this.manifestDigest = manifestDigest; 9972 this.user = user; 9973 this.instructionSets = instructionSets; 9974 this.abiOverride = abiOverride; 9975 } 9976 9977 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9978 abstract int doPreInstall(int status); 9979 9980 /** 9981 * Rename package into final resting place. All paths on the given 9982 * scanned package should be updated to reflect the rename. 9983 */ 9984 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9985 abstract int doPostInstall(int status, int uid); 9986 9987 /** @see PackageSettingBase#codePathString */ 9988 abstract String getCodePath(); 9989 /** @see PackageSettingBase#resourcePathString */ 9990 abstract String getResourcePath(); 9991 abstract String getLegacyNativeLibraryPath(); 9992 9993 // Need installer lock especially for dex file removal. 9994 abstract void cleanUpResourcesLI(); 9995 abstract boolean doPostDeleteLI(boolean delete); 9996 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9997 9998 /** 9999 * Called before the source arguments are copied. This is used mostly 10000 * for MoveParams when it needs to read the source file to put it in the 10001 * destination. 10002 */ 10003 int doPreCopy() { 10004 return PackageManager.INSTALL_SUCCEEDED; 10005 } 10006 10007 /** 10008 * Called after the source arguments are copied. This is used mostly for 10009 * MoveParams when it needs to read the source file to put it in the 10010 * destination. 10011 * 10012 * @return 10013 */ 10014 int doPostCopy(int uid) { 10015 return PackageManager.INSTALL_SUCCEEDED; 10016 } 10017 10018 protected boolean isFwdLocked() { 10019 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10020 } 10021 10022 protected boolean isExternalAsec() { 10023 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10024 } 10025 10026 UserHandle getUser() { 10027 return user; 10028 } 10029 } 10030 10031 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10032 if (!allCodePaths.isEmpty()) { 10033 if (instructionSets == null) { 10034 throw new IllegalStateException("instructionSet == null"); 10035 } 10036 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10037 for (String codePath : allCodePaths) { 10038 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10039 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10040 if (retCode < 0) { 10041 Slog.w(TAG, "Couldn't remove dex file for package: " 10042 + " at location " + codePath + ", retcode=" + retCode); 10043 // we don't consider this to be a failure of the core package deletion 10044 } 10045 } 10046 } 10047 } 10048 } 10049 10050 /** 10051 * Logic to handle installation of non-ASEC applications, including copying 10052 * and renaming logic. 10053 */ 10054 class FileInstallArgs extends InstallArgs { 10055 private File codeFile; 10056 private File resourceFile; 10057 private File legacyNativeLibraryPath; 10058 10059 // Example topology: 10060 // /data/app/com.example/base.apk 10061 // /data/app/com.example/split_foo.apk 10062 // /data/app/com.example/lib/arm/libfoo.so 10063 // /data/app/com.example/lib/arm64/libfoo.so 10064 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10065 10066 /** New install */ 10067 FileInstallArgs(InstallParams params) { 10068 super(params.origin, params.observer, params.installFlags, 10069 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10070 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10071 if (isFwdLocked()) { 10072 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10073 } 10074 } 10075 10076 /** Existing install */ 10077 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10078 String[] instructionSets) { 10079 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10080 this.codeFile = (codePath != null) ? new File(codePath) : null; 10081 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10082 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10083 new File(legacyNativeLibraryPath) : null; 10084 } 10085 10086 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10087 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10088 isFwdLocked(), abiOverride); 10089 10090 final StorageManager storage = StorageManager.from(mContext); 10091 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10092 } 10093 10094 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10095 if (origin.staged) { 10096 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10097 codeFile = origin.file; 10098 resourceFile = origin.file; 10099 return PackageManager.INSTALL_SUCCEEDED; 10100 } 10101 10102 try { 10103 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10104 codeFile = tempDir; 10105 resourceFile = tempDir; 10106 } catch (IOException e) { 10107 Slog.w(TAG, "Failed to create copy file: " + e); 10108 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10109 } 10110 10111 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10112 @Override 10113 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10114 if (!FileUtils.isValidExtFilename(name)) { 10115 throw new IllegalArgumentException("Invalid filename: " + name); 10116 } 10117 try { 10118 final File file = new File(codeFile, name); 10119 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10120 O_RDWR | O_CREAT, 0644); 10121 Os.chmod(file.getAbsolutePath(), 0644); 10122 return new ParcelFileDescriptor(fd); 10123 } catch (ErrnoException e) { 10124 throw new RemoteException("Failed to open: " + e.getMessage()); 10125 } 10126 } 10127 }; 10128 10129 int ret = PackageManager.INSTALL_SUCCEEDED; 10130 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10131 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10132 Slog.e(TAG, "Failed to copy package"); 10133 return ret; 10134 } 10135 10136 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10137 NativeLibraryHelper.Handle handle = null; 10138 try { 10139 handle = NativeLibraryHelper.Handle.create(codeFile); 10140 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10141 abiOverride); 10142 } catch (IOException e) { 10143 Slog.e(TAG, "Copying native libraries failed", e); 10144 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10145 } finally { 10146 IoUtils.closeQuietly(handle); 10147 } 10148 10149 return ret; 10150 } 10151 10152 int doPreInstall(int status) { 10153 if (status != PackageManager.INSTALL_SUCCEEDED) { 10154 cleanUp(); 10155 } 10156 return status; 10157 } 10158 10159 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10160 if (status != PackageManager.INSTALL_SUCCEEDED) { 10161 cleanUp(); 10162 return false; 10163 } else { 10164 final File targetDir = codeFile.getParentFile(); 10165 final File beforeCodeFile = codeFile; 10166 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10167 10168 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10169 try { 10170 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10171 } catch (ErrnoException e) { 10172 Slog.d(TAG, "Failed to rename", e); 10173 return false; 10174 } 10175 10176 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10177 Slog.d(TAG, "Failed to restorecon"); 10178 return false; 10179 } 10180 10181 // Reflect the rename internally 10182 codeFile = afterCodeFile; 10183 resourceFile = afterCodeFile; 10184 10185 // Reflect the rename in scanned details 10186 pkg.codePath = afterCodeFile.getAbsolutePath(); 10187 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10188 pkg.baseCodePath); 10189 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10190 pkg.splitCodePaths); 10191 10192 // Reflect the rename in app info 10193 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10194 pkg.applicationInfo.setCodePath(pkg.codePath); 10195 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10196 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10197 pkg.applicationInfo.setResourcePath(pkg.codePath); 10198 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10199 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10200 10201 return true; 10202 } 10203 } 10204 10205 int doPostInstall(int status, int uid) { 10206 if (status != PackageManager.INSTALL_SUCCEEDED) { 10207 cleanUp(); 10208 } 10209 return status; 10210 } 10211 10212 @Override 10213 String getCodePath() { 10214 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10215 } 10216 10217 @Override 10218 String getResourcePath() { 10219 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10220 } 10221 10222 @Override 10223 String getLegacyNativeLibraryPath() { 10224 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10225 } 10226 10227 private boolean cleanUp() { 10228 if (codeFile == null || !codeFile.exists()) { 10229 return false; 10230 } 10231 10232 if (codeFile.isDirectory()) { 10233 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10234 } else { 10235 codeFile.delete(); 10236 } 10237 10238 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10239 resourceFile.delete(); 10240 } 10241 10242 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10243 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10244 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10245 } 10246 legacyNativeLibraryPath.delete(); 10247 } 10248 10249 return true; 10250 } 10251 10252 void cleanUpResourcesLI() { 10253 // Try enumerating all code paths before deleting 10254 List<String> allCodePaths = Collections.EMPTY_LIST; 10255 if (codeFile != null && codeFile.exists()) { 10256 try { 10257 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10258 allCodePaths = pkg.getAllCodePaths(); 10259 } catch (PackageParserException e) { 10260 // Ignored; we tried our best 10261 } 10262 } 10263 10264 cleanUp(); 10265 removeDexFiles(allCodePaths, instructionSets); 10266 } 10267 10268 boolean doPostDeleteLI(boolean delete) { 10269 // XXX err, shouldn't we respect the delete flag? 10270 cleanUpResourcesLI(); 10271 return true; 10272 } 10273 } 10274 10275 private boolean isAsecExternal(String cid) { 10276 final String asecPath = PackageHelper.getSdFilesystem(cid); 10277 return !asecPath.startsWith(mAsecInternalPath); 10278 } 10279 10280 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10281 PackageManagerException { 10282 if (copyRet < 0) { 10283 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10284 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10285 throw new PackageManagerException(copyRet, message); 10286 } 10287 } 10288 } 10289 10290 /** 10291 * Extract the MountService "container ID" from the full code path of an 10292 * .apk. 10293 */ 10294 static String cidFromCodePath(String fullCodePath) { 10295 int eidx = fullCodePath.lastIndexOf("/"); 10296 String subStr1 = fullCodePath.substring(0, eidx); 10297 int sidx = subStr1.lastIndexOf("/"); 10298 return subStr1.substring(sidx+1, eidx); 10299 } 10300 10301 /** 10302 * Logic to handle installation of ASEC applications, including copying and 10303 * renaming logic. 10304 */ 10305 class AsecInstallArgs extends InstallArgs { 10306 static final String RES_FILE_NAME = "pkg.apk"; 10307 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10308 10309 String cid; 10310 String packagePath; 10311 String resourcePath; 10312 String legacyNativeLibraryDir; 10313 10314 /** New install */ 10315 AsecInstallArgs(InstallParams params) { 10316 super(params.origin, params.observer, params.installFlags, 10317 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10318 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10319 } 10320 10321 /** Existing install */ 10322 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10323 boolean isExternal, boolean isForwardLocked) { 10324 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10325 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10326 instructionSets, null); 10327 // Hackily pretend we're still looking at a full code path 10328 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10329 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10330 } 10331 10332 // Extract cid from fullCodePath 10333 int eidx = fullCodePath.lastIndexOf("/"); 10334 String subStr1 = fullCodePath.substring(0, eidx); 10335 int sidx = subStr1.lastIndexOf("/"); 10336 cid = subStr1.substring(sidx+1, eidx); 10337 setMountPath(subStr1); 10338 } 10339 10340 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10341 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10342 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10343 instructionSets, null); 10344 this.cid = cid; 10345 setMountPath(PackageHelper.getSdDir(cid)); 10346 } 10347 10348 void createCopyFile() { 10349 cid = mInstallerService.allocateExternalStageCidLegacy(); 10350 } 10351 10352 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10353 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10354 abiOverride); 10355 10356 final File target; 10357 if (isExternalAsec()) { 10358 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10359 } else { 10360 target = Environment.getDataDirectory(); 10361 } 10362 10363 final StorageManager storage = StorageManager.from(mContext); 10364 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10365 } 10366 10367 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10368 if (origin.staged) { 10369 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10370 cid = origin.cid; 10371 setMountPath(PackageHelper.getSdDir(cid)); 10372 return PackageManager.INSTALL_SUCCEEDED; 10373 } 10374 10375 if (temp) { 10376 createCopyFile(); 10377 } else { 10378 /* 10379 * Pre-emptively destroy the container since it's destroyed if 10380 * copying fails due to it existing anyway. 10381 */ 10382 PackageHelper.destroySdDir(cid); 10383 } 10384 10385 final String newMountPath = imcs.copyPackageToContainer( 10386 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10387 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10388 10389 if (newMountPath != null) { 10390 setMountPath(newMountPath); 10391 return PackageManager.INSTALL_SUCCEEDED; 10392 } else { 10393 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10394 } 10395 } 10396 10397 @Override 10398 String getCodePath() { 10399 return packagePath; 10400 } 10401 10402 @Override 10403 String getResourcePath() { 10404 return resourcePath; 10405 } 10406 10407 @Override 10408 String getLegacyNativeLibraryPath() { 10409 return legacyNativeLibraryDir; 10410 } 10411 10412 int doPreInstall(int status) { 10413 if (status != PackageManager.INSTALL_SUCCEEDED) { 10414 // Destroy container 10415 PackageHelper.destroySdDir(cid); 10416 } else { 10417 boolean mounted = PackageHelper.isContainerMounted(cid); 10418 if (!mounted) { 10419 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10420 Process.SYSTEM_UID); 10421 if (newMountPath != null) { 10422 setMountPath(newMountPath); 10423 } else { 10424 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10425 } 10426 } 10427 } 10428 return status; 10429 } 10430 10431 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10432 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10433 String newMountPath = null; 10434 if (PackageHelper.isContainerMounted(cid)) { 10435 // Unmount the container 10436 if (!PackageHelper.unMountSdDir(cid)) { 10437 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10438 return false; 10439 } 10440 } 10441 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10442 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10443 " which might be stale. Will try to clean up."); 10444 // Clean up the stale container and proceed to recreate. 10445 if (!PackageHelper.destroySdDir(newCacheId)) { 10446 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10447 return false; 10448 } 10449 // Successfully cleaned up stale container. Try to rename again. 10450 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10451 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10452 + " inspite of cleaning it up."); 10453 return false; 10454 } 10455 } 10456 if (!PackageHelper.isContainerMounted(newCacheId)) { 10457 Slog.w(TAG, "Mounting container " + newCacheId); 10458 newMountPath = PackageHelper.mountSdDir(newCacheId, 10459 getEncryptKey(), Process.SYSTEM_UID); 10460 } else { 10461 newMountPath = PackageHelper.getSdDir(newCacheId); 10462 } 10463 if (newMountPath == null) { 10464 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10465 return false; 10466 } 10467 Log.i(TAG, "Succesfully renamed " + cid + 10468 " to " + newCacheId + 10469 " at new path: " + newMountPath); 10470 cid = newCacheId; 10471 10472 final File beforeCodeFile = new File(packagePath); 10473 setMountPath(newMountPath); 10474 final File afterCodeFile = new File(packagePath); 10475 10476 // Reflect the rename in scanned details 10477 pkg.codePath = afterCodeFile.getAbsolutePath(); 10478 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10479 pkg.baseCodePath); 10480 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10481 pkg.splitCodePaths); 10482 10483 // Reflect the rename in app info 10484 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10485 pkg.applicationInfo.setCodePath(pkg.codePath); 10486 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10487 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10488 pkg.applicationInfo.setResourcePath(pkg.codePath); 10489 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10490 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10491 10492 return true; 10493 } 10494 10495 private void setMountPath(String mountPath) { 10496 final File mountFile = new File(mountPath); 10497 10498 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10499 if (monolithicFile.exists()) { 10500 packagePath = monolithicFile.getAbsolutePath(); 10501 if (isFwdLocked()) { 10502 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10503 } else { 10504 resourcePath = packagePath; 10505 } 10506 } else { 10507 packagePath = mountFile.getAbsolutePath(); 10508 resourcePath = packagePath; 10509 } 10510 10511 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10512 } 10513 10514 int doPostInstall(int status, int uid) { 10515 if (status != PackageManager.INSTALL_SUCCEEDED) { 10516 cleanUp(); 10517 } else { 10518 final int groupOwner; 10519 final String protectedFile; 10520 if (isFwdLocked()) { 10521 groupOwner = UserHandle.getSharedAppGid(uid); 10522 protectedFile = RES_FILE_NAME; 10523 } else { 10524 groupOwner = -1; 10525 protectedFile = null; 10526 } 10527 10528 if (uid < Process.FIRST_APPLICATION_UID 10529 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10530 Slog.e(TAG, "Failed to finalize " + cid); 10531 PackageHelper.destroySdDir(cid); 10532 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10533 } 10534 10535 boolean mounted = PackageHelper.isContainerMounted(cid); 10536 if (!mounted) { 10537 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10538 } 10539 } 10540 return status; 10541 } 10542 10543 private void cleanUp() { 10544 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10545 10546 // Destroy secure container 10547 PackageHelper.destroySdDir(cid); 10548 } 10549 10550 private List<String> getAllCodePaths() { 10551 final File codeFile = new File(getCodePath()); 10552 if (codeFile != null && codeFile.exists()) { 10553 try { 10554 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10555 return pkg.getAllCodePaths(); 10556 } catch (PackageParserException e) { 10557 // Ignored; we tried our best 10558 } 10559 } 10560 return Collections.EMPTY_LIST; 10561 } 10562 10563 void cleanUpResourcesLI() { 10564 // Enumerate all code paths before deleting 10565 cleanUpResourcesLI(getAllCodePaths()); 10566 } 10567 10568 private void cleanUpResourcesLI(List<String> allCodePaths) { 10569 cleanUp(); 10570 removeDexFiles(allCodePaths, instructionSets); 10571 } 10572 10573 10574 10575 String getPackageName() { 10576 return getAsecPackageName(cid); 10577 } 10578 10579 boolean doPostDeleteLI(boolean delete) { 10580 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10581 final List<String> allCodePaths = getAllCodePaths(); 10582 boolean mounted = PackageHelper.isContainerMounted(cid); 10583 if (mounted) { 10584 // Unmount first 10585 if (PackageHelper.unMountSdDir(cid)) { 10586 mounted = false; 10587 } 10588 } 10589 if (!mounted && delete) { 10590 cleanUpResourcesLI(allCodePaths); 10591 } 10592 return !mounted; 10593 } 10594 10595 @Override 10596 int doPreCopy() { 10597 if (isFwdLocked()) { 10598 if (!PackageHelper.fixSdPermissions(cid, 10599 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10600 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10601 } 10602 } 10603 10604 return PackageManager.INSTALL_SUCCEEDED; 10605 } 10606 10607 @Override 10608 int doPostCopy(int uid) { 10609 if (isFwdLocked()) { 10610 if (uid < Process.FIRST_APPLICATION_UID 10611 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10612 RES_FILE_NAME)) { 10613 Slog.e(TAG, "Failed to finalize " + cid); 10614 PackageHelper.destroySdDir(cid); 10615 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10616 } 10617 } 10618 10619 return PackageManager.INSTALL_SUCCEEDED; 10620 } 10621 } 10622 10623 static String getAsecPackageName(String packageCid) { 10624 int idx = packageCid.lastIndexOf("-"); 10625 if (idx == -1) { 10626 return packageCid; 10627 } 10628 return packageCid.substring(0, idx); 10629 } 10630 10631 // Utility method used to create code paths based on package name and available index. 10632 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10633 String idxStr = ""; 10634 int idx = 1; 10635 // Fall back to default value of idx=1 if prefix is not 10636 // part of oldCodePath 10637 if (oldCodePath != null) { 10638 String subStr = oldCodePath; 10639 // Drop the suffix right away 10640 if (suffix != null && subStr.endsWith(suffix)) { 10641 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10642 } 10643 // If oldCodePath already contains prefix find out the 10644 // ending index to either increment or decrement. 10645 int sidx = subStr.lastIndexOf(prefix); 10646 if (sidx != -1) { 10647 subStr = subStr.substring(sidx + prefix.length()); 10648 if (subStr != null) { 10649 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10650 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10651 } 10652 try { 10653 idx = Integer.parseInt(subStr); 10654 if (idx <= 1) { 10655 idx++; 10656 } else { 10657 idx--; 10658 } 10659 } catch(NumberFormatException e) { 10660 } 10661 } 10662 } 10663 } 10664 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10665 return prefix + idxStr; 10666 } 10667 10668 private File getNextCodePath(File targetDir, String packageName) { 10669 int suffix = 1; 10670 File result; 10671 do { 10672 result = new File(targetDir, packageName + "-" + suffix); 10673 suffix++; 10674 } while (result.exists()); 10675 return result; 10676 } 10677 10678 // Utility method that returns the relative package path with respect 10679 // to the installation directory. Like say for /data/data/com.test-1.apk 10680 // string com.test-1 is returned. 10681 static String deriveCodePathName(String codePath) { 10682 if (codePath == null) { 10683 return null; 10684 } 10685 final File codeFile = new File(codePath); 10686 final String name = codeFile.getName(); 10687 if (codeFile.isDirectory()) { 10688 return name; 10689 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10690 final int lastDot = name.lastIndexOf('.'); 10691 return name.substring(0, lastDot); 10692 } else { 10693 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10694 return null; 10695 } 10696 } 10697 10698 class PackageInstalledInfo { 10699 String name; 10700 int uid; 10701 // The set of users that originally had this package installed. 10702 int[] origUsers; 10703 // The set of users that now have this package installed. 10704 int[] newUsers; 10705 PackageParser.Package pkg; 10706 int returnCode; 10707 String returnMsg; 10708 PackageRemovedInfo removedInfo; 10709 10710 public void setError(int code, String msg) { 10711 returnCode = code; 10712 returnMsg = msg; 10713 Slog.w(TAG, msg); 10714 } 10715 10716 public void setError(String msg, PackageParserException e) { 10717 returnCode = e.error; 10718 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10719 Slog.w(TAG, msg, e); 10720 } 10721 10722 public void setError(String msg, PackageManagerException e) { 10723 returnCode = e.error; 10724 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10725 Slog.w(TAG, msg, e); 10726 } 10727 10728 // In some error cases we want to convey more info back to the observer 10729 String origPackage; 10730 String origPermission; 10731 } 10732 10733 /* 10734 * Install a non-existing package. 10735 */ 10736 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10737 UserHandle user, String installerPackageName, String volumeUuid, 10738 PackageInstalledInfo res) { 10739 // Remember this for later, in case we need to rollback this install 10740 String pkgName = pkg.packageName; 10741 10742 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10743 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10744 UserHandle.USER_OWNER).exists(); 10745 synchronized(mPackages) { 10746 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10747 // A package with the same name is already installed, though 10748 // it has been renamed to an older name. The package we 10749 // are trying to install should be installed as an update to 10750 // the existing one, but that has not been requested, so bail. 10751 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10752 + " without first uninstalling package running as " 10753 + mSettings.mRenamedPackages.get(pkgName)); 10754 return; 10755 } 10756 if (mPackages.containsKey(pkgName)) { 10757 // Don't allow installation over an existing package with the same name. 10758 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10759 + " without first uninstalling."); 10760 return; 10761 } 10762 } 10763 10764 try { 10765 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10766 System.currentTimeMillis(), user); 10767 10768 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10769 // delete the partially installed application. the data directory will have to be 10770 // restored if it was already existing 10771 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10772 // remove package from internal structures. Note that we want deletePackageX to 10773 // delete the package data and cache directories that it created in 10774 // scanPackageLocked, unless those directories existed before we even tried to 10775 // install. 10776 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10777 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10778 res.removedInfo, true); 10779 } 10780 10781 } catch (PackageManagerException e) { 10782 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10783 } 10784 } 10785 10786 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10787 // Upgrade keysets are being used. Determine if new package has a superset of the 10788 // required keys. 10789 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10791 for (int i = 0; i < upgradeKeySets.length; i++) { 10792 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10793 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10794 return true; 10795 } 10796 } 10797 return false; 10798 } 10799 10800 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10801 UserHandle user, String installerPackageName, String volumeUuid, 10802 PackageInstalledInfo res) { 10803 final PackageParser.Package oldPackage; 10804 final String pkgName = pkg.packageName; 10805 final int[] allUsers; 10806 final boolean[] perUserInstalled; 10807 final boolean weFroze; 10808 10809 // First find the old package info and check signatures 10810 synchronized(mPackages) { 10811 oldPackage = mPackages.get(pkgName); 10812 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10813 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10814 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10815 // default to original signature matching 10816 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10817 != PackageManager.SIGNATURE_MATCH) { 10818 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10819 "New package has a different signature: " + pkgName); 10820 return; 10821 } 10822 } else { 10823 if(!checkUpgradeKeySetLP(ps, pkg)) { 10824 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10825 "New package not signed by keys specified by upgrade-keysets: " 10826 + pkgName); 10827 return; 10828 } 10829 } 10830 10831 // In case of rollback, remember per-user/profile install state 10832 allUsers = sUserManager.getUserIds(); 10833 perUserInstalled = new boolean[allUsers.length]; 10834 for (int i = 0; i < allUsers.length; i++) { 10835 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10836 } 10837 10838 // Mark the app as frozen to prevent launching during the upgrade 10839 // process, and then kill all running instances 10840 if (!ps.frozen) { 10841 ps.frozen = true; 10842 weFroze = true; 10843 } else { 10844 weFroze = false; 10845 } 10846 } 10847 10848 // Now that we're guarded by frozen state, kill app during upgrade 10849 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 10850 10851 try { 10852 boolean sysPkg = (isSystemApp(oldPackage)); 10853 if (sysPkg) { 10854 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10855 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10856 } else { 10857 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10858 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10859 } 10860 } finally { 10861 // Regardless of success or failure of upgrade steps above, always 10862 // unfreeze the package if we froze it 10863 if (weFroze) { 10864 unfreezePackage(pkgName); 10865 } 10866 } 10867 } 10868 10869 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10870 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10871 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10872 String volumeUuid, PackageInstalledInfo res) { 10873 String pkgName = deletedPackage.packageName; 10874 boolean deletedPkg = true; 10875 boolean updatedSettings = false; 10876 10877 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10878 + deletedPackage); 10879 long origUpdateTime; 10880 if (pkg.mExtras != null) { 10881 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10882 } else { 10883 origUpdateTime = 0; 10884 } 10885 10886 // First delete the existing package while retaining the data directory 10887 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10888 res.removedInfo, true)) { 10889 // If the existing package wasn't successfully deleted 10890 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10891 deletedPkg = false; 10892 } else { 10893 // Successfully deleted the old package; proceed with replace. 10894 10895 // If deleted package lived in a container, give users a chance to 10896 // relinquish resources before killing. 10897 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10898 if (DEBUG_INSTALL) { 10899 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10900 } 10901 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10902 final ArrayList<String> pkgList = new ArrayList<String>(1); 10903 pkgList.add(deletedPackage.applicationInfo.packageName); 10904 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10905 } 10906 10907 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10908 try { 10909 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10910 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10911 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10912 perUserInstalled, res, user); 10913 updatedSettings = true; 10914 } catch (PackageManagerException e) { 10915 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10916 } 10917 } 10918 10919 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10920 // remove package from internal structures. Note that we want deletePackageX to 10921 // delete the package data and cache directories that it created in 10922 // scanPackageLocked, unless those directories existed before we even tried to 10923 // install. 10924 if(updatedSettings) { 10925 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10926 deletePackageLI( 10927 pkgName, null, true, allUsers, perUserInstalled, 10928 PackageManager.DELETE_KEEP_DATA, 10929 res.removedInfo, true); 10930 } 10931 // Since we failed to install the new package we need to restore the old 10932 // package that we deleted. 10933 if (deletedPkg) { 10934 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10935 File restoreFile = new File(deletedPackage.codePath); 10936 // Parse old package 10937 boolean oldExternal = isExternal(deletedPackage); 10938 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10939 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10940 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10941 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10942 try { 10943 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10944 } catch (PackageManagerException e) { 10945 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10946 + e.getMessage()); 10947 return; 10948 } 10949 // Restore of old package succeeded. Update permissions. 10950 // writer 10951 synchronized (mPackages) { 10952 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10953 UPDATE_PERMISSIONS_ALL); 10954 // can downgrade to reader 10955 mSettings.writeLPr(); 10956 } 10957 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10958 } 10959 } 10960 } 10961 10962 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10963 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10964 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10965 String volumeUuid, PackageInstalledInfo res) { 10966 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10967 + ", old=" + deletedPackage); 10968 boolean disabledSystem = false; 10969 boolean updatedSettings = false; 10970 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10971 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10972 != 0) { 10973 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10974 } 10975 String packageName = deletedPackage.packageName; 10976 if (packageName == null) { 10977 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10978 "Attempt to delete null packageName."); 10979 return; 10980 } 10981 PackageParser.Package oldPkg; 10982 PackageSetting oldPkgSetting; 10983 // reader 10984 synchronized (mPackages) { 10985 oldPkg = mPackages.get(packageName); 10986 oldPkgSetting = mSettings.mPackages.get(packageName); 10987 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10988 (oldPkgSetting == null)) { 10989 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10990 "Couldn't find package:" + packageName + " information"); 10991 return; 10992 } 10993 } 10994 10995 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10996 res.removedInfo.removedPackage = packageName; 10997 // Remove existing system package 10998 removePackageLI(oldPkgSetting, true); 10999 // writer 11000 synchronized (mPackages) { 11001 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11002 if (!disabledSystem && deletedPackage != null) { 11003 // We didn't need to disable the .apk as a current system package, 11004 // which means we are replacing another update that is already 11005 // installed. We need to make sure to delete the older one's .apk. 11006 res.removedInfo.args = createInstallArgsForExisting(0, 11007 deletedPackage.applicationInfo.getCodePath(), 11008 deletedPackage.applicationInfo.getResourcePath(), 11009 deletedPackage.applicationInfo.nativeLibraryRootDir, 11010 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11011 } else { 11012 res.removedInfo.args = null; 11013 } 11014 } 11015 11016 // Successfully disabled the old package. Now proceed with re-installation 11017 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11018 11019 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11020 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11021 11022 PackageParser.Package newPackage = null; 11023 try { 11024 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11025 if (newPackage.mExtras != null) { 11026 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11027 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11028 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11029 11030 // is the update attempting to change shared user? that isn't going to work... 11031 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11032 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11033 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11034 + " to " + newPkgSetting.sharedUser); 11035 updatedSettings = true; 11036 } 11037 } 11038 11039 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11040 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11041 perUserInstalled, res, user); 11042 updatedSettings = true; 11043 } 11044 11045 } catch (PackageManagerException e) { 11046 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11047 } 11048 11049 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11050 // Re installation failed. Restore old information 11051 // Remove new pkg information 11052 if (newPackage != null) { 11053 removeInstalledPackageLI(newPackage, true); 11054 } 11055 // Add back the old system package 11056 try { 11057 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11058 } catch (PackageManagerException e) { 11059 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11060 } 11061 // Restore the old system information in Settings 11062 synchronized (mPackages) { 11063 if (disabledSystem) { 11064 mSettings.enableSystemPackageLPw(packageName); 11065 } 11066 if (updatedSettings) { 11067 mSettings.setInstallerPackageName(packageName, 11068 oldPkgSetting.installerPackageName); 11069 } 11070 mSettings.writeLPr(); 11071 } 11072 } 11073 } 11074 11075 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11076 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11077 UserHandle user) { 11078 String pkgName = newPackage.packageName; 11079 synchronized (mPackages) { 11080 //write settings. the installStatus will be incomplete at this stage. 11081 //note that the new package setting would have already been 11082 //added to mPackages. It hasn't been persisted yet. 11083 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11084 mSettings.writeLPr(); 11085 } 11086 11087 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11088 11089 synchronized (mPackages) { 11090 updatePermissionsLPw(newPackage.packageName, newPackage, 11091 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11092 ? UPDATE_PERMISSIONS_ALL : 0)); 11093 // For system-bundled packages, we assume that installing an upgraded version 11094 // of the package implies that the user actually wants to run that new code, 11095 // so we enable the package. 11096 PackageSetting ps = mSettings.mPackages.get(pkgName); 11097 if (ps != null) { 11098 if (isSystemApp(newPackage)) { 11099 // NB: implicit assumption that system package upgrades apply to all users 11100 if (DEBUG_INSTALL) { 11101 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11102 } 11103 if (res.origUsers != null) { 11104 for (int userHandle : res.origUsers) { 11105 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11106 userHandle, installerPackageName); 11107 } 11108 } 11109 // Also convey the prior install/uninstall state 11110 if (allUsers != null && perUserInstalled != null) { 11111 for (int i = 0; i < allUsers.length; i++) { 11112 if (DEBUG_INSTALL) { 11113 Slog.d(TAG, " user " + allUsers[i] 11114 + " => " + perUserInstalled[i]); 11115 } 11116 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11117 } 11118 // these install state changes will be persisted in the 11119 // upcoming call to mSettings.writeLPr(). 11120 } 11121 } 11122 // It's implied that when a user requests installation, they want the app to be 11123 // installed and enabled. 11124 int userId = user.getIdentifier(); 11125 if (userId != UserHandle.USER_ALL) { 11126 ps.setInstalled(true, userId); 11127 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11128 } 11129 } 11130 res.name = pkgName; 11131 res.uid = newPackage.applicationInfo.uid; 11132 res.pkg = newPackage; 11133 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11134 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11135 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11136 //to update install status 11137 mSettings.writeLPr(); 11138 } 11139 } 11140 11141 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11142 final int installFlags = args.installFlags; 11143 final String installerPackageName = args.installerPackageName; 11144 final String volumeUuid = args.volumeUuid; 11145 final File tmpPackageFile = new File(args.getCodePath()); 11146 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11147 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11148 || (args.volumeUuid != null)); 11149 boolean replace = false; 11150 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11151 // Result object to be returned 11152 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11153 11154 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11155 // Retrieve PackageSettings and parse package 11156 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11157 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11158 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11159 PackageParser pp = new PackageParser(); 11160 pp.setSeparateProcesses(mSeparateProcesses); 11161 pp.setDisplayMetrics(mMetrics); 11162 11163 final PackageParser.Package pkg; 11164 try { 11165 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11166 } catch (PackageParserException e) { 11167 res.setError("Failed parse during installPackageLI", e); 11168 return; 11169 } 11170 11171 // Mark that we have an install time CPU ABI override. 11172 pkg.cpuAbiOverride = args.abiOverride; 11173 11174 String pkgName = res.name = pkg.packageName; 11175 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11176 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11177 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11178 return; 11179 } 11180 } 11181 11182 try { 11183 pp.collectCertificates(pkg, parseFlags); 11184 pp.collectManifestDigest(pkg); 11185 } catch (PackageParserException e) { 11186 res.setError("Failed collect during installPackageLI", e); 11187 return; 11188 } 11189 11190 /* If the installer passed in a manifest digest, compare it now. */ 11191 if (args.manifestDigest != null) { 11192 if (DEBUG_INSTALL) { 11193 final String parsedManifest = pkg.manifestDigest == null ? "null" 11194 : pkg.manifestDigest.toString(); 11195 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11196 + parsedManifest); 11197 } 11198 11199 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11200 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11201 return; 11202 } 11203 } else if (DEBUG_INSTALL) { 11204 final String parsedManifest = pkg.manifestDigest == null 11205 ? "null" : pkg.manifestDigest.toString(); 11206 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11207 } 11208 11209 // Get rid of all references to package scan path via parser. 11210 pp = null; 11211 String oldCodePath = null; 11212 boolean systemApp = false; 11213 synchronized (mPackages) { 11214 // Check if installing already existing package 11215 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11216 String oldName = mSettings.mRenamedPackages.get(pkgName); 11217 if (pkg.mOriginalPackages != null 11218 && pkg.mOriginalPackages.contains(oldName) 11219 && mPackages.containsKey(oldName)) { 11220 // This package is derived from an original package, 11221 // and this device has been updating from that original 11222 // name. We must continue using the original name, so 11223 // rename the new package here. 11224 pkg.setPackageName(oldName); 11225 pkgName = pkg.packageName; 11226 replace = true; 11227 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11228 + oldName + " pkgName=" + pkgName); 11229 } else if (mPackages.containsKey(pkgName)) { 11230 // This package, under its official name, already exists 11231 // on the device; we should replace it. 11232 replace = true; 11233 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11234 } 11235 } 11236 11237 PackageSetting ps = mSettings.mPackages.get(pkgName); 11238 if (ps != null) { 11239 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11240 11241 // Quick sanity check that we're signed correctly if updating; 11242 // we'll check this again later when scanning, but we want to 11243 // bail early here before tripping over redefined permissions. 11244 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11245 try { 11246 verifySignaturesLP(ps, pkg); 11247 } catch (PackageManagerException e) { 11248 res.setError(e.error, e.getMessage()); 11249 return; 11250 } 11251 } else { 11252 if (!checkUpgradeKeySetLP(ps, pkg)) { 11253 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11254 + pkg.packageName + " upgrade keys do not match the " 11255 + "previously installed version"); 11256 return; 11257 } 11258 } 11259 11260 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11261 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11262 systemApp = (ps.pkg.applicationInfo.flags & 11263 ApplicationInfo.FLAG_SYSTEM) != 0; 11264 } 11265 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11266 } 11267 11268 // Check whether the newly-scanned package wants to define an already-defined perm 11269 int N = pkg.permissions.size(); 11270 for (int i = N-1; i >= 0; i--) { 11271 PackageParser.Permission perm = pkg.permissions.get(i); 11272 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11273 if (bp != null) { 11274 // If the defining package is signed with our cert, it's okay. This 11275 // also includes the "updating the same package" case, of course. 11276 // "updating same package" could also involve key-rotation. 11277 final boolean sigsOk; 11278 if (!bp.sourcePackage.equals(pkg.packageName) 11279 || !(bp.packageSetting instanceof PackageSetting) 11280 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11281 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11282 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11283 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11284 } else { 11285 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11286 } 11287 if (!sigsOk) { 11288 // If the owning package is the system itself, we log but allow 11289 // install to proceed; we fail the install on all other permission 11290 // redefinitions. 11291 if (!bp.sourcePackage.equals("android")) { 11292 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11293 + pkg.packageName + " attempting to redeclare permission " 11294 + perm.info.name + " already owned by " + bp.sourcePackage); 11295 res.origPermission = perm.info.name; 11296 res.origPackage = bp.sourcePackage; 11297 return; 11298 } else { 11299 Slog.w(TAG, "Package " + pkg.packageName 11300 + " attempting to redeclare system permission " 11301 + perm.info.name + "; ignoring new declaration"); 11302 pkg.permissions.remove(i); 11303 } 11304 } 11305 } 11306 } 11307 11308 } 11309 11310 if (systemApp && onExternal) { 11311 // Disable updates to system apps on sdcard 11312 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11313 "Cannot install updates to system apps on sdcard"); 11314 return; 11315 } 11316 11317 // If app directory is not writable, dexopt will be called after the rename 11318 if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11319 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11320 scanFlags |= SCAN_NO_DEX; 11321 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11322 int result = mPackageDexOptimizer 11323 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11324 false /* defer */, false /* inclDependencies */); 11325 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11326 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11327 return; 11328 } 11329 } 11330 11331 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11332 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11333 return; 11334 } 11335 11336 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11337 11338 if (replace) { 11339 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11340 installerPackageName, volumeUuid, res); 11341 } else { 11342 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11343 args.user, installerPackageName, volumeUuid, res); 11344 } 11345 synchronized (mPackages) { 11346 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11347 if (ps != null) { 11348 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11349 } 11350 } 11351 } 11352 11353 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11354 if (mIntentFilterVerifierComponent == null) { 11355 Slog.d(TAG, "No IntentFilter verification will not be done as " 11356 + "there is no IntentFilterVerifier available!"); 11357 return; 11358 } 11359 11360 final int verifierUid = getPackageUid( 11361 mIntentFilterVerifierComponent.getPackageName(), 11362 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11363 11364 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11365 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11366 msg.obj = pkg; 11367 msg.arg1 = userId; 11368 msg.arg2 = verifierUid; 11369 11370 mHandler.sendMessage(msg); 11371 } 11372 11373 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11374 PackageParser.Package pkg) { 11375 int size = pkg.activities.size(); 11376 if (size == 0) { 11377 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11378 return; 11379 } 11380 11381 final boolean hasDomainURLs = hasDomainURLs(pkg); 11382 if (!hasDomainURLs) { 11383 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11384 return; 11385 } 11386 11387 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11388 + " Activities needs verification ..."); 11389 11390 final int verificationId = mIntentFilterVerificationToken++; 11391 int count = 0; 11392 final String packageName = pkg.packageName; 11393 ArrayList<String> allHosts = new ArrayList<>(); 11394 11395 synchronized (mPackages) { 11396 for (PackageParser.Activity a : pkg.activities) { 11397 for (ActivityIntentInfo filter : a.intents) { 11398 boolean needsFilterVerification = filter.needsVerification(); 11399 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11400 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11401 mIntentFilterVerifier.addOneIntentFilterVerification( 11402 verifierUid, userId, verificationId, filter, packageName); 11403 count++; 11404 } else if (!needsFilterVerification) { 11405 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11406 if (hasValidDomains(filter)) { 11407 ArrayList<String> hosts = filter.getHostsList(); 11408 if (hosts.size() > 0) { 11409 allHosts.addAll(hosts); 11410 } else { 11411 if (allHosts.isEmpty()) { 11412 allHosts.add("*"); 11413 } 11414 } 11415 } 11416 } else { 11417 Slog.d(TAG, "Verification already done for IntentFilter:" 11418 + filter.toString()); 11419 } 11420 } 11421 } 11422 } 11423 11424 if (count > 0) { 11425 mIntentFilterVerifier.startVerifications(userId); 11426 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11427 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11428 } else { 11429 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11430 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11431 packageName, allHosts) != null) { 11432 scheduleWriteSettingsLocked(); 11433 } 11434 } 11435 } 11436 11437 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11438 final ComponentName cn = filter.activity.getComponentName(); 11439 final String packageName = cn.getPackageName(); 11440 11441 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11442 packageName); 11443 if (ivi == null) { 11444 return true; 11445 } 11446 int status = ivi.getStatus(); 11447 switch (status) { 11448 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11449 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11450 return true; 11451 11452 default: 11453 // Nothing to do 11454 return false; 11455 } 11456 } 11457 11458 private static boolean isMultiArch(PackageSetting ps) { 11459 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11460 } 11461 11462 private static boolean isMultiArch(ApplicationInfo info) { 11463 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11464 } 11465 11466 private static boolean isExternal(PackageParser.Package pkg) { 11467 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11468 } 11469 11470 private static boolean isExternal(PackageSetting ps) { 11471 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11472 } 11473 11474 private static boolean isExternal(ApplicationInfo info) { 11475 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11476 } 11477 11478 private static boolean isSystemApp(PackageParser.Package pkg) { 11479 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11480 } 11481 11482 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11483 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11484 } 11485 11486 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11487 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11488 } 11489 11490 private static boolean isSystemApp(PackageSetting ps) { 11491 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11492 } 11493 11494 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11495 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11496 } 11497 11498 private int packageFlagsToInstallFlags(PackageSetting ps) { 11499 int installFlags = 0; 11500 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11501 // This existing package was an external ASEC install when we have 11502 // the external flag without a UUID 11503 installFlags |= PackageManager.INSTALL_EXTERNAL; 11504 } 11505 if (ps.isForwardLocked()) { 11506 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11507 } 11508 return installFlags; 11509 } 11510 11511 private void deleteTempPackageFiles() { 11512 final FilenameFilter filter = new FilenameFilter() { 11513 public boolean accept(File dir, String name) { 11514 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11515 } 11516 }; 11517 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11518 file.delete(); 11519 } 11520 } 11521 11522 @Override 11523 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11524 int flags) { 11525 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11526 flags); 11527 } 11528 11529 @Override 11530 public void deletePackage(final String packageName, 11531 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11532 mContext.enforceCallingOrSelfPermission( 11533 android.Manifest.permission.DELETE_PACKAGES, null); 11534 final int uid = Binder.getCallingUid(); 11535 if (UserHandle.getUserId(uid) != userId) { 11536 mContext.enforceCallingPermission( 11537 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11538 "deletePackage for user " + userId); 11539 } 11540 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11541 try { 11542 observer.onPackageDeleted(packageName, 11543 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11544 } catch (RemoteException re) { 11545 } 11546 return; 11547 } 11548 11549 boolean uninstallBlocked = false; 11550 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11551 int[] users = sUserManager.getUserIds(); 11552 for (int i = 0; i < users.length; ++i) { 11553 if (getBlockUninstallForUser(packageName, users[i])) { 11554 uninstallBlocked = true; 11555 break; 11556 } 11557 } 11558 } else { 11559 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11560 } 11561 if (uninstallBlocked) { 11562 try { 11563 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11564 null); 11565 } catch (RemoteException re) { 11566 } 11567 return; 11568 } 11569 11570 if (DEBUG_REMOVE) { 11571 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11572 } 11573 // Queue up an async operation since the package deletion may take a little while. 11574 mHandler.post(new Runnable() { 11575 public void run() { 11576 mHandler.removeCallbacks(this); 11577 final int returnCode = deletePackageX(packageName, userId, flags); 11578 if (observer != null) { 11579 try { 11580 observer.onPackageDeleted(packageName, returnCode, null); 11581 } catch (RemoteException e) { 11582 Log.i(TAG, "Observer no longer exists."); 11583 } //end catch 11584 } //end if 11585 } //end run 11586 }); 11587 } 11588 11589 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11590 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11591 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11592 try { 11593 if (dpm != null) { 11594 if (dpm.isDeviceOwner(packageName)) { 11595 return true; 11596 } 11597 int[] users; 11598 if (userId == UserHandle.USER_ALL) { 11599 users = sUserManager.getUserIds(); 11600 } else { 11601 users = new int[]{userId}; 11602 } 11603 for (int i = 0; i < users.length; ++i) { 11604 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11605 return true; 11606 } 11607 } 11608 } 11609 } catch (RemoteException e) { 11610 } 11611 return false; 11612 } 11613 11614 /** 11615 * This method is an internal method that could be get invoked either 11616 * to delete an installed package or to clean up a failed installation. 11617 * After deleting an installed package, a broadcast is sent to notify any 11618 * listeners that the package has been installed. For cleaning up a failed 11619 * installation, the broadcast is not necessary since the package's 11620 * installation wouldn't have sent the initial broadcast either 11621 * The key steps in deleting a package are 11622 * deleting the package information in internal structures like mPackages, 11623 * deleting the packages base directories through installd 11624 * updating mSettings to reflect current status 11625 * persisting settings for later use 11626 * sending a broadcast if necessary 11627 */ 11628 private int deletePackageX(String packageName, int userId, int flags) { 11629 final PackageRemovedInfo info = new PackageRemovedInfo(); 11630 final boolean res; 11631 11632 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11633 ? UserHandle.ALL : new UserHandle(userId); 11634 11635 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11636 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11637 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11638 } 11639 11640 boolean removedForAllUsers = false; 11641 boolean systemUpdate = false; 11642 11643 // for the uninstall-updates case and restricted profiles, remember the per- 11644 // userhandle installed state 11645 int[] allUsers; 11646 boolean[] perUserInstalled; 11647 synchronized (mPackages) { 11648 PackageSetting ps = mSettings.mPackages.get(packageName); 11649 allUsers = sUserManager.getUserIds(); 11650 perUserInstalled = new boolean[allUsers.length]; 11651 for (int i = 0; i < allUsers.length; i++) { 11652 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11653 } 11654 } 11655 11656 synchronized (mInstallLock) { 11657 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11658 res = deletePackageLI(packageName, removeForUser, 11659 true, allUsers, perUserInstalled, 11660 flags | REMOVE_CHATTY, info, true); 11661 systemUpdate = info.isRemovedPackageSystemUpdate; 11662 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11663 removedForAllUsers = true; 11664 } 11665 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11666 + " removedForAllUsers=" + removedForAllUsers); 11667 } 11668 11669 if (res) { 11670 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11671 11672 // If the removed package was a system update, the old system package 11673 // was re-enabled; we need to broadcast this information 11674 if (systemUpdate) { 11675 Bundle extras = new Bundle(1); 11676 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11677 ? info.removedAppId : info.uid); 11678 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11679 11680 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11681 extras, null, null, null); 11682 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11683 extras, null, null, null); 11684 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11685 null, packageName, null, null); 11686 } 11687 } 11688 // Force a gc here. 11689 Runtime.getRuntime().gc(); 11690 // Delete the resources here after sending the broadcast to let 11691 // other processes clean up before deleting resources. 11692 if (info.args != null) { 11693 synchronized (mInstallLock) { 11694 info.args.doPostDeleteLI(true); 11695 } 11696 } 11697 11698 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11699 } 11700 11701 static class PackageRemovedInfo { 11702 String removedPackage; 11703 int uid = -1; 11704 int removedAppId = -1; 11705 int[] removedUsers = null; 11706 boolean isRemovedPackageSystemUpdate = false; 11707 // Clean up resources deleted packages. 11708 InstallArgs args = null; 11709 11710 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11711 Bundle extras = new Bundle(1); 11712 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11713 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11714 if (replacing) { 11715 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11716 } 11717 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11718 if (removedPackage != null) { 11719 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11720 extras, null, null, removedUsers); 11721 if (fullRemove && !replacing) { 11722 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11723 extras, null, null, removedUsers); 11724 } 11725 } 11726 if (removedAppId >= 0) { 11727 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11728 removedUsers); 11729 } 11730 } 11731 } 11732 11733 /* 11734 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11735 * flag is not set, the data directory is removed as well. 11736 * make sure this flag is set for partially installed apps. If not its meaningless to 11737 * delete a partially installed application. 11738 */ 11739 private void removePackageDataLI(PackageSetting ps, 11740 int[] allUserHandles, boolean[] perUserInstalled, 11741 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11742 String packageName = ps.name; 11743 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11744 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11745 // Retrieve object to delete permissions for shared user later on 11746 final PackageSetting deletedPs; 11747 // reader 11748 synchronized (mPackages) { 11749 deletedPs = mSettings.mPackages.get(packageName); 11750 if (outInfo != null) { 11751 outInfo.removedPackage = packageName; 11752 outInfo.removedUsers = deletedPs != null 11753 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11754 : null; 11755 } 11756 } 11757 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11758 removeDataDirsLI(ps.volumeUuid, packageName); 11759 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11760 } 11761 // writer 11762 synchronized (mPackages) { 11763 if (deletedPs != null) { 11764 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11765 if (outInfo != null) { 11766 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11767 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11768 } 11769 updatePermissionsLPw(deletedPs.name, null, 0); 11770 if (deletedPs.sharedUser != null) { 11771 // Remove permissions associated with package. Since runtime 11772 // permissions are per user we have to kill the removed package 11773 // or packages running under the shared user of the removed 11774 // package if revoking the permissions requested only by the removed 11775 // package is successful and this causes a change in gids. 11776 for (int userId : UserManagerService.getInstance().getUserIds()) { 11777 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11778 userId); 11779 if (userIdToKill == UserHandle.USER_ALL 11780 || userIdToKill >= UserHandle.USER_OWNER) { 11781 // If gids changed for this user, kill all affected packages. 11782 mHandler.post(new Runnable() { 11783 @Override 11784 public void run() { 11785 // This has to happen with no lock held. 11786 killSettingPackagesForUser(deletedPs, userIdToKill, 11787 KILL_APP_REASON_GIDS_CHANGED); 11788 } 11789 }); 11790 break; 11791 } 11792 } 11793 } 11794 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11795 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11796 } 11797 // make sure to preserve per-user disabled state if this removal was just 11798 // a downgrade of a system app to the factory package 11799 if (allUserHandles != null && perUserInstalled != null) { 11800 if (DEBUG_REMOVE) { 11801 Slog.d(TAG, "Propagating install state across downgrade"); 11802 } 11803 for (int i = 0; i < allUserHandles.length; i++) { 11804 if (DEBUG_REMOVE) { 11805 Slog.d(TAG, " user " + allUserHandles[i] 11806 + " => " + perUserInstalled[i]); 11807 } 11808 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11809 } 11810 } 11811 } 11812 // can downgrade to reader 11813 if (writeSettings) { 11814 // Save settings now 11815 mSettings.writeLPr(); 11816 } 11817 } 11818 if (outInfo != null) { 11819 // A user ID was deleted here. Go through all users and remove it 11820 // from KeyStore. 11821 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11822 } 11823 } 11824 11825 static boolean locationIsPrivileged(File path) { 11826 try { 11827 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11828 .getCanonicalPath(); 11829 return path.getCanonicalPath().startsWith(privilegedAppDir); 11830 } catch (IOException e) { 11831 Slog.e(TAG, "Unable to access code path " + path); 11832 } 11833 return false; 11834 } 11835 11836 /* 11837 * Tries to delete system package. 11838 */ 11839 private boolean deleteSystemPackageLI(PackageSetting newPs, 11840 int[] allUserHandles, boolean[] perUserInstalled, 11841 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11842 final boolean applyUserRestrictions 11843 = (allUserHandles != null) && (perUserInstalled != null); 11844 PackageSetting disabledPs = null; 11845 // Confirm if the system package has been updated 11846 // An updated system app can be deleted. This will also have to restore 11847 // the system pkg from system partition 11848 // reader 11849 synchronized (mPackages) { 11850 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11851 } 11852 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11853 + " disabledPs=" + disabledPs); 11854 if (disabledPs == null) { 11855 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11856 return false; 11857 } else if (DEBUG_REMOVE) { 11858 Slog.d(TAG, "Deleting system pkg from data partition"); 11859 } 11860 if (DEBUG_REMOVE) { 11861 if (applyUserRestrictions) { 11862 Slog.d(TAG, "Remembering install states:"); 11863 for (int i = 0; i < allUserHandles.length; i++) { 11864 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11865 } 11866 } 11867 } 11868 // Delete the updated package 11869 outInfo.isRemovedPackageSystemUpdate = true; 11870 if (disabledPs.versionCode < newPs.versionCode) { 11871 // Delete data for downgrades 11872 flags &= ~PackageManager.DELETE_KEEP_DATA; 11873 } else { 11874 // Preserve data by setting flag 11875 flags |= PackageManager.DELETE_KEEP_DATA; 11876 } 11877 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11878 allUserHandles, perUserInstalled, outInfo, writeSettings); 11879 if (!ret) { 11880 return false; 11881 } 11882 // writer 11883 synchronized (mPackages) { 11884 // Reinstate the old system package 11885 mSettings.enableSystemPackageLPw(newPs.name); 11886 // Remove any native libraries from the upgraded package. 11887 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11888 } 11889 // Install the system package 11890 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11891 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11892 if (locationIsPrivileged(disabledPs.codePath)) { 11893 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11894 } 11895 11896 final PackageParser.Package newPkg; 11897 try { 11898 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11899 } catch (PackageManagerException e) { 11900 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11901 return false; 11902 } 11903 11904 // writer 11905 synchronized (mPackages) { 11906 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11907 updatePermissionsLPw(newPkg.packageName, newPkg, 11908 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11909 if (applyUserRestrictions) { 11910 if (DEBUG_REMOVE) { 11911 Slog.d(TAG, "Propagating install state across reinstall"); 11912 } 11913 for (int i = 0; i < allUserHandles.length; i++) { 11914 if (DEBUG_REMOVE) { 11915 Slog.d(TAG, " user " + allUserHandles[i] 11916 + " => " + perUserInstalled[i]); 11917 } 11918 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11919 } 11920 // Regardless of writeSettings we need to ensure that this restriction 11921 // state propagation is persisted 11922 mSettings.writeAllUsersPackageRestrictionsLPr(); 11923 } 11924 // can downgrade to reader here 11925 if (writeSettings) { 11926 mSettings.writeLPr(); 11927 } 11928 } 11929 return true; 11930 } 11931 11932 private boolean deleteInstalledPackageLI(PackageSetting ps, 11933 boolean deleteCodeAndResources, int flags, 11934 int[] allUserHandles, boolean[] perUserInstalled, 11935 PackageRemovedInfo outInfo, boolean writeSettings) { 11936 if (outInfo != null) { 11937 outInfo.uid = ps.appId; 11938 } 11939 11940 // Delete package data from internal structures and also remove data if flag is set 11941 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11942 11943 // Delete application code and resources 11944 if (deleteCodeAndResources && (outInfo != null)) { 11945 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11946 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11947 getAppDexInstructionSets(ps)); 11948 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11949 } 11950 return true; 11951 } 11952 11953 @Override 11954 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11955 int userId) { 11956 mContext.enforceCallingOrSelfPermission( 11957 android.Manifest.permission.DELETE_PACKAGES, null); 11958 synchronized (mPackages) { 11959 PackageSetting ps = mSettings.mPackages.get(packageName); 11960 if (ps == null) { 11961 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11962 return false; 11963 } 11964 if (!ps.getInstalled(userId)) { 11965 // Can't block uninstall for an app that is not installed or enabled. 11966 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11967 return false; 11968 } 11969 ps.setBlockUninstall(blockUninstall, userId); 11970 mSettings.writePackageRestrictionsLPr(userId); 11971 } 11972 return true; 11973 } 11974 11975 @Override 11976 public boolean getBlockUninstallForUser(String packageName, int userId) { 11977 synchronized (mPackages) { 11978 PackageSetting ps = mSettings.mPackages.get(packageName); 11979 if (ps == null) { 11980 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11981 return false; 11982 } 11983 return ps.getBlockUninstall(userId); 11984 } 11985 } 11986 11987 /* 11988 * This method handles package deletion in general 11989 */ 11990 private boolean deletePackageLI(String packageName, UserHandle user, 11991 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11992 int flags, PackageRemovedInfo outInfo, 11993 boolean writeSettings) { 11994 if (packageName == null) { 11995 Slog.w(TAG, "Attempt to delete null packageName."); 11996 return false; 11997 } 11998 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11999 PackageSetting ps; 12000 boolean dataOnly = false; 12001 int removeUser = -1; 12002 int appId = -1; 12003 synchronized (mPackages) { 12004 ps = mSettings.mPackages.get(packageName); 12005 if (ps == null) { 12006 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12007 return false; 12008 } 12009 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12010 && user.getIdentifier() != UserHandle.USER_ALL) { 12011 // The caller is asking that the package only be deleted for a single 12012 // user. To do this, we just mark its uninstalled state and delete 12013 // its data. If this is a system app, we only allow this to happen if 12014 // they have set the special DELETE_SYSTEM_APP which requests different 12015 // semantics than normal for uninstalling system apps. 12016 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12017 ps.setUserState(user.getIdentifier(), 12018 COMPONENT_ENABLED_STATE_DEFAULT, 12019 false, //installed 12020 true, //stopped 12021 true, //notLaunched 12022 false, //hidden 12023 null, null, null, 12024 false, // blockUninstall 12025 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12026 if (!isSystemApp(ps)) { 12027 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12028 // Other user still have this package installed, so all 12029 // we need to do is clear this user's data and save that 12030 // it is uninstalled. 12031 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12032 removeUser = user.getIdentifier(); 12033 appId = ps.appId; 12034 scheduleWritePackageRestrictionsLocked(removeUser); 12035 } else { 12036 // We need to set it back to 'installed' so the uninstall 12037 // broadcasts will be sent correctly. 12038 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12039 ps.setInstalled(true, user.getIdentifier()); 12040 } 12041 } else { 12042 // This is a system app, so we assume that the 12043 // other users still have this package installed, so all 12044 // we need to do is clear this user's data and save that 12045 // it is uninstalled. 12046 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12047 removeUser = user.getIdentifier(); 12048 appId = ps.appId; 12049 scheduleWritePackageRestrictionsLocked(removeUser); 12050 } 12051 } 12052 } 12053 12054 if (removeUser >= 0) { 12055 // From above, we determined that we are deleting this only 12056 // for a single user. Continue the work here. 12057 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12058 if (outInfo != null) { 12059 outInfo.removedPackage = packageName; 12060 outInfo.removedAppId = appId; 12061 outInfo.removedUsers = new int[] {removeUser}; 12062 } 12063 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12064 removeKeystoreDataIfNeeded(removeUser, appId); 12065 schedulePackageCleaning(packageName, removeUser, false); 12066 synchronized (mPackages) { 12067 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12068 scheduleWritePackageRestrictionsLocked(removeUser); 12069 } 12070 } 12071 return true; 12072 } 12073 12074 if (dataOnly) { 12075 // Delete application data first 12076 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12077 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12078 return true; 12079 } 12080 12081 boolean ret = false; 12082 if (isSystemApp(ps)) { 12083 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12084 // When an updated system application is deleted we delete the existing resources as well and 12085 // fall back to existing code in system partition 12086 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12087 flags, outInfo, writeSettings); 12088 } else { 12089 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12090 // Kill application pre-emptively especially for apps on sd. 12091 killApplication(packageName, ps.appId, "uninstall pkg"); 12092 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12093 allUserHandles, perUserInstalled, 12094 outInfo, writeSettings); 12095 } 12096 12097 return ret; 12098 } 12099 12100 private final class ClearStorageConnection implements ServiceConnection { 12101 IMediaContainerService mContainerService; 12102 12103 @Override 12104 public void onServiceConnected(ComponentName name, IBinder service) { 12105 synchronized (this) { 12106 mContainerService = IMediaContainerService.Stub.asInterface(service); 12107 notifyAll(); 12108 } 12109 } 12110 12111 @Override 12112 public void onServiceDisconnected(ComponentName name) { 12113 } 12114 } 12115 12116 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12117 final boolean mounted; 12118 if (Environment.isExternalStorageEmulated()) { 12119 mounted = true; 12120 } else { 12121 final String status = Environment.getExternalStorageState(); 12122 12123 mounted = status.equals(Environment.MEDIA_MOUNTED) 12124 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12125 } 12126 12127 if (!mounted) { 12128 return; 12129 } 12130 12131 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12132 int[] users; 12133 if (userId == UserHandle.USER_ALL) { 12134 users = sUserManager.getUserIds(); 12135 } else { 12136 users = new int[] { userId }; 12137 } 12138 final ClearStorageConnection conn = new ClearStorageConnection(); 12139 if (mContext.bindServiceAsUser( 12140 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12141 try { 12142 for (int curUser : users) { 12143 long timeout = SystemClock.uptimeMillis() + 5000; 12144 synchronized (conn) { 12145 long now = SystemClock.uptimeMillis(); 12146 while (conn.mContainerService == null && now < timeout) { 12147 try { 12148 conn.wait(timeout - now); 12149 } catch (InterruptedException e) { 12150 } 12151 } 12152 } 12153 if (conn.mContainerService == null) { 12154 return; 12155 } 12156 12157 final UserEnvironment userEnv = new UserEnvironment(curUser); 12158 clearDirectory(conn.mContainerService, 12159 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12160 if (allData) { 12161 clearDirectory(conn.mContainerService, 12162 userEnv.buildExternalStorageAppDataDirs(packageName)); 12163 clearDirectory(conn.mContainerService, 12164 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12165 } 12166 } 12167 } finally { 12168 mContext.unbindService(conn); 12169 } 12170 } 12171 } 12172 12173 @Override 12174 public void clearApplicationUserData(final String packageName, 12175 final IPackageDataObserver observer, final int userId) { 12176 mContext.enforceCallingOrSelfPermission( 12177 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12178 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12179 // Queue up an async operation since the package deletion may take a little while. 12180 mHandler.post(new Runnable() { 12181 public void run() { 12182 mHandler.removeCallbacks(this); 12183 final boolean succeeded; 12184 synchronized (mInstallLock) { 12185 succeeded = clearApplicationUserDataLI(packageName, userId); 12186 } 12187 clearExternalStorageDataSync(packageName, userId, true); 12188 if (succeeded) { 12189 // invoke DeviceStorageMonitor's update method to clear any notifications 12190 DeviceStorageMonitorInternal 12191 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12192 if (dsm != null) { 12193 dsm.checkMemory(); 12194 } 12195 } 12196 if(observer != null) { 12197 try { 12198 observer.onRemoveCompleted(packageName, succeeded); 12199 } catch (RemoteException e) { 12200 Log.i(TAG, "Observer no longer exists."); 12201 } 12202 } //end if observer 12203 } //end run 12204 }); 12205 } 12206 12207 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12208 if (packageName == null) { 12209 Slog.w(TAG, "Attempt to delete null packageName."); 12210 return false; 12211 } 12212 12213 // Try finding details about the requested package 12214 PackageParser.Package pkg; 12215 synchronized (mPackages) { 12216 pkg = mPackages.get(packageName); 12217 if (pkg == null) { 12218 final PackageSetting ps = mSettings.mPackages.get(packageName); 12219 if (ps != null) { 12220 pkg = ps.pkg; 12221 } 12222 } 12223 } 12224 12225 if (pkg == null) { 12226 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12227 } 12228 12229 // Always delete data directories for package, even if we found no other 12230 // record of app. This helps users recover from UID mismatches without 12231 // resorting to a full data wipe. 12232 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12233 if (retCode < 0) { 12234 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12235 return false; 12236 } 12237 12238 if (pkg == null) { 12239 return false; 12240 } 12241 12242 if (pkg != null && pkg.applicationInfo != null) { 12243 final int appId = pkg.applicationInfo.uid; 12244 removeKeystoreDataIfNeeded(userId, appId); 12245 } 12246 12247 // Create a native library symlink only if we have native libraries 12248 // and if the native libraries are 32 bit libraries. We do not provide 12249 // this symlink for 64 bit libraries. 12250 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12251 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12252 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12253 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12254 nativeLibPath, userId) < 0) { 12255 Slog.w(TAG, "Failed linking native library dir"); 12256 return false; 12257 } 12258 } 12259 12260 return true; 12261 } 12262 12263 /** 12264 * Remove entries from the keystore daemon. Will only remove it if the 12265 * {@code appId} is valid. 12266 */ 12267 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12268 if (appId < 0) { 12269 return; 12270 } 12271 12272 final KeyStore keyStore = KeyStore.getInstance(); 12273 if (keyStore != null) { 12274 if (userId == UserHandle.USER_ALL) { 12275 for (final int individual : sUserManager.getUserIds()) { 12276 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12277 } 12278 } else { 12279 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12280 } 12281 } else { 12282 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12283 } 12284 } 12285 12286 @Override 12287 public void deleteApplicationCacheFiles(final String packageName, 12288 final IPackageDataObserver observer) { 12289 mContext.enforceCallingOrSelfPermission( 12290 android.Manifest.permission.DELETE_CACHE_FILES, null); 12291 // Queue up an async operation since the package deletion may take a little while. 12292 final int userId = UserHandle.getCallingUserId(); 12293 mHandler.post(new Runnable() { 12294 public void run() { 12295 mHandler.removeCallbacks(this); 12296 final boolean succeded; 12297 synchronized (mInstallLock) { 12298 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12299 } 12300 clearExternalStorageDataSync(packageName, userId, false); 12301 if(observer != null) { 12302 try { 12303 observer.onRemoveCompleted(packageName, succeded); 12304 } catch (RemoteException e) { 12305 Log.i(TAG, "Observer no longer exists."); 12306 } 12307 } //end if observer 12308 } //end run 12309 }); 12310 } 12311 12312 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12313 if (packageName == null) { 12314 Slog.w(TAG, "Attempt to delete null packageName."); 12315 return false; 12316 } 12317 PackageParser.Package p; 12318 synchronized (mPackages) { 12319 p = mPackages.get(packageName); 12320 } 12321 if (p == null) { 12322 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12323 return false; 12324 } 12325 final ApplicationInfo applicationInfo = p.applicationInfo; 12326 if (applicationInfo == null) { 12327 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12328 return false; 12329 } 12330 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12331 if (retCode < 0) { 12332 Slog.w(TAG, "Couldn't remove cache files for package: " 12333 + packageName + " u" + userId); 12334 return false; 12335 } 12336 return true; 12337 } 12338 12339 @Override 12340 public void getPackageSizeInfo(final String packageName, int userHandle, 12341 final IPackageStatsObserver observer) { 12342 mContext.enforceCallingOrSelfPermission( 12343 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12344 if (packageName == null) { 12345 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12346 } 12347 12348 PackageStats stats = new PackageStats(packageName, userHandle); 12349 12350 /* 12351 * Queue up an async operation since the package measurement may take a 12352 * little while. 12353 */ 12354 Message msg = mHandler.obtainMessage(INIT_COPY); 12355 msg.obj = new MeasureParams(stats, observer); 12356 mHandler.sendMessage(msg); 12357 } 12358 12359 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12360 PackageStats pStats) { 12361 if (packageName == null) { 12362 Slog.w(TAG, "Attempt to get size of null packageName."); 12363 return false; 12364 } 12365 PackageParser.Package p; 12366 boolean dataOnly = false; 12367 String libDirRoot = null; 12368 String asecPath = null; 12369 PackageSetting ps = null; 12370 synchronized (mPackages) { 12371 p = mPackages.get(packageName); 12372 ps = mSettings.mPackages.get(packageName); 12373 if(p == null) { 12374 dataOnly = true; 12375 if((ps == null) || (ps.pkg == null)) { 12376 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12377 return false; 12378 } 12379 p = ps.pkg; 12380 } 12381 if (ps != null) { 12382 libDirRoot = ps.legacyNativeLibraryPathString; 12383 } 12384 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12385 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12386 if (secureContainerId != null) { 12387 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12388 } 12389 } 12390 } 12391 String publicSrcDir = null; 12392 if(!dataOnly) { 12393 final ApplicationInfo applicationInfo = p.applicationInfo; 12394 if (applicationInfo == null) { 12395 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12396 return false; 12397 } 12398 if (p.isForwardLocked()) { 12399 publicSrcDir = applicationInfo.getBaseResourcePath(); 12400 } 12401 } 12402 // TODO: extend to measure size of split APKs 12403 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12404 // not just the first level. 12405 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12406 // just the primary. 12407 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12408 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12409 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12410 if (res < 0) { 12411 return false; 12412 } 12413 12414 // Fix-up for forward-locked applications in ASEC containers. 12415 if (!isExternal(p)) { 12416 pStats.codeSize += pStats.externalCodeSize; 12417 pStats.externalCodeSize = 0L; 12418 } 12419 12420 return true; 12421 } 12422 12423 12424 @Override 12425 public void addPackageToPreferred(String packageName) { 12426 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12427 } 12428 12429 @Override 12430 public void removePackageFromPreferred(String packageName) { 12431 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12432 } 12433 12434 @Override 12435 public List<PackageInfo> getPreferredPackages(int flags) { 12436 return new ArrayList<PackageInfo>(); 12437 } 12438 12439 private int getUidTargetSdkVersionLockedLPr(int uid) { 12440 Object obj = mSettings.getUserIdLPr(uid); 12441 if (obj instanceof SharedUserSetting) { 12442 final SharedUserSetting sus = (SharedUserSetting) obj; 12443 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12444 final Iterator<PackageSetting> it = sus.packages.iterator(); 12445 while (it.hasNext()) { 12446 final PackageSetting ps = it.next(); 12447 if (ps.pkg != null) { 12448 int v = ps.pkg.applicationInfo.targetSdkVersion; 12449 if (v < vers) vers = v; 12450 } 12451 } 12452 return vers; 12453 } else if (obj instanceof PackageSetting) { 12454 final PackageSetting ps = (PackageSetting) obj; 12455 if (ps.pkg != null) { 12456 return ps.pkg.applicationInfo.targetSdkVersion; 12457 } 12458 } 12459 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12460 } 12461 12462 @Override 12463 public void addPreferredActivity(IntentFilter filter, int match, 12464 ComponentName[] set, ComponentName activity, int userId) { 12465 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12466 "Adding preferred"); 12467 } 12468 12469 private void addPreferredActivityInternal(IntentFilter filter, int match, 12470 ComponentName[] set, ComponentName activity, boolean always, int userId, 12471 String opname) { 12472 // writer 12473 int callingUid = Binder.getCallingUid(); 12474 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12475 if (filter.countActions() == 0) { 12476 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12477 return; 12478 } 12479 synchronized (mPackages) { 12480 if (mContext.checkCallingOrSelfPermission( 12481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12482 != PackageManager.PERMISSION_GRANTED) { 12483 if (getUidTargetSdkVersionLockedLPr(callingUid) 12484 < Build.VERSION_CODES.FROYO) { 12485 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12486 + callingUid); 12487 return; 12488 } 12489 mContext.enforceCallingOrSelfPermission( 12490 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12491 } 12492 12493 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12494 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12495 + userId + ":"); 12496 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12497 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12498 scheduleWritePackageRestrictionsLocked(userId); 12499 } 12500 } 12501 12502 @Override 12503 public void replacePreferredActivity(IntentFilter filter, int match, 12504 ComponentName[] set, ComponentName activity, int userId) { 12505 if (filter.countActions() != 1) { 12506 throw new IllegalArgumentException( 12507 "replacePreferredActivity expects filter to have only 1 action."); 12508 } 12509 if (filter.countDataAuthorities() != 0 12510 || filter.countDataPaths() != 0 12511 || filter.countDataSchemes() > 1 12512 || filter.countDataTypes() != 0) { 12513 throw new IllegalArgumentException( 12514 "replacePreferredActivity expects filter to have no data authorities, " + 12515 "paths, or types; and at most one scheme."); 12516 } 12517 12518 final int callingUid = Binder.getCallingUid(); 12519 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12520 synchronized (mPackages) { 12521 if (mContext.checkCallingOrSelfPermission( 12522 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12523 != PackageManager.PERMISSION_GRANTED) { 12524 if (getUidTargetSdkVersionLockedLPr(callingUid) 12525 < Build.VERSION_CODES.FROYO) { 12526 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12527 + Binder.getCallingUid()); 12528 return; 12529 } 12530 mContext.enforceCallingOrSelfPermission( 12531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12532 } 12533 12534 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12535 if (pir != null) { 12536 // Get all of the existing entries that exactly match this filter. 12537 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12538 if (existing != null && existing.size() == 1) { 12539 PreferredActivity cur = existing.get(0); 12540 if (DEBUG_PREFERRED) { 12541 Slog.i(TAG, "Checking replace of preferred:"); 12542 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12543 if (!cur.mPref.mAlways) { 12544 Slog.i(TAG, " -- CUR; not mAlways!"); 12545 } else { 12546 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12547 Slog.i(TAG, " -- CUR: mSet=" 12548 + Arrays.toString(cur.mPref.mSetComponents)); 12549 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12550 Slog.i(TAG, " -- NEW: mMatch=" 12551 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12552 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12553 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12554 } 12555 } 12556 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12557 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12558 && cur.mPref.sameSet(set)) { 12559 // Setting the preferred activity to what it happens to be already 12560 if (DEBUG_PREFERRED) { 12561 Slog.i(TAG, "Replacing with same preferred activity " 12562 + cur.mPref.mShortComponent + " for user " 12563 + userId + ":"); 12564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12565 } 12566 return; 12567 } 12568 } 12569 12570 if (existing != null) { 12571 if (DEBUG_PREFERRED) { 12572 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12573 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12574 } 12575 for (int i = 0; i < existing.size(); i++) { 12576 PreferredActivity pa = existing.get(i); 12577 if (DEBUG_PREFERRED) { 12578 Slog.i(TAG, "Removing existing preferred activity " 12579 + pa.mPref.mComponent + ":"); 12580 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12581 } 12582 pir.removeFilter(pa); 12583 } 12584 } 12585 } 12586 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12587 "Replacing preferred"); 12588 } 12589 } 12590 12591 @Override 12592 public void clearPackagePreferredActivities(String packageName) { 12593 final int uid = Binder.getCallingUid(); 12594 // writer 12595 synchronized (mPackages) { 12596 PackageParser.Package pkg = mPackages.get(packageName); 12597 if (pkg == null || pkg.applicationInfo.uid != uid) { 12598 if (mContext.checkCallingOrSelfPermission( 12599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12600 != PackageManager.PERMISSION_GRANTED) { 12601 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12602 < Build.VERSION_CODES.FROYO) { 12603 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12604 + Binder.getCallingUid()); 12605 return; 12606 } 12607 mContext.enforceCallingOrSelfPermission( 12608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12609 } 12610 } 12611 12612 int user = UserHandle.getCallingUserId(); 12613 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12614 scheduleWritePackageRestrictionsLocked(user); 12615 } 12616 } 12617 } 12618 12619 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12620 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12621 ArrayList<PreferredActivity> removed = null; 12622 boolean changed = false; 12623 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12624 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12625 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12626 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12627 continue; 12628 } 12629 Iterator<PreferredActivity> it = pir.filterIterator(); 12630 while (it.hasNext()) { 12631 PreferredActivity pa = it.next(); 12632 // Mark entry for removal only if it matches the package name 12633 // and the entry is of type "always". 12634 if (packageName == null || 12635 (pa.mPref.mComponent.getPackageName().equals(packageName) 12636 && pa.mPref.mAlways)) { 12637 if (removed == null) { 12638 removed = new ArrayList<PreferredActivity>(); 12639 } 12640 removed.add(pa); 12641 } 12642 } 12643 if (removed != null) { 12644 for (int j=0; j<removed.size(); j++) { 12645 PreferredActivity pa = removed.get(j); 12646 pir.removeFilter(pa); 12647 } 12648 changed = true; 12649 } 12650 } 12651 return changed; 12652 } 12653 12654 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12655 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12656 if (userId == UserHandle.USER_ALL) { 12657 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12658 for (int oneUserId : sUserManager.getUserIds()) { 12659 scheduleWritePackageRestrictionsLocked(oneUserId); 12660 } 12661 } else { 12662 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12663 scheduleWritePackageRestrictionsLocked(userId); 12664 } 12665 } 12666 12667 @Override 12668 public void resetPreferredActivities(int userId) { 12669 /* TODO: Actually use userId. Why is it being passed in? */ 12670 mContext.enforceCallingOrSelfPermission( 12671 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12672 // writer 12673 synchronized (mPackages) { 12674 int user = UserHandle.getCallingUserId(); 12675 clearPackagePreferredActivitiesLPw(null, user); 12676 mSettings.readDefaultPreferredAppsLPw(this, user); 12677 scheduleWritePackageRestrictionsLocked(user); 12678 } 12679 } 12680 12681 @Override 12682 public int getPreferredActivities(List<IntentFilter> outFilters, 12683 List<ComponentName> outActivities, String packageName) { 12684 12685 int num = 0; 12686 final int userId = UserHandle.getCallingUserId(); 12687 // reader 12688 synchronized (mPackages) { 12689 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12690 if (pir != null) { 12691 final Iterator<PreferredActivity> it = pir.filterIterator(); 12692 while (it.hasNext()) { 12693 final PreferredActivity pa = it.next(); 12694 if (packageName == null 12695 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12696 && pa.mPref.mAlways)) { 12697 if (outFilters != null) { 12698 outFilters.add(new IntentFilter(pa)); 12699 } 12700 if (outActivities != null) { 12701 outActivities.add(pa.mPref.mComponent); 12702 } 12703 } 12704 } 12705 } 12706 } 12707 12708 return num; 12709 } 12710 12711 @Override 12712 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12713 int userId) { 12714 int callingUid = Binder.getCallingUid(); 12715 if (callingUid != Process.SYSTEM_UID) { 12716 throw new SecurityException( 12717 "addPersistentPreferredActivity can only be run by the system"); 12718 } 12719 if (filter.countActions() == 0) { 12720 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12721 return; 12722 } 12723 synchronized (mPackages) { 12724 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12725 " :"); 12726 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12727 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12728 new PersistentPreferredActivity(filter, activity)); 12729 scheduleWritePackageRestrictionsLocked(userId); 12730 } 12731 } 12732 12733 @Override 12734 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12735 int callingUid = Binder.getCallingUid(); 12736 if (callingUid != Process.SYSTEM_UID) { 12737 throw new SecurityException( 12738 "clearPackagePersistentPreferredActivities can only be run by the system"); 12739 } 12740 ArrayList<PersistentPreferredActivity> removed = null; 12741 boolean changed = false; 12742 synchronized (mPackages) { 12743 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12744 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12745 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12746 .valueAt(i); 12747 if (userId != thisUserId) { 12748 continue; 12749 } 12750 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12751 while (it.hasNext()) { 12752 PersistentPreferredActivity ppa = it.next(); 12753 // Mark entry for removal only if it matches the package name. 12754 if (ppa.mComponent.getPackageName().equals(packageName)) { 12755 if (removed == null) { 12756 removed = new ArrayList<PersistentPreferredActivity>(); 12757 } 12758 removed.add(ppa); 12759 } 12760 } 12761 if (removed != null) { 12762 for (int j=0; j<removed.size(); j++) { 12763 PersistentPreferredActivity ppa = removed.get(j); 12764 ppir.removeFilter(ppa); 12765 } 12766 changed = true; 12767 } 12768 } 12769 12770 if (changed) { 12771 scheduleWritePackageRestrictionsLocked(userId); 12772 } 12773 } 12774 } 12775 12776 /** 12777 * Non-Binder method, support for the backup/restore mechanism: write the 12778 * full set of preferred activities in its canonical XML format. Returns true 12779 * on success; false otherwise. 12780 */ 12781 @Override 12782 public byte[] getPreferredActivityBackup(int userId) { 12783 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12784 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12785 } 12786 12787 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12788 try { 12789 final XmlSerializer serializer = new FastXmlSerializer(); 12790 serializer.setOutput(dataStream, "utf-8"); 12791 serializer.startDocument(null, true); 12792 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12793 12794 synchronized (mPackages) { 12795 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12796 } 12797 12798 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12799 serializer.endDocument(); 12800 serializer.flush(); 12801 } catch (Exception e) { 12802 if (DEBUG_BACKUP) { 12803 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12804 } 12805 return null; 12806 } 12807 12808 return dataStream.toByteArray(); 12809 } 12810 12811 @Override 12812 public void restorePreferredActivities(byte[] backup, int userId) { 12813 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12814 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12815 } 12816 12817 try { 12818 final XmlPullParser parser = Xml.newPullParser(); 12819 parser.setInput(new ByteArrayInputStream(backup), null); 12820 12821 int type; 12822 while ((type = parser.next()) != XmlPullParser.START_TAG 12823 && type != XmlPullParser.END_DOCUMENT) { 12824 } 12825 if (type != XmlPullParser.START_TAG) { 12826 // oops didn't find a start tag?! 12827 if (DEBUG_BACKUP) { 12828 Slog.e(TAG, "Didn't find start tag during restore"); 12829 } 12830 return; 12831 } 12832 12833 // this is supposed to be TAG_PREFERRED_BACKUP 12834 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12835 if (DEBUG_BACKUP) { 12836 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12837 } 12838 return; 12839 } 12840 12841 // skip interfering stuff, then we're aligned with the backing implementation 12842 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12843 synchronized (mPackages) { 12844 mSettings.readPreferredActivitiesLPw(parser, userId); 12845 } 12846 } catch (Exception e) { 12847 if (DEBUG_BACKUP) { 12848 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12849 } 12850 } 12851 } 12852 12853 @Override 12854 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12855 int sourceUserId, int targetUserId, int flags) { 12856 mContext.enforceCallingOrSelfPermission( 12857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12858 int callingUid = Binder.getCallingUid(); 12859 enforceOwnerRights(ownerPackage, callingUid); 12860 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12861 if (intentFilter.countActions() == 0) { 12862 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12863 return; 12864 } 12865 synchronized (mPackages) { 12866 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12867 ownerPackage, targetUserId, flags); 12868 CrossProfileIntentResolver resolver = 12869 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12870 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12871 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12872 if (existing != null) { 12873 int size = existing.size(); 12874 for (int i = 0; i < size; i++) { 12875 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12876 return; 12877 } 12878 } 12879 } 12880 resolver.addFilter(newFilter); 12881 scheduleWritePackageRestrictionsLocked(sourceUserId); 12882 } 12883 } 12884 12885 @Override 12886 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12887 mContext.enforceCallingOrSelfPermission( 12888 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12889 int callingUid = Binder.getCallingUid(); 12890 enforceOwnerRights(ownerPackage, callingUid); 12891 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12892 synchronized (mPackages) { 12893 CrossProfileIntentResolver resolver = 12894 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12895 ArraySet<CrossProfileIntentFilter> set = 12896 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12897 for (CrossProfileIntentFilter filter : set) { 12898 if (filter.getOwnerPackage().equals(ownerPackage)) { 12899 resolver.removeFilter(filter); 12900 } 12901 } 12902 scheduleWritePackageRestrictionsLocked(sourceUserId); 12903 } 12904 } 12905 12906 // Enforcing that callingUid is owning pkg on userId 12907 private void enforceOwnerRights(String pkg, int callingUid) { 12908 // The system owns everything. 12909 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12910 return; 12911 } 12912 int callingUserId = UserHandle.getUserId(callingUid); 12913 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12914 if (pi == null) { 12915 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12916 + callingUserId); 12917 } 12918 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12919 throw new SecurityException("Calling uid " + callingUid 12920 + " does not own package " + pkg); 12921 } 12922 } 12923 12924 @Override 12925 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12926 Intent intent = new Intent(Intent.ACTION_MAIN); 12927 intent.addCategory(Intent.CATEGORY_HOME); 12928 12929 final int callingUserId = UserHandle.getCallingUserId(); 12930 List<ResolveInfo> list = queryIntentActivities(intent, null, 12931 PackageManager.GET_META_DATA, callingUserId); 12932 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12933 true, false, false, callingUserId); 12934 12935 allHomeCandidates.clear(); 12936 if (list != null) { 12937 for (ResolveInfo ri : list) { 12938 allHomeCandidates.add(ri); 12939 } 12940 } 12941 return (preferred == null || preferred.activityInfo == null) 12942 ? null 12943 : new ComponentName(preferred.activityInfo.packageName, 12944 preferred.activityInfo.name); 12945 } 12946 12947 @Override 12948 public void setApplicationEnabledSetting(String appPackageName, 12949 int newState, int flags, int userId, String callingPackage) { 12950 if (!sUserManager.exists(userId)) return; 12951 if (callingPackage == null) { 12952 callingPackage = Integer.toString(Binder.getCallingUid()); 12953 } 12954 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12955 } 12956 12957 @Override 12958 public void setComponentEnabledSetting(ComponentName componentName, 12959 int newState, int flags, int userId) { 12960 if (!sUserManager.exists(userId)) return; 12961 setEnabledSetting(componentName.getPackageName(), 12962 componentName.getClassName(), newState, flags, userId, null); 12963 } 12964 12965 private void setEnabledSetting(final String packageName, String className, int newState, 12966 final int flags, int userId, String callingPackage) { 12967 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12968 || newState == COMPONENT_ENABLED_STATE_ENABLED 12969 || newState == COMPONENT_ENABLED_STATE_DISABLED 12970 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12971 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12972 throw new IllegalArgumentException("Invalid new component state: " 12973 + newState); 12974 } 12975 PackageSetting pkgSetting; 12976 final int uid = Binder.getCallingUid(); 12977 final int permission = mContext.checkCallingOrSelfPermission( 12978 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12979 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12980 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12981 boolean sendNow = false; 12982 boolean isApp = (className == null); 12983 String componentName = isApp ? packageName : className; 12984 int packageUid = -1; 12985 ArrayList<String> components; 12986 12987 // writer 12988 synchronized (mPackages) { 12989 pkgSetting = mSettings.mPackages.get(packageName); 12990 if (pkgSetting == null) { 12991 if (className == null) { 12992 throw new IllegalArgumentException( 12993 "Unknown package: " + packageName); 12994 } 12995 throw new IllegalArgumentException( 12996 "Unknown component: " + packageName 12997 + "/" + className); 12998 } 12999 // Allow root and verify that userId is not being specified by a different user 13000 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13001 throw new SecurityException( 13002 "Permission Denial: attempt to change component state from pid=" 13003 + Binder.getCallingPid() 13004 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13005 } 13006 if (className == null) { 13007 // We're dealing with an application/package level state change 13008 if (pkgSetting.getEnabled(userId) == newState) { 13009 // Nothing to do 13010 return; 13011 } 13012 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13013 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13014 // Don't care about who enables an app. 13015 callingPackage = null; 13016 } 13017 pkgSetting.setEnabled(newState, userId, callingPackage); 13018 // pkgSetting.pkg.mSetEnabled = newState; 13019 } else { 13020 // We're dealing with a component level state change 13021 // First, verify that this is a valid class name. 13022 PackageParser.Package pkg = pkgSetting.pkg; 13023 if (pkg == null || !pkg.hasComponentClassName(className)) { 13024 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13025 throw new IllegalArgumentException("Component class " + className 13026 + " does not exist in " + packageName); 13027 } else { 13028 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13029 + className + " does not exist in " + packageName); 13030 } 13031 } 13032 switch (newState) { 13033 case COMPONENT_ENABLED_STATE_ENABLED: 13034 if (!pkgSetting.enableComponentLPw(className, userId)) { 13035 return; 13036 } 13037 break; 13038 case COMPONENT_ENABLED_STATE_DISABLED: 13039 if (!pkgSetting.disableComponentLPw(className, userId)) { 13040 return; 13041 } 13042 break; 13043 case COMPONENT_ENABLED_STATE_DEFAULT: 13044 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13045 return; 13046 } 13047 break; 13048 default: 13049 Slog.e(TAG, "Invalid new component state: " + newState); 13050 return; 13051 } 13052 } 13053 scheduleWritePackageRestrictionsLocked(userId); 13054 components = mPendingBroadcasts.get(userId, packageName); 13055 final boolean newPackage = components == null; 13056 if (newPackage) { 13057 components = new ArrayList<String>(); 13058 } 13059 if (!components.contains(componentName)) { 13060 components.add(componentName); 13061 } 13062 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13063 sendNow = true; 13064 // Purge entry from pending broadcast list if another one exists already 13065 // since we are sending one right away. 13066 mPendingBroadcasts.remove(userId, packageName); 13067 } else { 13068 if (newPackage) { 13069 mPendingBroadcasts.put(userId, packageName, components); 13070 } 13071 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13072 // Schedule a message 13073 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13074 } 13075 } 13076 } 13077 13078 long callingId = Binder.clearCallingIdentity(); 13079 try { 13080 if (sendNow) { 13081 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13082 sendPackageChangedBroadcast(packageName, 13083 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13084 } 13085 } finally { 13086 Binder.restoreCallingIdentity(callingId); 13087 } 13088 } 13089 13090 private void sendPackageChangedBroadcast(String packageName, 13091 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13092 if (DEBUG_INSTALL) 13093 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13094 + componentNames); 13095 Bundle extras = new Bundle(4); 13096 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13097 String nameList[] = new String[componentNames.size()]; 13098 componentNames.toArray(nameList); 13099 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13100 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13101 extras.putInt(Intent.EXTRA_UID, packageUid); 13102 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13103 new int[] {UserHandle.getUserId(packageUid)}); 13104 } 13105 13106 @Override 13107 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13108 if (!sUserManager.exists(userId)) return; 13109 final int uid = Binder.getCallingUid(); 13110 final int permission = mContext.checkCallingOrSelfPermission( 13111 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13112 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13113 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13114 // writer 13115 synchronized (mPackages) { 13116 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13117 uid, userId)) { 13118 scheduleWritePackageRestrictionsLocked(userId); 13119 } 13120 } 13121 } 13122 13123 @Override 13124 public String getInstallerPackageName(String packageName) { 13125 // reader 13126 synchronized (mPackages) { 13127 return mSettings.getInstallerPackageNameLPr(packageName); 13128 } 13129 } 13130 13131 @Override 13132 public int getApplicationEnabledSetting(String packageName, int userId) { 13133 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13134 int uid = Binder.getCallingUid(); 13135 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13136 // reader 13137 synchronized (mPackages) { 13138 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13139 } 13140 } 13141 13142 @Override 13143 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13144 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13145 int uid = Binder.getCallingUid(); 13146 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13147 // reader 13148 synchronized (mPackages) { 13149 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13150 } 13151 } 13152 13153 @Override 13154 public void enterSafeMode() { 13155 enforceSystemOrRoot("Only the system can request entering safe mode"); 13156 13157 if (!mSystemReady) { 13158 mSafeMode = true; 13159 } 13160 } 13161 13162 @Override 13163 public void systemReady() { 13164 mSystemReady = true; 13165 13166 // Read the compatibilty setting when the system is ready. 13167 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13168 mContext.getContentResolver(), 13169 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13170 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13171 if (DEBUG_SETTINGS) { 13172 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13173 } 13174 13175 synchronized (mPackages) { 13176 // Verify that all of the preferred activity components actually 13177 // exist. It is possible for applications to be updated and at 13178 // that point remove a previously declared activity component that 13179 // had been set as a preferred activity. We try to clean this up 13180 // the next time we encounter that preferred activity, but it is 13181 // possible for the user flow to never be able to return to that 13182 // situation so here we do a sanity check to make sure we haven't 13183 // left any junk around. 13184 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13185 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13186 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13187 removed.clear(); 13188 for (PreferredActivity pa : pir.filterSet()) { 13189 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13190 removed.add(pa); 13191 } 13192 } 13193 if (removed.size() > 0) { 13194 for (int r=0; r<removed.size(); r++) { 13195 PreferredActivity pa = removed.get(r); 13196 Slog.w(TAG, "Removing dangling preferred activity: " 13197 + pa.mPref.mComponent); 13198 pir.removeFilter(pa); 13199 } 13200 mSettings.writePackageRestrictionsLPr( 13201 mSettings.mPreferredActivities.keyAt(i)); 13202 } 13203 } 13204 } 13205 sUserManager.systemReady(); 13206 13207 // Kick off any messages waiting for system ready 13208 if (mPostSystemReadyMessages != null) { 13209 for (Message msg : mPostSystemReadyMessages) { 13210 msg.sendToTarget(); 13211 } 13212 mPostSystemReadyMessages = null; 13213 } 13214 13215 // Watch for external volumes that come and go over time 13216 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13217 storage.registerListener(mStorageListener); 13218 13219 mInstallerService.systemReady(); 13220 } 13221 13222 @Override 13223 public boolean isSafeMode() { 13224 return mSafeMode; 13225 } 13226 13227 @Override 13228 public boolean hasSystemUidErrors() { 13229 return mHasSystemUidErrors; 13230 } 13231 13232 static String arrayToString(int[] array) { 13233 StringBuffer buf = new StringBuffer(128); 13234 buf.append('['); 13235 if (array != null) { 13236 for (int i=0; i<array.length; i++) { 13237 if (i > 0) buf.append(", "); 13238 buf.append(array[i]); 13239 } 13240 } 13241 buf.append(']'); 13242 return buf.toString(); 13243 } 13244 13245 static class DumpState { 13246 public static final int DUMP_LIBS = 1 << 0; 13247 public static final int DUMP_FEATURES = 1 << 1; 13248 public static final int DUMP_RESOLVERS = 1 << 2; 13249 public static final int DUMP_PERMISSIONS = 1 << 3; 13250 public static final int DUMP_PACKAGES = 1 << 4; 13251 public static final int DUMP_SHARED_USERS = 1 << 5; 13252 public static final int DUMP_MESSAGES = 1 << 6; 13253 public static final int DUMP_PROVIDERS = 1 << 7; 13254 public static final int DUMP_VERIFIERS = 1 << 8; 13255 public static final int DUMP_PREFERRED = 1 << 9; 13256 public static final int DUMP_PREFERRED_XML = 1 << 10; 13257 public static final int DUMP_KEYSETS = 1 << 11; 13258 public static final int DUMP_VERSION = 1 << 12; 13259 public static final int DUMP_INSTALLS = 1 << 13; 13260 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13261 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13262 13263 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13264 13265 private int mTypes; 13266 13267 private int mOptions; 13268 13269 private boolean mTitlePrinted; 13270 13271 private SharedUserSetting mSharedUser; 13272 13273 public boolean isDumping(int type) { 13274 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13275 return true; 13276 } 13277 13278 return (mTypes & type) != 0; 13279 } 13280 13281 public void setDump(int type) { 13282 mTypes |= type; 13283 } 13284 13285 public boolean isOptionEnabled(int option) { 13286 return (mOptions & option) != 0; 13287 } 13288 13289 public void setOptionEnabled(int option) { 13290 mOptions |= option; 13291 } 13292 13293 public boolean onTitlePrinted() { 13294 final boolean printed = mTitlePrinted; 13295 mTitlePrinted = true; 13296 return printed; 13297 } 13298 13299 public boolean getTitlePrinted() { 13300 return mTitlePrinted; 13301 } 13302 13303 public void setTitlePrinted(boolean enabled) { 13304 mTitlePrinted = enabled; 13305 } 13306 13307 public SharedUserSetting getSharedUser() { 13308 return mSharedUser; 13309 } 13310 13311 public void setSharedUser(SharedUserSetting user) { 13312 mSharedUser = user; 13313 } 13314 } 13315 13316 @Override 13317 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13318 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13319 != PackageManager.PERMISSION_GRANTED) { 13320 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13321 + Binder.getCallingPid() 13322 + ", uid=" + Binder.getCallingUid() 13323 + " without permission " 13324 + android.Manifest.permission.DUMP); 13325 return; 13326 } 13327 13328 DumpState dumpState = new DumpState(); 13329 boolean fullPreferred = false; 13330 boolean checkin = false; 13331 13332 String packageName = null; 13333 13334 int opti = 0; 13335 while (opti < args.length) { 13336 String opt = args[opti]; 13337 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13338 break; 13339 } 13340 opti++; 13341 13342 if ("-a".equals(opt)) { 13343 // Right now we only know how to print all. 13344 } else if ("-h".equals(opt)) { 13345 pw.println("Package manager dump options:"); 13346 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13347 pw.println(" --checkin: dump for a checkin"); 13348 pw.println(" -f: print details of intent filters"); 13349 pw.println(" -h: print this help"); 13350 pw.println(" cmd may be one of:"); 13351 pw.println(" l[ibraries]: list known shared libraries"); 13352 pw.println(" f[ibraries]: list device features"); 13353 pw.println(" k[eysets]: print known keysets"); 13354 pw.println(" r[esolvers]: dump intent resolvers"); 13355 pw.println(" perm[issions]: dump permissions"); 13356 pw.println(" pref[erred]: print preferred package settings"); 13357 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13358 pw.println(" prov[iders]: dump content providers"); 13359 pw.println(" p[ackages]: dump installed packages"); 13360 pw.println(" s[hared-users]: dump shared user IDs"); 13361 pw.println(" m[essages]: print collected runtime messages"); 13362 pw.println(" v[erifiers]: print package verifier info"); 13363 pw.println(" version: print database version info"); 13364 pw.println(" write: write current settings now"); 13365 pw.println(" <package.name>: info about given package"); 13366 pw.println(" installs: details about install sessions"); 13367 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13368 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13369 return; 13370 } else if ("--checkin".equals(opt)) { 13371 checkin = true; 13372 } else if ("-f".equals(opt)) { 13373 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13374 } else { 13375 pw.println("Unknown argument: " + opt + "; use -h for help"); 13376 } 13377 } 13378 13379 // Is the caller requesting to dump a particular piece of data? 13380 if (opti < args.length) { 13381 String cmd = args[opti]; 13382 opti++; 13383 // Is this a package name? 13384 if ("android".equals(cmd) || cmd.contains(".")) { 13385 packageName = cmd; 13386 // When dumping a single package, we always dump all of its 13387 // filter information since the amount of data will be reasonable. 13388 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13389 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13390 dumpState.setDump(DumpState.DUMP_LIBS); 13391 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13392 dumpState.setDump(DumpState.DUMP_FEATURES); 13393 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13394 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13395 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13396 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13397 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13398 dumpState.setDump(DumpState.DUMP_PREFERRED); 13399 } else if ("preferred-xml".equals(cmd)) { 13400 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13401 if (opti < args.length && "--full".equals(args[opti])) { 13402 fullPreferred = true; 13403 opti++; 13404 } 13405 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13406 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13407 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13408 dumpState.setDump(DumpState.DUMP_PACKAGES); 13409 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13410 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13411 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13412 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13413 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13414 dumpState.setDump(DumpState.DUMP_MESSAGES); 13415 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13416 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13417 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13418 || "intent-filter-verifiers".equals(cmd)) { 13419 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13420 } else if ("version".equals(cmd)) { 13421 dumpState.setDump(DumpState.DUMP_VERSION); 13422 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13423 dumpState.setDump(DumpState.DUMP_KEYSETS); 13424 } else if ("installs".equals(cmd)) { 13425 dumpState.setDump(DumpState.DUMP_INSTALLS); 13426 } else if ("write".equals(cmd)) { 13427 synchronized (mPackages) { 13428 mSettings.writeLPr(); 13429 pw.println("Settings written."); 13430 return; 13431 } 13432 } 13433 } 13434 13435 if (checkin) { 13436 pw.println("vers,1"); 13437 } 13438 13439 // reader 13440 synchronized (mPackages) { 13441 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13442 if (!checkin) { 13443 if (dumpState.onTitlePrinted()) 13444 pw.println(); 13445 pw.println("Database versions:"); 13446 pw.print(" SDK Version:"); 13447 pw.print(" internal="); 13448 pw.print(mSettings.mInternalSdkPlatform); 13449 pw.print(" external="); 13450 pw.println(mSettings.mExternalSdkPlatform); 13451 pw.print(" DB Version:"); 13452 pw.print(" internal="); 13453 pw.print(mSettings.mInternalDatabaseVersion); 13454 pw.print(" external="); 13455 pw.println(mSettings.mExternalDatabaseVersion); 13456 } 13457 } 13458 13459 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13460 if (!checkin) { 13461 if (dumpState.onTitlePrinted()) 13462 pw.println(); 13463 pw.println("Verifiers:"); 13464 pw.print(" Required: "); 13465 pw.print(mRequiredVerifierPackage); 13466 pw.print(" (uid="); 13467 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13468 pw.println(")"); 13469 } else if (mRequiredVerifierPackage != null) { 13470 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13471 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13472 } 13473 } 13474 13475 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13476 packageName == null) { 13477 if (mIntentFilterVerifierComponent != null) { 13478 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13479 if (!checkin) { 13480 if (dumpState.onTitlePrinted()) 13481 pw.println(); 13482 pw.println("Intent Filter Verifier:"); 13483 pw.print(" Using: "); 13484 pw.print(verifierPackageName); 13485 pw.print(" (uid="); 13486 pw.print(getPackageUid(verifierPackageName, 0)); 13487 pw.println(")"); 13488 } else if (verifierPackageName != null) { 13489 pw.print("ifv,"); pw.print(verifierPackageName); 13490 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13491 } 13492 } else { 13493 pw.println(); 13494 pw.println("No Intent Filter Verifier available!"); 13495 } 13496 } 13497 13498 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13499 boolean printedHeader = false; 13500 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13501 while (it.hasNext()) { 13502 String name = it.next(); 13503 SharedLibraryEntry ent = mSharedLibraries.get(name); 13504 if (!checkin) { 13505 if (!printedHeader) { 13506 if (dumpState.onTitlePrinted()) 13507 pw.println(); 13508 pw.println("Libraries:"); 13509 printedHeader = true; 13510 } 13511 pw.print(" "); 13512 } else { 13513 pw.print("lib,"); 13514 } 13515 pw.print(name); 13516 if (!checkin) { 13517 pw.print(" -> "); 13518 } 13519 if (ent.path != null) { 13520 if (!checkin) { 13521 pw.print("(jar) "); 13522 pw.print(ent.path); 13523 } else { 13524 pw.print(",jar,"); 13525 pw.print(ent.path); 13526 } 13527 } else { 13528 if (!checkin) { 13529 pw.print("(apk) "); 13530 pw.print(ent.apk); 13531 } else { 13532 pw.print(",apk,"); 13533 pw.print(ent.apk); 13534 } 13535 } 13536 pw.println(); 13537 } 13538 } 13539 13540 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13541 if (dumpState.onTitlePrinted()) 13542 pw.println(); 13543 if (!checkin) { 13544 pw.println("Features:"); 13545 } 13546 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13547 while (it.hasNext()) { 13548 String name = it.next(); 13549 if (!checkin) { 13550 pw.print(" "); 13551 } else { 13552 pw.print("feat,"); 13553 } 13554 pw.println(name); 13555 } 13556 } 13557 13558 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13559 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13560 : "Activity Resolver Table:", " ", packageName, 13561 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13562 dumpState.setTitlePrinted(true); 13563 } 13564 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13565 : "Receiver Resolver Table:", " ", packageName, 13566 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13567 dumpState.setTitlePrinted(true); 13568 } 13569 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13570 : "Service Resolver Table:", " ", packageName, 13571 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13572 dumpState.setTitlePrinted(true); 13573 } 13574 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13575 : "Provider Resolver Table:", " ", packageName, 13576 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13577 dumpState.setTitlePrinted(true); 13578 } 13579 } 13580 13581 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13582 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13583 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13584 int user = mSettings.mPreferredActivities.keyAt(i); 13585 if (pir.dump(pw, 13586 dumpState.getTitlePrinted() 13587 ? "\nPreferred Activities User " + user + ":" 13588 : "Preferred Activities User " + user + ":", " ", 13589 packageName, true, false)) { 13590 dumpState.setTitlePrinted(true); 13591 } 13592 } 13593 } 13594 13595 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13596 pw.flush(); 13597 FileOutputStream fout = new FileOutputStream(fd); 13598 BufferedOutputStream str = new BufferedOutputStream(fout); 13599 XmlSerializer serializer = new FastXmlSerializer(); 13600 try { 13601 serializer.setOutput(str, "utf-8"); 13602 serializer.startDocument(null, true); 13603 serializer.setFeature( 13604 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13605 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13606 serializer.endDocument(); 13607 serializer.flush(); 13608 } catch (IllegalArgumentException e) { 13609 pw.println("Failed writing: " + e); 13610 } catch (IllegalStateException e) { 13611 pw.println("Failed writing: " + e); 13612 } catch (IOException e) { 13613 pw.println("Failed writing: " + e); 13614 } 13615 } 13616 13617 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13618 pw.println(); 13619 int count = mSettings.mPackages.size(); 13620 if (count == 0) { 13621 pw.println("No domain preferred apps!"); 13622 pw.println(); 13623 } else { 13624 final String prefix = " "; 13625 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13626 if (allPackageSettings.size() == 0) { 13627 pw.println("No domain preferred apps!"); 13628 pw.println(); 13629 } else { 13630 pw.println("Domain preferred apps status:"); 13631 pw.println(); 13632 count = 0; 13633 for (PackageSetting ps : allPackageSettings) { 13634 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13635 if (ivi == null || ivi.getPackageName() == null) continue; 13636 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13637 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13638 pw.println(prefix + "Status: " + ivi.getStatusString()); 13639 pw.println(); 13640 count++; 13641 } 13642 if (count == 0) { 13643 pw.println(prefix + "No domain preferred app status!"); 13644 pw.println(); 13645 } 13646 for (int userId : sUserManager.getUserIds()) { 13647 pw.println("Domain preferred apps for User " + userId + ":"); 13648 pw.println(); 13649 count = 0; 13650 for (PackageSetting ps : allPackageSettings) { 13651 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13652 if (ivi == null || ivi.getPackageName() == null) { 13653 continue; 13654 } 13655 final int status = ps.getDomainVerificationStatusForUser(userId); 13656 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13657 continue; 13658 } 13659 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13660 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13661 String statusStr = IntentFilterVerificationInfo. 13662 getStatusStringFromValue(status); 13663 pw.println(prefix + "Status: " + statusStr); 13664 pw.println(); 13665 count++; 13666 } 13667 if (count == 0) { 13668 pw.println(prefix + "No domain preferred apps!"); 13669 pw.println(); 13670 } 13671 } 13672 } 13673 } 13674 } 13675 13676 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13677 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13678 if (packageName == null) { 13679 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13680 if (iperm == 0) { 13681 if (dumpState.onTitlePrinted()) 13682 pw.println(); 13683 pw.println("AppOp Permissions:"); 13684 } 13685 pw.print(" AppOp Permission "); 13686 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13687 pw.println(":"); 13688 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13689 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13690 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13691 } 13692 } 13693 } 13694 } 13695 13696 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13697 boolean printedSomething = false; 13698 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13699 if (packageName != null && !packageName.equals(p.info.packageName)) { 13700 continue; 13701 } 13702 if (!printedSomething) { 13703 if (dumpState.onTitlePrinted()) 13704 pw.println(); 13705 pw.println("Registered ContentProviders:"); 13706 printedSomething = true; 13707 } 13708 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13709 pw.print(" "); pw.println(p.toString()); 13710 } 13711 printedSomething = false; 13712 for (Map.Entry<String, PackageParser.Provider> entry : 13713 mProvidersByAuthority.entrySet()) { 13714 PackageParser.Provider p = entry.getValue(); 13715 if (packageName != null && !packageName.equals(p.info.packageName)) { 13716 continue; 13717 } 13718 if (!printedSomething) { 13719 if (dumpState.onTitlePrinted()) 13720 pw.println(); 13721 pw.println("ContentProvider Authorities:"); 13722 printedSomething = true; 13723 } 13724 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13725 pw.print(" "); pw.println(p.toString()); 13726 if (p.info != null && p.info.applicationInfo != null) { 13727 final String appInfo = p.info.applicationInfo.toString(); 13728 pw.print(" applicationInfo="); pw.println(appInfo); 13729 } 13730 } 13731 } 13732 13733 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13734 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13735 } 13736 13737 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13738 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13739 } 13740 13741 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13742 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13743 } 13744 13745 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13746 // XXX should handle packageName != null by dumping only install data that 13747 // the given package is involved with. 13748 if (dumpState.onTitlePrinted()) pw.println(); 13749 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13750 } 13751 13752 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13753 if (dumpState.onTitlePrinted()) pw.println(); 13754 mSettings.dumpReadMessagesLPr(pw, dumpState); 13755 13756 pw.println(); 13757 pw.println("Package warning messages:"); 13758 BufferedReader in = null; 13759 String line = null; 13760 try { 13761 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13762 while ((line = in.readLine()) != null) { 13763 if (line.contains("ignored: updated version")) continue; 13764 pw.println(line); 13765 } 13766 } catch (IOException ignored) { 13767 } finally { 13768 IoUtils.closeQuietly(in); 13769 } 13770 } 13771 13772 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13773 BufferedReader in = null; 13774 String line = null; 13775 try { 13776 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13777 while ((line = in.readLine()) != null) { 13778 if (line.contains("ignored: updated version")) continue; 13779 pw.print("msg,"); 13780 pw.println(line); 13781 } 13782 } catch (IOException ignored) { 13783 } finally { 13784 IoUtils.closeQuietly(in); 13785 } 13786 } 13787 } 13788 } 13789 13790 // ------- apps on sdcard specific code ------- 13791 static final boolean DEBUG_SD_INSTALL = false; 13792 13793 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13794 13795 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13796 13797 private boolean mMediaMounted = false; 13798 13799 static String getEncryptKey() { 13800 try { 13801 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13802 SD_ENCRYPTION_KEYSTORE_NAME); 13803 if (sdEncKey == null) { 13804 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13805 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13806 if (sdEncKey == null) { 13807 Slog.e(TAG, "Failed to create encryption keys"); 13808 return null; 13809 } 13810 } 13811 return sdEncKey; 13812 } catch (NoSuchAlgorithmException nsae) { 13813 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13814 return null; 13815 } catch (IOException ioe) { 13816 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13817 return null; 13818 } 13819 } 13820 13821 /* 13822 * Update media status on PackageManager. 13823 */ 13824 @Override 13825 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13826 int callingUid = Binder.getCallingUid(); 13827 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13828 throw new SecurityException("Media status can only be updated by the system"); 13829 } 13830 // reader; this apparently protects mMediaMounted, but should probably 13831 // be a different lock in that case. 13832 synchronized (mPackages) { 13833 Log.i(TAG, "Updating external media status from " 13834 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13835 + (mediaStatus ? "mounted" : "unmounted")); 13836 if (DEBUG_SD_INSTALL) 13837 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13838 + ", mMediaMounted=" + mMediaMounted); 13839 if (mediaStatus == mMediaMounted) { 13840 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13841 : 0, -1); 13842 mHandler.sendMessage(msg); 13843 return; 13844 } 13845 mMediaMounted = mediaStatus; 13846 } 13847 // Queue up an async operation since the package installation may take a 13848 // little while. 13849 mHandler.post(new Runnable() { 13850 public void run() { 13851 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13852 } 13853 }); 13854 } 13855 13856 /** 13857 * Called by MountService when the initial ASECs to scan are available. 13858 * Should block until all the ASEC containers are finished being scanned. 13859 */ 13860 public void scanAvailableAsecs() { 13861 updateExternalMediaStatusInner(true, false, false); 13862 if (mShouldRestoreconData) { 13863 SELinuxMMAC.setRestoreconDone(); 13864 mShouldRestoreconData = false; 13865 } 13866 } 13867 13868 /* 13869 * Collect information of applications on external media, map them against 13870 * existing containers and update information based on current mount status. 13871 * Please note that we always have to report status if reportStatus has been 13872 * set to true especially when unloading packages. 13873 */ 13874 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13875 boolean externalStorage) { 13876 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13877 int[] uidArr = EmptyArray.INT; 13878 13879 final String[] list = PackageHelper.getSecureContainerList(); 13880 if (ArrayUtils.isEmpty(list)) { 13881 Log.i(TAG, "No secure containers found"); 13882 } else { 13883 // Process list of secure containers and categorize them 13884 // as active or stale based on their package internal state. 13885 13886 // reader 13887 synchronized (mPackages) { 13888 for (String cid : list) { 13889 // Leave stages untouched for now; installer service owns them 13890 if (PackageInstallerService.isStageName(cid)) continue; 13891 13892 if (DEBUG_SD_INSTALL) 13893 Log.i(TAG, "Processing container " + cid); 13894 String pkgName = getAsecPackageName(cid); 13895 if (pkgName == null) { 13896 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13897 continue; 13898 } 13899 if (DEBUG_SD_INSTALL) 13900 Log.i(TAG, "Looking for pkg : " + pkgName); 13901 13902 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13903 if (ps == null) { 13904 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13905 continue; 13906 } 13907 13908 /* 13909 * Skip packages that are not external if we're unmounting 13910 * external storage. 13911 */ 13912 if (externalStorage && !isMounted && !isExternal(ps)) { 13913 continue; 13914 } 13915 13916 final AsecInstallArgs args = new AsecInstallArgs(cid, 13917 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13918 // The package status is changed only if the code path 13919 // matches between settings and the container id. 13920 if (ps.codePathString != null 13921 && ps.codePathString.startsWith(args.getCodePath())) { 13922 if (DEBUG_SD_INSTALL) { 13923 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13924 + " at code path: " + ps.codePathString); 13925 } 13926 13927 // We do have a valid package installed on sdcard 13928 processCids.put(args, ps.codePathString); 13929 final int uid = ps.appId; 13930 if (uid != -1) { 13931 uidArr = ArrayUtils.appendInt(uidArr, uid); 13932 } 13933 } else { 13934 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13935 + ps.codePathString); 13936 } 13937 } 13938 } 13939 13940 Arrays.sort(uidArr); 13941 } 13942 13943 // Process packages with valid entries. 13944 if (isMounted) { 13945 if (DEBUG_SD_INSTALL) 13946 Log.i(TAG, "Loading packages"); 13947 loadMediaPackages(processCids, uidArr); 13948 startCleaningPackages(); 13949 mInstallerService.onSecureContainersAvailable(); 13950 } else { 13951 if (DEBUG_SD_INSTALL) 13952 Log.i(TAG, "Unloading packages"); 13953 unloadMediaPackages(processCids, uidArr, reportStatus); 13954 } 13955 } 13956 13957 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13958 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13959 final int size = infos.size(); 13960 final String[] packageNames = new String[size]; 13961 final int[] packageUids = new int[size]; 13962 for (int i = 0; i < size; i++) { 13963 final ApplicationInfo info = infos.get(i); 13964 packageNames[i] = info.packageName; 13965 packageUids[i] = info.uid; 13966 } 13967 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13968 finishedReceiver); 13969 } 13970 13971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13972 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13973 sendResourcesChangedBroadcast(mediaStatus, replacing, 13974 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13975 } 13976 13977 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13978 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13979 int size = pkgList.length; 13980 if (size > 0) { 13981 // Send broadcasts here 13982 Bundle extras = new Bundle(); 13983 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13984 if (uidArr != null) { 13985 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13986 } 13987 if (replacing) { 13988 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13989 } 13990 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13991 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13992 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13993 } 13994 } 13995 13996 /* 13997 * Look at potentially valid container ids from processCids If package 13998 * information doesn't match the one on record or package scanning fails, 13999 * the cid is added to list of removeCids. We currently don't delete stale 14000 * containers. 14001 */ 14002 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14003 ArrayList<String> pkgList = new ArrayList<String>(); 14004 Set<AsecInstallArgs> keys = processCids.keySet(); 14005 14006 for (AsecInstallArgs args : keys) { 14007 String codePath = processCids.get(args); 14008 if (DEBUG_SD_INSTALL) 14009 Log.i(TAG, "Loading container : " + args.cid); 14010 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14011 try { 14012 // Make sure there are no container errors first. 14013 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14014 Slog.e(TAG, "Failed to mount cid : " + args.cid 14015 + " when installing from sdcard"); 14016 continue; 14017 } 14018 // Check code path here. 14019 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14020 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14021 + " does not match one in settings " + codePath); 14022 continue; 14023 } 14024 // Parse package 14025 int parseFlags = mDefParseFlags; 14026 if (args.isExternalAsec()) { 14027 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14028 } 14029 if (args.isFwdLocked()) { 14030 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14031 } 14032 14033 synchronized (mInstallLock) { 14034 PackageParser.Package pkg = null; 14035 try { 14036 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14037 } catch (PackageManagerException e) { 14038 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14039 } 14040 // Scan the package 14041 if (pkg != null) { 14042 /* 14043 * TODO why is the lock being held? doPostInstall is 14044 * called in other places without the lock. This needs 14045 * to be straightened out. 14046 */ 14047 // writer 14048 synchronized (mPackages) { 14049 retCode = PackageManager.INSTALL_SUCCEEDED; 14050 pkgList.add(pkg.packageName); 14051 // Post process args 14052 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14053 pkg.applicationInfo.uid); 14054 } 14055 } else { 14056 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14057 } 14058 } 14059 14060 } finally { 14061 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14062 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14063 } 14064 } 14065 } 14066 // writer 14067 synchronized (mPackages) { 14068 // If the platform SDK has changed since the last time we booted, 14069 // we need to re-grant app permission to catch any new ones that 14070 // appear. This is really a hack, and means that apps can in some 14071 // cases get permissions that the user didn't initially explicitly 14072 // allow... it would be nice to have some better way to handle 14073 // this situation. 14074 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14075 if (regrantPermissions) 14076 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14077 + mSdkVersion + "; regranting permissions for external storage"); 14078 mSettings.mExternalSdkPlatform = mSdkVersion; 14079 14080 // Make sure group IDs have been assigned, and any permission 14081 // changes in other apps are accounted for 14082 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14083 | (regrantPermissions 14084 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14085 : 0)); 14086 14087 mSettings.updateExternalDatabaseVersion(); 14088 14089 // can downgrade to reader 14090 // Persist settings 14091 mSettings.writeLPr(); 14092 } 14093 // Send a broadcast to let everyone know we are done processing 14094 if (pkgList.size() > 0) { 14095 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14096 } 14097 } 14098 14099 /* 14100 * Utility method to unload a list of specified containers 14101 */ 14102 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14103 // Just unmount all valid containers. 14104 for (AsecInstallArgs arg : cidArgs) { 14105 synchronized (mInstallLock) { 14106 arg.doPostDeleteLI(false); 14107 } 14108 } 14109 } 14110 14111 /* 14112 * Unload packages mounted on external media. This involves deleting package 14113 * data from internal structures, sending broadcasts about diabled packages, 14114 * gc'ing to free up references, unmounting all secure containers 14115 * corresponding to packages on external media, and posting a 14116 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14117 * that we always have to post this message if status has been requested no 14118 * matter what. 14119 */ 14120 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14121 final boolean reportStatus) { 14122 if (DEBUG_SD_INSTALL) 14123 Log.i(TAG, "unloading media packages"); 14124 ArrayList<String> pkgList = new ArrayList<String>(); 14125 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14126 final Set<AsecInstallArgs> keys = processCids.keySet(); 14127 for (AsecInstallArgs args : keys) { 14128 String pkgName = args.getPackageName(); 14129 if (DEBUG_SD_INSTALL) 14130 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14131 // Delete package internally 14132 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14133 synchronized (mInstallLock) { 14134 boolean res = deletePackageLI(pkgName, null, false, null, null, 14135 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14136 if (res) { 14137 pkgList.add(pkgName); 14138 } else { 14139 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14140 failedList.add(args); 14141 } 14142 } 14143 } 14144 14145 // reader 14146 synchronized (mPackages) { 14147 // We didn't update the settings after removing each package; 14148 // write them now for all packages. 14149 mSettings.writeLPr(); 14150 } 14151 14152 // We have to absolutely send UPDATED_MEDIA_STATUS only 14153 // after confirming that all the receivers processed the ordered 14154 // broadcast when packages get disabled, force a gc to clean things up. 14155 // and unload all the containers. 14156 if (pkgList.size() > 0) { 14157 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14158 new IIntentReceiver.Stub() { 14159 public void performReceive(Intent intent, int resultCode, String data, 14160 Bundle extras, boolean ordered, boolean sticky, 14161 int sendingUser) throws RemoteException { 14162 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14163 reportStatus ? 1 : 0, 1, keys); 14164 mHandler.sendMessage(msg); 14165 } 14166 }); 14167 } else { 14168 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14169 keys); 14170 mHandler.sendMessage(msg); 14171 } 14172 } 14173 14174 private void loadPrivatePackages(VolumeInfo vol) { 14175 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14176 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14177 synchronized (mPackages) { 14178 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14179 for (PackageSetting ps : packages) { 14180 synchronized (mInstallLock) { 14181 final PackageParser.Package pkg; 14182 try { 14183 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14184 loaded.add(pkg.applicationInfo); 14185 } catch (PackageManagerException e) { 14186 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14187 } 14188 } 14189 } 14190 14191 // TODO: regrant any permissions that changed based since original install 14192 14193 mSettings.writeLPr(); 14194 } 14195 14196 Slog.d(TAG, "Loaded packages " + loaded); 14197 sendResourcesChangedBroadcast(true, false, loaded, null); 14198 } 14199 14200 private void unloadPrivatePackages(VolumeInfo vol) { 14201 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14202 synchronized (mPackages) { 14203 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14204 for (PackageSetting ps : packages) { 14205 if (ps.pkg == null) continue; 14206 synchronized (mInstallLock) { 14207 final ApplicationInfo info = ps.pkg.applicationInfo; 14208 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14209 if (deletePackageLI(ps.name, null, false, null, null, 14210 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14211 unloaded.add(info); 14212 } else { 14213 Slog.w(TAG, "Failed to unload " + ps.codePath); 14214 } 14215 } 14216 } 14217 14218 mSettings.writeLPr(); 14219 } 14220 14221 Slog.d(TAG, "Unloaded packages " + unloaded); 14222 sendResourcesChangedBroadcast(false, false, unloaded, null); 14223 } 14224 14225 private void unfreezePackage(String packageName) { 14226 synchronized (mPackages) { 14227 final PackageSetting ps = mSettings.mPackages.get(packageName); 14228 if (ps != null) { 14229 ps.frozen = false; 14230 } 14231 } 14232 } 14233 14234 @Override 14235 public int movePackage(final String packageName, final String volumeUuid) { 14236 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14237 14238 final int moveId = mNextMoveId.getAndIncrement(); 14239 try { 14240 movePackageInternal(packageName, volumeUuid, moveId); 14241 } catch (PackageManagerException e) { 14242 Slog.d(TAG, "Failed to move " + packageName, e); 14243 mMoveCallbacks.notifyStatusChanged(moveId, 14244 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14245 } 14246 return moveId; 14247 } 14248 14249 private void movePackageInternal(final String packageName, final String volumeUuid, 14250 final int moveId) throws PackageManagerException { 14251 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14252 final PackageManager pm = mContext.getPackageManager(); 14253 14254 final boolean currentAsec; 14255 final String currentVolumeUuid; 14256 final File codeFile; 14257 final String installerPackageName; 14258 final String packageAbiOverride; 14259 final int appId; 14260 final String seinfo; 14261 final String label; 14262 14263 // reader 14264 synchronized (mPackages) { 14265 final PackageParser.Package pkg = mPackages.get(packageName); 14266 final PackageSetting ps = mSettings.mPackages.get(packageName); 14267 if (pkg == null || ps == null) { 14268 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14269 } 14270 14271 if (pkg.applicationInfo.isSystemApp()) { 14272 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14273 "Cannot move system application"); 14274 } 14275 14276 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14277 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14278 "Package already moved to " + volumeUuid); 14279 } 14280 14281 if (ps.frozen) { 14282 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14283 "Failed to move already frozen package"); 14284 } 14285 14286 ps.frozen = true; 14287 14288 currentAsec = pkg.applicationInfo.isForwardLocked() 14289 || pkg.applicationInfo.isExternalAsec(); 14290 currentVolumeUuid = ps.volumeUuid; 14291 codeFile = new File(pkg.codePath); 14292 installerPackageName = ps.installerPackageName; 14293 packageAbiOverride = ps.cpuAbiOverrideString; 14294 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14295 seinfo = pkg.applicationInfo.seinfo; 14296 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14297 } 14298 14299 // Now that we're guarded by frozen state, kill app during upgrade 14300 killApplication(packageName, appId, "move pkg"); 14301 14302 final Bundle extras = new Bundle(); 14303 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14304 extras.putString(Intent.EXTRA_TITLE, label); 14305 mMoveCallbacks.notifyCreated(moveId, extras); 14306 14307 int installFlags; 14308 final boolean moveData; 14309 14310 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14311 installFlags = INSTALL_INTERNAL; 14312 moveData = !currentAsec; 14313 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14314 installFlags = INSTALL_EXTERNAL; 14315 moveData = false; 14316 } else { 14317 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14318 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14319 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14320 || !volume.isMountedWritable()) { 14321 unfreezePackage(packageName); 14322 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14323 "Move location not mounted private volume"); 14324 } 14325 14326 Preconditions.checkState(!currentAsec); 14327 14328 installFlags = INSTALL_INTERNAL; 14329 moveData = true; 14330 } 14331 14332 Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid); 14333 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14334 14335 if (moveData) { 14336 synchronized (mInstallLock) { 14337 // TODO: split this into separate copy and delete operations 14338 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14339 seinfo) != 0) { 14340 unfreezePackage(packageName); 14341 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14342 "Failed to move private data to " + volumeUuid); 14343 } 14344 } 14345 } 14346 14347 mMoveCallbacks.notifyStatusChanged(moveId, 50); 14348 14349 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14350 @Override 14351 public void onUserActionRequired(Intent intent) throws RemoteException { 14352 throw new IllegalStateException(); 14353 } 14354 14355 @Override 14356 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14357 Bundle extras) throws RemoteException { 14358 Slog.d(TAG, "Install result for move: " 14359 + PackageManager.installStatusToString(returnCode, msg)); 14360 14361 // Regardless of success or failure of the move operation, 14362 // always unfreeze the package 14363 unfreezePackage(packageName); 14364 14365 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14366 switch (status) { 14367 case PackageInstaller.STATUS_SUCCESS: 14368 mMoveCallbacks.notifyStatusChanged(moveId, 14369 PackageManager.MOVE_SUCCEEDED); 14370 break; 14371 case PackageInstaller.STATUS_FAILURE_STORAGE: 14372 mMoveCallbacks.notifyStatusChanged(moveId, 14373 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14374 break; 14375 default: 14376 mMoveCallbacks.notifyStatusChanged(moveId, 14377 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14378 break; 14379 } 14380 } 14381 }; 14382 14383 // Treat a move like reinstalling an existing app, which ensures that we 14384 // process everythign uniformly, like unpacking native libraries. 14385 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14386 14387 final Message msg = mHandler.obtainMessage(INIT_COPY); 14388 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14389 msg.obj = new InstallParams(origin, installObserver, installFlags, 14390 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14391 mHandler.sendMessage(msg); 14392 } 14393 14394 @Override 14395 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14397 14398 final int realMoveId = mNextMoveId.getAndIncrement(); 14399 final Bundle extras = new Bundle(); 14400 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14401 mMoveCallbacks.notifyCreated(realMoveId, extras); 14402 14403 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14404 @Override 14405 public void onCreated(int moveId, Bundle extras) { 14406 // Ignored 14407 } 14408 14409 @Override 14410 public void onStatusChanged(int moveId, int status, long estMillis) { 14411 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14412 } 14413 }; 14414 14415 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14416 storage.setPrimaryStorageUuid(volumeUuid, callback); 14417 return realMoveId; 14418 } 14419 14420 @Override 14421 public int getMoveStatus(int moveId) { 14422 mContext.enforceCallingOrSelfPermission( 14423 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14424 return mMoveCallbacks.mLastStatus.get(moveId); 14425 } 14426 14427 @Override 14428 public void registerMoveCallback(IPackageMoveObserver callback) { 14429 mContext.enforceCallingOrSelfPermission( 14430 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14431 mMoveCallbacks.register(callback); 14432 } 14433 14434 @Override 14435 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14436 mContext.enforceCallingOrSelfPermission( 14437 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14438 mMoveCallbacks.unregister(callback); 14439 } 14440 14441 @Override 14442 public boolean setInstallLocation(int loc) { 14443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14444 null); 14445 if (getInstallLocation() == loc) { 14446 return true; 14447 } 14448 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14449 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14450 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14451 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14452 return true; 14453 } 14454 return false; 14455 } 14456 14457 @Override 14458 public int getInstallLocation() { 14459 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14460 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14461 PackageHelper.APP_INSTALL_AUTO); 14462 } 14463 14464 /** Called by UserManagerService */ 14465 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14466 mDirtyUsers.remove(userHandle); 14467 mSettings.removeUserLPw(userHandle); 14468 mPendingBroadcasts.remove(userHandle); 14469 if (mInstaller != null) { 14470 // Technically, we shouldn't be doing this with the package lock 14471 // held. However, this is very rare, and there is already so much 14472 // other disk I/O going on, that we'll let it slide for now. 14473 final StorageManager storage = StorageManager.from(mContext); 14474 final List<VolumeInfo> vols = storage.getVolumes(); 14475 for (VolumeInfo vol : vols) { 14476 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14477 final String volumeUuid = vol.getFsUuid(); 14478 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14479 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14480 } 14481 } 14482 } 14483 mUserNeedsBadging.delete(userHandle); 14484 removeUnusedPackagesLILPw(userManager, userHandle); 14485 } 14486 14487 /** 14488 * We're removing userHandle and would like to remove any downloaded packages 14489 * that are no longer in use by any other user. 14490 * @param userHandle the user being removed 14491 */ 14492 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14493 final boolean DEBUG_CLEAN_APKS = false; 14494 int [] users = userManager.getUserIdsLPr(); 14495 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14496 while (psit.hasNext()) { 14497 PackageSetting ps = psit.next(); 14498 if (ps.pkg == null) { 14499 continue; 14500 } 14501 final String packageName = ps.pkg.packageName; 14502 // Skip over if system app 14503 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14504 continue; 14505 } 14506 if (DEBUG_CLEAN_APKS) { 14507 Slog.i(TAG, "Checking package " + packageName); 14508 } 14509 boolean keep = false; 14510 for (int i = 0; i < users.length; i++) { 14511 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14512 keep = true; 14513 if (DEBUG_CLEAN_APKS) { 14514 Slog.i(TAG, " Keeping package " + packageName + " for user " 14515 + users[i]); 14516 } 14517 break; 14518 } 14519 } 14520 if (!keep) { 14521 if (DEBUG_CLEAN_APKS) { 14522 Slog.i(TAG, " Removing package " + packageName); 14523 } 14524 mHandler.post(new Runnable() { 14525 public void run() { 14526 deletePackageX(packageName, userHandle, 0); 14527 } //end run 14528 }); 14529 } 14530 } 14531 } 14532 14533 /** Called by UserManagerService */ 14534 void createNewUserLILPw(int userHandle, File path) { 14535 if (mInstaller != null) { 14536 mInstaller.createUserConfig(userHandle); 14537 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14538 } 14539 } 14540 14541 void newUserCreatedLILPw(int userHandle) { 14542 // Adding a user requires updating runtime permissions for system apps. 14543 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14544 } 14545 14546 @Override 14547 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14548 mContext.enforceCallingOrSelfPermission( 14549 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14550 "Only package verification agents can read the verifier device identity"); 14551 14552 synchronized (mPackages) { 14553 return mSettings.getVerifierDeviceIdentityLPw(); 14554 } 14555 } 14556 14557 @Override 14558 public void setPermissionEnforced(String permission, boolean enforced) { 14559 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14560 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14561 synchronized (mPackages) { 14562 if (mSettings.mReadExternalStorageEnforced == null 14563 || mSettings.mReadExternalStorageEnforced != enforced) { 14564 mSettings.mReadExternalStorageEnforced = enforced; 14565 mSettings.writeLPr(); 14566 } 14567 } 14568 // kill any non-foreground processes so we restart them and 14569 // grant/revoke the GID. 14570 final IActivityManager am = ActivityManagerNative.getDefault(); 14571 if (am != null) { 14572 final long token = Binder.clearCallingIdentity(); 14573 try { 14574 am.killProcessesBelowForeground("setPermissionEnforcement"); 14575 } catch (RemoteException e) { 14576 } finally { 14577 Binder.restoreCallingIdentity(token); 14578 } 14579 } 14580 } else { 14581 throw new IllegalArgumentException("No selective enforcement for " + permission); 14582 } 14583 } 14584 14585 @Override 14586 @Deprecated 14587 public boolean isPermissionEnforced(String permission) { 14588 return true; 14589 } 14590 14591 @Override 14592 public boolean isStorageLow() { 14593 final long token = Binder.clearCallingIdentity(); 14594 try { 14595 final DeviceStorageMonitorInternal 14596 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14597 if (dsm != null) { 14598 return dsm.isMemoryLow(); 14599 } else { 14600 return false; 14601 } 14602 } finally { 14603 Binder.restoreCallingIdentity(token); 14604 } 14605 } 14606 14607 @Override 14608 public IPackageInstaller getPackageInstaller() { 14609 return mInstallerService; 14610 } 14611 14612 private boolean userNeedsBadging(int userId) { 14613 int index = mUserNeedsBadging.indexOfKey(userId); 14614 if (index < 0) { 14615 final UserInfo userInfo; 14616 final long token = Binder.clearCallingIdentity(); 14617 try { 14618 userInfo = sUserManager.getUserInfo(userId); 14619 } finally { 14620 Binder.restoreCallingIdentity(token); 14621 } 14622 final boolean b; 14623 if (userInfo != null && userInfo.isManagedProfile()) { 14624 b = true; 14625 } else { 14626 b = false; 14627 } 14628 mUserNeedsBadging.put(userId, b); 14629 return b; 14630 } 14631 return mUserNeedsBadging.valueAt(index); 14632 } 14633 14634 @Override 14635 public KeySet getKeySetByAlias(String packageName, String alias) { 14636 if (packageName == null || alias == null) { 14637 return null; 14638 } 14639 synchronized(mPackages) { 14640 final PackageParser.Package pkg = mPackages.get(packageName); 14641 if (pkg == null) { 14642 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14643 throw new IllegalArgumentException("Unknown package: " + packageName); 14644 } 14645 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14646 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14647 } 14648 } 14649 14650 @Override 14651 public KeySet getSigningKeySet(String packageName) { 14652 if (packageName == null) { 14653 return null; 14654 } 14655 synchronized(mPackages) { 14656 final PackageParser.Package pkg = mPackages.get(packageName); 14657 if (pkg == null) { 14658 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14659 throw new IllegalArgumentException("Unknown package: " + packageName); 14660 } 14661 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14662 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14663 throw new SecurityException("May not access signing KeySet of other apps."); 14664 } 14665 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14666 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14667 } 14668 } 14669 14670 @Override 14671 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14672 if (packageName == null || ks == null) { 14673 return false; 14674 } 14675 synchronized(mPackages) { 14676 final PackageParser.Package pkg = mPackages.get(packageName); 14677 if (pkg == null) { 14678 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14679 throw new IllegalArgumentException("Unknown package: " + packageName); 14680 } 14681 IBinder ksh = ks.getToken(); 14682 if (ksh instanceof KeySetHandle) { 14683 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14684 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14685 } 14686 return false; 14687 } 14688 } 14689 14690 @Override 14691 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14692 if (packageName == null || ks == null) { 14693 return false; 14694 } 14695 synchronized(mPackages) { 14696 final PackageParser.Package pkg = mPackages.get(packageName); 14697 if (pkg == null) { 14698 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14699 throw new IllegalArgumentException("Unknown package: " + packageName); 14700 } 14701 IBinder ksh = ks.getToken(); 14702 if (ksh instanceof KeySetHandle) { 14703 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14704 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14705 } 14706 return false; 14707 } 14708 } 14709 14710 public void getUsageStatsIfNoPackageUsageInfo() { 14711 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14712 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14713 if (usm == null) { 14714 throw new IllegalStateException("UsageStatsManager must be initialized"); 14715 } 14716 long now = System.currentTimeMillis(); 14717 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14718 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14719 String packageName = entry.getKey(); 14720 PackageParser.Package pkg = mPackages.get(packageName); 14721 if (pkg == null) { 14722 continue; 14723 } 14724 UsageStats usage = entry.getValue(); 14725 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14726 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14727 } 14728 } 14729 } 14730 14731 /** 14732 * Check and throw if the given before/after packages would be considered a 14733 * downgrade. 14734 */ 14735 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14736 throws PackageManagerException { 14737 if (after.versionCode < before.mVersionCode) { 14738 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14739 "Update version code " + after.versionCode + " is older than current " 14740 + before.mVersionCode); 14741 } else if (after.versionCode == before.mVersionCode) { 14742 if (after.baseRevisionCode < before.baseRevisionCode) { 14743 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14744 "Update base revision code " + after.baseRevisionCode 14745 + " is older than current " + before.baseRevisionCode); 14746 } 14747 14748 if (!ArrayUtils.isEmpty(after.splitNames)) { 14749 for (int i = 0; i < after.splitNames.length; i++) { 14750 final String splitName = after.splitNames[i]; 14751 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14752 if (j != -1) { 14753 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14754 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14755 "Update split " + splitName + " revision code " 14756 + after.splitRevisionCodes[i] + " is older than current " 14757 + before.splitRevisionCodes[j]); 14758 } 14759 } 14760 } 14761 } 14762 } 14763 } 14764 14765 private static class MoveCallbacks extends Handler { 14766 private static final int MSG_CREATED = 1; 14767 private static final int MSG_STATUS_CHANGED = 2; 14768 14769 private final RemoteCallbackList<IPackageMoveObserver> 14770 mCallbacks = new RemoteCallbackList<>(); 14771 14772 private final SparseIntArray mLastStatus = new SparseIntArray(); 14773 14774 public MoveCallbacks(Looper looper) { 14775 super(looper); 14776 } 14777 14778 public void register(IPackageMoveObserver callback) { 14779 mCallbacks.register(callback); 14780 } 14781 14782 public void unregister(IPackageMoveObserver callback) { 14783 mCallbacks.unregister(callback); 14784 } 14785 14786 @Override 14787 public void handleMessage(Message msg) { 14788 final SomeArgs args = (SomeArgs) msg.obj; 14789 final int n = mCallbacks.beginBroadcast(); 14790 for (int i = 0; i < n; i++) { 14791 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14792 try { 14793 invokeCallback(callback, msg.what, args); 14794 } catch (RemoteException ignored) { 14795 } 14796 } 14797 mCallbacks.finishBroadcast(); 14798 args.recycle(); 14799 } 14800 14801 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14802 throws RemoteException { 14803 switch (what) { 14804 case MSG_CREATED: { 14805 callback.onCreated(args.argi1, (Bundle) args.arg2); 14806 break; 14807 } 14808 case MSG_STATUS_CHANGED: { 14809 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14810 break; 14811 } 14812 } 14813 } 14814 14815 private void notifyCreated(int moveId, Bundle extras) { 14816 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 14817 14818 final SomeArgs args = SomeArgs.obtain(); 14819 args.argi1 = moveId; 14820 args.arg2 = extras; 14821 obtainMessage(MSG_CREATED, args).sendToTarget(); 14822 } 14823 14824 private void notifyStatusChanged(int moveId, int status) { 14825 notifyStatusChanged(moveId, status, -1); 14826 } 14827 14828 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14829 Slog.v(TAG, "Move " + moveId + " status " + status); 14830 14831 final SomeArgs args = SomeArgs.obtain(); 14832 args.argi1 = moveId; 14833 args.argi2 = status; 14834 args.arg3 = estMillis; 14835 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14836 14837 synchronized (mLastStatus) { 14838 mLastStatus.put(moveId, status); 14839 } 14840 } 14841 } 14842} 14843