PackageManagerService.java revision 94056d1cb8183bde3e942336735b289b9654deb1
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.MOVE_EXTERNAL_MEDIA; 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.PackageManager.MOVE_INTERNAL; 58import static android.content.pm.PackageParser.isApkFile; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 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.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.text.format.DateUtils; 165import android.util.ArrayMap; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.util.Xml; 178import android.view.Display; 179 180import dalvik.system.DexFile; 181import dalvik.system.VMRuntime; 182 183import libcore.io.IoUtils; 184import libcore.util.EmptyArray; 185 186import com.android.internal.R; 187import com.android.internal.app.IMediaContainerService; 188import com.android.internal.app.ResolverActivity; 189import com.android.internal.content.NativeLibraryHelper; 190import com.android.internal.content.PackageHelper; 191import com.android.internal.os.IParcelFileDescriptorFactory; 192import com.android.internal.util.ArrayUtils; 193import com.android.internal.util.FastPrintWriter; 194import com.android.internal.util.FastXmlSerializer; 195import com.android.internal.util.IndentingPrintWriter; 196import com.android.server.EventLogTags; 197import com.android.server.IntentResolver; 198import com.android.server.LocalServices; 199import com.android.server.ServiceThread; 200import com.android.server.SystemConfig; 201import com.android.server.Watchdog; 202import com.android.server.pm.Settings.DatabaseVersion; 203import com.android.server.storage.DeviceStorageMonitorInternal; 204 205import org.xmlpull.v1.XmlPullParser; 206import org.xmlpull.v1.XmlSerializer; 207 208import java.io.BufferedInputStream; 209import java.io.BufferedOutputStream; 210import java.io.BufferedReader; 211import java.io.ByteArrayInputStream; 212import java.io.ByteArrayOutputStream; 213import java.io.File; 214import java.io.FileDescriptor; 215import java.io.FileNotFoundException; 216import java.io.FileOutputStream; 217import java.io.FileReader; 218import java.io.FilenameFilter; 219import java.io.IOException; 220import java.io.InputStream; 221import java.io.PrintWriter; 222import java.nio.charset.StandardCharsets; 223import java.security.NoSuchAlgorithmException; 224import java.security.PublicKey; 225import java.security.cert.CertificateEncodingException; 226import java.security.cert.CertificateException; 227import java.text.SimpleDateFormat; 228import java.util.ArrayList; 229import java.util.Arrays; 230import java.util.Collection; 231import java.util.Collections; 232import java.util.Comparator; 233import java.util.Date; 234import java.util.Iterator; 235import java.util.List; 236import java.util.Map; 237import java.util.Objects; 238import java.util.Set; 239import java.util.concurrent.atomic.AtomicBoolean; 240import java.util.concurrent.atomic.AtomicLong; 241 242/** 243 * Keep track of all those .apks everywhere. 244 * 245 * This is very central to the platform's security; please run the unit 246 * tests whenever making modifications here: 247 * 248mmm frameworks/base/tests/AndroidTests 249adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 250adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 251 * 252 * {@hide} 253 */ 254public class PackageManagerService extends IPackageManager.Stub { 255 static final String TAG = "PackageManager"; 256 static final boolean DEBUG_SETTINGS = false; 257 static final boolean DEBUG_PREFERRED = false; 258 static final boolean DEBUG_UPGRADE = false; 259 private static final boolean DEBUG_BACKUP = true; 260 private static final boolean DEBUG_INSTALL = false; 261 private static final boolean DEBUG_REMOVE = false; 262 private static final boolean DEBUG_BROADCASTS = false; 263 private static final boolean DEBUG_SHOW_INFO = false; 264 private static final boolean DEBUG_PACKAGE_INFO = false; 265 private static final boolean DEBUG_INTENT_MATCHING = false; 266 private static final boolean DEBUG_PACKAGE_SCANNING = false; 267 private static final boolean DEBUG_VERIFY = false; 268 private static final boolean DEBUG_DEXOPT = false; 269 private static final boolean DEBUG_ABI_SELECTION = false; 270 271 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 272 273 private static final int RADIO_UID = Process.PHONE_UID; 274 private static final int LOG_UID = Process.LOG_UID; 275 private static final int NFC_UID = Process.NFC_UID; 276 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 277 private static final int SHELL_UID = Process.SHELL_UID; 278 279 // Cap the size of permission trees that 3rd party apps can define 280 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 281 282 // Suffix used during package installation when copying/moving 283 // package apks to install directory. 284 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 285 286 static final int SCAN_NO_DEX = 1<<1; 287 static final int SCAN_FORCE_DEX = 1<<2; 288 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 289 static final int SCAN_NEW_INSTALL = 1<<4; 290 static final int SCAN_NO_PATHS = 1<<5; 291 static final int SCAN_UPDATE_TIME = 1<<6; 292 static final int SCAN_DEFER_DEX = 1<<7; 293 static final int SCAN_BOOTING = 1<<8; 294 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 295 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 296 static final int SCAN_REPLACING = 1<<11; 297 static final int SCAN_REQUIRE_KNOWN = 1<<12; 298 299 static final int REMOVE_CHATTY = 1<<16; 300 301 /** 302 * Timeout (in milliseconds) after which the watchdog should declare that 303 * our handler thread is wedged. The usual default for such things is one 304 * minute but we sometimes do very lengthy I/O operations on this thread, 305 * such as installing multi-gigabyte applications, so ours needs to be longer. 306 */ 307 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 308 309 /** 310 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 311 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 312 * settings entry if available, otherwise we use the hardcoded default. If it's been 313 * more than this long since the last fstrim, we force one during the boot sequence. 314 * 315 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 316 * one gets run at the next available charging+idle time. This final mandatory 317 * no-fstrim check kicks in only of the other scheduling criteria is never met. 318 */ 319 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 320 321 /** 322 * Whether verification is enabled by default. 323 */ 324 private static final boolean DEFAULT_VERIFY_ENABLE = true; 325 326 /** 327 * The default maximum time to wait for the verification agent to return in 328 * milliseconds. 329 */ 330 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 331 332 /** 333 * The default response for package verification timeout. 334 * 335 * This can be either PackageManager.VERIFICATION_ALLOW or 336 * PackageManager.VERIFICATION_REJECT. 337 */ 338 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 339 340 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 341 342 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 343 DEFAULT_CONTAINER_PACKAGE, 344 "com.android.defcontainer.DefaultContainerService"); 345 346 private static final String KILL_APP_REASON_GIDS_CHANGED = 347 "permission grant or revoke changed gids"; 348 349 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 350 "permissions revoked"; 351 352 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 353 354 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 355 356 /** Permission grant: not grant the permission. */ 357 private static final int GRANT_DENIED = 1; 358 359 /** Permission grant: grant the permission as an install permission. */ 360 private static final int GRANT_INSTALL = 2; 361 362 /** Permission grant: grant the permission as a runtime one. */ 363 private static final int GRANT_RUNTIME = 3; 364 365 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 366 private static final int GRANT_UPGRADE = 4; 367 368 final ServiceThread mHandlerThread; 369 370 final PackageHandler mHandler; 371 372 /** 373 * Messages for {@link #mHandler} that need to wait for system ready before 374 * being dispatched. 375 */ 376 private ArrayList<Message> mPostSystemReadyMessages; 377 378 final int mSdkVersion = Build.VERSION.SDK_INT; 379 380 final Context mContext; 381 final boolean mFactoryTest; 382 final boolean mOnlyCore; 383 final boolean mLazyDexOpt; 384 final long mDexOptLRUThresholdInMills; 385 final DisplayMetrics mMetrics; 386 final int mDefParseFlags; 387 final String[] mSeparateProcesses; 388 final boolean mIsUpgrade; 389 390 // This is where all application persistent data goes. 391 final File mAppDataDir; 392 393 // This is where all application persistent data goes for secondary users. 394 final File mUserAppDataDir; 395 396 /** The location for ASEC container files on internal storage. */ 397 final String mAsecInternalPath; 398 399 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 400 // LOCK HELD. Can be called with mInstallLock held. 401 final Installer mInstaller; 402 403 /** Directory where installed third-party apps stored */ 404 final File mAppInstallDir; 405 406 /** 407 * Directory to which applications installed internally have their 408 * 32 bit native libraries copied. 409 */ 410 private File mAppLib32InstallDir; 411 412 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 413 // apps. 414 final File mDrmAppPrivateInstallDir; 415 416 // ---------------------------------------------------------------- 417 418 // Lock for state used when installing and doing other long running 419 // operations. Methods that must be called with this lock held have 420 // the suffix "LI". 421 final Object mInstallLock = new Object(); 422 423 // ---------------------------------------------------------------- 424 425 // Keys are String (package name), values are Package. This also serves 426 // as the lock for the global state. Methods that must be called with 427 // this lock held have the prefix "LP". 428 final ArrayMap<String, PackageParser.Package> mPackages = 429 new ArrayMap<String, PackageParser.Package>(); 430 431 // Tracks available target package names -> overlay package paths. 432 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 433 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 434 435 final Settings mSettings; 436 boolean mRestoredSettings; 437 438 // System configuration read by SystemConfig. 439 final int[] mGlobalGids; 440 final SparseArray<ArraySet<String>> mSystemPermissions; 441 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 442 443 // If mac_permissions.xml was found for seinfo labeling. 444 boolean mFoundPolicyFile; 445 446 // If a recursive restorecon of /data/data/<pkg> is needed. 447 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 448 449 public static final class SharedLibraryEntry { 450 public final String path; 451 public final String apk; 452 453 SharedLibraryEntry(String _path, String _apk) { 454 path = _path; 455 apk = _apk; 456 } 457 } 458 459 // Currently known shared libraries. 460 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 461 new ArrayMap<String, SharedLibraryEntry>(); 462 463 // All available activities, for your resolving pleasure. 464 final ActivityIntentResolver mActivities = 465 new ActivityIntentResolver(); 466 467 // All available receivers, for your resolving pleasure. 468 final ActivityIntentResolver mReceivers = 469 new ActivityIntentResolver(); 470 471 // All available services, for your resolving pleasure. 472 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 473 474 // All available providers, for your resolving pleasure. 475 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 476 477 // Mapping from provider base names (first directory in content URI codePath) 478 // to the provider information. 479 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 480 new ArrayMap<String, PackageParser.Provider>(); 481 482 // Mapping from instrumentation class names to info about them. 483 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 484 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 485 486 // Mapping from permission names to info about them. 487 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 488 new ArrayMap<String, PackageParser.PermissionGroup>(); 489 490 // Packages whose data we have transfered into another package, thus 491 // should no longer exist. 492 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 493 494 // Broadcast actions that are only available to the system. 495 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 496 497 /** List of packages waiting for verification. */ 498 final SparseArray<PackageVerificationState> mPendingVerification 499 = new SparseArray<PackageVerificationState>(); 500 501 /** Set of packages associated with each app op permission. */ 502 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 503 504 final PackageInstallerService mInstallerService; 505 506 private final PackageDexOptimizer mPackageDexOptimizer; 507 // Cache of users who need badging. 508 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 509 510 /** Token for keys in mPendingVerification. */ 511 private int mPendingVerificationToken = 0; 512 513 volatile boolean mSystemReady; 514 volatile boolean mSafeMode; 515 volatile boolean mHasSystemUidErrors; 516 517 ApplicationInfo mAndroidApplication; 518 final ActivityInfo mResolveActivity = new ActivityInfo(); 519 final ResolveInfo mResolveInfo = new ResolveInfo(); 520 ComponentName mResolveComponentName; 521 PackageParser.Package mPlatformPackage; 522 ComponentName mCustomResolverComponentName; 523 524 boolean mResolverReplaced = false; 525 526 private final ComponentName mIntentFilterVerifierComponent; 527 private int mIntentFilterVerificationToken = 0; 528 529 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 530 = new SparseArray<IntentFilterVerificationState>(); 531 532 private interface IntentFilterVerifier<T extends IntentFilter> { 533 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 534 T filter, String packageName); 535 void startVerifications(int userId); 536 void receiveVerificationResponse(int verificationId); 537 } 538 539 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 540 private Context mContext; 541 private ComponentName mIntentFilterVerifierComponent; 542 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 543 544 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 545 mContext = context; 546 mIntentFilterVerifierComponent = verifierComponent; 547 } 548 549 private String getDefaultScheme() { 550 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 551 return IntentFilter.SCHEME_HTTP; 552 } 553 554 @Override 555 public void startVerifications(int userId) { 556 // Launch verifications requests 557 int count = mCurrentIntentFilterVerifications.size(); 558 for (int n=0; n<count; n++) { 559 int verificationId = mCurrentIntentFilterVerifications.get(n); 560 final IntentFilterVerificationState ivs = 561 mIntentFilterVerificationStates.get(verificationId); 562 563 String packageName = ivs.getPackageName(); 564 565 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 566 final int filterCount = filters.size(); 567 ArraySet<String> domainsSet = new ArraySet<>(); 568 for (int m=0; m<filterCount; m++) { 569 PackageParser.ActivityIntentInfo filter = filters.get(m); 570 domainsSet.addAll(filter.getHostsList()); 571 } 572 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 573 synchronized (mPackages) { 574 if (mSettings.createIntentFilterVerificationIfNeededLPw( 575 packageName, domainsList) != null) { 576 scheduleWriteSettingsLocked(); 577 } 578 } 579 sendVerificationRequest(userId, verificationId, ivs); 580 } 581 mCurrentIntentFilterVerifications.clear(); 582 } 583 584 private void sendVerificationRequest(int userId, int verificationId, 585 IntentFilterVerificationState ivs) { 586 587 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 588 verificationIntent.putExtra( 589 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 590 verificationId); 591 verificationIntent.putExtra( 592 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 593 getDefaultScheme()); 594 verificationIntent.putExtra( 595 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 596 ivs.getHostsString()); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 599 ivs.getPackageName()); 600 verificationIntent.setComponent(mIntentFilterVerifierComponent); 601 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 602 603 UserHandle user = new UserHandle(userId); 604 mContext.sendBroadcastAsUser(verificationIntent, user); 605 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 606 } 607 608 public void receiveVerificationResponse(int verificationId) { 609 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 610 611 final boolean verified = ivs.isVerified(); 612 613 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 614 final int count = filters.size(); 615 for (int n=0; n<count; n++) { 616 PackageParser.ActivityIntentInfo filter = filters.get(n); 617 filter.setVerified(verified); 618 619 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 620 + verified + " and hosts:" + ivs.getHostsString()); 621 } 622 623 mIntentFilterVerificationStates.remove(verificationId); 624 625 final String packageName = ivs.getPackageName(); 626 IntentFilterVerificationInfo ivi = null; 627 628 synchronized (mPackages) { 629 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 630 } 631 if (ivi == null) { 632 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 633 + verificationId + " packageName:" + packageName); 634 return; 635 } 636 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 637 + verificationId); 638 639 synchronized (mPackages) { 640 if (verified) { 641 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 642 } else { 643 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 644 } 645 scheduleWriteSettingsLocked(); 646 647 final int userId = ivs.getUserId(); 648 if (userId != UserHandle.USER_ALL) { 649 final int userStatus = 650 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 651 652 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 653 boolean needUpdate = false; 654 655 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 656 // already been set by the User thru the Disambiguation dialog 657 switch (userStatus) { 658 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 659 if (verified) { 660 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 661 } else { 662 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 663 } 664 needUpdate = true; 665 break; 666 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 needUpdate = true; 671 } 672 break; 673 674 default: 675 // Nothing to do 676 } 677 678 if (needUpdate) { 679 mSettings.updateIntentFilterVerificationStatusLPw( 680 packageName, updatedStatus, userId); 681 scheduleWritePackageRestrictionsLocked(userId); 682 } 683 } 684 } 685 } 686 687 @Override 688 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 689 ActivityIntentInfo filter, String packageName) { 690 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 691 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 692 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 693 return false; 694 } 695 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 696 if (ivs == null) { 697 ivs = createDomainVerificationState(verifierId, userId, verificationId, 698 packageName); 699 } 700 if (!hasValidDomains(filter)) { 701 return false; 702 } 703 ivs.addFilter(filter); 704 return true; 705 } 706 707 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 708 int userId, int verificationId, String packageName) { 709 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 710 verifierId, userId, packageName); 711 ivs.setPendingState(); 712 synchronized (mPackages) { 713 mIntentFilterVerificationStates.append(verificationId, ivs); 714 mCurrentIntentFilterVerifications.add(verificationId); 715 } 716 return ivs; 717 } 718 } 719 720 private static boolean hasValidDomains(ActivityIntentInfo filter) { 721 return hasValidDomains(filter, true); 722 } 723 724 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 725 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 726 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 727 if (!hasHTTPorHTTPS) { 728 if (logging) { 729 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 730 } 731 return false; 732 } 733 return true; 734 } 735 736 private IntentFilterVerifier mIntentFilterVerifier; 737 738 // Set of pending broadcasts for aggregating enable/disable of components. 739 static class PendingPackageBroadcasts { 740 // for each user id, a map of <package name -> components within that package> 741 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 742 743 public PendingPackageBroadcasts() { 744 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 745 } 746 747 public ArrayList<String> get(int userId, String packageName) { 748 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 749 return packages.get(packageName); 750 } 751 752 public void put(int userId, String packageName, ArrayList<String> components) { 753 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 754 packages.put(packageName, components); 755 } 756 757 public void remove(int userId, String packageName) { 758 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 759 if (packages != null) { 760 packages.remove(packageName); 761 } 762 } 763 764 public void remove(int userId) { 765 mUidMap.remove(userId); 766 } 767 768 public int userIdCount() { 769 return mUidMap.size(); 770 } 771 772 public int userIdAt(int n) { 773 return mUidMap.keyAt(n); 774 } 775 776 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 777 return mUidMap.get(userId); 778 } 779 780 public int size() { 781 // total number of pending broadcast entries across all userIds 782 int num = 0; 783 for (int i = 0; i< mUidMap.size(); i++) { 784 num += mUidMap.valueAt(i).size(); 785 } 786 return num; 787 } 788 789 public void clear() { 790 mUidMap.clear(); 791 } 792 793 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 794 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 795 if (map == null) { 796 map = new ArrayMap<String, ArrayList<String>>(); 797 mUidMap.put(userId, map); 798 } 799 return map; 800 } 801 } 802 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 803 804 // Service Connection to remote media container service to copy 805 // package uri's from external media onto secure containers 806 // or internal storage. 807 private IMediaContainerService mContainerService = null; 808 809 static final int SEND_PENDING_BROADCAST = 1; 810 static final int MCS_BOUND = 3; 811 static final int END_COPY = 4; 812 static final int INIT_COPY = 5; 813 static final int MCS_UNBIND = 6; 814 static final int START_CLEANING_PACKAGE = 7; 815 static final int FIND_INSTALL_LOC = 8; 816 static final int POST_INSTALL = 9; 817 static final int MCS_RECONNECT = 10; 818 static final int MCS_GIVE_UP = 11; 819 static final int UPDATED_MEDIA_STATUS = 12; 820 static final int WRITE_SETTINGS = 13; 821 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 822 static final int PACKAGE_VERIFIED = 15; 823 static final int CHECK_PENDING_VERIFICATION = 16; 824 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 825 static final int INTENT_FILTER_VERIFIED = 18; 826 827 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 828 829 // Delay time in millisecs 830 static final int BROADCAST_DELAY = 10 * 1000; 831 832 static UserManagerService sUserManager; 833 834 // Stores a list of users whose package restrictions file needs to be updated 835 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 836 837 final private DefaultContainerConnection mDefContainerConn = 838 new DefaultContainerConnection(); 839 class DefaultContainerConnection implements ServiceConnection { 840 public void onServiceConnected(ComponentName name, IBinder service) { 841 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 842 IMediaContainerService imcs = 843 IMediaContainerService.Stub.asInterface(service); 844 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 845 } 846 847 public void onServiceDisconnected(ComponentName name) { 848 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 849 } 850 }; 851 852 // Recordkeeping of restore-after-install operations that are currently in flight 853 // between the Package Manager and the Backup Manager 854 class PostInstallData { 855 public InstallArgs args; 856 public PackageInstalledInfo res; 857 858 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 859 args = _a; 860 res = _r; 861 } 862 }; 863 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 864 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 865 866 // backup/restore of preferred activity state 867 private static final String TAG_PREFERRED_BACKUP = "pa"; 868 869 private final String mRequiredVerifierPackage; 870 871 private final PackageUsage mPackageUsage = new PackageUsage(); 872 873 private class PackageUsage { 874 private static final int WRITE_INTERVAL 875 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 876 877 private final Object mFileLock = new Object(); 878 private final AtomicLong mLastWritten = new AtomicLong(0); 879 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 880 881 private boolean mIsHistoricalPackageUsageAvailable = true; 882 883 boolean isHistoricalPackageUsageAvailable() { 884 return mIsHistoricalPackageUsageAvailable; 885 } 886 887 void write(boolean force) { 888 if (force) { 889 writeInternal(); 890 return; 891 } 892 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 893 && !DEBUG_DEXOPT) { 894 return; 895 } 896 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 897 new Thread("PackageUsage_DiskWriter") { 898 @Override 899 public void run() { 900 try { 901 writeInternal(); 902 } finally { 903 mBackgroundWriteRunning.set(false); 904 } 905 } 906 }.start(); 907 } 908 } 909 910 private void writeInternal() { 911 synchronized (mPackages) { 912 synchronized (mFileLock) { 913 AtomicFile file = getFile(); 914 FileOutputStream f = null; 915 try { 916 f = file.startWrite(); 917 BufferedOutputStream out = new BufferedOutputStream(f); 918 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 919 StringBuilder sb = new StringBuilder(); 920 for (PackageParser.Package pkg : mPackages.values()) { 921 if (pkg.mLastPackageUsageTimeInMills == 0) { 922 continue; 923 } 924 sb.setLength(0); 925 sb.append(pkg.packageName); 926 sb.append(' '); 927 sb.append((long)pkg.mLastPackageUsageTimeInMills); 928 sb.append('\n'); 929 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 930 } 931 out.flush(); 932 file.finishWrite(f); 933 } catch (IOException e) { 934 if (f != null) { 935 file.failWrite(f); 936 } 937 Log.e(TAG, "Failed to write package usage times", e); 938 } 939 } 940 } 941 mLastWritten.set(SystemClock.elapsedRealtime()); 942 } 943 944 void readLP() { 945 synchronized (mFileLock) { 946 AtomicFile file = getFile(); 947 BufferedInputStream in = null; 948 try { 949 in = new BufferedInputStream(file.openRead()); 950 StringBuffer sb = new StringBuffer(); 951 while (true) { 952 String packageName = readToken(in, sb, ' '); 953 if (packageName == null) { 954 break; 955 } 956 String timeInMillisString = readToken(in, sb, '\n'); 957 if (timeInMillisString == null) { 958 throw new IOException("Failed to find last usage time for package " 959 + packageName); 960 } 961 PackageParser.Package pkg = mPackages.get(packageName); 962 if (pkg == null) { 963 continue; 964 } 965 long timeInMillis; 966 try { 967 timeInMillis = Long.parseLong(timeInMillisString.toString()); 968 } catch (NumberFormatException e) { 969 throw new IOException("Failed to parse " + timeInMillisString 970 + " as a long.", e); 971 } 972 pkg.mLastPackageUsageTimeInMills = timeInMillis; 973 } 974 } catch (FileNotFoundException expected) { 975 mIsHistoricalPackageUsageAvailable = false; 976 } catch (IOException e) { 977 Log.w(TAG, "Failed to read package usage times", e); 978 } finally { 979 IoUtils.closeQuietly(in); 980 } 981 } 982 mLastWritten.set(SystemClock.elapsedRealtime()); 983 } 984 985 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 986 throws IOException { 987 sb.setLength(0); 988 while (true) { 989 int ch = in.read(); 990 if (ch == -1) { 991 if (sb.length() == 0) { 992 return null; 993 } 994 throw new IOException("Unexpected EOF"); 995 } 996 if (ch == endOfToken) { 997 return sb.toString(); 998 } 999 sb.append((char)ch); 1000 } 1001 } 1002 1003 private AtomicFile getFile() { 1004 File dataDir = Environment.getDataDirectory(); 1005 File systemDir = new File(dataDir, "system"); 1006 File fname = new File(systemDir, "package-usage.list"); 1007 return new AtomicFile(fname); 1008 } 1009 } 1010 1011 class PackageHandler extends Handler { 1012 private boolean mBound = false; 1013 final ArrayList<HandlerParams> mPendingInstalls = 1014 new ArrayList<HandlerParams>(); 1015 1016 private boolean connectToService() { 1017 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1018 " DefaultContainerService"); 1019 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1020 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1021 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1022 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1023 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1024 mBound = true; 1025 return true; 1026 } 1027 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1028 return false; 1029 } 1030 1031 private void disconnectService() { 1032 mContainerService = null; 1033 mBound = false; 1034 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1035 mContext.unbindService(mDefContainerConn); 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 } 1038 1039 PackageHandler(Looper looper) { 1040 super(looper); 1041 } 1042 1043 public void handleMessage(Message msg) { 1044 try { 1045 doHandleMessage(msg); 1046 } finally { 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1048 } 1049 } 1050 1051 void doHandleMessage(Message msg) { 1052 switch (msg.what) { 1053 case INIT_COPY: { 1054 HandlerParams params = (HandlerParams) msg.obj; 1055 int idx = mPendingInstalls.size(); 1056 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1057 // If a bind was already initiated we dont really 1058 // need to do anything. The pending install 1059 // will be processed later on. 1060 if (!mBound) { 1061 // If this is the only one pending we might 1062 // have to bind to the service again. 1063 if (!connectToService()) { 1064 Slog.e(TAG, "Failed to bind to media container service"); 1065 params.serviceError(); 1066 return; 1067 } else { 1068 // Once we bind to the service, the first 1069 // pending request will be processed. 1070 mPendingInstalls.add(idx, params); 1071 } 1072 } else { 1073 mPendingInstalls.add(idx, params); 1074 // Already bound to the service. Just make 1075 // sure we trigger off processing the first request. 1076 if (idx == 0) { 1077 mHandler.sendEmptyMessage(MCS_BOUND); 1078 } 1079 } 1080 break; 1081 } 1082 case MCS_BOUND: { 1083 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1084 if (msg.obj != null) { 1085 mContainerService = (IMediaContainerService) msg.obj; 1086 } 1087 if (mContainerService == null) { 1088 // Something seriously wrong. Bail out 1089 Slog.e(TAG, "Cannot bind to media container service"); 1090 for (HandlerParams params : mPendingInstalls) { 1091 // Indicate service bind error 1092 params.serviceError(); 1093 } 1094 mPendingInstalls.clear(); 1095 } else if (mPendingInstalls.size() > 0) { 1096 HandlerParams params = mPendingInstalls.get(0); 1097 if (params != null) { 1098 if (params.startCopy()) { 1099 // We are done... look for more work or to 1100 // go idle. 1101 if (DEBUG_SD_INSTALL) Log.i(TAG, 1102 "Checking for more work or unbind..."); 1103 // Delete pending install 1104 if (mPendingInstalls.size() > 0) { 1105 mPendingInstalls.remove(0); 1106 } 1107 if (mPendingInstalls.size() == 0) { 1108 if (mBound) { 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, 1110 "Posting delayed MCS_UNBIND"); 1111 removeMessages(MCS_UNBIND); 1112 Message ubmsg = obtainMessage(MCS_UNBIND); 1113 // Unbind after a little delay, to avoid 1114 // continual thrashing. 1115 sendMessageDelayed(ubmsg, 10000); 1116 } 1117 } else { 1118 // There are more pending requests in queue. 1119 // Just post MCS_BOUND message to trigger processing 1120 // of next pending install. 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Posting MCS_BOUND for next work"); 1123 mHandler.sendEmptyMessage(MCS_BOUND); 1124 } 1125 } 1126 } 1127 } else { 1128 // Should never happen ideally. 1129 Slog.w(TAG, "Empty queue"); 1130 } 1131 break; 1132 } 1133 case MCS_RECONNECT: { 1134 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1135 if (mPendingInstalls.size() > 0) { 1136 if (mBound) { 1137 disconnectService(); 1138 } 1139 if (!connectToService()) { 1140 Slog.e(TAG, "Failed to bind to media container service"); 1141 for (HandlerParams params : mPendingInstalls) { 1142 // Indicate service bind error 1143 params.serviceError(); 1144 } 1145 mPendingInstalls.clear(); 1146 } 1147 } 1148 break; 1149 } 1150 case MCS_UNBIND: { 1151 // If there is no actual work left, then time to unbind. 1152 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1153 1154 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1155 if (mBound) { 1156 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1157 1158 disconnectService(); 1159 } 1160 } else if (mPendingInstalls.size() > 0) { 1161 // There are more pending requests in queue. 1162 // Just post MCS_BOUND message to trigger processing 1163 // of next pending install. 1164 mHandler.sendEmptyMessage(MCS_BOUND); 1165 } 1166 1167 break; 1168 } 1169 case MCS_GIVE_UP: { 1170 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1171 mPendingInstalls.remove(0); 1172 break; 1173 } 1174 case SEND_PENDING_BROADCAST: { 1175 String packages[]; 1176 ArrayList<String> components[]; 1177 int size = 0; 1178 int uids[]; 1179 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1180 synchronized (mPackages) { 1181 if (mPendingBroadcasts == null) { 1182 return; 1183 } 1184 size = mPendingBroadcasts.size(); 1185 if (size <= 0) { 1186 // Nothing to be done. Just return 1187 return; 1188 } 1189 packages = new String[size]; 1190 components = new ArrayList[size]; 1191 uids = new int[size]; 1192 int i = 0; // filling out the above arrays 1193 1194 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1195 int packageUserId = mPendingBroadcasts.userIdAt(n); 1196 Iterator<Map.Entry<String, ArrayList<String>>> it 1197 = mPendingBroadcasts.packagesForUserId(packageUserId) 1198 .entrySet().iterator(); 1199 while (it.hasNext() && i < size) { 1200 Map.Entry<String, ArrayList<String>> ent = it.next(); 1201 packages[i] = ent.getKey(); 1202 components[i] = ent.getValue(); 1203 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1204 uids[i] = (ps != null) 1205 ? UserHandle.getUid(packageUserId, ps.appId) 1206 : -1; 1207 i++; 1208 } 1209 } 1210 size = i; 1211 mPendingBroadcasts.clear(); 1212 } 1213 // Send broadcasts 1214 for (int i = 0; i < size; i++) { 1215 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1216 } 1217 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1218 break; 1219 } 1220 case START_CLEANING_PACKAGE: { 1221 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1222 final String packageName = (String)msg.obj; 1223 final int userId = msg.arg1; 1224 final boolean andCode = msg.arg2 != 0; 1225 synchronized (mPackages) { 1226 if (userId == UserHandle.USER_ALL) { 1227 int[] users = sUserManager.getUserIds(); 1228 for (int user : users) { 1229 mSettings.addPackageToCleanLPw( 1230 new PackageCleanItem(user, packageName, andCode)); 1231 } 1232 } else { 1233 mSettings.addPackageToCleanLPw( 1234 new PackageCleanItem(userId, packageName, andCode)); 1235 } 1236 } 1237 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1238 startCleaningPackages(); 1239 } break; 1240 case POST_INSTALL: { 1241 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1242 PostInstallData data = mRunningInstalls.get(msg.arg1); 1243 mRunningInstalls.delete(msg.arg1); 1244 boolean deleteOld = false; 1245 1246 if (data != null) { 1247 InstallArgs args = data.args; 1248 PackageInstalledInfo res = data.res; 1249 1250 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1251 res.removedInfo.sendBroadcast(false, true, false); 1252 Bundle extras = new Bundle(1); 1253 extras.putInt(Intent.EXTRA_UID, res.uid); 1254 1255 // Now that we successfully installed the package, grant runtime 1256 // permissions if requested before broadcasting the install. 1257 if ((args.installFlags 1258 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1259 grantRequestedRuntimePermissions(res.pkg, 1260 args.user.getIdentifier()); 1261 } 1262 1263 // Determine the set of users who are adding this 1264 // package for the first time vs. those who are seeing 1265 // an update. 1266 int[] firstUsers; 1267 int[] updateUsers = new int[0]; 1268 if (res.origUsers == null || res.origUsers.length == 0) { 1269 firstUsers = res.newUsers; 1270 } else { 1271 firstUsers = new int[0]; 1272 for (int i=0; i<res.newUsers.length; i++) { 1273 int user = res.newUsers[i]; 1274 boolean isNew = true; 1275 for (int j=0; j<res.origUsers.length; j++) { 1276 if (res.origUsers[j] == user) { 1277 isNew = false; 1278 break; 1279 } 1280 } 1281 if (isNew) { 1282 int[] newFirst = new int[firstUsers.length+1]; 1283 System.arraycopy(firstUsers, 0, newFirst, 0, 1284 firstUsers.length); 1285 newFirst[firstUsers.length] = user; 1286 firstUsers = newFirst; 1287 } else { 1288 int[] newUpdate = new int[updateUsers.length+1]; 1289 System.arraycopy(updateUsers, 0, newUpdate, 0, 1290 updateUsers.length); 1291 newUpdate[updateUsers.length] = user; 1292 updateUsers = newUpdate; 1293 } 1294 } 1295 } 1296 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1297 res.pkg.applicationInfo.packageName, 1298 extras, null, null, firstUsers); 1299 final boolean update = res.removedInfo.removedPackage != null; 1300 if (update) { 1301 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1302 } 1303 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1304 res.pkg.applicationInfo.packageName, 1305 extras, null, null, updateUsers); 1306 if (update) { 1307 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1308 res.pkg.applicationInfo.packageName, 1309 extras, null, null, updateUsers); 1310 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1311 null, null, 1312 res.pkg.applicationInfo.packageName, null, updateUsers); 1313 1314 // treat asec-hosted packages like removable media on upgrade 1315 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1316 if (DEBUG_INSTALL) { 1317 Slog.i(TAG, "upgrading pkg " + res.pkg 1318 + " is ASEC-hosted -> AVAILABLE"); 1319 } 1320 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1321 ArrayList<String> pkgList = new ArrayList<String>(1); 1322 pkgList.add(res.pkg.applicationInfo.packageName); 1323 sendResourcesChangedBroadcast(true, true, 1324 pkgList,uidArray, null); 1325 } 1326 } 1327 if (res.removedInfo.args != null) { 1328 // Remove the replaced package's older resources safely now 1329 deleteOld = true; 1330 } 1331 1332 // Log current value of "unknown sources" setting 1333 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1334 getUnknownSourcesSettings()); 1335 } 1336 // Force a gc to clear up things 1337 Runtime.getRuntime().gc(); 1338 // We delete after a gc for applications on sdcard. 1339 if (deleteOld) { 1340 synchronized (mInstallLock) { 1341 res.removedInfo.args.doPostDeleteLI(true); 1342 } 1343 } 1344 if (args.observer != null) { 1345 try { 1346 Bundle extras = extrasForInstallResult(res); 1347 args.observer.onPackageInstalled(res.name, res.returnCode, 1348 res.returnMsg, extras); 1349 } catch (RemoteException e) { 1350 Slog.i(TAG, "Observer no longer exists."); 1351 } 1352 } 1353 } else { 1354 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1355 } 1356 } break; 1357 case UPDATED_MEDIA_STATUS: { 1358 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1359 boolean reportStatus = msg.arg1 == 1; 1360 boolean doGc = msg.arg2 == 1; 1361 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1362 if (doGc) { 1363 // Force a gc to clear up stale containers. 1364 Runtime.getRuntime().gc(); 1365 } 1366 if (msg.obj != null) { 1367 @SuppressWarnings("unchecked") 1368 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1369 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1370 // Unload containers 1371 unloadAllContainers(args); 1372 } 1373 if (reportStatus) { 1374 try { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1376 PackageHelper.getMountService().finishMediaUpdate(); 1377 } catch (RemoteException e) { 1378 Log.e(TAG, "MountService not running?"); 1379 } 1380 } 1381 } break; 1382 case WRITE_SETTINGS: { 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1384 synchronized (mPackages) { 1385 removeMessages(WRITE_SETTINGS); 1386 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1387 mSettings.writeLPr(); 1388 mDirtyUsers.clear(); 1389 } 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1391 } break; 1392 case WRITE_PACKAGE_RESTRICTIONS: { 1393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1394 synchronized (mPackages) { 1395 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1396 for (int userId : mDirtyUsers) { 1397 mSettings.writePackageRestrictionsLPr(userId); 1398 } 1399 mDirtyUsers.clear(); 1400 } 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1402 } break; 1403 case CHECK_PENDING_VERIFICATION: { 1404 final int verificationId = msg.arg1; 1405 final PackageVerificationState state = mPendingVerification.get(verificationId); 1406 1407 if ((state != null) && !state.timeoutExtended()) { 1408 final InstallArgs args = state.getInstallArgs(); 1409 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1410 1411 Slog.i(TAG, "Verification timed out for " + originUri); 1412 mPendingVerification.remove(verificationId); 1413 1414 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1415 1416 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1417 Slog.i(TAG, "Continuing with installation of " + originUri); 1418 state.setVerifierResponse(Binder.getCallingUid(), 1419 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1420 broadcastPackageVerified(verificationId, originUri, 1421 PackageManager.VERIFICATION_ALLOW, 1422 state.getInstallArgs().getUser()); 1423 try { 1424 ret = args.copyApk(mContainerService, true); 1425 } catch (RemoteException e) { 1426 Slog.e(TAG, "Could not contact the ContainerService"); 1427 } 1428 } else { 1429 broadcastPackageVerified(verificationId, originUri, 1430 PackageManager.VERIFICATION_REJECT, 1431 state.getInstallArgs().getUser()); 1432 } 1433 1434 processPendingInstall(args, ret); 1435 mHandler.sendEmptyMessage(MCS_UNBIND); 1436 } 1437 break; 1438 } 1439 case PACKAGE_VERIFIED: { 1440 final int verificationId = msg.arg1; 1441 1442 final PackageVerificationState state = mPendingVerification.get(verificationId); 1443 if (state == null) { 1444 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1445 break; 1446 } 1447 1448 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1449 1450 state.setVerifierResponse(response.callerUid, response.code); 1451 1452 if (state.isVerificationComplete()) { 1453 mPendingVerification.remove(verificationId); 1454 1455 final InstallArgs args = state.getInstallArgs(); 1456 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1457 1458 int ret; 1459 if (state.isInstallAllowed()) { 1460 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1461 broadcastPackageVerified(verificationId, originUri, 1462 response.code, state.getInstallArgs().getUser()); 1463 try { 1464 ret = args.copyApk(mContainerService, true); 1465 } catch (RemoteException e) { 1466 Slog.e(TAG, "Could not contact the ContainerService"); 1467 } 1468 } else { 1469 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1470 } 1471 1472 processPendingInstall(args, ret); 1473 1474 mHandler.sendEmptyMessage(MCS_UNBIND); 1475 } 1476 1477 break; 1478 } 1479 case START_INTENT_FILTER_VERIFICATIONS: { 1480 int userId = msg.arg1; 1481 int verifierUid = msg.arg2; 1482 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1483 1484 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1485 break; 1486 } 1487 case INTENT_FILTER_VERIFIED: { 1488 final int verificationId = msg.arg1; 1489 1490 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1491 verificationId); 1492 if (state == null) { 1493 Slog.w(TAG, "Invalid IntentFilter verification token " 1494 + verificationId + " received"); 1495 break; 1496 } 1497 1498 final int userId = state.getUserId(); 1499 1500 Slog.d(TAG, "Processing IntentFilter verification with token:" 1501 + verificationId + " and userId:" + userId); 1502 1503 final IntentFilterVerificationResponse response = 1504 (IntentFilterVerificationResponse) msg.obj; 1505 1506 state.setVerifierResponse(response.callerUid, response.code); 1507 1508 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1509 + " and userId:" + userId 1510 + " is settings verifier response with response code:" 1511 + response.code); 1512 1513 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1514 Slog.d(TAG, "Domains failing verification: " 1515 + response.getFailedDomainsString()); 1516 } 1517 1518 if (state.isVerificationComplete()) { 1519 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1520 } else { 1521 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1522 + " was not said to be complete"); 1523 } 1524 1525 break; 1526 } 1527 } 1528 } 1529 } 1530 1531 private StorageEventListener mStorageListener = new StorageEventListener() { 1532 @Override 1533 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1534 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1535 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1536 // TODO: ensure that private directories exist for all active users 1537 // TODO: remove user data whose serial number doesn't match 1538 loadPrivatePackages(vol); 1539 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1540 unloadPrivatePackages(vol); 1541 } 1542 } 1543 1544 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1545 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1546 updateExternalMediaStatus(true, false); 1547 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1548 updateExternalMediaStatus(false, false); 1549 } 1550 } 1551 } 1552 }; 1553 1554 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1555 if (userId >= UserHandle.USER_OWNER) { 1556 grantRequestedRuntimePermissionsForUser(pkg, userId); 1557 } else if (userId == UserHandle.USER_ALL) { 1558 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1559 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1560 } 1561 } 1562 } 1563 1564 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1565 SettingBase sb = (SettingBase) pkg.mExtras; 1566 if (sb == null) { 1567 return; 1568 } 1569 1570 PermissionsState permissionsState = sb.getPermissionsState(); 1571 1572 for (String permission : pkg.requestedPermissions) { 1573 BasePermission bp = mSettings.mPermissions.get(permission); 1574 if (bp != null && bp.isRuntime()) { 1575 permissionsState.grantRuntimePermission(bp, userId); 1576 } 1577 } 1578 } 1579 1580 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1581 Bundle extras = null; 1582 switch (res.returnCode) { 1583 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1584 extras = new Bundle(); 1585 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1586 res.origPermission); 1587 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1588 res.origPackage); 1589 break; 1590 } 1591 } 1592 return extras; 1593 } 1594 1595 void scheduleWriteSettingsLocked() { 1596 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1597 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1598 } 1599 } 1600 1601 void scheduleWritePackageRestrictionsLocked(int userId) { 1602 if (!sUserManager.exists(userId)) return; 1603 mDirtyUsers.add(userId); 1604 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1605 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1606 } 1607 } 1608 1609 public static PackageManagerService main(Context context, Installer installer, 1610 boolean factoryTest, boolean onlyCore) { 1611 PackageManagerService m = new PackageManagerService(context, installer, 1612 factoryTest, onlyCore); 1613 ServiceManager.addService("package", m); 1614 return m; 1615 } 1616 1617 static String[] splitString(String str, char sep) { 1618 int count = 1; 1619 int i = 0; 1620 while ((i=str.indexOf(sep, i)) >= 0) { 1621 count++; 1622 i++; 1623 } 1624 1625 String[] res = new String[count]; 1626 i=0; 1627 count = 0; 1628 int lastI=0; 1629 while ((i=str.indexOf(sep, i)) >= 0) { 1630 res[count] = str.substring(lastI, i); 1631 count++; 1632 i++; 1633 lastI = i; 1634 } 1635 res[count] = str.substring(lastI, str.length()); 1636 return res; 1637 } 1638 1639 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1640 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1641 Context.DISPLAY_SERVICE); 1642 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1643 } 1644 1645 public PackageManagerService(Context context, Installer installer, 1646 boolean factoryTest, boolean onlyCore) { 1647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1648 SystemClock.uptimeMillis()); 1649 1650 if (mSdkVersion <= 0) { 1651 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1652 } 1653 1654 mContext = context; 1655 mFactoryTest = factoryTest; 1656 mOnlyCore = onlyCore; 1657 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1658 mMetrics = new DisplayMetrics(); 1659 mSettings = new Settings(mPackages); 1660 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1661 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1662 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1663 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1664 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1665 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1666 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1667 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1668 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1669 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1670 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1671 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1672 1673 // TODO: add a property to control this? 1674 long dexOptLRUThresholdInMinutes; 1675 if (mLazyDexOpt) { 1676 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1677 } else { 1678 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1679 } 1680 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1681 1682 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1683 if (separateProcesses != null && separateProcesses.length() > 0) { 1684 if ("*".equals(separateProcesses)) { 1685 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1686 mSeparateProcesses = null; 1687 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1688 } else { 1689 mDefParseFlags = 0; 1690 mSeparateProcesses = separateProcesses.split(","); 1691 Slog.w(TAG, "Running with debug.separate_processes: " 1692 + separateProcesses); 1693 } 1694 } else { 1695 mDefParseFlags = 0; 1696 mSeparateProcesses = null; 1697 } 1698 1699 mInstaller = installer; 1700 mPackageDexOptimizer = new PackageDexOptimizer(this); 1701 1702 getDefaultDisplayMetrics(context, mMetrics); 1703 1704 SystemConfig systemConfig = SystemConfig.getInstance(); 1705 mGlobalGids = systemConfig.getGlobalGids(); 1706 mSystemPermissions = systemConfig.getSystemPermissions(); 1707 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1708 1709 synchronized (mInstallLock) { 1710 // writer 1711 synchronized (mPackages) { 1712 mHandlerThread = new ServiceThread(TAG, 1713 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1714 mHandlerThread.start(); 1715 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1716 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1717 1718 File dataDir = Environment.getDataDirectory(); 1719 mAppDataDir = new File(dataDir, "data"); 1720 mAppInstallDir = new File(dataDir, "app"); 1721 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1722 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1723 mUserAppDataDir = new File(dataDir, "user"); 1724 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1725 1726 sUserManager = new UserManagerService(context, this, 1727 mInstallLock, mPackages); 1728 1729 // Propagate permission configuration in to package manager. 1730 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1731 = systemConfig.getPermissions(); 1732 for (int i=0; i<permConfig.size(); i++) { 1733 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1734 BasePermission bp = mSettings.mPermissions.get(perm.name); 1735 if (bp == null) { 1736 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1737 mSettings.mPermissions.put(perm.name, bp); 1738 } 1739 if (perm.gids != null) { 1740 bp.setGids(perm.gids, perm.perUser); 1741 } 1742 } 1743 1744 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1745 for (int i=0; i<libConfig.size(); i++) { 1746 mSharedLibraries.put(libConfig.keyAt(i), 1747 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1748 } 1749 1750 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1751 1752 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1753 mSdkVersion, mOnlyCore); 1754 1755 String customResolverActivity = Resources.getSystem().getString( 1756 R.string.config_customResolverActivity); 1757 if (TextUtils.isEmpty(customResolverActivity)) { 1758 customResolverActivity = null; 1759 } else { 1760 mCustomResolverComponentName = ComponentName.unflattenFromString( 1761 customResolverActivity); 1762 } 1763 1764 long startTime = SystemClock.uptimeMillis(); 1765 1766 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1767 startTime); 1768 1769 // Set flag to monitor and not change apk file paths when 1770 // scanning install directories. 1771 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1772 1773 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1774 1775 /** 1776 * Add everything in the in the boot class path to the 1777 * list of process files because dexopt will have been run 1778 * if necessary during zygote startup. 1779 */ 1780 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1781 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1782 1783 if (bootClassPath != null) { 1784 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1785 for (String element : bootClassPathElements) { 1786 alreadyDexOpted.add(element); 1787 } 1788 } else { 1789 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1790 } 1791 1792 if (systemServerClassPath != null) { 1793 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1794 for (String element : systemServerClassPathElements) { 1795 alreadyDexOpted.add(element); 1796 } 1797 } else { 1798 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1799 } 1800 1801 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1802 final String[] dexCodeInstructionSets = 1803 getDexCodeInstructionSets( 1804 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1805 1806 /** 1807 * Ensure all external libraries have had dexopt run on them. 1808 */ 1809 if (mSharedLibraries.size() > 0) { 1810 // NOTE: For now, we're compiling these system "shared libraries" 1811 // (and framework jars) into all available architectures. It's possible 1812 // to compile them only when we come across an app that uses them (there's 1813 // already logic for that in scanPackageLI) but that adds some complexity. 1814 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1815 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1816 final String lib = libEntry.path; 1817 if (lib == null) { 1818 continue; 1819 } 1820 1821 try { 1822 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1823 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1824 alreadyDexOpted.add(lib); 1825 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1826 } 1827 } catch (FileNotFoundException e) { 1828 Slog.w(TAG, "Library not found: " + lib); 1829 } catch (IOException e) { 1830 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1831 + e.getMessage()); 1832 } 1833 } 1834 } 1835 } 1836 1837 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1838 1839 // Gross hack for now: we know this file doesn't contain any 1840 // code, so don't dexopt it to avoid the resulting log spew. 1841 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1842 1843 // Gross hack for now: we know this file is only part of 1844 // the boot class path for art, so don't dexopt it to 1845 // avoid the resulting log spew. 1846 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1847 1848 /** 1849 * And there are a number of commands implemented in Java, which 1850 * we currently need to do the dexopt on so that they can be 1851 * run from a non-root shell. 1852 */ 1853 String[] frameworkFiles = frameworkDir.list(); 1854 if (frameworkFiles != null) { 1855 // TODO: We could compile these only for the most preferred ABI. We should 1856 // first double check that the dex files for these commands are not referenced 1857 // by other system apps. 1858 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1859 for (int i=0; i<frameworkFiles.length; i++) { 1860 File libPath = new File(frameworkDir, frameworkFiles[i]); 1861 String path = libPath.getPath(); 1862 // Skip the file if we already did it. 1863 if (alreadyDexOpted.contains(path)) { 1864 continue; 1865 } 1866 // Skip the file if it is not a type we want to dexopt. 1867 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1868 continue; 1869 } 1870 try { 1871 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1872 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1873 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1874 } 1875 } catch (FileNotFoundException e) { 1876 Slog.w(TAG, "Jar not found: " + path); 1877 } catch (IOException e) { 1878 Slog.w(TAG, "Exception reading jar: " + path, e); 1879 } 1880 } 1881 } 1882 } 1883 1884 // Collect vendor overlay packages. 1885 // (Do this before scanning any apps.) 1886 // For security and version matching reason, only consider 1887 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1888 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1889 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1890 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1891 1892 // Find base frameworks (resource packages without code). 1893 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1894 | PackageParser.PARSE_IS_SYSTEM_DIR 1895 | PackageParser.PARSE_IS_PRIVILEGED, 1896 scanFlags | SCAN_NO_DEX, 0); 1897 1898 // Collected privileged system packages. 1899 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1900 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1901 | PackageParser.PARSE_IS_SYSTEM_DIR 1902 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1903 1904 // Collect ordinary system packages. 1905 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1906 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1907 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1908 1909 // Collect all vendor packages. 1910 File vendorAppDir = new File("/vendor/app"); 1911 try { 1912 vendorAppDir = vendorAppDir.getCanonicalFile(); 1913 } catch (IOException e) { 1914 // failed to look up canonical path, continue with original one 1915 } 1916 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1918 1919 // Collect all OEM packages. 1920 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1921 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1922 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1923 1924 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1925 mInstaller.moveFiles(); 1926 1927 // Prune any system packages that no longer exist. 1928 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1929 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1930 if (!mOnlyCore) { 1931 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1932 while (psit.hasNext()) { 1933 PackageSetting ps = psit.next(); 1934 1935 /* 1936 * If this is not a system app, it can't be a 1937 * disable system app. 1938 */ 1939 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1940 continue; 1941 } 1942 1943 /* 1944 * If the package is scanned, it's not erased. 1945 */ 1946 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1947 if (scannedPkg != null) { 1948 /* 1949 * If the system app is both scanned and in the 1950 * disabled packages list, then it must have been 1951 * added via OTA. Remove it from the currently 1952 * scanned package so the previously user-installed 1953 * application can be scanned. 1954 */ 1955 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1956 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1957 + ps.name + "; removing system app. Last known codePath=" 1958 + ps.codePathString + ", installStatus=" + ps.installStatus 1959 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1960 + scannedPkg.mVersionCode); 1961 removePackageLI(ps, true); 1962 expectingBetter.put(ps.name, ps.codePath); 1963 } 1964 1965 continue; 1966 } 1967 1968 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1969 psit.remove(); 1970 logCriticalInfo(Log.WARN, "System package " + ps.name 1971 + " no longer exists; wiping its data"); 1972 removeDataDirsLI(null, ps.name); 1973 } else { 1974 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1975 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1976 possiblyDeletedUpdatedSystemApps.add(ps.name); 1977 } 1978 } 1979 } 1980 } 1981 1982 //look for any incomplete package installations 1983 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1984 //clean up list 1985 for(int i = 0; i < deletePkgsList.size(); i++) { 1986 //clean up here 1987 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1988 } 1989 //delete tmp files 1990 deleteTempPackageFiles(); 1991 1992 // Remove any shared userIDs that have no associated packages 1993 mSettings.pruneSharedUsersLPw(); 1994 1995 if (!mOnlyCore) { 1996 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1997 SystemClock.uptimeMillis()); 1998 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 1999 2000 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2001 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2002 2003 /** 2004 * Remove disable package settings for any updated system 2005 * apps that were removed via an OTA. If they're not a 2006 * previously-updated app, remove them completely. 2007 * Otherwise, just revoke their system-level permissions. 2008 */ 2009 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2010 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2011 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2012 2013 String msg; 2014 if (deletedPkg == null) { 2015 msg = "Updated system package " + deletedAppName 2016 + " no longer exists; wiping its data"; 2017 removeDataDirsLI(null, deletedAppName); 2018 } else { 2019 msg = "Updated system app + " + deletedAppName 2020 + " no longer present; removing system privileges for " 2021 + deletedAppName; 2022 2023 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2024 2025 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2026 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2027 } 2028 logCriticalInfo(Log.WARN, msg); 2029 } 2030 2031 /** 2032 * Make sure all system apps that we expected to appear on 2033 * the userdata partition actually showed up. If they never 2034 * appeared, crawl back and revive the system version. 2035 */ 2036 for (int i = 0; i < expectingBetter.size(); i++) { 2037 final String packageName = expectingBetter.keyAt(i); 2038 if (!mPackages.containsKey(packageName)) { 2039 final File scanFile = expectingBetter.valueAt(i); 2040 2041 logCriticalInfo(Log.WARN, "Expected better " + packageName 2042 + " but never showed up; reverting to system"); 2043 2044 final int reparseFlags; 2045 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2046 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2047 | PackageParser.PARSE_IS_SYSTEM_DIR 2048 | PackageParser.PARSE_IS_PRIVILEGED; 2049 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2050 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2051 | PackageParser.PARSE_IS_SYSTEM_DIR; 2052 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2053 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2054 | PackageParser.PARSE_IS_SYSTEM_DIR; 2055 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2056 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2057 | PackageParser.PARSE_IS_SYSTEM_DIR; 2058 } else { 2059 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2060 continue; 2061 } 2062 2063 mSettings.enableSystemPackageLPw(packageName); 2064 2065 try { 2066 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2067 } catch (PackageManagerException e) { 2068 Slog.e(TAG, "Failed to parse original system package: " 2069 + e.getMessage()); 2070 } 2071 } 2072 } 2073 } 2074 2075 // Now that we know all of the shared libraries, update all clients to have 2076 // the correct library paths. 2077 updateAllSharedLibrariesLPw(); 2078 2079 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2080 // NOTE: We ignore potential failures here during a system scan (like 2081 // the rest of the commands above) because there's precious little we 2082 // can do about it. A settings error is reported, though. 2083 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2084 false /* force dexopt */, false /* defer dexopt */); 2085 } 2086 2087 // Now that we know all the packages we are keeping, 2088 // read and update their last usage times. 2089 mPackageUsage.readLP(); 2090 2091 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2092 SystemClock.uptimeMillis()); 2093 Slog.i(TAG, "Time to scan packages: " 2094 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2095 + " seconds"); 2096 2097 // If the platform SDK has changed since the last time we booted, 2098 // we need to re-grant app permission to catch any new ones that 2099 // appear. This is really a hack, and means that apps can in some 2100 // cases get permissions that the user didn't initially explicitly 2101 // allow... it would be nice to have some better way to handle 2102 // this situation. 2103 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2104 != mSdkVersion; 2105 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2106 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2107 + "; regranting permissions for internal storage"); 2108 mSettings.mInternalSdkPlatform = mSdkVersion; 2109 2110 // For now runtime permissions are toggled via a system property. 2111 if (!RUNTIME_PERMISSIONS_ENABLED) { 2112 // Remove the runtime permissions state if the feature 2113 // was disabled by flipping the system property. 2114 mSettings.deleteRuntimePermissionsFiles(); 2115 } 2116 2117 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2118 | (regrantPermissions 2119 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2120 : 0)); 2121 2122 // If this is the first boot, and it is a normal boot, then 2123 // we need to initialize the default preferred apps. 2124 if (!mRestoredSettings && !onlyCore) { 2125 mSettings.readDefaultPreferredAppsLPw(this, 0); 2126 } 2127 2128 // If this is first boot after an OTA, and a normal boot, then 2129 // we need to clear code cache directories. 2130 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2131 if (mIsUpgrade && !onlyCore) { 2132 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2133 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2134 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2135 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2136 } 2137 mSettings.mFingerprint = Build.FINGERPRINT; 2138 } 2139 2140 // All the changes are done during package scanning. 2141 mSettings.updateInternalDatabaseVersion(); 2142 2143 // can downgrade to reader 2144 mSettings.writeLPr(); 2145 2146 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2147 SystemClock.uptimeMillis()); 2148 2149 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2150 2151 mInstallerService = new PackageInstallerService(context, this); 2152 2153 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2154 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2155 mIntentFilterVerifierComponent); 2156 2157 primeDomainVerificationsLPw(false); 2158 2159 } // synchronized (mPackages) 2160 } // synchronized (mInstallLock) 2161 2162 // Now after opening every single application zip, make sure they 2163 // are all flushed. Not really needed, but keeps things nice and 2164 // tidy. 2165 Runtime.getRuntime().gc(); 2166 } 2167 2168 @Override 2169 public boolean isFirstBoot() { 2170 return !mRestoredSettings; 2171 } 2172 2173 @Override 2174 public boolean isOnlyCoreApps() { 2175 return mOnlyCore; 2176 } 2177 2178 @Override 2179 public boolean isUpgrade() { 2180 return mIsUpgrade; 2181 } 2182 2183 private String getRequiredVerifierLPr() { 2184 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2185 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2186 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2187 2188 String requiredVerifier = null; 2189 2190 final int N = receivers.size(); 2191 for (int i = 0; i < N; i++) { 2192 final ResolveInfo info = receivers.get(i); 2193 2194 if (info.activityInfo == null) { 2195 continue; 2196 } 2197 2198 final String packageName = info.activityInfo.packageName; 2199 2200 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2201 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2202 continue; 2203 } 2204 2205 if (requiredVerifier != null) { 2206 throw new RuntimeException("There can be only one required verifier"); 2207 } 2208 2209 requiredVerifier = packageName; 2210 } 2211 2212 return requiredVerifier; 2213 } 2214 2215 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2216 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2217 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2218 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2219 2220 ComponentName verifierComponentName = null; 2221 2222 int priority = -1000; 2223 final int N = receivers.size(); 2224 for (int i = 0; i < N; i++) { 2225 final ResolveInfo info = receivers.get(i); 2226 2227 if (info.activityInfo == null) { 2228 continue; 2229 } 2230 2231 final String packageName = info.activityInfo.packageName; 2232 2233 final PackageSetting ps = mSettings.mPackages.get(packageName); 2234 if (ps == null) { 2235 continue; 2236 } 2237 2238 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2239 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2240 continue; 2241 } 2242 2243 // Select the IntentFilterVerifier with the highest priority 2244 if (priority < info.priority) { 2245 priority = info.priority; 2246 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2247 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2248 " with priority: " + info.priority); 2249 } 2250 } 2251 2252 return verifierComponentName; 2253 } 2254 2255 private void primeDomainVerificationsLPw(boolean logging) { 2256 Slog.d(TAG, "Start priming domain verification"); 2257 boolean updated = false; 2258 ArrayList<String> allHosts = new ArrayList<>(); 2259 for (PackageParser.Package pkg : mPackages.values()) { 2260 final String packageName = pkg.packageName; 2261 if (!hasDomainURLs(pkg)) { 2262 if (logging) { 2263 Slog.d(TAG, "No priming domain verifications for " + 2264 "package with no domain URLs: " + packageName); 2265 } 2266 continue; 2267 } 2268 for (PackageParser.Activity a : pkg.activities) { 2269 for (ActivityIntentInfo filter : a.intents) { 2270 if (hasValidDomains(filter, false)) { 2271 allHosts.addAll(filter.getHostsList()); 2272 } 2273 } 2274 } 2275 if (allHosts.size() > 0) { 2276 allHosts.add("*"); 2277 } 2278 IntentFilterVerificationInfo ivi = 2279 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2280 if (ivi != null) { 2281 // We will always log this 2282 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2283 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2284 updated = true; 2285 } 2286 else { 2287 if (logging) { 2288 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2289 } 2290 } 2291 allHosts.clear(); 2292 } 2293 if (updated) { 2294 scheduleWriteSettingsLocked(); 2295 } 2296 Slog.d(TAG, "End priming domain verification"); 2297 } 2298 2299 @Override 2300 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2301 throws RemoteException { 2302 try { 2303 return super.onTransact(code, data, reply, flags); 2304 } catch (RuntimeException e) { 2305 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2306 Slog.wtf(TAG, "Package Manager Crash", e); 2307 } 2308 throw e; 2309 } 2310 } 2311 2312 void cleanupInstallFailedPackage(PackageSetting ps) { 2313 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2314 2315 removeDataDirsLI(ps.volumeUuid, ps.name); 2316 if (ps.codePath != null) { 2317 if (ps.codePath.isDirectory()) { 2318 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2319 } else { 2320 ps.codePath.delete(); 2321 } 2322 } 2323 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2324 if (ps.resourcePath.isDirectory()) { 2325 FileUtils.deleteContents(ps.resourcePath); 2326 } 2327 ps.resourcePath.delete(); 2328 } 2329 mSettings.removePackageLPw(ps.name); 2330 } 2331 2332 static int[] appendInts(int[] cur, int[] add) { 2333 if (add == null) return cur; 2334 if (cur == null) return add; 2335 final int N = add.length; 2336 for (int i=0; i<N; i++) { 2337 cur = appendInt(cur, add[i]); 2338 } 2339 return cur; 2340 } 2341 2342 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2343 if (!sUserManager.exists(userId)) return null; 2344 final PackageSetting ps = (PackageSetting) p.mExtras; 2345 if (ps == null) { 2346 return null; 2347 } 2348 2349 final PermissionsState permissionsState = ps.getPermissionsState(); 2350 2351 final int[] gids = permissionsState.computeGids(userId); 2352 final Set<String> permissions = permissionsState.getPermissions(userId); 2353 final PackageUserState state = ps.readUserState(userId); 2354 2355 return PackageParser.generatePackageInfo(p, gids, flags, 2356 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2357 } 2358 2359 @Override 2360 public boolean isPackageAvailable(String packageName, int userId) { 2361 if (!sUserManager.exists(userId)) return false; 2362 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2363 synchronized (mPackages) { 2364 PackageParser.Package p = mPackages.get(packageName); 2365 if (p != null) { 2366 final PackageSetting ps = (PackageSetting) p.mExtras; 2367 if (ps != null) { 2368 final PackageUserState state = ps.readUserState(userId); 2369 if (state != null) { 2370 return PackageParser.isAvailable(state); 2371 } 2372 } 2373 } 2374 } 2375 return false; 2376 } 2377 2378 @Override 2379 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2380 if (!sUserManager.exists(userId)) return null; 2381 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2382 // reader 2383 synchronized (mPackages) { 2384 PackageParser.Package p = mPackages.get(packageName); 2385 if (DEBUG_PACKAGE_INFO) 2386 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2387 if (p != null) { 2388 return generatePackageInfo(p, flags, userId); 2389 } 2390 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2391 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2392 } 2393 } 2394 return null; 2395 } 2396 2397 @Override 2398 public String[] currentToCanonicalPackageNames(String[] names) { 2399 String[] out = new String[names.length]; 2400 // reader 2401 synchronized (mPackages) { 2402 for (int i=names.length-1; i>=0; i--) { 2403 PackageSetting ps = mSettings.mPackages.get(names[i]); 2404 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2405 } 2406 } 2407 return out; 2408 } 2409 2410 @Override 2411 public String[] canonicalToCurrentPackageNames(String[] names) { 2412 String[] out = new String[names.length]; 2413 // reader 2414 synchronized (mPackages) { 2415 for (int i=names.length-1; i>=0; i--) { 2416 String cur = mSettings.mRenamedPackages.get(names[i]); 2417 out[i] = cur != null ? cur : names[i]; 2418 } 2419 } 2420 return out; 2421 } 2422 2423 @Override 2424 public int getPackageUid(String packageName, int userId) { 2425 if (!sUserManager.exists(userId)) return -1; 2426 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2427 2428 // reader 2429 synchronized (mPackages) { 2430 PackageParser.Package p = mPackages.get(packageName); 2431 if(p != null) { 2432 return UserHandle.getUid(userId, p.applicationInfo.uid); 2433 } 2434 PackageSetting ps = mSettings.mPackages.get(packageName); 2435 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2436 return -1; 2437 } 2438 p = ps.pkg; 2439 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2440 } 2441 } 2442 2443 @Override 2444 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2445 if (!sUserManager.exists(userId)) { 2446 return null; 2447 } 2448 2449 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2450 "getPackageGids"); 2451 2452 // reader 2453 synchronized (mPackages) { 2454 PackageParser.Package p = mPackages.get(packageName); 2455 if (DEBUG_PACKAGE_INFO) { 2456 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2457 } 2458 if (p != null) { 2459 PackageSetting ps = (PackageSetting) p.mExtras; 2460 return ps.getPermissionsState().computeGids(userId); 2461 } 2462 } 2463 2464 return null; 2465 } 2466 2467 static PermissionInfo generatePermissionInfo( 2468 BasePermission bp, int flags) { 2469 if (bp.perm != null) { 2470 return PackageParser.generatePermissionInfo(bp.perm, flags); 2471 } 2472 PermissionInfo pi = new PermissionInfo(); 2473 pi.name = bp.name; 2474 pi.packageName = bp.sourcePackage; 2475 pi.nonLocalizedLabel = bp.name; 2476 pi.protectionLevel = bp.protectionLevel; 2477 return pi; 2478 } 2479 2480 @Override 2481 public PermissionInfo getPermissionInfo(String name, int flags) { 2482 // reader 2483 synchronized (mPackages) { 2484 final BasePermission p = mSettings.mPermissions.get(name); 2485 if (p != null) { 2486 return generatePermissionInfo(p, flags); 2487 } 2488 return null; 2489 } 2490 } 2491 2492 @Override 2493 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2494 // reader 2495 synchronized (mPackages) { 2496 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2497 for (BasePermission p : mSettings.mPermissions.values()) { 2498 if (group == null) { 2499 if (p.perm == null || p.perm.info.group == null) { 2500 out.add(generatePermissionInfo(p, flags)); 2501 } 2502 } else { 2503 if (p.perm != null && group.equals(p.perm.info.group)) { 2504 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2505 } 2506 } 2507 } 2508 2509 if (out.size() > 0) { 2510 return out; 2511 } 2512 return mPermissionGroups.containsKey(group) ? out : null; 2513 } 2514 } 2515 2516 @Override 2517 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2518 // reader 2519 synchronized (mPackages) { 2520 return PackageParser.generatePermissionGroupInfo( 2521 mPermissionGroups.get(name), flags); 2522 } 2523 } 2524 2525 @Override 2526 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2527 // reader 2528 synchronized (mPackages) { 2529 final int N = mPermissionGroups.size(); 2530 ArrayList<PermissionGroupInfo> out 2531 = new ArrayList<PermissionGroupInfo>(N); 2532 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2533 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2534 } 2535 return out; 2536 } 2537 } 2538 2539 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2540 int userId) { 2541 if (!sUserManager.exists(userId)) return null; 2542 PackageSetting ps = mSettings.mPackages.get(packageName); 2543 if (ps != null) { 2544 if (ps.pkg == null) { 2545 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2546 flags, userId); 2547 if (pInfo != null) { 2548 return pInfo.applicationInfo; 2549 } 2550 return null; 2551 } 2552 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2553 ps.readUserState(userId), userId); 2554 } 2555 return null; 2556 } 2557 2558 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2559 int userId) { 2560 if (!sUserManager.exists(userId)) return null; 2561 PackageSetting ps = mSettings.mPackages.get(packageName); 2562 if (ps != null) { 2563 PackageParser.Package pkg = ps.pkg; 2564 if (pkg == null) { 2565 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2566 return null; 2567 } 2568 // Only data remains, so we aren't worried about code paths 2569 pkg = new PackageParser.Package(packageName); 2570 pkg.applicationInfo.packageName = packageName; 2571 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2572 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2573 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2574 packageName, userId).getAbsolutePath(); 2575 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2576 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2577 } 2578 return generatePackageInfo(pkg, flags, userId); 2579 } 2580 return null; 2581 } 2582 2583 @Override 2584 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2585 if (!sUserManager.exists(userId)) return null; 2586 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2587 // writer 2588 synchronized (mPackages) { 2589 PackageParser.Package p = mPackages.get(packageName); 2590 if (DEBUG_PACKAGE_INFO) Log.v( 2591 TAG, "getApplicationInfo " + packageName 2592 + ": " + p); 2593 if (p != null) { 2594 PackageSetting ps = mSettings.mPackages.get(packageName); 2595 if (ps == null) return null; 2596 // Note: isEnabledLP() does not apply here - always return info 2597 return PackageParser.generateApplicationInfo( 2598 p, flags, ps.readUserState(userId), userId); 2599 } 2600 if ("android".equals(packageName)||"system".equals(packageName)) { 2601 return mAndroidApplication; 2602 } 2603 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2604 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2605 } 2606 } 2607 return null; 2608 } 2609 2610 @Override 2611 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2612 final IPackageDataObserver observer) { 2613 mContext.enforceCallingOrSelfPermission( 2614 android.Manifest.permission.CLEAR_APP_CACHE, null); 2615 // Queue up an async operation since clearing cache may take a little while. 2616 mHandler.post(new Runnable() { 2617 public void run() { 2618 mHandler.removeCallbacks(this); 2619 int retCode = -1; 2620 synchronized (mInstallLock) { 2621 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2622 if (retCode < 0) { 2623 Slog.w(TAG, "Couldn't clear application caches"); 2624 } 2625 } 2626 if (observer != null) { 2627 try { 2628 observer.onRemoveCompleted(null, (retCode >= 0)); 2629 } catch (RemoteException e) { 2630 Slog.w(TAG, "RemoveException when invoking call back"); 2631 } 2632 } 2633 } 2634 }); 2635 } 2636 2637 @Override 2638 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2639 final IntentSender pi) { 2640 mContext.enforceCallingOrSelfPermission( 2641 android.Manifest.permission.CLEAR_APP_CACHE, null); 2642 // Queue up an async operation since clearing cache may take a little while. 2643 mHandler.post(new Runnable() { 2644 public void run() { 2645 mHandler.removeCallbacks(this); 2646 int retCode = -1; 2647 synchronized (mInstallLock) { 2648 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2649 if (retCode < 0) { 2650 Slog.w(TAG, "Couldn't clear application caches"); 2651 } 2652 } 2653 if(pi != null) { 2654 try { 2655 // Callback via pending intent 2656 int code = (retCode >= 0) ? 1 : 0; 2657 pi.sendIntent(null, code, null, 2658 null, null); 2659 } catch (SendIntentException e1) { 2660 Slog.i(TAG, "Failed to send pending intent"); 2661 } 2662 } 2663 } 2664 }); 2665 } 2666 2667 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2668 synchronized (mInstallLock) { 2669 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2670 throw new IOException("Failed to free enough space"); 2671 } 2672 } 2673 } 2674 2675 @Override 2676 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2677 if (!sUserManager.exists(userId)) return null; 2678 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2679 synchronized (mPackages) { 2680 PackageParser.Activity a = mActivities.mActivities.get(component); 2681 2682 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2683 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2684 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2685 if (ps == null) return null; 2686 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2687 userId); 2688 } 2689 if (mResolveComponentName.equals(component)) { 2690 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2691 new PackageUserState(), userId); 2692 } 2693 } 2694 return null; 2695 } 2696 2697 @Override 2698 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2699 String resolvedType) { 2700 synchronized (mPackages) { 2701 PackageParser.Activity a = mActivities.mActivities.get(component); 2702 if (a == null) { 2703 return false; 2704 } 2705 for (int i=0; i<a.intents.size(); i++) { 2706 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2707 intent.getData(), intent.getCategories(), TAG) >= 0) { 2708 return true; 2709 } 2710 } 2711 return false; 2712 } 2713 } 2714 2715 @Override 2716 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2717 if (!sUserManager.exists(userId)) return null; 2718 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2719 synchronized (mPackages) { 2720 PackageParser.Activity a = mReceivers.mActivities.get(component); 2721 if (DEBUG_PACKAGE_INFO) Log.v( 2722 TAG, "getReceiverInfo " + component + ": " + a); 2723 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2724 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2725 if (ps == null) return null; 2726 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2727 userId); 2728 } 2729 } 2730 return null; 2731 } 2732 2733 @Override 2734 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2737 synchronized (mPackages) { 2738 PackageParser.Service s = mServices.mServices.get(component); 2739 if (DEBUG_PACKAGE_INFO) Log.v( 2740 TAG, "getServiceInfo " + component + ": " + s); 2741 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2742 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2743 if (ps == null) return null; 2744 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2745 userId); 2746 } 2747 } 2748 return null; 2749 } 2750 2751 @Override 2752 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2753 if (!sUserManager.exists(userId)) return null; 2754 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2755 synchronized (mPackages) { 2756 PackageParser.Provider p = mProviders.mProviders.get(component); 2757 if (DEBUG_PACKAGE_INFO) Log.v( 2758 TAG, "getProviderInfo " + component + ": " + p); 2759 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2760 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2761 if (ps == null) return null; 2762 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2763 userId); 2764 } 2765 } 2766 return null; 2767 } 2768 2769 @Override 2770 public String[] getSystemSharedLibraryNames() { 2771 Set<String> libSet; 2772 synchronized (mPackages) { 2773 libSet = mSharedLibraries.keySet(); 2774 int size = libSet.size(); 2775 if (size > 0) { 2776 String[] libs = new String[size]; 2777 libSet.toArray(libs); 2778 return libs; 2779 } 2780 } 2781 return null; 2782 } 2783 2784 /** 2785 * @hide 2786 */ 2787 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2788 synchronized (mPackages) { 2789 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2790 if (lib != null && lib.apk != null) { 2791 return mPackages.get(lib.apk); 2792 } 2793 } 2794 return null; 2795 } 2796 2797 @Override 2798 public FeatureInfo[] getSystemAvailableFeatures() { 2799 Collection<FeatureInfo> featSet; 2800 synchronized (mPackages) { 2801 featSet = mAvailableFeatures.values(); 2802 int size = featSet.size(); 2803 if (size > 0) { 2804 FeatureInfo[] features = new FeatureInfo[size+1]; 2805 featSet.toArray(features); 2806 FeatureInfo fi = new FeatureInfo(); 2807 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2808 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2809 features[size] = fi; 2810 return features; 2811 } 2812 } 2813 return null; 2814 } 2815 2816 @Override 2817 public boolean hasSystemFeature(String name) { 2818 synchronized (mPackages) { 2819 return mAvailableFeatures.containsKey(name); 2820 } 2821 } 2822 2823 private void checkValidCaller(int uid, int userId) { 2824 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2825 return; 2826 2827 throw new SecurityException("Caller uid=" + uid 2828 + " is not privileged to communicate with user=" + userId); 2829 } 2830 2831 @Override 2832 public int checkPermission(String permName, String pkgName, int userId) { 2833 if (!sUserManager.exists(userId)) { 2834 return PackageManager.PERMISSION_DENIED; 2835 } 2836 2837 synchronized (mPackages) { 2838 final PackageParser.Package p = mPackages.get(pkgName); 2839 if (p != null && p.mExtras != null) { 2840 final PackageSetting ps = (PackageSetting) p.mExtras; 2841 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2842 return PackageManager.PERMISSION_GRANTED; 2843 } 2844 } 2845 } 2846 2847 return PackageManager.PERMISSION_DENIED; 2848 } 2849 2850 @Override 2851 public int checkUidPermission(String permName, int uid) { 2852 final int userId = UserHandle.getUserId(uid); 2853 2854 if (!sUserManager.exists(userId)) { 2855 return PackageManager.PERMISSION_DENIED; 2856 } 2857 2858 synchronized (mPackages) { 2859 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2860 if (obj != null) { 2861 final SettingBase ps = (SettingBase) obj; 2862 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2863 return PackageManager.PERMISSION_GRANTED; 2864 } 2865 } else { 2866 ArraySet<String> perms = mSystemPermissions.get(uid); 2867 if (perms != null && perms.contains(permName)) { 2868 return PackageManager.PERMISSION_GRANTED; 2869 } 2870 } 2871 } 2872 2873 return PackageManager.PERMISSION_DENIED; 2874 } 2875 2876 /** 2877 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2878 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2879 * @param checkShell TODO(yamasani): 2880 * @param message the message to log on security exception 2881 */ 2882 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2883 boolean checkShell, String message) { 2884 if (userId < 0) { 2885 throw new IllegalArgumentException("Invalid userId " + userId); 2886 } 2887 if (checkShell) { 2888 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2889 } 2890 if (userId == UserHandle.getUserId(callingUid)) return; 2891 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2892 if (requireFullPermission) { 2893 mContext.enforceCallingOrSelfPermission( 2894 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2895 } else { 2896 try { 2897 mContext.enforceCallingOrSelfPermission( 2898 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2899 } catch (SecurityException se) { 2900 mContext.enforceCallingOrSelfPermission( 2901 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2902 } 2903 } 2904 } 2905 } 2906 2907 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2908 if (callingUid == Process.SHELL_UID) { 2909 if (userHandle >= 0 2910 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2911 throw new SecurityException("Shell does not have permission to access user " 2912 + userHandle); 2913 } else if (userHandle < 0) { 2914 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2915 + Debug.getCallers(3)); 2916 } 2917 } 2918 } 2919 2920 private BasePermission findPermissionTreeLP(String permName) { 2921 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2922 if (permName.startsWith(bp.name) && 2923 permName.length() > bp.name.length() && 2924 permName.charAt(bp.name.length()) == '.') { 2925 return bp; 2926 } 2927 } 2928 return null; 2929 } 2930 2931 private BasePermission checkPermissionTreeLP(String permName) { 2932 if (permName != null) { 2933 BasePermission bp = findPermissionTreeLP(permName); 2934 if (bp != null) { 2935 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2936 return bp; 2937 } 2938 throw new SecurityException("Calling uid " 2939 + Binder.getCallingUid() 2940 + " is not allowed to add to permission tree " 2941 + bp.name + " owned by uid " + bp.uid); 2942 } 2943 } 2944 throw new SecurityException("No permission tree found for " + permName); 2945 } 2946 2947 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2948 if (s1 == null) { 2949 return s2 == null; 2950 } 2951 if (s2 == null) { 2952 return false; 2953 } 2954 if (s1.getClass() != s2.getClass()) { 2955 return false; 2956 } 2957 return s1.equals(s2); 2958 } 2959 2960 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2961 if (pi1.icon != pi2.icon) return false; 2962 if (pi1.logo != pi2.logo) return false; 2963 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2964 if (!compareStrings(pi1.name, pi2.name)) return false; 2965 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2966 // We'll take care of setting this one. 2967 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2968 // These are not currently stored in settings. 2969 //if (!compareStrings(pi1.group, pi2.group)) return false; 2970 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2971 //if (pi1.labelRes != pi2.labelRes) return false; 2972 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2973 return true; 2974 } 2975 2976 int permissionInfoFootprint(PermissionInfo info) { 2977 int size = info.name.length(); 2978 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2979 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2980 return size; 2981 } 2982 2983 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2984 int size = 0; 2985 for (BasePermission perm : mSettings.mPermissions.values()) { 2986 if (perm.uid == tree.uid) { 2987 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2988 } 2989 } 2990 return size; 2991 } 2992 2993 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2994 // We calculate the max size of permissions defined by this uid and throw 2995 // if that plus the size of 'info' would exceed our stated maximum. 2996 if (tree.uid != Process.SYSTEM_UID) { 2997 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2998 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2999 throw new SecurityException("Permission tree size cap exceeded"); 3000 } 3001 } 3002 } 3003 3004 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3005 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3006 throw new SecurityException("Label must be specified in permission"); 3007 } 3008 BasePermission tree = checkPermissionTreeLP(info.name); 3009 BasePermission bp = mSettings.mPermissions.get(info.name); 3010 boolean added = bp == null; 3011 boolean changed = true; 3012 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3013 if (added) { 3014 enforcePermissionCapLocked(info, tree); 3015 bp = new BasePermission(info.name, tree.sourcePackage, 3016 BasePermission.TYPE_DYNAMIC); 3017 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3018 throw new SecurityException( 3019 "Not allowed to modify non-dynamic permission " 3020 + info.name); 3021 } else { 3022 if (bp.protectionLevel == fixedLevel 3023 && bp.perm.owner.equals(tree.perm.owner) 3024 && bp.uid == tree.uid 3025 && comparePermissionInfos(bp.perm.info, info)) { 3026 changed = false; 3027 } 3028 } 3029 bp.protectionLevel = fixedLevel; 3030 info = new PermissionInfo(info); 3031 info.protectionLevel = fixedLevel; 3032 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3033 bp.perm.info.packageName = tree.perm.info.packageName; 3034 bp.uid = tree.uid; 3035 if (added) { 3036 mSettings.mPermissions.put(info.name, bp); 3037 } 3038 if (changed) { 3039 if (!async) { 3040 mSettings.writeLPr(); 3041 } else { 3042 scheduleWriteSettingsLocked(); 3043 } 3044 } 3045 return added; 3046 } 3047 3048 @Override 3049 public boolean addPermission(PermissionInfo info) { 3050 synchronized (mPackages) { 3051 return addPermissionLocked(info, false); 3052 } 3053 } 3054 3055 @Override 3056 public boolean addPermissionAsync(PermissionInfo info) { 3057 synchronized (mPackages) { 3058 return addPermissionLocked(info, true); 3059 } 3060 } 3061 3062 @Override 3063 public void removePermission(String name) { 3064 synchronized (mPackages) { 3065 checkPermissionTreeLP(name); 3066 BasePermission bp = mSettings.mPermissions.get(name); 3067 if (bp != null) { 3068 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3069 throw new SecurityException( 3070 "Not allowed to modify non-dynamic permission " 3071 + name); 3072 } 3073 mSettings.mPermissions.remove(name); 3074 mSettings.writeLPr(); 3075 } 3076 } 3077 } 3078 3079 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3080 BasePermission bp) { 3081 int index = pkg.requestedPermissions.indexOf(bp.name); 3082 if (index == -1) { 3083 throw new SecurityException("Package " + pkg.packageName 3084 + " has not requested permission " + bp.name); 3085 } 3086 if (!bp.isRuntime()) { 3087 throw new SecurityException("Permission " + bp.name 3088 + " is not a changeable permission type"); 3089 } 3090 } 3091 3092 @Override 3093 public boolean grantPermission(String packageName, String name, int userId) { 3094 if (!RUNTIME_PERMISSIONS_ENABLED) { 3095 return false; 3096 } 3097 3098 if (!sUserManager.exists(userId)) { 3099 return false; 3100 } 3101 3102 mContext.enforceCallingOrSelfPermission( 3103 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3104 "grantPermission"); 3105 3106 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3107 "grantPermission"); 3108 3109 boolean gidsChanged = false; 3110 final SettingBase sb; 3111 3112 synchronized (mPackages) { 3113 final PackageParser.Package pkg = mPackages.get(packageName); 3114 if (pkg == null) { 3115 throw new IllegalArgumentException("Unknown package: " + packageName); 3116 } 3117 3118 final BasePermission bp = mSettings.mPermissions.get(name); 3119 if (bp == null) { 3120 throw new IllegalArgumentException("Unknown permission: " + name); 3121 } 3122 3123 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3124 3125 sb = (SettingBase) pkg.mExtras; 3126 if (sb == null) { 3127 throw new IllegalArgumentException("Unknown package: " + packageName); 3128 } 3129 3130 final PermissionsState permissionsState = sb.getPermissionsState(); 3131 3132 final int result = permissionsState.grantRuntimePermission(bp, userId); 3133 switch (result) { 3134 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3135 return false; 3136 } 3137 3138 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3139 gidsChanged = true; 3140 } break; 3141 } 3142 3143 // Not critical if that is lost - app has to request again. 3144 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3145 } 3146 3147 if (gidsChanged) { 3148 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3149 } 3150 3151 return true; 3152 } 3153 3154 @Override 3155 public boolean revokePermission(String packageName, String name, int userId) { 3156 if (!RUNTIME_PERMISSIONS_ENABLED) { 3157 return false; 3158 } 3159 3160 if (!sUserManager.exists(userId)) { 3161 return false; 3162 } 3163 3164 mContext.enforceCallingOrSelfPermission( 3165 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3166 "revokePermission"); 3167 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3169 "revokePermission"); 3170 3171 final SettingBase sb; 3172 3173 synchronized (mPackages) { 3174 final PackageParser.Package pkg = mPackages.get(packageName); 3175 if (pkg == null) { 3176 throw new IllegalArgumentException("Unknown package: " + packageName); 3177 } 3178 3179 final BasePermission bp = mSettings.mPermissions.get(name); 3180 if (bp == null) { 3181 throw new IllegalArgumentException("Unknown permission: " + name); 3182 } 3183 3184 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3185 3186 sb = (SettingBase) pkg.mExtras; 3187 if (sb == null) { 3188 throw new IllegalArgumentException("Unknown package: " + packageName); 3189 } 3190 3191 final PermissionsState permissionsState = sb.getPermissionsState(); 3192 3193 if (permissionsState.revokeRuntimePermission(bp, userId) == 3194 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3195 return false; 3196 } 3197 3198 // Critical, after this call all should never have the permission. 3199 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3200 } 3201 3202 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3203 3204 return true; 3205 } 3206 3207 @Override 3208 public boolean isProtectedBroadcast(String actionName) { 3209 synchronized (mPackages) { 3210 return mProtectedBroadcasts.contains(actionName); 3211 } 3212 } 3213 3214 @Override 3215 public int checkSignatures(String pkg1, String pkg2) { 3216 synchronized (mPackages) { 3217 final PackageParser.Package p1 = mPackages.get(pkg1); 3218 final PackageParser.Package p2 = mPackages.get(pkg2); 3219 if (p1 == null || p1.mExtras == null 3220 || p2 == null || p2.mExtras == null) { 3221 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3222 } 3223 return compareSignatures(p1.mSignatures, p2.mSignatures); 3224 } 3225 } 3226 3227 @Override 3228 public int checkUidSignatures(int uid1, int uid2) { 3229 // Map to base uids. 3230 uid1 = UserHandle.getAppId(uid1); 3231 uid2 = UserHandle.getAppId(uid2); 3232 // reader 3233 synchronized (mPackages) { 3234 Signature[] s1; 3235 Signature[] s2; 3236 Object obj = mSettings.getUserIdLPr(uid1); 3237 if (obj != null) { 3238 if (obj instanceof SharedUserSetting) { 3239 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3240 } else if (obj instanceof PackageSetting) { 3241 s1 = ((PackageSetting)obj).signatures.mSignatures; 3242 } else { 3243 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3244 } 3245 } else { 3246 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3247 } 3248 obj = mSettings.getUserIdLPr(uid2); 3249 if (obj != null) { 3250 if (obj instanceof SharedUserSetting) { 3251 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3252 } else if (obj instanceof PackageSetting) { 3253 s2 = ((PackageSetting)obj).signatures.mSignatures; 3254 } else { 3255 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3256 } 3257 } else { 3258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3259 } 3260 return compareSignatures(s1, s2); 3261 } 3262 } 3263 3264 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3265 final long identity = Binder.clearCallingIdentity(); 3266 try { 3267 if (sb instanceof SharedUserSetting) { 3268 SharedUserSetting sus = (SharedUserSetting) sb; 3269 final int packageCount = sus.packages.size(); 3270 for (int i = 0; i < packageCount; i++) { 3271 PackageSetting susPs = sus.packages.valueAt(i); 3272 if (userId == UserHandle.USER_ALL) { 3273 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3274 } else { 3275 final int uid = UserHandle.getUid(userId, susPs.appId); 3276 killUid(uid, reason); 3277 } 3278 } 3279 } else if (sb instanceof PackageSetting) { 3280 PackageSetting ps = (PackageSetting) sb; 3281 if (userId == UserHandle.USER_ALL) { 3282 killApplication(ps.pkg.packageName, ps.appId, reason); 3283 } else { 3284 final int uid = UserHandle.getUid(userId, ps.appId); 3285 killUid(uid, reason); 3286 } 3287 } 3288 } finally { 3289 Binder.restoreCallingIdentity(identity); 3290 } 3291 } 3292 3293 private static void killUid(int uid, String reason) { 3294 IActivityManager am = ActivityManagerNative.getDefault(); 3295 if (am != null) { 3296 try { 3297 am.killUid(uid, reason); 3298 } catch (RemoteException e) { 3299 /* ignore - same process */ 3300 } 3301 } 3302 } 3303 3304 /** 3305 * Compares two sets of signatures. Returns: 3306 * <br /> 3307 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3308 * <br /> 3309 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3310 * <br /> 3311 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3312 * <br /> 3313 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3314 * <br /> 3315 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3316 */ 3317 static int compareSignatures(Signature[] s1, Signature[] s2) { 3318 if (s1 == null) { 3319 return s2 == null 3320 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3321 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3322 } 3323 3324 if (s2 == null) { 3325 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3326 } 3327 3328 if (s1.length != s2.length) { 3329 return PackageManager.SIGNATURE_NO_MATCH; 3330 } 3331 3332 // Since both signature sets are of size 1, we can compare without HashSets. 3333 if (s1.length == 1) { 3334 return s1[0].equals(s2[0]) ? 3335 PackageManager.SIGNATURE_MATCH : 3336 PackageManager.SIGNATURE_NO_MATCH; 3337 } 3338 3339 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3340 for (Signature sig : s1) { 3341 set1.add(sig); 3342 } 3343 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3344 for (Signature sig : s2) { 3345 set2.add(sig); 3346 } 3347 // Make sure s2 contains all signatures in s1. 3348 if (set1.equals(set2)) { 3349 return PackageManager.SIGNATURE_MATCH; 3350 } 3351 return PackageManager.SIGNATURE_NO_MATCH; 3352 } 3353 3354 /** 3355 * If the database version for this type of package (internal storage or 3356 * external storage) is less than the version where package signatures 3357 * were updated, return true. 3358 */ 3359 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3360 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3361 DatabaseVersion.SIGNATURE_END_ENTITY)) 3362 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3363 DatabaseVersion.SIGNATURE_END_ENTITY)); 3364 } 3365 3366 /** 3367 * Used for backward compatibility to make sure any packages with 3368 * certificate chains get upgraded to the new style. {@code existingSigs} 3369 * will be in the old format (since they were stored on disk from before the 3370 * system upgrade) and {@code scannedSigs} will be in the newer format. 3371 */ 3372 private int compareSignaturesCompat(PackageSignatures existingSigs, 3373 PackageParser.Package scannedPkg) { 3374 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3375 return PackageManager.SIGNATURE_NO_MATCH; 3376 } 3377 3378 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3379 for (Signature sig : existingSigs.mSignatures) { 3380 existingSet.add(sig); 3381 } 3382 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3383 for (Signature sig : scannedPkg.mSignatures) { 3384 try { 3385 Signature[] chainSignatures = sig.getChainSignatures(); 3386 for (Signature chainSig : chainSignatures) { 3387 scannedCompatSet.add(chainSig); 3388 } 3389 } catch (CertificateEncodingException e) { 3390 scannedCompatSet.add(sig); 3391 } 3392 } 3393 /* 3394 * Make sure the expanded scanned set contains all signatures in the 3395 * existing one. 3396 */ 3397 if (scannedCompatSet.equals(existingSet)) { 3398 // Migrate the old signatures to the new scheme. 3399 existingSigs.assignSignatures(scannedPkg.mSignatures); 3400 // The new KeySets will be re-added later in the scanning process. 3401 synchronized (mPackages) { 3402 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3403 } 3404 return PackageManager.SIGNATURE_MATCH; 3405 } 3406 return PackageManager.SIGNATURE_NO_MATCH; 3407 } 3408 3409 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3410 if (isExternal(scannedPkg)) { 3411 return mSettings.isExternalDatabaseVersionOlderThan( 3412 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3413 } else { 3414 return mSettings.isInternalDatabaseVersionOlderThan( 3415 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3416 } 3417 } 3418 3419 private int compareSignaturesRecover(PackageSignatures existingSigs, 3420 PackageParser.Package scannedPkg) { 3421 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3422 return PackageManager.SIGNATURE_NO_MATCH; 3423 } 3424 3425 String msg = null; 3426 try { 3427 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3428 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3429 + scannedPkg.packageName); 3430 return PackageManager.SIGNATURE_MATCH; 3431 } 3432 } catch (CertificateException e) { 3433 msg = e.getMessage(); 3434 } 3435 3436 logCriticalInfo(Log.INFO, 3437 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3438 return PackageManager.SIGNATURE_NO_MATCH; 3439 } 3440 3441 @Override 3442 public String[] getPackagesForUid(int uid) { 3443 uid = UserHandle.getAppId(uid); 3444 // reader 3445 synchronized (mPackages) { 3446 Object obj = mSettings.getUserIdLPr(uid); 3447 if (obj instanceof SharedUserSetting) { 3448 final SharedUserSetting sus = (SharedUserSetting) obj; 3449 final int N = sus.packages.size(); 3450 final String[] res = new String[N]; 3451 final Iterator<PackageSetting> it = sus.packages.iterator(); 3452 int i = 0; 3453 while (it.hasNext()) { 3454 res[i++] = it.next().name; 3455 } 3456 return res; 3457 } else if (obj instanceof PackageSetting) { 3458 final PackageSetting ps = (PackageSetting) obj; 3459 return new String[] { ps.name }; 3460 } 3461 } 3462 return null; 3463 } 3464 3465 @Override 3466 public String getNameForUid(int uid) { 3467 // reader 3468 synchronized (mPackages) { 3469 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3470 if (obj instanceof SharedUserSetting) { 3471 final SharedUserSetting sus = (SharedUserSetting) obj; 3472 return sus.name + ":" + sus.userId; 3473 } else if (obj instanceof PackageSetting) { 3474 final PackageSetting ps = (PackageSetting) obj; 3475 return ps.name; 3476 } 3477 } 3478 return null; 3479 } 3480 3481 @Override 3482 public int getUidForSharedUser(String sharedUserName) { 3483 if(sharedUserName == null) { 3484 return -1; 3485 } 3486 // reader 3487 synchronized (mPackages) { 3488 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3489 if (suid == null) { 3490 return -1; 3491 } 3492 return suid.userId; 3493 } 3494 } 3495 3496 @Override 3497 public int getFlagsForUid(int uid) { 3498 synchronized (mPackages) { 3499 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3500 if (obj instanceof SharedUserSetting) { 3501 final SharedUserSetting sus = (SharedUserSetting) obj; 3502 return sus.pkgFlags; 3503 } else if (obj instanceof PackageSetting) { 3504 final PackageSetting ps = (PackageSetting) obj; 3505 return ps.pkgFlags; 3506 } 3507 } 3508 return 0; 3509 } 3510 3511 @Override 3512 public int getPrivateFlagsForUid(int uid) { 3513 synchronized (mPackages) { 3514 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3515 if (obj instanceof SharedUserSetting) { 3516 final SharedUserSetting sus = (SharedUserSetting) obj; 3517 return sus.pkgPrivateFlags; 3518 } else if (obj instanceof PackageSetting) { 3519 final PackageSetting ps = (PackageSetting) obj; 3520 return ps.pkgPrivateFlags; 3521 } 3522 } 3523 return 0; 3524 } 3525 3526 @Override 3527 public boolean isUidPrivileged(int uid) { 3528 uid = UserHandle.getAppId(uid); 3529 // reader 3530 synchronized (mPackages) { 3531 Object obj = mSettings.getUserIdLPr(uid); 3532 if (obj instanceof SharedUserSetting) { 3533 final SharedUserSetting sus = (SharedUserSetting) obj; 3534 final Iterator<PackageSetting> it = sus.packages.iterator(); 3535 while (it.hasNext()) { 3536 if (it.next().isPrivileged()) { 3537 return true; 3538 } 3539 } 3540 } else if (obj instanceof PackageSetting) { 3541 final PackageSetting ps = (PackageSetting) obj; 3542 return ps.isPrivileged(); 3543 } 3544 } 3545 return false; 3546 } 3547 3548 @Override 3549 public String[] getAppOpPermissionPackages(String permissionName) { 3550 synchronized (mPackages) { 3551 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3552 if (pkgs == null) { 3553 return null; 3554 } 3555 return pkgs.toArray(new String[pkgs.size()]); 3556 } 3557 } 3558 3559 @Override 3560 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3561 int flags, int userId) { 3562 if (!sUserManager.exists(userId)) return null; 3563 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3564 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3565 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3566 } 3567 3568 @Override 3569 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3570 IntentFilter filter, int match, ComponentName activity) { 3571 final int userId = UserHandle.getCallingUserId(); 3572 if (DEBUG_PREFERRED) { 3573 Log.v(TAG, "setLastChosenActivity intent=" + intent 3574 + " resolvedType=" + resolvedType 3575 + " flags=" + flags 3576 + " filter=" + filter 3577 + " match=" + match 3578 + " activity=" + activity); 3579 filter.dump(new PrintStreamPrinter(System.out), " "); 3580 } 3581 intent.setComponent(null); 3582 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3583 // Find any earlier preferred or last chosen entries and nuke them 3584 findPreferredActivity(intent, resolvedType, 3585 flags, query, 0, false, true, false, userId); 3586 // Add the new activity as the last chosen for this filter 3587 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3588 "Setting last chosen"); 3589 } 3590 3591 @Override 3592 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3593 final int userId = UserHandle.getCallingUserId(); 3594 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3595 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3596 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3597 false, false, false, userId); 3598 } 3599 3600 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3601 int flags, List<ResolveInfo> query, int userId) { 3602 if (query != null) { 3603 final int N = query.size(); 3604 if (N == 1) { 3605 return query.get(0); 3606 } else if (N > 1) { 3607 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3608 // If there is more than one activity with the same priority, 3609 // then let the user decide between them. 3610 ResolveInfo r0 = query.get(0); 3611 ResolveInfo r1 = query.get(1); 3612 if (DEBUG_INTENT_MATCHING || debug) { 3613 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3614 + r1.activityInfo.name + "=" + r1.priority); 3615 } 3616 // If the first activity has a higher priority, or a different 3617 // default, then it is always desireable to pick it. 3618 if (r0.priority != r1.priority 3619 || r0.preferredOrder != r1.preferredOrder 3620 || r0.isDefault != r1.isDefault) { 3621 return query.get(0); 3622 } 3623 // If we have saved a preference for a preferred activity for 3624 // this Intent, use that. 3625 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3626 flags, query, r0.priority, true, false, debug, userId); 3627 if (ri != null) { 3628 return ri; 3629 } 3630 if (userId != 0) { 3631 ri = new ResolveInfo(mResolveInfo); 3632 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3633 ri.activityInfo.applicationInfo = new ApplicationInfo( 3634 ri.activityInfo.applicationInfo); 3635 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3636 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3637 return ri; 3638 } 3639 return mResolveInfo; 3640 } 3641 } 3642 return null; 3643 } 3644 3645 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3646 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3647 final int N = query.size(); 3648 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3649 .get(userId); 3650 // Get the list of persistent preferred activities that handle the intent 3651 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3652 List<PersistentPreferredActivity> pprefs = ppir != null 3653 ? ppir.queryIntent(intent, resolvedType, 3654 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3655 : null; 3656 if (pprefs != null && pprefs.size() > 0) { 3657 final int M = pprefs.size(); 3658 for (int i=0; i<M; i++) { 3659 final PersistentPreferredActivity ppa = pprefs.get(i); 3660 if (DEBUG_PREFERRED || debug) { 3661 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3662 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3663 + "\n component=" + ppa.mComponent); 3664 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3665 } 3666 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3667 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3668 if (DEBUG_PREFERRED || debug) { 3669 Slog.v(TAG, "Found persistent preferred activity:"); 3670 if (ai != null) { 3671 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3672 } else { 3673 Slog.v(TAG, " null"); 3674 } 3675 } 3676 if (ai == null) { 3677 // This previously registered persistent preferred activity 3678 // component is no longer known. Ignore it and do NOT remove it. 3679 continue; 3680 } 3681 for (int j=0; j<N; j++) { 3682 final ResolveInfo ri = query.get(j); 3683 if (!ri.activityInfo.applicationInfo.packageName 3684 .equals(ai.applicationInfo.packageName)) { 3685 continue; 3686 } 3687 if (!ri.activityInfo.name.equals(ai.name)) { 3688 continue; 3689 } 3690 // Found a persistent preference that can handle the intent. 3691 if (DEBUG_PREFERRED || debug) { 3692 Slog.v(TAG, "Returning persistent preferred activity: " + 3693 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3694 } 3695 return ri; 3696 } 3697 } 3698 } 3699 return null; 3700 } 3701 3702 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3703 List<ResolveInfo> query, int priority, boolean always, 3704 boolean removeMatches, boolean debug, int userId) { 3705 if (!sUserManager.exists(userId)) return null; 3706 // writer 3707 synchronized (mPackages) { 3708 if (intent.getSelector() != null) { 3709 intent = intent.getSelector(); 3710 } 3711 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3712 3713 // Try to find a matching persistent preferred activity. 3714 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3715 debug, userId); 3716 3717 // If a persistent preferred activity matched, use it. 3718 if (pri != null) { 3719 return pri; 3720 } 3721 3722 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3723 // Get the list of preferred activities that handle the intent 3724 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3725 List<PreferredActivity> prefs = pir != null 3726 ? pir.queryIntent(intent, resolvedType, 3727 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3728 : null; 3729 if (prefs != null && prefs.size() > 0) { 3730 boolean changed = false; 3731 try { 3732 // First figure out how good the original match set is. 3733 // We will only allow preferred activities that came 3734 // from the same match quality. 3735 int match = 0; 3736 3737 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3738 3739 final int N = query.size(); 3740 for (int j=0; j<N; j++) { 3741 final ResolveInfo ri = query.get(j); 3742 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3743 + ": 0x" + Integer.toHexString(match)); 3744 if (ri.match > match) { 3745 match = ri.match; 3746 } 3747 } 3748 3749 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3750 + Integer.toHexString(match)); 3751 3752 match &= IntentFilter.MATCH_CATEGORY_MASK; 3753 final int M = prefs.size(); 3754 for (int i=0; i<M; i++) { 3755 final PreferredActivity pa = prefs.get(i); 3756 if (DEBUG_PREFERRED || debug) { 3757 Slog.v(TAG, "Checking PreferredActivity ds=" 3758 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3759 + "\n component=" + pa.mPref.mComponent); 3760 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3761 } 3762 if (pa.mPref.mMatch != match) { 3763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3764 + Integer.toHexString(pa.mPref.mMatch)); 3765 continue; 3766 } 3767 // If it's not an "always" type preferred activity and that's what we're 3768 // looking for, skip it. 3769 if (always && !pa.mPref.mAlways) { 3770 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3771 continue; 3772 } 3773 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3774 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3775 if (DEBUG_PREFERRED || debug) { 3776 Slog.v(TAG, "Found preferred activity:"); 3777 if (ai != null) { 3778 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3779 } else { 3780 Slog.v(TAG, " null"); 3781 } 3782 } 3783 if (ai == null) { 3784 // This previously registered preferred activity 3785 // component is no longer known. Most likely an update 3786 // to the app was installed and in the new version this 3787 // component no longer exists. Clean it up by removing 3788 // it from the preferred activities list, and skip it. 3789 Slog.w(TAG, "Removing dangling preferred activity: " 3790 + pa.mPref.mComponent); 3791 pir.removeFilter(pa); 3792 changed = true; 3793 continue; 3794 } 3795 for (int j=0; j<N; j++) { 3796 final ResolveInfo ri = query.get(j); 3797 if (!ri.activityInfo.applicationInfo.packageName 3798 .equals(ai.applicationInfo.packageName)) { 3799 continue; 3800 } 3801 if (!ri.activityInfo.name.equals(ai.name)) { 3802 continue; 3803 } 3804 3805 if (removeMatches) { 3806 pir.removeFilter(pa); 3807 changed = true; 3808 if (DEBUG_PREFERRED) { 3809 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3810 } 3811 break; 3812 } 3813 3814 // Okay we found a previously set preferred or last chosen app. 3815 // If the result set is different from when this 3816 // was created, we need to clear it and re-ask the 3817 // user their preference, if we're looking for an "always" type entry. 3818 if (always && !pa.mPref.sameSet(query)) { 3819 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3820 + intent + " type " + resolvedType); 3821 if (DEBUG_PREFERRED) { 3822 Slog.v(TAG, "Removing preferred activity since set changed " 3823 + pa.mPref.mComponent); 3824 } 3825 pir.removeFilter(pa); 3826 // Re-add the filter as a "last chosen" entry (!always) 3827 PreferredActivity lastChosen = new PreferredActivity( 3828 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3829 pir.addFilter(lastChosen); 3830 changed = true; 3831 return null; 3832 } 3833 3834 // Yay! Either the set matched or we're looking for the last chosen 3835 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3836 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3837 return ri; 3838 } 3839 } 3840 } finally { 3841 if (changed) { 3842 if (DEBUG_PREFERRED) { 3843 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3844 } 3845 scheduleWritePackageRestrictionsLocked(userId); 3846 } 3847 } 3848 } 3849 } 3850 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3851 return null; 3852 } 3853 3854 /* 3855 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3856 */ 3857 @Override 3858 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3859 int targetUserId) { 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3862 List<CrossProfileIntentFilter> matches = 3863 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3864 if (matches != null) { 3865 int size = matches.size(); 3866 for (int i = 0; i < size; i++) { 3867 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3868 } 3869 } 3870 return false; 3871 } 3872 3873 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3874 String resolvedType, int userId) { 3875 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3876 if (resolver != null) { 3877 return resolver.queryIntent(intent, resolvedType, false, userId); 3878 } 3879 return null; 3880 } 3881 3882 @Override 3883 public List<ResolveInfo> queryIntentActivities(Intent intent, 3884 String resolvedType, int flags, int userId) { 3885 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3886 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3887 ComponentName comp = intent.getComponent(); 3888 if (comp == null) { 3889 if (intent.getSelector() != null) { 3890 intent = intent.getSelector(); 3891 comp = intent.getComponent(); 3892 } 3893 } 3894 3895 if (comp != null) { 3896 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3897 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3898 if (ai != null) { 3899 final ResolveInfo ri = new ResolveInfo(); 3900 ri.activityInfo = ai; 3901 list.add(ri); 3902 } 3903 return list; 3904 } 3905 3906 // reader 3907 synchronized (mPackages) { 3908 final String pkgName = intent.getPackage(); 3909 if (pkgName == null) { 3910 List<CrossProfileIntentFilter> matchingFilters = 3911 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3912 // Check for results that need to skip the current profile. 3913 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3914 resolvedType, flags, userId); 3915 if (resolveInfo != null) { 3916 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3917 result.add(resolveInfo); 3918 return filterIfNotPrimaryUser(result, userId); 3919 } 3920 // Check for cross profile results. 3921 resolveInfo = queryCrossProfileIntents( 3922 matchingFilters, intent, resolvedType, flags, userId); 3923 3924 // Check for results in the current profile. 3925 List<ResolveInfo> result = mActivities.queryIntent( 3926 intent, resolvedType, flags, userId); 3927 if (resolveInfo != null) { 3928 result.add(resolveInfo); 3929 Collections.sort(result, mResolvePrioritySorter); 3930 } 3931 result = filterIfNotPrimaryUser(result, userId); 3932 if (result.size() > 1 && hasWebURI(intent)) { 3933 return filterCandidatesWithDomainPreferedActivitiesLPr(result); 3934 } 3935 return result; 3936 } 3937 final PackageParser.Package pkg = mPackages.get(pkgName); 3938 if (pkg != null) { 3939 return filterIfNotPrimaryUser( 3940 mActivities.queryIntentForPackage( 3941 intent, resolvedType, flags, pkg.activities, userId), 3942 userId); 3943 } 3944 return new ArrayList<ResolveInfo>(); 3945 } 3946 } 3947 3948 /** 3949 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3950 * 3951 * @return filtered list 3952 */ 3953 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3954 if (userId == UserHandle.USER_OWNER) { 3955 return resolveInfos; 3956 } 3957 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3958 ResolveInfo info = resolveInfos.get(i); 3959 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3960 resolveInfos.remove(i); 3961 } 3962 } 3963 return resolveInfos; 3964 } 3965 3966 private static boolean hasWebURI(Intent intent) { 3967 if (intent.getData() == null) { 3968 return false; 3969 } 3970 final String scheme = intent.getScheme(); 3971 if (TextUtils.isEmpty(scheme)) { 3972 return false; 3973 } 3974 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 3975 } 3976 3977 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 3978 List<ResolveInfo> candidates) { 3979 if (DEBUG_PREFERRED) { 3980 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3981 candidates.size()); 3982 } 3983 3984 final int userId = UserHandle.getCallingUserId(); 3985 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 3986 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 3987 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 3988 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 3989 3990 synchronized (mPackages) { 3991 final int count = candidates.size(); 3992 // First, try to use the domain prefered App 3993 for (int n=0; n<count; n++) { 3994 ResolveInfo info = candidates.get(n); 3995 String packageName = info.activityInfo.packageName; 3996 PackageSetting ps = mSettings.mPackages.get(packageName); 3997 if (ps != null) { 3998 // Try to get the status from User settings first 3999 int status = getDomainVerificationStatusLPr(ps, userId); 4000 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4001 result.add(info); 4002 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4003 neverList.add(info); 4004 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4005 undefinedList.add(info); 4006 } 4007 // Add to the special match all list (Browser use case) 4008 if (info.handleAllWebDataURI) { 4009 matchAllList.add(info); 4010 } 4011 } 4012 } 4013 // If there is nothing selected, add all candidates and remove the ones that the User 4014 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4015 // also remove any Browser Apps ones. 4016 // If there is still none after this pass, add all undefined one and Browser Apps and 4017 // let the User decide with the Disambiguation dialog if there are several ones. 4018 if (result.size() == 0) { 4019 result.addAll(candidates); 4020 } 4021 result.removeAll(neverList); 4022 result.removeAll(matchAllList); 4023 if (result.size() == 0) { 4024 result.addAll(undefinedList); 4025 result.addAll(matchAllList); 4026 } 4027 } 4028 if (DEBUG_PREFERRED) { 4029 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4030 result.size()); 4031 } 4032 return result; 4033 } 4034 4035 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4036 int status = ps.getDomainVerificationStatusForUser(userId); 4037 // if none available, get the master status 4038 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4039 if (ps.getIntentFilterVerificationInfo() != null) { 4040 status = ps.getIntentFilterVerificationInfo().getStatus(); 4041 } 4042 } 4043 return status; 4044 } 4045 4046 private ResolveInfo querySkipCurrentProfileIntents( 4047 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4048 int flags, int sourceUserId) { 4049 if (matchingFilters != null) { 4050 int size = matchingFilters.size(); 4051 for (int i = 0; i < size; i ++) { 4052 CrossProfileIntentFilter filter = matchingFilters.get(i); 4053 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4054 // Checking if there are activities in the target user that can handle the 4055 // intent. 4056 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4057 flags, sourceUserId); 4058 if (resolveInfo != null) { 4059 return resolveInfo; 4060 } 4061 } 4062 } 4063 } 4064 return null; 4065 } 4066 4067 // Return matching ResolveInfo if any for skip current profile intent filters. 4068 private ResolveInfo queryCrossProfileIntents( 4069 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4070 int flags, int sourceUserId) { 4071 if (matchingFilters != null) { 4072 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4073 // match the same intent. For performance reasons, it is better not to 4074 // run queryIntent twice for the same userId 4075 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4076 int size = matchingFilters.size(); 4077 for (int i = 0; i < size; i++) { 4078 CrossProfileIntentFilter filter = matchingFilters.get(i); 4079 int targetUserId = filter.getTargetUserId(); 4080 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4081 && !alreadyTriedUserIds.get(targetUserId)) { 4082 // Checking if there are activities in the target user that can handle the 4083 // intent. 4084 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4085 flags, sourceUserId); 4086 if (resolveInfo != null) return resolveInfo; 4087 alreadyTriedUserIds.put(targetUserId, true); 4088 } 4089 } 4090 } 4091 return null; 4092 } 4093 4094 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4095 String resolvedType, int flags, int sourceUserId) { 4096 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4097 resolvedType, flags, filter.getTargetUserId()); 4098 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4099 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4100 } 4101 return null; 4102 } 4103 4104 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4105 int sourceUserId, int targetUserId) { 4106 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4107 String className; 4108 if (targetUserId == UserHandle.USER_OWNER) { 4109 className = FORWARD_INTENT_TO_USER_OWNER; 4110 } else { 4111 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4112 } 4113 ComponentName forwardingActivityComponentName = new ComponentName( 4114 mAndroidApplication.packageName, className); 4115 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4116 sourceUserId); 4117 if (targetUserId == UserHandle.USER_OWNER) { 4118 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4119 forwardingResolveInfo.noResourceId = true; 4120 } 4121 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4122 forwardingResolveInfo.priority = 0; 4123 forwardingResolveInfo.preferredOrder = 0; 4124 forwardingResolveInfo.match = 0; 4125 forwardingResolveInfo.isDefault = true; 4126 forwardingResolveInfo.filter = filter; 4127 forwardingResolveInfo.targetUserId = targetUserId; 4128 return forwardingResolveInfo; 4129 } 4130 4131 @Override 4132 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4133 Intent[] specifics, String[] specificTypes, Intent intent, 4134 String resolvedType, int flags, int userId) { 4135 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4136 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4137 false, "query intent activity options"); 4138 final String resultsAction = intent.getAction(); 4139 4140 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4141 | PackageManager.GET_RESOLVED_FILTER, userId); 4142 4143 if (DEBUG_INTENT_MATCHING) { 4144 Log.v(TAG, "Query " + intent + ": " + results); 4145 } 4146 4147 int specificsPos = 0; 4148 int N; 4149 4150 // todo: note that the algorithm used here is O(N^2). This 4151 // isn't a problem in our current environment, but if we start running 4152 // into situations where we have more than 5 or 10 matches then this 4153 // should probably be changed to something smarter... 4154 4155 // First we go through and resolve each of the specific items 4156 // that were supplied, taking care of removing any corresponding 4157 // duplicate items in the generic resolve list. 4158 if (specifics != null) { 4159 for (int i=0; i<specifics.length; i++) { 4160 final Intent sintent = specifics[i]; 4161 if (sintent == null) { 4162 continue; 4163 } 4164 4165 if (DEBUG_INTENT_MATCHING) { 4166 Log.v(TAG, "Specific #" + i + ": " + sintent); 4167 } 4168 4169 String action = sintent.getAction(); 4170 if (resultsAction != null && resultsAction.equals(action)) { 4171 // If this action was explicitly requested, then don't 4172 // remove things that have it. 4173 action = null; 4174 } 4175 4176 ResolveInfo ri = null; 4177 ActivityInfo ai = null; 4178 4179 ComponentName comp = sintent.getComponent(); 4180 if (comp == null) { 4181 ri = resolveIntent( 4182 sintent, 4183 specificTypes != null ? specificTypes[i] : null, 4184 flags, userId); 4185 if (ri == null) { 4186 continue; 4187 } 4188 if (ri == mResolveInfo) { 4189 // ACK! Must do something better with this. 4190 } 4191 ai = ri.activityInfo; 4192 comp = new ComponentName(ai.applicationInfo.packageName, 4193 ai.name); 4194 } else { 4195 ai = getActivityInfo(comp, flags, userId); 4196 if (ai == null) { 4197 continue; 4198 } 4199 } 4200 4201 // Look for any generic query activities that are duplicates 4202 // of this specific one, and remove them from the results. 4203 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4204 N = results.size(); 4205 int j; 4206 for (j=specificsPos; j<N; j++) { 4207 ResolveInfo sri = results.get(j); 4208 if ((sri.activityInfo.name.equals(comp.getClassName()) 4209 && sri.activityInfo.applicationInfo.packageName.equals( 4210 comp.getPackageName())) 4211 || (action != null && sri.filter.matchAction(action))) { 4212 results.remove(j); 4213 if (DEBUG_INTENT_MATCHING) Log.v( 4214 TAG, "Removing duplicate item from " + j 4215 + " due to specific " + specificsPos); 4216 if (ri == null) { 4217 ri = sri; 4218 } 4219 j--; 4220 N--; 4221 } 4222 } 4223 4224 // Add this specific item to its proper place. 4225 if (ri == null) { 4226 ri = new ResolveInfo(); 4227 ri.activityInfo = ai; 4228 } 4229 results.add(specificsPos, ri); 4230 ri.specificIndex = i; 4231 specificsPos++; 4232 } 4233 } 4234 4235 // Now we go through the remaining generic results and remove any 4236 // duplicate actions that are found here. 4237 N = results.size(); 4238 for (int i=specificsPos; i<N-1; i++) { 4239 final ResolveInfo rii = results.get(i); 4240 if (rii.filter == null) { 4241 continue; 4242 } 4243 4244 // Iterate over all of the actions of this result's intent 4245 // filter... typically this should be just one. 4246 final Iterator<String> it = rii.filter.actionsIterator(); 4247 if (it == null) { 4248 continue; 4249 } 4250 while (it.hasNext()) { 4251 final String action = it.next(); 4252 if (resultsAction != null && resultsAction.equals(action)) { 4253 // If this action was explicitly requested, then don't 4254 // remove things that have it. 4255 continue; 4256 } 4257 for (int j=i+1; j<N; j++) { 4258 final ResolveInfo rij = results.get(j); 4259 if (rij.filter != null && rij.filter.hasAction(action)) { 4260 results.remove(j); 4261 if (DEBUG_INTENT_MATCHING) Log.v( 4262 TAG, "Removing duplicate item from " + j 4263 + " due to action " + action + " at " + i); 4264 j--; 4265 N--; 4266 } 4267 } 4268 } 4269 4270 // If the caller didn't request filter information, drop it now 4271 // so we don't have to marshall/unmarshall it. 4272 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4273 rii.filter = null; 4274 } 4275 } 4276 4277 // Filter out the caller activity if so requested. 4278 if (caller != null) { 4279 N = results.size(); 4280 for (int i=0; i<N; i++) { 4281 ActivityInfo ainfo = results.get(i).activityInfo; 4282 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4283 && caller.getClassName().equals(ainfo.name)) { 4284 results.remove(i); 4285 break; 4286 } 4287 } 4288 } 4289 4290 // If the caller didn't request filter information, 4291 // drop them now so we don't have to 4292 // marshall/unmarshall it. 4293 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4294 N = results.size(); 4295 for (int i=0; i<N; i++) { 4296 results.get(i).filter = null; 4297 } 4298 } 4299 4300 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4301 return results; 4302 } 4303 4304 @Override 4305 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4306 int userId) { 4307 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4308 ComponentName comp = intent.getComponent(); 4309 if (comp == null) { 4310 if (intent.getSelector() != null) { 4311 intent = intent.getSelector(); 4312 comp = intent.getComponent(); 4313 } 4314 } 4315 if (comp != null) { 4316 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4317 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4318 if (ai != null) { 4319 ResolveInfo ri = new ResolveInfo(); 4320 ri.activityInfo = ai; 4321 list.add(ri); 4322 } 4323 return list; 4324 } 4325 4326 // reader 4327 synchronized (mPackages) { 4328 String pkgName = intent.getPackage(); 4329 if (pkgName == null) { 4330 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4331 } 4332 final PackageParser.Package pkg = mPackages.get(pkgName); 4333 if (pkg != null) { 4334 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4335 userId); 4336 } 4337 return null; 4338 } 4339 } 4340 4341 @Override 4342 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4343 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4344 if (!sUserManager.exists(userId)) return null; 4345 if (query != null) { 4346 if (query.size() >= 1) { 4347 // If there is more than one service with the same priority, 4348 // just arbitrarily pick the first one. 4349 return query.get(0); 4350 } 4351 } 4352 return null; 4353 } 4354 4355 @Override 4356 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4357 int userId) { 4358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4359 ComponentName comp = intent.getComponent(); 4360 if (comp == null) { 4361 if (intent.getSelector() != null) { 4362 intent = intent.getSelector(); 4363 comp = intent.getComponent(); 4364 } 4365 } 4366 if (comp != null) { 4367 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4368 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4369 if (si != null) { 4370 final ResolveInfo ri = new ResolveInfo(); 4371 ri.serviceInfo = si; 4372 list.add(ri); 4373 } 4374 return list; 4375 } 4376 4377 // reader 4378 synchronized (mPackages) { 4379 String pkgName = intent.getPackage(); 4380 if (pkgName == null) { 4381 return mServices.queryIntent(intent, resolvedType, flags, userId); 4382 } 4383 final PackageParser.Package pkg = mPackages.get(pkgName); 4384 if (pkg != null) { 4385 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4386 userId); 4387 } 4388 return null; 4389 } 4390 } 4391 4392 @Override 4393 public List<ResolveInfo> queryIntentContentProviders( 4394 Intent intent, String resolvedType, int flags, int userId) { 4395 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4396 ComponentName comp = intent.getComponent(); 4397 if (comp == null) { 4398 if (intent.getSelector() != null) { 4399 intent = intent.getSelector(); 4400 comp = intent.getComponent(); 4401 } 4402 } 4403 if (comp != null) { 4404 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4405 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4406 if (pi != null) { 4407 final ResolveInfo ri = new ResolveInfo(); 4408 ri.providerInfo = pi; 4409 list.add(ri); 4410 } 4411 return list; 4412 } 4413 4414 // reader 4415 synchronized (mPackages) { 4416 String pkgName = intent.getPackage(); 4417 if (pkgName == null) { 4418 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4419 } 4420 final PackageParser.Package pkg = mPackages.get(pkgName); 4421 if (pkg != null) { 4422 return mProviders.queryIntentForPackage( 4423 intent, resolvedType, flags, pkg.providers, userId); 4424 } 4425 return null; 4426 } 4427 } 4428 4429 @Override 4430 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4431 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4432 4433 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4434 4435 // writer 4436 synchronized (mPackages) { 4437 ArrayList<PackageInfo> list; 4438 if (listUninstalled) { 4439 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4440 for (PackageSetting ps : mSettings.mPackages.values()) { 4441 PackageInfo pi; 4442 if (ps.pkg != null) { 4443 pi = generatePackageInfo(ps.pkg, flags, userId); 4444 } else { 4445 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4446 } 4447 if (pi != null) { 4448 list.add(pi); 4449 } 4450 } 4451 } else { 4452 list = new ArrayList<PackageInfo>(mPackages.size()); 4453 for (PackageParser.Package p : mPackages.values()) { 4454 PackageInfo pi = generatePackageInfo(p, flags, userId); 4455 if (pi != null) { 4456 list.add(pi); 4457 } 4458 } 4459 } 4460 4461 return new ParceledListSlice<PackageInfo>(list); 4462 } 4463 } 4464 4465 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4466 String[] permissions, boolean[] tmp, int flags, int userId) { 4467 int numMatch = 0; 4468 final PermissionsState permissionsState = ps.getPermissionsState(); 4469 for (int i=0; i<permissions.length; i++) { 4470 final String permission = permissions[i]; 4471 if (permissionsState.hasPermission(permission, userId)) { 4472 tmp[i] = true; 4473 numMatch++; 4474 } else { 4475 tmp[i] = false; 4476 } 4477 } 4478 if (numMatch == 0) { 4479 return; 4480 } 4481 PackageInfo pi; 4482 if (ps.pkg != null) { 4483 pi = generatePackageInfo(ps.pkg, flags, userId); 4484 } else { 4485 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4486 } 4487 // The above might return null in cases of uninstalled apps or install-state 4488 // skew across users/profiles. 4489 if (pi != null) { 4490 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4491 if (numMatch == permissions.length) { 4492 pi.requestedPermissions = permissions; 4493 } else { 4494 pi.requestedPermissions = new String[numMatch]; 4495 numMatch = 0; 4496 for (int i=0; i<permissions.length; i++) { 4497 if (tmp[i]) { 4498 pi.requestedPermissions[numMatch] = permissions[i]; 4499 numMatch++; 4500 } 4501 } 4502 } 4503 } 4504 list.add(pi); 4505 } 4506 } 4507 4508 @Override 4509 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4510 String[] permissions, int flags, int userId) { 4511 if (!sUserManager.exists(userId)) return null; 4512 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4513 4514 // writer 4515 synchronized (mPackages) { 4516 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4517 boolean[] tmpBools = new boolean[permissions.length]; 4518 if (listUninstalled) { 4519 for (PackageSetting ps : mSettings.mPackages.values()) { 4520 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4521 } 4522 } else { 4523 for (PackageParser.Package pkg : mPackages.values()) { 4524 PackageSetting ps = (PackageSetting)pkg.mExtras; 4525 if (ps != null) { 4526 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4527 userId); 4528 } 4529 } 4530 } 4531 4532 return new ParceledListSlice<PackageInfo>(list); 4533 } 4534 } 4535 4536 @Override 4537 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4538 if (!sUserManager.exists(userId)) return null; 4539 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4540 4541 // writer 4542 synchronized (mPackages) { 4543 ArrayList<ApplicationInfo> list; 4544 if (listUninstalled) { 4545 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4546 for (PackageSetting ps : mSettings.mPackages.values()) { 4547 ApplicationInfo ai; 4548 if (ps.pkg != null) { 4549 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4550 ps.readUserState(userId), userId); 4551 } else { 4552 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4553 } 4554 if (ai != null) { 4555 list.add(ai); 4556 } 4557 } 4558 } else { 4559 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4560 for (PackageParser.Package p : mPackages.values()) { 4561 if (p.mExtras != null) { 4562 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4563 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4564 if (ai != null) { 4565 list.add(ai); 4566 } 4567 } 4568 } 4569 } 4570 4571 return new ParceledListSlice<ApplicationInfo>(list); 4572 } 4573 } 4574 4575 public List<ApplicationInfo> getPersistentApplications(int flags) { 4576 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4577 4578 // reader 4579 synchronized (mPackages) { 4580 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4581 final int userId = UserHandle.getCallingUserId(); 4582 while (i.hasNext()) { 4583 final PackageParser.Package p = i.next(); 4584 if (p.applicationInfo != null 4585 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4586 && (!mSafeMode || isSystemApp(p))) { 4587 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4588 if (ps != null) { 4589 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4590 ps.readUserState(userId), userId); 4591 if (ai != null) { 4592 finalList.add(ai); 4593 } 4594 } 4595 } 4596 } 4597 } 4598 4599 return finalList; 4600 } 4601 4602 @Override 4603 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4604 if (!sUserManager.exists(userId)) return null; 4605 // reader 4606 synchronized (mPackages) { 4607 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4608 PackageSetting ps = provider != null 4609 ? mSettings.mPackages.get(provider.owner.packageName) 4610 : null; 4611 return ps != null 4612 && mSettings.isEnabledLPr(provider.info, flags, userId) 4613 && (!mSafeMode || (provider.info.applicationInfo.flags 4614 &ApplicationInfo.FLAG_SYSTEM) != 0) 4615 ? PackageParser.generateProviderInfo(provider, flags, 4616 ps.readUserState(userId), userId) 4617 : null; 4618 } 4619 } 4620 4621 /** 4622 * @deprecated 4623 */ 4624 @Deprecated 4625 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4626 // reader 4627 synchronized (mPackages) { 4628 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4629 .entrySet().iterator(); 4630 final int userId = UserHandle.getCallingUserId(); 4631 while (i.hasNext()) { 4632 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4633 PackageParser.Provider p = entry.getValue(); 4634 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4635 4636 if (ps != null && p.syncable 4637 && (!mSafeMode || (p.info.applicationInfo.flags 4638 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4639 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4640 ps.readUserState(userId), userId); 4641 if (info != null) { 4642 outNames.add(entry.getKey()); 4643 outInfo.add(info); 4644 } 4645 } 4646 } 4647 } 4648 } 4649 4650 @Override 4651 public List<ProviderInfo> queryContentProviders(String processName, 4652 int uid, int flags) { 4653 ArrayList<ProviderInfo> finalList = null; 4654 // reader 4655 synchronized (mPackages) { 4656 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4657 final int userId = processName != null ? 4658 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4659 while (i.hasNext()) { 4660 final PackageParser.Provider p = i.next(); 4661 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4662 if (ps != null && p.info.authority != null 4663 && (processName == null 4664 || (p.info.processName.equals(processName) 4665 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4666 && mSettings.isEnabledLPr(p.info, flags, userId) 4667 && (!mSafeMode 4668 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4669 if (finalList == null) { 4670 finalList = new ArrayList<ProviderInfo>(3); 4671 } 4672 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4673 ps.readUserState(userId), userId); 4674 if (info != null) { 4675 finalList.add(info); 4676 } 4677 } 4678 } 4679 } 4680 4681 if (finalList != null) { 4682 Collections.sort(finalList, mProviderInitOrderSorter); 4683 } 4684 4685 return finalList; 4686 } 4687 4688 @Override 4689 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4690 int flags) { 4691 // reader 4692 synchronized (mPackages) { 4693 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4694 return PackageParser.generateInstrumentationInfo(i, flags); 4695 } 4696 } 4697 4698 @Override 4699 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4700 int flags) { 4701 ArrayList<InstrumentationInfo> finalList = 4702 new ArrayList<InstrumentationInfo>(); 4703 4704 // reader 4705 synchronized (mPackages) { 4706 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4707 while (i.hasNext()) { 4708 final PackageParser.Instrumentation p = i.next(); 4709 if (targetPackage == null 4710 || targetPackage.equals(p.info.targetPackage)) { 4711 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4712 flags); 4713 if (ii != null) { 4714 finalList.add(ii); 4715 } 4716 } 4717 } 4718 } 4719 4720 return finalList; 4721 } 4722 4723 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4724 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4725 if (overlays == null) { 4726 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4727 return; 4728 } 4729 for (PackageParser.Package opkg : overlays.values()) { 4730 // Not much to do if idmap fails: we already logged the error 4731 // and we certainly don't want to abort installation of pkg simply 4732 // because an overlay didn't fit properly. For these reasons, 4733 // ignore the return value of createIdmapForPackagePairLI. 4734 createIdmapForPackagePairLI(pkg, opkg); 4735 } 4736 } 4737 4738 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4739 PackageParser.Package opkg) { 4740 if (!opkg.mTrustedOverlay) { 4741 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4742 opkg.baseCodePath + ": overlay not trusted"); 4743 return false; 4744 } 4745 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4746 if (overlaySet == null) { 4747 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4748 opkg.baseCodePath + " but target package has no known overlays"); 4749 return false; 4750 } 4751 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4752 // TODO: generate idmap for split APKs 4753 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4754 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4755 + opkg.baseCodePath); 4756 return false; 4757 } 4758 PackageParser.Package[] overlayArray = 4759 overlaySet.values().toArray(new PackageParser.Package[0]); 4760 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4761 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4762 return p1.mOverlayPriority - p2.mOverlayPriority; 4763 } 4764 }; 4765 Arrays.sort(overlayArray, cmp); 4766 4767 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4768 int i = 0; 4769 for (PackageParser.Package p : overlayArray) { 4770 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4771 } 4772 return true; 4773 } 4774 4775 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4776 final File[] files = dir.listFiles(); 4777 if (ArrayUtils.isEmpty(files)) { 4778 Log.d(TAG, "No files in app dir " + dir); 4779 return; 4780 } 4781 4782 if (DEBUG_PACKAGE_SCANNING) { 4783 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4784 + " flags=0x" + Integer.toHexString(parseFlags)); 4785 } 4786 4787 for (File file : files) { 4788 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4789 && !PackageInstallerService.isStageName(file.getName()); 4790 if (!isPackage) { 4791 // Ignore entries which are not packages 4792 continue; 4793 } 4794 try { 4795 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4796 scanFlags, currentTime, null); 4797 } catch (PackageManagerException e) { 4798 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4799 4800 // Delete invalid userdata apps 4801 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4802 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4803 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4804 if (file.isDirectory()) { 4805 mInstaller.rmPackageDir(file.getAbsolutePath()); 4806 } else { 4807 file.delete(); 4808 } 4809 } 4810 } 4811 } 4812 } 4813 4814 private static File getSettingsProblemFile() { 4815 File dataDir = Environment.getDataDirectory(); 4816 File systemDir = new File(dataDir, "system"); 4817 File fname = new File(systemDir, "uiderrors.txt"); 4818 return fname; 4819 } 4820 4821 static void reportSettingsProblem(int priority, String msg) { 4822 logCriticalInfo(priority, msg); 4823 } 4824 4825 static void logCriticalInfo(int priority, String msg) { 4826 Slog.println(priority, TAG, msg); 4827 EventLogTags.writePmCriticalInfo(msg); 4828 try { 4829 File fname = getSettingsProblemFile(); 4830 FileOutputStream out = new FileOutputStream(fname, true); 4831 PrintWriter pw = new FastPrintWriter(out); 4832 SimpleDateFormat formatter = new SimpleDateFormat(); 4833 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4834 pw.println(dateString + ": " + msg); 4835 pw.close(); 4836 FileUtils.setPermissions( 4837 fname.toString(), 4838 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4839 -1, -1); 4840 } catch (java.io.IOException e) { 4841 } 4842 } 4843 4844 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4845 PackageParser.Package pkg, File srcFile, int parseFlags) 4846 throws PackageManagerException { 4847 if (ps != null 4848 && ps.codePath.equals(srcFile) 4849 && ps.timeStamp == srcFile.lastModified() 4850 && !isCompatSignatureUpdateNeeded(pkg) 4851 && !isRecoverSignatureUpdateNeeded(pkg)) { 4852 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4853 if (ps.signatures.mSignatures != null 4854 && ps.signatures.mSignatures.length != 0 4855 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4856 // Optimization: reuse the existing cached certificates 4857 // if the package appears to be unchanged. 4858 pkg.mSignatures = ps.signatures.mSignatures; 4859 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4860 synchronized (mPackages) { 4861 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4862 } 4863 return; 4864 } 4865 4866 Slog.w(TAG, "PackageSetting for " + ps.name 4867 + " is missing signatures. Collecting certs again to recover them."); 4868 } else { 4869 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4870 } 4871 4872 try { 4873 pp.collectCertificates(pkg, parseFlags); 4874 pp.collectManifestDigest(pkg); 4875 } catch (PackageParserException e) { 4876 throw PackageManagerException.from(e); 4877 } 4878 } 4879 4880 /* 4881 * Scan a package and return the newly parsed package. 4882 * Returns null in case of errors and the error code is stored in mLastScanError 4883 */ 4884 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4885 long currentTime, UserHandle user) throws PackageManagerException { 4886 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4887 parseFlags |= mDefParseFlags; 4888 PackageParser pp = new PackageParser(); 4889 pp.setSeparateProcesses(mSeparateProcesses); 4890 pp.setOnlyCoreApps(mOnlyCore); 4891 pp.setDisplayMetrics(mMetrics); 4892 4893 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4894 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4895 } 4896 4897 final PackageParser.Package pkg; 4898 try { 4899 pkg = pp.parsePackage(scanFile, parseFlags); 4900 } catch (PackageParserException e) { 4901 throw PackageManagerException.from(e); 4902 } 4903 4904 PackageSetting ps = null; 4905 PackageSetting updatedPkg; 4906 // reader 4907 synchronized (mPackages) { 4908 // Look to see if we already know about this package. 4909 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4910 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4911 // This package has been renamed to its original name. Let's 4912 // use that. 4913 ps = mSettings.peekPackageLPr(oldName); 4914 } 4915 // If there was no original package, see one for the real package name. 4916 if (ps == null) { 4917 ps = mSettings.peekPackageLPr(pkg.packageName); 4918 } 4919 // Check to see if this package could be hiding/updating a system 4920 // package. Must look for it either under the original or real 4921 // package name depending on our state. 4922 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4923 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4924 } 4925 boolean updatedPkgBetter = false; 4926 // First check if this is a system package that may involve an update 4927 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4928 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4929 // it needs to drop FLAG_PRIVILEGED. 4930 if (locationIsPrivileged(scanFile)) { 4931 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4932 } else { 4933 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4934 } 4935 4936 if (ps != null && !ps.codePath.equals(scanFile)) { 4937 // The path has changed from what was last scanned... check the 4938 // version of the new path against what we have stored to determine 4939 // what to do. 4940 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4941 if (pkg.mVersionCode <= ps.versionCode) { 4942 // The system package has been updated and the code path does not match 4943 // Ignore entry. Skip it. 4944 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4945 + " ignored: updated version " + ps.versionCode 4946 + " better than this " + pkg.mVersionCode); 4947 if (!updatedPkg.codePath.equals(scanFile)) { 4948 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4949 + ps.name + " changing from " + updatedPkg.codePathString 4950 + " to " + scanFile); 4951 updatedPkg.codePath = scanFile; 4952 updatedPkg.codePathString = scanFile.toString(); 4953 updatedPkg.resourcePath = scanFile; 4954 updatedPkg.resourcePathString = scanFile.toString(); 4955 } 4956 updatedPkg.pkg = pkg; 4957 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4958 } else { 4959 // The current app on the system partition is better than 4960 // what we have updated to on the data partition; switch 4961 // back to the system partition version. 4962 // At this point, its safely assumed that package installation for 4963 // apps in system partition will go through. If not there won't be a working 4964 // version of the app 4965 // writer 4966 synchronized (mPackages) { 4967 // Just remove the loaded entries from package lists. 4968 mPackages.remove(ps.name); 4969 } 4970 4971 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4972 + " reverting from " + ps.codePathString 4973 + ": new version " + pkg.mVersionCode 4974 + " better than installed " + ps.versionCode); 4975 4976 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4977 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4978 getAppDexInstructionSets(ps)); 4979 synchronized (mInstallLock) { 4980 args.cleanUpResourcesLI(); 4981 } 4982 synchronized (mPackages) { 4983 mSettings.enableSystemPackageLPw(ps.name); 4984 } 4985 updatedPkgBetter = true; 4986 } 4987 } 4988 } 4989 4990 if (updatedPkg != null) { 4991 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4992 // initially 4993 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4994 4995 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4996 // flag set initially 4997 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4998 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4999 } 5000 } 5001 5002 // Verify certificates against what was last scanned 5003 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5004 5005 /* 5006 * A new system app appeared, but we already had a non-system one of the 5007 * same name installed earlier. 5008 */ 5009 boolean shouldHideSystemApp = false; 5010 if (updatedPkg == null && ps != null 5011 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5012 /* 5013 * Check to make sure the signatures match first. If they don't, 5014 * wipe the installed application and its data. 5015 */ 5016 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5017 != PackageManager.SIGNATURE_MATCH) { 5018 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5019 + " signatures don't match existing userdata copy; removing"); 5020 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5021 ps = null; 5022 } else { 5023 /* 5024 * If the newly-added system app is an older version than the 5025 * already installed version, hide it. It will be scanned later 5026 * and re-added like an update. 5027 */ 5028 if (pkg.mVersionCode <= ps.versionCode) { 5029 shouldHideSystemApp = true; 5030 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5031 + " but new version " + pkg.mVersionCode + " better than installed " 5032 + ps.versionCode + "; hiding system"); 5033 } else { 5034 /* 5035 * The newly found system app is a newer version that the 5036 * one previously installed. Simply remove the 5037 * already-installed application and replace it with our own 5038 * while keeping the application data. 5039 */ 5040 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5041 + " reverting from " + ps.codePathString + ": new version " 5042 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5043 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5044 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5045 getAppDexInstructionSets(ps)); 5046 synchronized (mInstallLock) { 5047 args.cleanUpResourcesLI(); 5048 } 5049 } 5050 } 5051 } 5052 5053 // The apk is forward locked (not public) if its code and resources 5054 // are kept in different files. (except for app in either system or 5055 // vendor path). 5056 // TODO grab this value from PackageSettings 5057 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5058 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5059 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5060 } 5061 } 5062 5063 // TODO: extend to support forward-locked splits 5064 String resourcePath = null; 5065 String baseResourcePath = null; 5066 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5067 if (ps != null && ps.resourcePathString != null) { 5068 resourcePath = ps.resourcePathString; 5069 baseResourcePath = ps.resourcePathString; 5070 } else { 5071 // Should not happen at all. Just log an error. 5072 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5073 } 5074 } else { 5075 resourcePath = pkg.codePath; 5076 baseResourcePath = pkg.baseCodePath; 5077 } 5078 5079 // Set application objects path explicitly. 5080 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5081 pkg.applicationInfo.setCodePath(pkg.codePath); 5082 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5083 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5084 pkg.applicationInfo.setResourcePath(resourcePath); 5085 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5086 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5087 5088 // Note that we invoke the following method only if we are about to unpack an application 5089 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5090 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5091 5092 /* 5093 * If the system app should be overridden by a previously installed 5094 * data, hide the system app now and let the /data/app scan pick it up 5095 * again. 5096 */ 5097 if (shouldHideSystemApp) { 5098 synchronized (mPackages) { 5099 /* 5100 * We have to grant systems permissions before we hide, because 5101 * grantPermissions will assume the package update is trying to 5102 * expand its permissions. 5103 */ 5104 grantPermissionsLPw(pkg, true, pkg.packageName); 5105 mSettings.disableSystemPackageLPw(pkg.packageName); 5106 } 5107 } 5108 5109 return scannedPkg; 5110 } 5111 5112 private static String fixProcessName(String defProcessName, 5113 String processName, int uid) { 5114 if (processName == null) { 5115 return defProcessName; 5116 } 5117 return processName; 5118 } 5119 5120 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5121 throws PackageManagerException { 5122 if (pkgSetting.signatures.mSignatures != null) { 5123 // Already existing package. Make sure signatures match 5124 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5125 == PackageManager.SIGNATURE_MATCH; 5126 if (!match) { 5127 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5128 == PackageManager.SIGNATURE_MATCH; 5129 } 5130 if (!match) { 5131 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5132 == PackageManager.SIGNATURE_MATCH; 5133 } 5134 if (!match) { 5135 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5136 + pkg.packageName + " signatures do not match the " 5137 + "previously installed version; ignoring!"); 5138 } 5139 } 5140 5141 // Check for shared user signatures 5142 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5143 // Already existing package. Make sure signatures match 5144 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5145 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5146 if (!match) { 5147 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5148 == PackageManager.SIGNATURE_MATCH; 5149 } 5150 if (!match) { 5151 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5152 == PackageManager.SIGNATURE_MATCH; 5153 } 5154 if (!match) { 5155 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5156 "Package " + pkg.packageName 5157 + " has no signatures that match those in shared user " 5158 + pkgSetting.sharedUser.name + "; ignoring!"); 5159 } 5160 } 5161 } 5162 5163 /** 5164 * Enforces that only the system UID or root's UID can call a method exposed 5165 * via Binder. 5166 * 5167 * @param message used as message if SecurityException is thrown 5168 * @throws SecurityException if the caller is not system or root 5169 */ 5170 private static final void enforceSystemOrRoot(String message) { 5171 final int uid = Binder.getCallingUid(); 5172 if (uid != Process.SYSTEM_UID && uid != 0) { 5173 throw new SecurityException(message); 5174 } 5175 } 5176 5177 @Override 5178 public void performBootDexOpt() { 5179 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5180 5181 // Before everything else, see whether we need to fstrim. 5182 try { 5183 IMountService ms = PackageHelper.getMountService(); 5184 if (ms != null) { 5185 final boolean isUpgrade = isUpgrade(); 5186 boolean doTrim = isUpgrade; 5187 if (doTrim) { 5188 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5189 } else { 5190 final long interval = android.provider.Settings.Global.getLong( 5191 mContext.getContentResolver(), 5192 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5193 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5194 if (interval > 0) { 5195 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5196 if (timeSinceLast > interval) { 5197 doTrim = true; 5198 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5199 + "; running immediately"); 5200 } 5201 } 5202 } 5203 if (doTrim) { 5204 if (!isFirstBoot()) { 5205 try { 5206 ActivityManagerNative.getDefault().showBootMessage( 5207 mContext.getResources().getString( 5208 R.string.android_upgrading_fstrim), true); 5209 } catch (RemoteException e) { 5210 } 5211 } 5212 ms.runMaintenance(); 5213 } 5214 } else { 5215 Slog.e(TAG, "Mount service unavailable!"); 5216 } 5217 } catch (RemoteException e) { 5218 // Can't happen; MountService is local 5219 } 5220 5221 final ArraySet<PackageParser.Package> pkgs; 5222 synchronized (mPackages) { 5223 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5224 } 5225 5226 if (pkgs != null) { 5227 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5228 // in case the device runs out of space. 5229 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5230 // Give priority to core apps. 5231 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5232 PackageParser.Package pkg = it.next(); 5233 if (pkg.coreApp) { 5234 if (DEBUG_DEXOPT) { 5235 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5236 } 5237 sortedPkgs.add(pkg); 5238 it.remove(); 5239 } 5240 } 5241 // Give priority to system apps that listen for pre boot complete. 5242 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5243 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5244 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5245 PackageParser.Package pkg = it.next(); 5246 if (pkgNames.contains(pkg.packageName)) { 5247 if (DEBUG_DEXOPT) { 5248 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5249 } 5250 sortedPkgs.add(pkg); 5251 it.remove(); 5252 } 5253 } 5254 // Give priority to system apps. 5255 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5256 PackageParser.Package pkg = it.next(); 5257 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5258 if (DEBUG_DEXOPT) { 5259 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5260 } 5261 sortedPkgs.add(pkg); 5262 it.remove(); 5263 } 5264 } 5265 // Give priority to updated system apps. 5266 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5267 PackageParser.Package pkg = it.next(); 5268 if (pkg.isUpdatedSystemApp()) { 5269 if (DEBUG_DEXOPT) { 5270 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5271 } 5272 sortedPkgs.add(pkg); 5273 it.remove(); 5274 } 5275 } 5276 // Give priority to apps that listen for boot complete. 5277 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5278 pkgNames = getPackageNamesForIntent(intent); 5279 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5280 PackageParser.Package pkg = it.next(); 5281 if (pkgNames.contains(pkg.packageName)) { 5282 if (DEBUG_DEXOPT) { 5283 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5284 } 5285 sortedPkgs.add(pkg); 5286 it.remove(); 5287 } 5288 } 5289 // Filter out packages that aren't recently used. 5290 filterRecentlyUsedApps(pkgs); 5291 // Add all remaining apps. 5292 for (PackageParser.Package pkg : pkgs) { 5293 if (DEBUG_DEXOPT) { 5294 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5295 } 5296 sortedPkgs.add(pkg); 5297 } 5298 5299 // If we want to be lazy, filter everything that wasn't recently used. 5300 if (mLazyDexOpt) { 5301 filterRecentlyUsedApps(sortedPkgs); 5302 } 5303 5304 int i = 0; 5305 int total = sortedPkgs.size(); 5306 File dataDir = Environment.getDataDirectory(); 5307 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5308 if (lowThreshold == 0) { 5309 throw new IllegalStateException("Invalid low memory threshold"); 5310 } 5311 for (PackageParser.Package pkg : sortedPkgs) { 5312 long usableSpace = dataDir.getUsableSpace(); 5313 if (usableSpace < lowThreshold) { 5314 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5315 break; 5316 } 5317 performBootDexOpt(pkg, ++i, total); 5318 } 5319 } 5320 } 5321 5322 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5323 // Filter out packages that aren't recently used. 5324 // 5325 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5326 // should do a full dexopt. 5327 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5328 int total = pkgs.size(); 5329 int skipped = 0; 5330 long now = System.currentTimeMillis(); 5331 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5332 PackageParser.Package pkg = i.next(); 5333 long then = pkg.mLastPackageUsageTimeInMills; 5334 if (then + mDexOptLRUThresholdInMills < now) { 5335 if (DEBUG_DEXOPT) { 5336 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5337 ((then == 0) ? "never" : new Date(then))); 5338 } 5339 i.remove(); 5340 skipped++; 5341 } 5342 } 5343 if (DEBUG_DEXOPT) { 5344 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5345 } 5346 } 5347 } 5348 5349 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5350 List<ResolveInfo> ris = null; 5351 try { 5352 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5353 intent, null, 0, UserHandle.USER_OWNER); 5354 } catch (RemoteException e) { 5355 } 5356 ArraySet<String> pkgNames = new ArraySet<String>(); 5357 if (ris != null) { 5358 for (ResolveInfo ri : ris) { 5359 pkgNames.add(ri.activityInfo.packageName); 5360 } 5361 } 5362 return pkgNames; 5363 } 5364 5365 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5366 if (DEBUG_DEXOPT) { 5367 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5368 } 5369 if (!isFirstBoot()) { 5370 try { 5371 ActivityManagerNative.getDefault().showBootMessage( 5372 mContext.getResources().getString(R.string.android_upgrading_apk, 5373 curr, total), true); 5374 } catch (RemoteException e) { 5375 } 5376 } 5377 PackageParser.Package p = pkg; 5378 synchronized (mInstallLock) { 5379 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5380 false /* force dex */, false /* defer */, true /* include dependencies */); 5381 } 5382 } 5383 5384 @Override 5385 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5386 return performDexOpt(packageName, instructionSet, false); 5387 } 5388 5389 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5390 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5391 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5392 if (!dexopt && !updateUsage) { 5393 // We aren't going to dexopt or update usage, so bail early. 5394 return false; 5395 } 5396 PackageParser.Package p; 5397 final String targetInstructionSet; 5398 synchronized (mPackages) { 5399 p = mPackages.get(packageName); 5400 if (p == null) { 5401 return false; 5402 } 5403 if (updateUsage) { 5404 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5405 } 5406 mPackageUsage.write(false); 5407 if (!dexopt) { 5408 // We aren't going to dexopt, so bail early. 5409 return false; 5410 } 5411 5412 targetInstructionSet = instructionSet != null ? instructionSet : 5413 getPrimaryInstructionSet(p.applicationInfo); 5414 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5415 return false; 5416 } 5417 } 5418 5419 synchronized (mInstallLock) { 5420 final String[] instructionSets = new String[] { targetInstructionSet }; 5421 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5422 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5423 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5424 } 5425 } 5426 5427 public ArraySet<String> getPackagesThatNeedDexOpt() { 5428 ArraySet<String> pkgs = null; 5429 synchronized (mPackages) { 5430 for (PackageParser.Package p : mPackages.values()) { 5431 if (DEBUG_DEXOPT) { 5432 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5433 } 5434 if (!p.mDexOptPerformed.isEmpty()) { 5435 continue; 5436 } 5437 if (pkgs == null) { 5438 pkgs = new ArraySet<String>(); 5439 } 5440 pkgs.add(p.packageName); 5441 } 5442 } 5443 return pkgs; 5444 } 5445 5446 public void shutdown() { 5447 mPackageUsage.write(true); 5448 } 5449 5450 @Override 5451 public void forceDexOpt(String packageName) { 5452 enforceSystemOrRoot("forceDexOpt"); 5453 5454 PackageParser.Package pkg; 5455 synchronized (mPackages) { 5456 pkg = mPackages.get(packageName); 5457 if (pkg == null) { 5458 throw new IllegalArgumentException("Missing package: " + packageName); 5459 } 5460 } 5461 5462 synchronized (mInstallLock) { 5463 final String[] instructionSets = new String[] { 5464 getPrimaryInstructionSet(pkg.applicationInfo) }; 5465 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5466 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5467 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5468 throw new IllegalStateException("Failed to dexopt: " + res); 5469 } 5470 } 5471 } 5472 5473 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5474 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5475 Slog.w(TAG, "Unable to update from " + oldPkg.name 5476 + " to " + newPkg.packageName 5477 + ": old package not in system partition"); 5478 return false; 5479 } else if (mPackages.get(oldPkg.name) != null) { 5480 Slog.w(TAG, "Unable to update from " + oldPkg.name 5481 + " to " + newPkg.packageName 5482 + ": old package still exists"); 5483 return false; 5484 } 5485 return true; 5486 } 5487 5488 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5489 int[] users = sUserManager.getUserIds(); 5490 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5491 if (res < 0) { 5492 return res; 5493 } 5494 for (int user : users) { 5495 if (user != 0) { 5496 res = mInstaller.createUserData(volumeUuid, packageName, 5497 UserHandle.getUid(user, uid), user, seinfo); 5498 if (res < 0) { 5499 return res; 5500 } 5501 } 5502 } 5503 return res; 5504 } 5505 5506 private int removeDataDirsLI(String volumeUuid, String packageName) { 5507 int[] users = sUserManager.getUserIds(); 5508 int res = 0; 5509 for (int user : users) { 5510 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5511 if (resInner < 0) { 5512 res = resInner; 5513 } 5514 } 5515 5516 return res; 5517 } 5518 5519 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5520 int[] users = sUserManager.getUserIds(); 5521 int res = 0; 5522 for (int user : users) { 5523 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5524 if (resInner < 0) { 5525 res = resInner; 5526 } 5527 } 5528 return res; 5529 } 5530 5531 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5532 PackageParser.Package changingLib) { 5533 if (file.path != null) { 5534 usesLibraryFiles.add(file.path); 5535 return; 5536 } 5537 PackageParser.Package p = mPackages.get(file.apk); 5538 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5539 // If we are doing this while in the middle of updating a library apk, 5540 // then we need to make sure to use that new apk for determining the 5541 // dependencies here. (We haven't yet finished committing the new apk 5542 // to the package manager state.) 5543 if (p == null || p.packageName.equals(changingLib.packageName)) { 5544 p = changingLib; 5545 } 5546 } 5547 if (p != null) { 5548 usesLibraryFiles.addAll(p.getAllCodePaths()); 5549 } 5550 } 5551 5552 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5553 PackageParser.Package changingLib) throws PackageManagerException { 5554 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5555 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5556 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5557 for (int i=0; i<N; i++) { 5558 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5559 if (file == null) { 5560 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5561 "Package " + pkg.packageName + " requires unavailable shared library " 5562 + pkg.usesLibraries.get(i) + "; failing!"); 5563 } 5564 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5565 } 5566 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5567 for (int i=0; i<N; i++) { 5568 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5569 if (file == null) { 5570 Slog.w(TAG, "Package " + pkg.packageName 5571 + " desires unavailable shared library " 5572 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5573 } else { 5574 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5575 } 5576 } 5577 N = usesLibraryFiles.size(); 5578 if (N > 0) { 5579 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5580 } else { 5581 pkg.usesLibraryFiles = null; 5582 } 5583 } 5584 } 5585 5586 private static boolean hasString(List<String> list, List<String> which) { 5587 if (list == null) { 5588 return false; 5589 } 5590 for (int i=list.size()-1; i>=0; i--) { 5591 for (int j=which.size()-1; j>=0; j--) { 5592 if (which.get(j).equals(list.get(i))) { 5593 return true; 5594 } 5595 } 5596 } 5597 return false; 5598 } 5599 5600 private void updateAllSharedLibrariesLPw() { 5601 for (PackageParser.Package pkg : mPackages.values()) { 5602 try { 5603 updateSharedLibrariesLPw(pkg, null); 5604 } catch (PackageManagerException e) { 5605 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5606 } 5607 } 5608 } 5609 5610 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5611 PackageParser.Package changingPkg) { 5612 ArrayList<PackageParser.Package> res = null; 5613 for (PackageParser.Package pkg : mPackages.values()) { 5614 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5615 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5616 if (res == null) { 5617 res = new ArrayList<PackageParser.Package>(); 5618 } 5619 res.add(pkg); 5620 try { 5621 updateSharedLibrariesLPw(pkg, changingPkg); 5622 } catch (PackageManagerException e) { 5623 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5624 } 5625 } 5626 } 5627 return res; 5628 } 5629 5630 /** 5631 * Derive the value of the {@code cpuAbiOverride} based on the provided 5632 * value and an optional stored value from the package settings. 5633 */ 5634 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5635 String cpuAbiOverride = null; 5636 5637 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5638 cpuAbiOverride = null; 5639 } else if (abiOverride != null) { 5640 cpuAbiOverride = abiOverride; 5641 } else if (settings != null) { 5642 cpuAbiOverride = settings.cpuAbiOverrideString; 5643 } 5644 5645 return cpuAbiOverride; 5646 } 5647 5648 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5649 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5650 boolean success = false; 5651 try { 5652 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5653 currentTime, user); 5654 success = true; 5655 return res; 5656 } finally { 5657 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5658 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5659 } 5660 } 5661 } 5662 5663 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5664 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5665 final File scanFile = new File(pkg.codePath); 5666 if (pkg.applicationInfo.getCodePath() == null || 5667 pkg.applicationInfo.getResourcePath() == null) { 5668 // Bail out. The resource and code paths haven't been set. 5669 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5670 "Code and resource paths haven't been set correctly"); 5671 } 5672 5673 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5674 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5675 } else { 5676 // Only allow system apps to be flagged as core apps. 5677 pkg.coreApp = false; 5678 } 5679 5680 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5681 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5682 } 5683 5684 if (mCustomResolverComponentName != null && 5685 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5686 setUpCustomResolverActivity(pkg); 5687 } 5688 5689 if (pkg.packageName.equals("android")) { 5690 synchronized (mPackages) { 5691 if (mAndroidApplication != null) { 5692 Slog.w(TAG, "*************************************************"); 5693 Slog.w(TAG, "Core android package being redefined. Skipping."); 5694 Slog.w(TAG, " file=" + scanFile); 5695 Slog.w(TAG, "*************************************************"); 5696 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5697 "Core android package being redefined. Skipping."); 5698 } 5699 5700 // Set up information for our fall-back user intent resolution activity. 5701 mPlatformPackage = pkg; 5702 pkg.mVersionCode = mSdkVersion; 5703 mAndroidApplication = pkg.applicationInfo; 5704 5705 if (!mResolverReplaced) { 5706 mResolveActivity.applicationInfo = mAndroidApplication; 5707 mResolveActivity.name = ResolverActivity.class.getName(); 5708 mResolveActivity.packageName = mAndroidApplication.packageName; 5709 mResolveActivity.processName = "system:ui"; 5710 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5711 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5712 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5713 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5714 mResolveActivity.exported = true; 5715 mResolveActivity.enabled = true; 5716 mResolveInfo.activityInfo = mResolveActivity; 5717 mResolveInfo.priority = 0; 5718 mResolveInfo.preferredOrder = 0; 5719 mResolveInfo.match = 0; 5720 mResolveComponentName = new ComponentName( 5721 mAndroidApplication.packageName, mResolveActivity.name); 5722 } 5723 } 5724 } 5725 5726 if (DEBUG_PACKAGE_SCANNING) { 5727 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5728 Log.d(TAG, "Scanning package " + pkg.packageName); 5729 } 5730 5731 if (mPackages.containsKey(pkg.packageName) 5732 || mSharedLibraries.containsKey(pkg.packageName)) { 5733 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5734 "Application package " + pkg.packageName 5735 + " already installed. Skipping duplicate."); 5736 } 5737 5738 // If we're only installing presumed-existing packages, require that the 5739 // scanned APK is both already known and at the path previously established 5740 // for it. Previously unknown packages we pick up normally, but if we have an 5741 // a priori expectation about this package's install presence, enforce it. 5742 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5743 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5744 if (known != null) { 5745 if (DEBUG_PACKAGE_SCANNING) { 5746 Log.d(TAG, "Examining " + pkg.codePath 5747 + " and requiring known paths " + known.codePathString 5748 + " & " + known.resourcePathString); 5749 } 5750 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5751 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5752 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5753 "Application package " + pkg.packageName 5754 + " found at " + pkg.applicationInfo.getCodePath() 5755 + " but expected at " + known.codePathString + "; ignoring."); 5756 } 5757 } 5758 } 5759 5760 // Initialize package source and resource directories 5761 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5762 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5763 5764 SharedUserSetting suid = null; 5765 PackageSetting pkgSetting = null; 5766 5767 if (!isSystemApp(pkg)) { 5768 // Only system apps can use these features. 5769 pkg.mOriginalPackages = null; 5770 pkg.mRealPackage = null; 5771 pkg.mAdoptPermissions = null; 5772 } 5773 5774 // writer 5775 synchronized (mPackages) { 5776 if (pkg.mSharedUserId != null) { 5777 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5778 if (suid == null) { 5779 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5780 "Creating application package " + pkg.packageName 5781 + " for shared user failed"); 5782 } 5783 if (DEBUG_PACKAGE_SCANNING) { 5784 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5785 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5786 + "): packages=" + suid.packages); 5787 } 5788 } 5789 5790 // Check if we are renaming from an original package name. 5791 PackageSetting origPackage = null; 5792 String realName = null; 5793 if (pkg.mOriginalPackages != null) { 5794 // This package may need to be renamed to a previously 5795 // installed name. Let's check on that... 5796 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5797 if (pkg.mOriginalPackages.contains(renamed)) { 5798 // This package had originally been installed as the 5799 // original name, and we have already taken care of 5800 // transitioning to the new one. Just update the new 5801 // one to continue using the old name. 5802 realName = pkg.mRealPackage; 5803 if (!pkg.packageName.equals(renamed)) { 5804 // Callers into this function may have already taken 5805 // care of renaming the package; only do it here if 5806 // it is not already done. 5807 pkg.setPackageName(renamed); 5808 } 5809 5810 } else { 5811 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5812 if ((origPackage = mSettings.peekPackageLPr( 5813 pkg.mOriginalPackages.get(i))) != null) { 5814 // We do have the package already installed under its 5815 // original name... should we use it? 5816 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5817 // New package is not compatible with original. 5818 origPackage = null; 5819 continue; 5820 } else if (origPackage.sharedUser != null) { 5821 // Make sure uid is compatible between packages. 5822 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5823 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5824 + " to " + pkg.packageName + ": old uid " 5825 + origPackage.sharedUser.name 5826 + " differs from " + pkg.mSharedUserId); 5827 origPackage = null; 5828 continue; 5829 } 5830 } else { 5831 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5832 + pkg.packageName + " to old name " + origPackage.name); 5833 } 5834 break; 5835 } 5836 } 5837 } 5838 } 5839 5840 if (mTransferedPackages.contains(pkg.packageName)) { 5841 Slog.w(TAG, "Package " + pkg.packageName 5842 + " was transferred to another, but its .apk remains"); 5843 } 5844 5845 // Just create the setting, don't add it yet. For already existing packages 5846 // the PkgSetting exists already and doesn't have to be created. 5847 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5848 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5849 pkg.applicationInfo.primaryCpuAbi, 5850 pkg.applicationInfo.secondaryCpuAbi, 5851 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5852 user, false); 5853 if (pkgSetting == null) { 5854 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5855 "Creating application package " + pkg.packageName + " failed"); 5856 } 5857 5858 if (pkgSetting.origPackage != null) { 5859 // If we are first transitioning from an original package, 5860 // fix up the new package's name now. We need to do this after 5861 // looking up the package under its new name, so getPackageLP 5862 // can take care of fiddling things correctly. 5863 pkg.setPackageName(origPackage.name); 5864 5865 // File a report about this. 5866 String msg = "New package " + pkgSetting.realName 5867 + " renamed to replace old package " + pkgSetting.name; 5868 reportSettingsProblem(Log.WARN, msg); 5869 5870 // Make a note of it. 5871 mTransferedPackages.add(origPackage.name); 5872 5873 // No longer need to retain this. 5874 pkgSetting.origPackage = null; 5875 } 5876 5877 if (realName != null) { 5878 // Make a note of it. 5879 mTransferedPackages.add(pkg.packageName); 5880 } 5881 5882 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5883 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5884 } 5885 5886 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5887 // Check all shared libraries and map to their actual file path. 5888 // We only do this here for apps not on a system dir, because those 5889 // are the only ones that can fail an install due to this. We 5890 // will take care of the system apps by updating all of their 5891 // library paths after the scan is done. 5892 updateSharedLibrariesLPw(pkg, null); 5893 } 5894 5895 if (mFoundPolicyFile) { 5896 SELinuxMMAC.assignSeinfoValue(pkg); 5897 } 5898 5899 pkg.applicationInfo.uid = pkgSetting.appId; 5900 pkg.mExtras = pkgSetting; 5901 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5902 try { 5903 verifySignaturesLP(pkgSetting, pkg); 5904 // We just determined the app is signed correctly, so bring 5905 // over the latest parsed certs. 5906 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5907 } catch (PackageManagerException e) { 5908 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5909 throw e; 5910 } 5911 // The signature has changed, but this package is in the system 5912 // image... let's recover! 5913 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5914 // However... if this package is part of a shared user, but it 5915 // doesn't match the signature of the shared user, let's fail. 5916 // What this means is that you can't change the signatures 5917 // associated with an overall shared user, which doesn't seem all 5918 // that unreasonable. 5919 if (pkgSetting.sharedUser != null) { 5920 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5921 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5922 throw new PackageManagerException( 5923 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5924 "Signature mismatch for shared user : " 5925 + pkgSetting.sharedUser); 5926 } 5927 } 5928 // File a report about this. 5929 String msg = "System package " + pkg.packageName 5930 + " signature changed; retaining data."; 5931 reportSettingsProblem(Log.WARN, msg); 5932 } 5933 } else { 5934 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5935 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5936 + pkg.packageName + " upgrade keys do not match the " 5937 + "previously installed version"); 5938 } else { 5939 // We just determined the app is signed correctly, so bring 5940 // over the latest parsed certs. 5941 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5942 } 5943 } 5944 // Verify that this new package doesn't have any content providers 5945 // that conflict with existing packages. Only do this if the 5946 // package isn't already installed, since we don't want to break 5947 // things that are installed. 5948 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5949 final int N = pkg.providers.size(); 5950 int i; 5951 for (i=0; i<N; i++) { 5952 PackageParser.Provider p = pkg.providers.get(i); 5953 if (p.info.authority != null) { 5954 String names[] = p.info.authority.split(";"); 5955 for (int j = 0; j < names.length; j++) { 5956 if (mProvidersByAuthority.containsKey(names[j])) { 5957 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5958 final String otherPackageName = 5959 ((other != null && other.getComponentName() != null) ? 5960 other.getComponentName().getPackageName() : "?"); 5961 throw new PackageManagerException( 5962 INSTALL_FAILED_CONFLICTING_PROVIDER, 5963 "Can't install because provider name " + names[j] 5964 + " (in package " + pkg.applicationInfo.packageName 5965 + ") is already used by " + otherPackageName); 5966 } 5967 } 5968 } 5969 } 5970 } 5971 5972 if (pkg.mAdoptPermissions != null) { 5973 // This package wants to adopt ownership of permissions from 5974 // another package. 5975 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5976 final String origName = pkg.mAdoptPermissions.get(i); 5977 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5978 if (orig != null) { 5979 if (verifyPackageUpdateLPr(orig, pkg)) { 5980 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5981 + pkg.packageName); 5982 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5983 } 5984 } 5985 } 5986 } 5987 } 5988 5989 final String pkgName = pkg.packageName; 5990 5991 final long scanFileTime = scanFile.lastModified(); 5992 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5993 pkg.applicationInfo.processName = fixProcessName( 5994 pkg.applicationInfo.packageName, 5995 pkg.applicationInfo.processName, 5996 pkg.applicationInfo.uid); 5997 5998 File dataPath; 5999 if (mPlatformPackage == pkg) { 6000 // The system package is special. 6001 dataPath = new File(Environment.getDataDirectory(), "system"); 6002 6003 pkg.applicationInfo.dataDir = dataPath.getPath(); 6004 6005 } else { 6006 // This is a normal package, need to make its data directory. 6007 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6008 UserHandle.USER_OWNER); 6009 6010 boolean uidError = false; 6011 if (dataPath.exists()) { 6012 int currentUid = 0; 6013 try { 6014 StructStat stat = Os.stat(dataPath.getPath()); 6015 currentUid = stat.st_uid; 6016 } catch (ErrnoException e) { 6017 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6018 } 6019 6020 // If we have mismatched owners for the data path, we have a problem. 6021 if (currentUid != pkg.applicationInfo.uid) { 6022 boolean recovered = false; 6023 if (currentUid == 0) { 6024 // The directory somehow became owned by root. Wow. 6025 // This is probably because the system was stopped while 6026 // installd was in the middle of messing with its libs 6027 // directory. Ask installd to fix that. 6028 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6029 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6030 if (ret >= 0) { 6031 recovered = true; 6032 String msg = "Package " + pkg.packageName 6033 + " unexpectedly changed to uid 0; recovered to " + 6034 + pkg.applicationInfo.uid; 6035 reportSettingsProblem(Log.WARN, msg); 6036 } 6037 } 6038 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6039 || (scanFlags&SCAN_BOOTING) != 0)) { 6040 // If this is a system app, we can at least delete its 6041 // current data so the application will still work. 6042 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6043 if (ret >= 0) { 6044 // TODO: Kill the processes first 6045 // Old data gone! 6046 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6047 ? "System package " : "Third party package "; 6048 String msg = prefix + pkg.packageName 6049 + " has changed from uid: " 6050 + currentUid + " to " 6051 + pkg.applicationInfo.uid + "; old data erased"; 6052 reportSettingsProblem(Log.WARN, msg); 6053 recovered = true; 6054 6055 // And now re-install the app. 6056 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6057 pkg.applicationInfo.seinfo); 6058 if (ret == -1) { 6059 // Ack should not happen! 6060 msg = prefix + pkg.packageName 6061 + " could not have data directory re-created after delete."; 6062 reportSettingsProblem(Log.WARN, msg); 6063 throw new PackageManagerException( 6064 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6065 } 6066 } 6067 if (!recovered) { 6068 mHasSystemUidErrors = true; 6069 } 6070 } else if (!recovered) { 6071 // If we allow this install to proceed, we will be broken. 6072 // Abort, abort! 6073 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6074 "scanPackageLI"); 6075 } 6076 if (!recovered) { 6077 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6078 + pkg.applicationInfo.uid + "/fs_" 6079 + currentUid; 6080 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6081 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6082 String msg = "Package " + pkg.packageName 6083 + " has mismatched uid: " 6084 + currentUid + " on disk, " 6085 + pkg.applicationInfo.uid + " in settings"; 6086 // writer 6087 synchronized (mPackages) { 6088 mSettings.mReadMessages.append(msg); 6089 mSettings.mReadMessages.append('\n'); 6090 uidError = true; 6091 if (!pkgSetting.uidError) { 6092 reportSettingsProblem(Log.ERROR, msg); 6093 } 6094 } 6095 } 6096 } 6097 pkg.applicationInfo.dataDir = dataPath.getPath(); 6098 if (mShouldRestoreconData) { 6099 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6100 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6101 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6102 } 6103 } else { 6104 if (DEBUG_PACKAGE_SCANNING) { 6105 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6106 Log.v(TAG, "Want this data dir: " + dataPath); 6107 } 6108 //invoke installer to do the actual installation 6109 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6110 pkg.applicationInfo.seinfo); 6111 if (ret < 0) { 6112 // Error from installer 6113 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6114 "Unable to create data dirs [errorCode=" + ret + "]"); 6115 } 6116 6117 if (dataPath.exists()) { 6118 pkg.applicationInfo.dataDir = dataPath.getPath(); 6119 } else { 6120 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6121 pkg.applicationInfo.dataDir = null; 6122 } 6123 } 6124 6125 pkgSetting.uidError = uidError; 6126 } 6127 6128 final String path = scanFile.getPath(); 6129 final String codePath = pkg.applicationInfo.getCodePath(); 6130 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6131 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6132 setBundledAppAbisAndRoots(pkg, pkgSetting); 6133 6134 // If we haven't found any native libraries for the app, check if it has 6135 // renderscript code. We'll need to force the app to 32 bit if it has 6136 // renderscript bitcode. 6137 if (pkg.applicationInfo.primaryCpuAbi == null 6138 && pkg.applicationInfo.secondaryCpuAbi == null 6139 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6140 NativeLibraryHelper.Handle handle = null; 6141 try { 6142 handle = NativeLibraryHelper.Handle.create(scanFile); 6143 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6144 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6145 } 6146 } catch (IOException ioe) { 6147 Slog.w(TAG, "Error scanning system app : " + ioe); 6148 } finally { 6149 IoUtils.closeQuietly(handle); 6150 } 6151 } 6152 6153 setNativeLibraryPaths(pkg); 6154 } else { 6155 // TODO: We can probably be smarter about this stuff. For installed apps, 6156 // we can calculate this information at install time once and for all. For 6157 // system apps, we can probably assume that this information doesn't change 6158 // after the first boot scan. As things stand, we do lots of unnecessary work. 6159 6160 // Give ourselves some initial paths; we'll come back for another 6161 // pass once we've determined ABI below. 6162 setNativeLibraryPaths(pkg); 6163 6164 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6165 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6166 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6167 6168 NativeLibraryHelper.Handle handle = null; 6169 try { 6170 handle = NativeLibraryHelper.Handle.create(scanFile); 6171 // TODO(multiArch): This can be null for apps that didn't go through the 6172 // usual installation process. We can calculate it again, like we 6173 // do during install time. 6174 // 6175 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6176 // unnecessary. 6177 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6178 6179 // Null out the abis so that they can be recalculated. 6180 pkg.applicationInfo.primaryCpuAbi = null; 6181 pkg.applicationInfo.secondaryCpuAbi = null; 6182 if (isMultiArch(pkg.applicationInfo)) { 6183 // Warn if we've set an abiOverride for multi-lib packages.. 6184 // By definition, we need to copy both 32 and 64 bit libraries for 6185 // such packages. 6186 if (pkg.cpuAbiOverride != null 6187 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6188 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6189 } 6190 6191 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6192 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6193 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6194 if (isAsec) { 6195 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6196 } else { 6197 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6198 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6199 useIsaSpecificSubdirs); 6200 } 6201 } 6202 6203 maybeThrowExceptionForMultiArchCopy( 6204 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6205 6206 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6207 if (isAsec) { 6208 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6209 } else { 6210 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6211 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6212 useIsaSpecificSubdirs); 6213 } 6214 } 6215 6216 maybeThrowExceptionForMultiArchCopy( 6217 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6218 6219 if (abi64 >= 0) { 6220 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6221 } 6222 6223 if (abi32 >= 0) { 6224 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6225 if (abi64 >= 0) { 6226 pkg.applicationInfo.secondaryCpuAbi = abi; 6227 } else { 6228 pkg.applicationInfo.primaryCpuAbi = abi; 6229 } 6230 } 6231 } else { 6232 String[] abiList = (cpuAbiOverride != null) ? 6233 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6234 6235 // Enable gross and lame hacks for apps that are built with old 6236 // SDK tools. We must scan their APKs for renderscript bitcode and 6237 // not launch them if it's present. Don't bother checking on devices 6238 // that don't have 64 bit support. 6239 boolean needsRenderScriptOverride = false; 6240 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6241 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6242 abiList = Build.SUPPORTED_32_BIT_ABIS; 6243 needsRenderScriptOverride = true; 6244 } 6245 6246 final int copyRet; 6247 if (isAsec) { 6248 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6249 } else { 6250 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6251 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6252 } 6253 6254 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6255 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6256 "Error unpackaging native libs for app, errorCode=" + copyRet); 6257 } 6258 6259 if (copyRet >= 0) { 6260 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6261 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6262 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6263 } else if (needsRenderScriptOverride) { 6264 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6265 } 6266 } 6267 } catch (IOException ioe) { 6268 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6269 } finally { 6270 IoUtils.closeQuietly(handle); 6271 } 6272 6273 // Now that we've calculated the ABIs and determined if it's an internal app, 6274 // we will go ahead and populate the nativeLibraryPath. 6275 setNativeLibraryPaths(pkg); 6276 6277 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6278 final int[] userIds = sUserManager.getUserIds(); 6279 synchronized (mInstallLock) { 6280 // Create a native library symlink only if we have native libraries 6281 // and if the native libraries are 32 bit libraries. We do not provide 6282 // this symlink for 64 bit libraries. 6283 if (pkg.applicationInfo.primaryCpuAbi != null && 6284 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6285 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6286 for (int userId : userIds) { 6287 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6288 nativeLibPath, userId) < 0) { 6289 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6290 "Failed linking native library dir (user=" + userId + ")"); 6291 } 6292 } 6293 } 6294 } 6295 } 6296 6297 // This is a special case for the "system" package, where the ABI is 6298 // dictated by the zygote configuration (and init.rc). We should keep track 6299 // of this ABI so that we can deal with "normal" applications that run under 6300 // the same UID correctly. 6301 if (mPlatformPackage == pkg) { 6302 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6303 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6304 } 6305 6306 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6307 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6308 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6309 // Copy the derived override back to the parsed package, so that we can 6310 // update the package settings accordingly. 6311 pkg.cpuAbiOverride = cpuAbiOverride; 6312 6313 if (DEBUG_ABI_SELECTION) { 6314 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6315 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6316 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6317 } 6318 6319 // Push the derived path down into PackageSettings so we know what to 6320 // clean up at uninstall time. 6321 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6322 6323 if (DEBUG_ABI_SELECTION) { 6324 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6325 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6326 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6327 } 6328 6329 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6330 // We don't do this here during boot because we can do it all 6331 // at once after scanning all existing packages. 6332 // 6333 // We also do this *before* we perform dexopt on this package, so that 6334 // we can avoid redundant dexopts, and also to make sure we've got the 6335 // code and package path correct. 6336 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6337 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6338 } 6339 6340 if ((scanFlags & SCAN_NO_DEX) == 0) { 6341 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6342 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6343 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6344 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6345 } 6346 } 6347 if (mFactoryTest && pkg.requestedPermissions.contains( 6348 android.Manifest.permission.FACTORY_TEST)) { 6349 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6350 } 6351 6352 ArrayList<PackageParser.Package> clientLibPkgs = null; 6353 6354 // writer 6355 synchronized (mPackages) { 6356 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6357 // Only system apps can add new shared libraries. 6358 if (pkg.libraryNames != null) { 6359 for (int i=0; i<pkg.libraryNames.size(); i++) { 6360 String name = pkg.libraryNames.get(i); 6361 boolean allowed = false; 6362 if (pkg.isUpdatedSystemApp()) { 6363 // New library entries can only be added through the 6364 // system image. This is important to get rid of a lot 6365 // of nasty edge cases: for example if we allowed a non- 6366 // system update of the app to add a library, then uninstalling 6367 // the update would make the library go away, and assumptions 6368 // we made such as through app install filtering would now 6369 // have allowed apps on the device which aren't compatible 6370 // with it. Better to just have the restriction here, be 6371 // conservative, and create many fewer cases that can negatively 6372 // impact the user experience. 6373 final PackageSetting sysPs = mSettings 6374 .getDisabledSystemPkgLPr(pkg.packageName); 6375 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6376 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6377 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6378 allowed = true; 6379 allowed = true; 6380 break; 6381 } 6382 } 6383 } 6384 } else { 6385 allowed = true; 6386 } 6387 if (allowed) { 6388 if (!mSharedLibraries.containsKey(name)) { 6389 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6390 } else if (!name.equals(pkg.packageName)) { 6391 Slog.w(TAG, "Package " + pkg.packageName + " library " 6392 + name + " already exists; skipping"); 6393 } 6394 } else { 6395 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6396 + name + " that is not declared on system image; skipping"); 6397 } 6398 } 6399 if ((scanFlags&SCAN_BOOTING) == 0) { 6400 // If we are not booting, we need to update any applications 6401 // that are clients of our shared library. If we are booting, 6402 // this will all be done once the scan is complete. 6403 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6404 } 6405 } 6406 } 6407 } 6408 6409 // We also need to dexopt any apps that are dependent on this library. Note that 6410 // if these fail, we should abort the install since installing the library will 6411 // result in some apps being broken. 6412 if (clientLibPkgs != null) { 6413 if ((scanFlags & SCAN_NO_DEX) == 0) { 6414 for (int i = 0; i < clientLibPkgs.size(); i++) { 6415 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6416 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6417 null /* instruction sets */, forceDex, 6418 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6419 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6420 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6421 "scanPackageLI failed to dexopt clientLibPkgs"); 6422 } 6423 } 6424 } 6425 } 6426 6427 // Request the ActivityManager to kill the process(only for existing packages) 6428 // so that we do not end up in a confused state while the user is still using the older 6429 // version of the application while the new one gets installed. 6430 if ((scanFlags & SCAN_REPLACING) != 0) { 6431 killApplication(pkg.applicationInfo.packageName, 6432 pkg.applicationInfo.uid, "update pkg"); 6433 } 6434 6435 // Also need to kill any apps that are dependent on the library. 6436 if (clientLibPkgs != null) { 6437 for (int i=0; i<clientLibPkgs.size(); i++) { 6438 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6439 killApplication(clientPkg.applicationInfo.packageName, 6440 clientPkg.applicationInfo.uid, "update lib"); 6441 } 6442 } 6443 6444 // writer 6445 synchronized (mPackages) { 6446 // We don't expect installation to fail beyond this point 6447 6448 // Add the new setting to mSettings 6449 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6450 // Add the new setting to mPackages 6451 mPackages.put(pkg.applicationInfo.packageName, pkg); 6452 // Make sure we don't accidentally delete its data. 6453 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6454 while (iter.hasNext()) { 6455 PackageCleanItem item = iter.next(); 6456 if (pkgName.equals(item.packageName)) { 6457 iter.remove(); 6458 } 6459 } 6460 6461 // Take care of first install / last update times. 6462 if (currentTime != 0) { 6463 if (pkgSetting.firstInstallTime == 0) { 6464 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6465 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6466 pkgSetting.lastUpdateTime = currentTime; 6467 } 6468 } else if (pkgSetting.firstInstallTime == 0) { 6469 // We need *something*. Take time time stamp of the file. 6470 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6471 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6472 if (scanFileTime != pkgSetting.timeStamp) { 6473 // A package on the system image has changed; consider this 6474 // to be an update. 6475 pkgSetting.lastUpdateTime = scanFileTime; 6476 } 6477 } 6478 6479 // Add the package's KeySets to the global KeySetManagerService 6480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6481 try { 6482 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6483 if (pkg.mKeySetMapping != null) { 6484 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6485 if (pkg.mUpgradeKeySets != null) { 6486 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6487 } 6488 } 6489 } catch (NullPointerException e) { 6490 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6491 } catch (IllegalArgumentException e) { 6492 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6493 } 6494 6495 int N = pkg.providers.size(); 6496 StringBuilder r = null; 6497 int i; 6498 for (i=0; i<N; i++) { 6499 PackageParser.Provider p = pkg.providers.get(i); 6500 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6501 p.info.processName, pkg.applicationInfo.uid); 6502 mProviders.addProvider(p); 6503 p.syncable = p.info.isSyncable; 6504 if (p.info.authority != null) { 6505 String names[] = p.info.authority.split(";"); 6506 p.info.authority = null; 6507 for (int j = 0; j < names.length; j++) { 6508 if (j == 1 && p.syncable) { 6509 // We only want the first authority for a provider to possibly be 6510 // syncable, so if we already added this provider using a different 6511 // authority clear the syncable flag. We copy the provider before 6512 // changing it because the mProviders object contains a reference 6513 // to a provider that we don't want to change. 6514 // Only do this for the second authority since the resulting provider 6515 // object can be the same for all future authorities for this provider. 6516 p = new PackageParser.Provider(p); 6517 p.syncable = false; 6518 } 6519 if (!mProvidersByAuthority.containsKey(names[j])) { 6520 mProvidersByAuthority.put(names[j], p); 6521 if (p.info.authority == null) { 6522 p.info.authority = names[j]; 6523 } else { 6524 p.info.authority = p.info.authority + ";" + names[j]; 6525 } 6526 if (DEBUG_PACKAGE_SCANNING) { 6527 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6528 Log.d(TAG, "Registered content provider: " + names[j] 6529 + ", className = " + p.info.name + ", isSyncable = " 6530 + p.info.isSyncable); 6531 } 6532 } else { 6533 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6534 Slog.w(TAG, "Skipping provider name " + names[j] + 6535 " (in package " + pkg.applicationInfo.packageName + 6536 "): name already used by " 6537 + ((other != null && other.getComponentName() != null) 6538 ? other.getComponentName().getPackageName() : "?")); 6539 } 6540 } 6541 } 6542 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6543 if (r == null) { 6544 r = new StringBuilder(256); 6545 } else { 6546 r.append(' '); 6547 } 6548 r.append(p.info.name); 6549 } 6550 } 6551 if (r != null) { 6552 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6553 } 6554 6555 N = pkg.services.size(); 6556 r = null; 6557 for (i=0; i<N; i++) { 6558 PackageParser.Service s = pkg.services.get(i); 6559 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6560 s.info.processName, pkg.applicationInfo.uid); 6561 mServices.addService(s); 6562 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6563 if (r == null) { 6564 r = new StringBuilder(256); 6565 } else { 6566 r.append(' '); 6567 } 6568 r.append(s.info.name); 6569 } 6570 } 6571 if (r != null) { 6572 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6573 } 6574 6575 N = pkg.receivers.size(); 6576 r = null; 6577 for (i=0; i<N; i++) { 6578 PackageParser.Activity a = pkg.receivers.get(i); 6579 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6580 a.info.processName, pkg.applicationInfo.uid); 6581 mReceivers.addActivity(a, "receiver"); 6582 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6583 if (r == null) { 6584 r = new StringBuilder(256); 6585 } else { 6586 r.append(' '); 6587 } 6588 r.append(a.info.name); 6589 } 6590 } 6591 if (r != null) { 6592 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6593 } 6594 6595 N = pkg.activities.size(); 6596 r = null; 6597 for (i=0; i<N; i++) { 6598 PackageParser.Activity a = pkg.activities.get(i); 6599 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6600 a.info.processName, pkg.applicationInfo.uid); 6601 mActivities.addActivity(a, "activity"); 6602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6603 if (r == null) { 6604 r = new StringBuilder(256); 6605 } else { 6606 r.append(' '); 6607 } 6608 r.append(a.info.name); 6609 } 6610 } 6611 if (r != null) { 6612 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6613 } 6614 6615 N = pkg.permissionGroups.size(); 6616 r = null; 6617 for (i=0; i<N; i++) { 6618 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6619 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6620 if (cur == null) { 6621 mPermissionGroups.put(pg.info.name, pg); 6622 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6623 if (r == null) { 6624 r = new StringBuilder(256); 6625 } else { 6626 r.append(' '); 6627 } 6628 r.append(pg.info.name); 6629 } 6630 } else { 6631 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6632 + pg.info.packageName + " ignored: original from " 6633 + cur.info.packageName); 6634 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6635 if (r == null) { 6636 r = new StringBuilder(256); 6637 } else { 6638 r.append(' '); 6639 } 6640 r.append("DUP:"); 6641 r.append(pg.info.name); 6642 } 6643 } 6644 } 6645 if (r != null) { 6646 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6647 } 6648 6649 N = pkg.permissions.size(); 6650 r = null; 6651 for (i=0; i<N; i++) { 6652 PackageParser.Permission p = pkg.permissions.get(i); 6653 6654 // Now that permission groups have a special meaning, we ignore permission 6655 // groups for legacy apps to prevent unexpected behavior. In particular, 6656 // permissions for one app being granted to someone just becuase they happen 6657 // to be in a group defined by another app (before this had no implications). 6658 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6659 p.group = mPermissionGroups.get(p.info.group); 6660 // Warn for a permission in an unknown group. 6661 if (p.info.group != null && p.group == null) { 6662 Slog.w(TAG, "Permission " + p.info.name + " from package " 6663 + p.info.packageName + " in an unknown group " + p.info.group); 6664 } 6665 } 6666 6667 ArrayMap<String, BasePermission> permissionMap = 6668 p.tree ? mSettings.mPermissionTrees 6669 : mSettings.mPermissions; 6670 BasePermission bp = permissionMap.get(p.info.name); 6671 6672 // Allow system apps to redefine non-system permissions 6673 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6674 final boolean currentOwnerIsSystem = (bp.perm != null 6675 && isSystemApp(bp.perm.owner)); 6676 if (isSystemApp(p.owner)) { 6677 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6678 // It's a built-in permission and no owner, take ownership now 6679 bp.packageSetting = pkgSetting; 6680 bp.perm = p; 6681 bp.uid = pkg.applicationInfo.uid; 6682 bp.sourcePackage = p.info.packageName; 6683 } else if (!currentOwnerIsSystem) { 6684 String msg = "New decl " + p.owner + " of permission " 6685 + p.info.name + " is system; overriding " + bp.sourcePackage; 6686 reportSettingsProblem(Log.WARN, msg); 6687 bp = null; 6688 } 6689 } 6690 } 6691 6692 if (bp == null) { 6693 bp = new BasePermission(p.info.name, p.info.packageName, 6694 BasePermission.TYPE_NORMAL); 6695 permissionMap.put(p.info.name, bp); 6696 } 6697 6698 if (bp.perm == null) { 6699 if (bp.sourcePackage == null 6700 || bp.sourcePackage.equals(p.info.packageName)) { 6701 BasePermission tree = findPermissionTreeLP(p.info.name); 6702 if (tree == null 6703 || tree.sourcePackage.equals(p.info.packageName)) { 6704 bp.packageSetting = pkgSetting; 6705 bp.perm = p; 6706 bp.uid = pkg.applicationInfo.uid; 6707 bp.sourcePackage = p.info.packageName; 6708 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6709 if (r == null) { 6710 r = new StringBuilder(256); 6711 } else { 6712 r.append(' '); 6713 } 6714 r.append(p.info.name); 6715 } 6716 } else { 6717 Slog.w(TAG, "Permission " + p.info.name + " from package " 6718 + p.info.packageName + " ignored: base tree " 6719 + tree.name + " is from package " 6720 + tree.sourcePackage); 6721 } 6722 } else { 6723 Slog.w(TAG, "Permission " + p.info.name + " from package " 6724 + p.info.packageName + " ignored: original from " 6725 + bp.sourcePackage); 6726 } 6727 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append("DUP:"); 6734 r.append(p.info.name); 6735 } 6736 if (bp.perm == p) { 6737 bp.protectionLevel = p.info.protectionLevel; 6738 } 6739 } 6740 6741 if (r != null) { 6742 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6743 } 6744 6745 N = pkg.instrumentation.size(); 6746 r = null; 6747 for (i=0; i<N; i++) { 6748 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6749 a.info.packageName = pkg.applicationInfo.packageName; 6750 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6751 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6752 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6753 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6754 a.info.dataDir = pkg.applicationInfo.dataDir; 6755 6756 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6757 // need other information about the application, like the ABI and what not ? 6758 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6759 mInstrumentation.put(a.getComponentName(), a); 6760 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6761 if (r == null) { 6762 r = new StringBuilder(256); 6763 } else { 6764 r.append(' '); 6765 } 6766 r.append(a.info.name); 6767 } 6768 } 6769 if (r != null) { 6770 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6771 } 6772 6773 if (pkg.protectedBroadcasts != null) { 6774 N = pkg.protectedBroadcasts.size(); 6775 for (i=0; i<N; i++) { 6776 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6777 } 6778 } 6779 6780 pkgSetting.setTimeStamp(scanFileTime); 6781 6782 // Create idmap files for pairs of (packages, overlay packages). 6783 // Note: "android", ie framework-res.apk, is handled by native layers. 6784 if (pkg.mOverlayTarget != null) { 6785 // This is an overlay package. 6786 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6787 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6788 mOverlays.put(pkg.mOverlayTarget, 6789 new ArrayMap<String, PackageParser.Package>()); 6790 } 6791 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6792 map.put(pkg.packageName, pkg); 6793 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6794 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6795 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6796 "scanPackageLI failed to createIdmap"); 6797 } 6798 } 6799 } else if (mOverlays.containsKey(pkg.packageName) && 6800 !pkg.packageName.equals("android")) { 6801 // This is a regular package, with one or more known overlay packages. 6802 createIdmapsForPackageLI(pkg); 6803 } 6804 } 6805 6806 return pkg; 6807 } 6808 6809 /** 6810 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6811 * i.e, so that all packages can be run inside a single process if required. 6812 * 6813 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6814 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6815 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6816 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6817 * updating a package that belongs to a shared user. 6818 * 6819 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6820 * adds unnecessary complexity. 6821 */ 6822 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6823 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6824 String requiredInstructionSet = null; 6825 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6826 requiredInstructionSet = VMRuntime.getInstructionSet( 6827 scannedPackage.applicationInfo.primaryCpuAbi); 6828 } 6829 6830 PackageSetting requirer = null; 6831 for (PackageSetting ps : packagesForUser) { 6832 // If packagesForUser contains scannedPackage, we skip it. This will happen 6833 // when scannedPackage is an update of an existing package. Without this check, 6834 // we will never be able to change the ABI of any package belonging to a shared 6835 // user, even if it's compatible with other packages. 6836 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6837 if (ps.primaryCpuAbiString == null) { 6838 continue; 6839 } 6840 6841 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6842 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6843 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6844 // this but there's not much we can do. 6845 String errorMessage = "Instruction set mismatch, " 6846 + ((requirer == null) ? "[caller]" : requirer) 6847 + " requires " + requiredInstructionSet + " whereas " + ps 6848 + " requires " + instructionSet; 6849 Slog.w(TAG, errorMessage); 6850 } 6851 6852 if (requiredInstructionSet == null) { 6853 requiredInstructionSet = instructionSet; 6854 requirer = ps; 6855 } 6856 } 6857 } 6858 6859 if (requiredInstructionSet != null) { 6860 String adjustedAbi; 6861 if (requirer != null) { 6862 // requirer != null implies that either scannedPackage was null or that scannedPackage 6863 // did not require an ABI, in which case we have to adjust scannedPackage to match 6864 // the ABI of the set (which is the same as requirer's ABI) 6865 adjustedAbi = requirer.primaryCpuAbiString; 6866 if (scannedPackage != null) { 6867 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6868 } 6869 } else { 6870 // requirer == null implies that we're updating all ABIs in the set to 6871 // match scannedPackage. 6872 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6873 } 6874 6875 for (PackageSetting ps : packagesForUser) { 6876 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6877 if (ps.primaryCpuAbiString != null) { 6878 continue; 6879 } 6880 6881 ps.primaryCpuAbiString = adjustedAbi; 6882 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6883 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6884 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6885 6886 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6887 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6888 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6889 ps.primaryCpuAbiString = null; 6890 ps.pkg.applicationInfo.primaryCpuAbi = null; 6891 return; 6892 } else { 6893 mInstaller.rmdex(ps.codePathString, 6894 getDexCodeInstructionSet(getPreferredInstructionSet())); 6895 } 6896 } 6897 } 6898 } 6899 } 6900 } 6901 6902 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6903 synchronized (mPackages) { 6904 mResolverReplaced = true; 6905 // Set up information for custom user intent resolution activity. 6906 mResolveActivity.applicationInfo = pkg.applicationInfo; 6907 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6908 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6909 mResolveActivity.processName = pkg.applicationInfo.packageName; 6910 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6911 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6912 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6913 mResolveActivity.theme = 0; 6914 mResolveActivity.exported = true; 6915 mResolveActivity.enabled = true; 6916 mResolveInfo.activityInfo = mResolveActivity; 6917 mResolveInfo.priority = 0; 6918 mResolveInfo.preferredOrder = 0; 6919 mResolveInfo.match = 0; 6920 mResolveComponentName = mCustomResolverComponentName; 6921 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6922 mResolveComponentName); 6923 } 6924 } 6925 6926 private static String calculateBundledApkRoot(final String codePathString) { 6927 final File codePath = new File(codePathString); 6928 final File codeRoot; 6929 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6930 codeRoot = Environment.getRootDirectory(); 6931 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6932 codeRoot = Environment.getOemDirectory(); 6933 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6934 codeRoot = Environment.getVendorDirectory(); 6935 } else { 6936 // Unrecognized code path; take its top real segment as the apk root: 6937 // e.g. /something/app/blah.apk => /something 6938 try { 6939 File f = codePath.getCanonicalFile(); 6940 File parent = f.getParentFile(); // non-null because codePath is a file 6941 File tmp; 6942 while ((tmp = parent.getParentFile()) != null) { 6943 f = parent; 6944 parent = tmp; 6945 } 6946 codeRoot = f; 6947 Slog.w(TAG, "Unrecognized code path " 6948 + codePath + " - using " + codeRoot); 6949 } catch (IOException e) { 6950 // Can't canonicalize the code path -- shenanigans? 6951 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6952 return Environment.getRootDirectory().getPath(); 6953 } 6954 } 6955 return codeRoot.getPath(); 6956 } 6957 6958 /** 6959 * Derive and set the location of native libraries for the given package, 6960 * which varies depending on where and how the package was installed. 6961 */ 6962 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6963 final ApplicationInfo info = pkg.applicationInfo; 6964 final String codePath = pkg.codePath; 6965 final File codeFile = new File(codePath); 6966 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6967 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6968 6969 info.nativeLibraryRootDir = null; 6970 info.nativeLibraryRootRequiresIsa = false; 6971 info.nativeLibraryDir = null; 6972 info.secondaryNativeLibraryDir = null; 6973 6974 if (isApkFile(codeFile)) { 6975 // Monolithic install 6976 if (bundledApp) { 6977 // If "/system/lib64/apkname" exists, assume that is the per-package 6978 // native library directory to use; otherwise use "/system/lib/apkname". 6979 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6980 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6981 getPrimaryInstructionSet(info)); 6982 6983 // This is a bundled system app so choose the path based on the ABI. 6984 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6985 // is just the default path. 6986 final String apkName = deriveCodePathName(codePath); 6987 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6988 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6989 apkName).getAbsolutePath(); 6990 6991 if (info.secondaryCpuAbi != null) { 6992 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6993 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6994 secondaryLibDir, apkName).getAbsolutePath(); 6995 } 6996 } else if (asecApp) { 6997 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6998 .getAbsolutePath(); 6999 } else { 7000 final String apkName = deriveCodePathName(codePath); 7001 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7002 .getAbsolutePath(); 7003 } 7004 7005 info.nativeLibraryRootRequiresIsa = false; 7006 info.nativeLibraryDir = info.nativeLibraryRootDir; 7007 } else { 7008 // Cluster install 7009 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7010 info.nativeLibraryRootRequiresIsa = true; 7011 7012 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7013 getPrimaryInstructionSet(info)).getAbsolutePath(); 7014 7015 if (info.secondaryCpuAbi != null) { 7016 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7017 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7018 } 7019 } 7020 } 7021 7022 /** 7023 * Calculate the abis and roots for a bundled app. These can uniquely 7024 * be determined from the contents of the system partition, i.e whether 7025 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7026 * of this information, and instead assume that the system was built 7027 * sensibly. 7028 */ 7029 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7030 PackageSetting pkgSetting) { 7031 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7032 7033 // If "/system/lib64/apkname" exists, assume that is the per-package 7034 // native library directory to use; otherwise use "/system/lib/apkname". 7035 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7036 setBundledAppAbi(pkg, apkRoot, apkName); 7037 // pkgSetting might be null during rescan following uninstall of updates 7038 // to a bundled app, so accommodate that possibility. The settings in 7039 // that case will be established later from the parsed package. 7040 // 7041 // If the settings aren't null, sync them up with what we've just derived. 7042 // note that apkRoot isn't stored in the package settings. 7043 if (pkgSetting != null) { 7044 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7045 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7046 } 7047 } 7048 7049 /** 7050 * Deduces the ABI of a bundled app and sets the relevant fields on the 7051 * parsed pkg object. 7052 * 7053 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7054 * under which system libraries are installed. 7055 * @param apkName the name of the installed package. 7056 */ 7057 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7058 final File codeFile = new File(pkg.codePath); 7059 7060 final boolean has64BitLibs; 7061 final boolean has32BitLibs; 7062 if (isApkFile(codeFile)) { 7063 // Monolithic install 7064 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7065 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7066 } else { 7067 // Cluster install 7068 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7069 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7070 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7071 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7072 has64BitLibs = (new File(rootDir, isa)).exists(); 7073 } else { 7074 has64BitLibs = false; 7075 } 7076 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7077 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7078 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7079 has32BitLibs = (new File(rootDir, isa)).exists(); 7080 } else { 7081 has32BitLibs = false; 7082 } 7083 } 7084 7085 if (has64BitLibs && !has32BitLibs) { 7086 // The package has 64 bit libs, but not 32 bit libs. Its primary 7087 // ABI should be 64 bit. We can safely assume here that the bundled 7088 // native libraries correspond to the most preferred ABI in the list. 7089 7090 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7091 pkg.applicationInfo.secondaryCpuAbi = null; 7092 } else if (has32BitLibs && !has64BitLibs) { 7093 // The package has 32 bit libs but not 64 bit libs. Its primary 7094 // ABI should be 32 bit. 7095 7096 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7097 pkg.applicationInfo.secondaryCpuAbi = null; 7098 } else if (has32BitLibs && has64BitLibs) { 7099 // The application has both 64 and 32 bit bundled libraries. We check 7100 // here that the app declares multiArch support, and warn if it doesn't. 7101 // 7102 // We will be lenient here and record both ABIs. The primary will be the 7103 // ABI that's higher on the list, i.e, a device that's configured to prefer 7104 // 64 bit apps will see a 64 bit primary ABI, 7105 7106 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7107 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7108 } 7109 7110 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7111 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7112 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7113 } else { 7114 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7115 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7116 } 7117 } else { 7118 pkg.applicationInfo.primaryCpuAbi = null; 7119 pkg.applicationInfo.secondaryCpuAbi = null; 7120 } 7121 } 7122 7123 private void killApplication(String pkgName, int appId, String reason) { 7124 // Request the ActivityManager to kill the process(only for existing packages) 7125 // so that we do not end up in a confused state while the user is still using the older 7126 // version of the application while the new one gets installed. 7127 IActivityManager am = ActivityManagerNative.getDefault(); 7128 if (am != null) { 7129 try { 7130 am.killApplicationWithAppId(pkgName, appId, reason); 7131 } catch (RemoteException e) { 7132 } 7133 } 7134 } 7135 7136 void removePackageLI(PackageSetting ps, boolean chatty) { 7137 if (DEBUG_INSTALL) { 7138 if (chatty) 7139 Log.d(TAG, "Removing package " + ps.name); 7140 } 7141 7142 // writer 7143 synchronized (mPackages) { 7144 mPackages.remove(ps.name); 7145 final PackageParser.Package pkg = ps.pkg; 7146 if (pkg != null) { 7147 cleanPackageDataStructuresLILPw(pkg, chatty); 7148 } 7149 } 7150 } 7151 7152 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7153 if (DEBUG_INSTALL) { 7154 if (chatty) 7155 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7156 } 7157 7158 // writer 7159 synchronized (mPackages) { 7160 mPackages.remove(pkg.applicationInfo.packageName); 7161 cleanPackageDataStructuresLILPw(pkg, chatty); 7162 } 7163 } 7164 7165 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7166 int N = pkg.providers.size(); 7167 StringBuilder r = null; 7168 int i; 7169 for (i=0; i<N; i++) { 7170 PackageParser.Provider p = pkg.providers.get(i); 7171 mProviders.removeProvider(p); 7172 if (p.info.authority == null) { 7173 7174 /* There was another ContentProvider with this authority when 7175 * this app was installed so this authority is null, 7176 * Ignore it as we don't have to unregister the provider. 7177 */ 7178 continue; 7179 } 7180 String names[] = p.info.authority.split(";"); 7181 for (int j = 0; j < names.length; j++) { 7182 if (mProvidersByAuthority.get(names[j]) == p) { 7183 mProvidersByAuthority.remove(names[j]); 7184 if (DEBUG_REMOVE) { 7185 if (chatty) 7186 Log.d(TAG, "Unregistered content provider: " + names[j] 7187 + ", className = " + p.info.name + ", isSyncable = " 7188 + p.info.isSyncable); 7189 } 7190 } 7191 } 7192 if (DEBUG_REMOVE && chatty) { 7193 if (r == null) { 7194 r = new StringBuilder(256); 7195 } else { 7196 r.append(' '); 7197 } 7198 r.append(p.info.name); 7199 } 7200 } 7201 if (r != null) { 7202 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7203 } 7204 7205 N = pkg.services.size(); 7206 r = null; 7207 for (i=0; i<N; i++) { 7208 PackageParser.Service s = pkg.services.get(i); 7209 mServices.removeService(s); 7210 if (chatty) { 7211 if (r == null) { 7212 r = new StringBuilder(256); 7213 } else { 7214 r.append(' '); 7215 } 7216 r.append(s.info.name); 7217 } 7218 } 7219 if (r != null) { 7220 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7221 } 7222 7223 N = pkg.receivers.size(); 7224 r = null; 7225 for (i=0; i<N; i++) { 7226 PackageParser.Activity a = pkg.receivers.get(i); 7227 mReceivers.removeActivity(a, "receiver"); 7228 if (DEBUG_REMOVE && chatty) { 7229 if (r == null) { 7230 r = new StringBuilder(256); 7231 } else { 7232 r.append(' '); 7233 } 7234 r.append(a.info.name); 7235 } 7236 } 7237 if (r != null) { 7238 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7239 } 7240 7241 N = pkg.activities.size(); 7242 r = null; 7243 for (i=0; i<N; i++) { 7244 PackageParser.Activity a = pkg.activities.get(i); 7245 mActivities.removeActivity(a, "activity"); 7246 if (DEBUG_REMOVE && chatty) { 7247 if (r == null) { 7248 r = new StringBuilder(256); 7249 } else { 7250 r.append(' '); 7251 } 7252 r.append(a.info.name); 7253 } 7254 } 7255 if (r != null) { 7256 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7257 } 7258 7259 N = pkg.permissions.size(); 7260 r = null; 7261 for (i=0; i<N; i++) { 7262 PackageParser.Permission p = pkg.permissions.get(i); 7263 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7264 if (bp == null) { 7265 bp = mSettings.mPermissionTrees.get(p.info.name); 7266 } 7267 if (bp != null && bp.perm == p) { 7268 bp.perm = null; 7269 if (DEBUG_REMOVE && chatty) { 7270 if (r == null) { 7271 r = new StringBuilder(256); 7272 } else { 7273 r.append(' '); 7274 } 7275 r.append(p.info.name); 7276 } 7277 } 7278 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7279 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7280 if (appOpPerms != null) { 7281 appOpPerms.remove(pkg.packageName); 7282 } 7283 } 7284 } 7285 if (r != null) { 7286 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7287 } 7288 7289 N = pkg.requestedPermissions.size(); 7290 r = null; 7291 for (i=0; i<N; i++) { 7292 String perm = pkg.requestedPermissions.get(i); 7293 BasePermission bp = mSettings.mPermissions.get(perm); 7294 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7295 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7296 if (appOpPerms != null) { 7297 appOpPerms.remove(pkg.packageName); 7298 if (appOpPerms.isEmpty()) { 7299 mAppOpPermissionPackages.remove(perm); 7300 } 7301 } 7302 } 7303 } 7304 if (r != null) { 7305 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7306 } 7307 7308 N = pkg.instrumentation.size(); 7309 r = null; 7310 for (i=0; i<N; i++) { 7311 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7312 mInstrumentation.remove(a.getComponentName()); 7313 if (DEBUG_REMOVE && chatty) { 7314 if (r == null) { 7315 r = new StringBuilder(256); 7316 } else { 7317 r.append(' '); 7318 } 7319 r.append(a.info.name); 7320 } 7321 } 7322 if (r != null) { 7323 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7324 } 7325 7326 r = null; 7327 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7328 // Only system apps can hold shared libraries. 7329 if (pkg.libraryNames != null) { 7330 for (i=0; i<pkg.libraryNames.size(); i++) { 7331 String name = pkg.libraryNames.get(i); 7332 SharedLibraryEntry cur = mSharedLibraries.get(name); 7333 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7334 mSharedLibraries.remove(name); 7335 if (DEBUG_REMOVE && chatty) { 7336 if (r == null) { 7337 r = new StringBuilder(256); 7338 } else { 7339 r.append(' '); 7340 } 7341 r.append(name); 7342 } 7343 } 7344 } 7345 } 7346 } 7347 if (r != null) { 7348 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7349 } 7350 } 7351 7352 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7353 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7354 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7355 return true; 7356 } 7357 } 7358 return false; 7359 } 7360 7361 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7362 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7363 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7364 7365 private void updatePermissionsLPw(String changingPkg, 7366 PackageParser.Package pkgInfo, int flags) { 7367 // Make sure there are no dangling permission trees. 7368 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7369 while (it.hasNext()) { 7370 final BasePermission bp = it.next(); 7371 if (bp.packageSetting == null) { 7372 // We may not yet have parsed the package, so just see if 7373 // we still know about its settings. 7374 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7375 } 7376 if (bp.packageSetting == null) { 7377 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7378 + " from package " + bp.sourcePackage); 7379 it.remove(); 7380 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7381 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7382 Slog.i(TAG, "Removing old permission tree: " + bp.name 7383 + " from package " + bp.sourcePackage); 7384 flags |= UPDATE_PERMISSIONS_ALL; 7385 it.remove(); 7386 } 7387 } 7388 } 7389 7390 // Make sure all dynamic permissions have been assigned to a package, 7391 // and make sure there are no dangling permissions. 7392 it = mSettings.mPermissions.values().iterator(); 7393 while (it.hasNext()) { 7394 final BasePermission bp = it.next(); 7395 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7396 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7397 + bp.name + " pkg=" + bp.sourcePackage 7398 + " info=" + bp.pendingInfo); 7399 if (bp.packageSetting == null && bp.pendingInfo != null) { 7400 final BasePermission tree = findPermissionTreeLP(bp.name); 7401 if (tree != null && tree.perm != null) { 7402 bp.packageSetting = tree.packageSetting; 7403 bp.perm = new PackageParser.Permission(tree.perm.owner, 7404 new PermissionInfo(bp.pendingInfo)); 7405 bp.perm.info.packageName = tree.perm.info.packageName; 7406 bp.perm.info.name = bp.name; 7407 bp.uid = tree.uid; 7408 } 7409 } 7410 } 7411 if (bp.packageSetting == null) { 7412 // We may not yet have parsed the package, so just see if 7413 // we still know about its settings. 7414 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7415 } 7416 if (bp.packageSetting == null) { 7417 Slog.w(TAG, "Removing dangling permission: " + bp.name 7418 + " from package " + bp.sourcePackage); 7419 it.remove(); 7420 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7421 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7422 Slog.i(TAG, "Removing old permission: " + bp.name 7423 + " from package " + bp.sourcePackage); 7424 flags |= UPDATE_PERMISSIONS_ALL; 7425 it.remove(); 7426 } 7427 } 7428 } 7429 7430 // Now update the permissions for all packages, in particular 7431 // replace the granted permissions of the system packages. 7432 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7433 for (PackageParser.Package pkg : mPackages.values()) { 7434 if (pkg != pkgInfo) { 7435 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7436 changingPkg); 7437 } 7438 } 7439 } 7440 7441 if (pkgInfo != null) { 7442 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7443 } 7444 } 7445 7446 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7447 String packageOfInterest) { 7448 // IMPORTANT: There are two types of permissions: install and runtime. 7449 // Install time permissions are granted when the app is installed to 7450 // all device users and users added in the future. Runtime permissions 7451 // are granted at runtime explicitly to specific users. Normal and signature 7452 // protected permissions are install time permissions. Dangerous permissions 7453 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7454 // otherwise they are runtime permissions. This function does not manage 7455 // runtime permissions except for the case an app targeting Lollipop MR1 7456 // being upgraded to target a newer SDK, in which case dangerous permissions 7457 // are transformed from install time to runtime ones. 7458 7459 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7460 if (ps == null) { 7461 return; 7462 } 7463 7464 PermissionsState permissionsState = ps.getPermissionsState(); 7465 PermissionsState origPermissions = permissionsState; 7466 7467 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7468 7469 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7470 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7471 7472 boolean changedInstallPermission = false; 7473 7474 if (replace) { 7475 ps.installPermissionsFixed = false; 7476 if (!ps.isSharedUser()) { 7477 origPermissions = new PermissionsState(permissionsState); 7478 permissionsState.reset(); 7479 } 7480 } 7481 7482 permissionsState.setGlobalGids(mGlobalGids); 7483 7484 final int N = pkg.requestedPermissions.size(); 7485 for (int i=0; i<N; i++) { 7486 final String name = pkg.requestedPermissions.get(i); 7487 final BasePermission bp = mSettings.mPermissions.get(name); 7488 7489 if (DEBUG_INSTALL) { 7490 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7491 } 7492 7493 if (bp == null || bp.packageSetting == null) { 7494 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7495 Slog.w(TAG, "Unknown permission " + name 7496 + " in package " + pkg.packageName); 7497 } 7498 continue; 7499 } 7500 7501 final String perm = bp.name; 7502 boolean allowedSig = false; 7503 int grant = GRANT_DENIED; 7504 7505 // Keep track of app op permissions. 7506 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7507 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7508 if (pkgs == null) { 7509 pkgs = new ArraySet<>(); 7510 mAppOpPermissionPackages.put(bp.name, pkgs); 7511 } 7512 pkgs.add(pkg.packageName); 7513 } 7514 7515 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7516 switch (level) { 7517 case PermissionInfo.PROTECTION_NORMAL: { 7518 // For all apps normal permissions are install time ones. 7519 grant = GRANT_INSTALL; 7520 } break; 7521 7522 case PermissionInfo.PROTECTION_DANGEROUS: { 7523 if (!RUNTIME_PERMISSIONS_ENABLED 7524 || pkg.applicationInfo.targetSdkVersion 7525 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7526 // For legacy apps dangerous permissions are install time ones. 7527 grant = GRANT_INSTALL; 7528 } else if (ps.isSystem()) { 7529 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7530 if (origPermissions.hasInstallPermission(bp.name)) { 7531 // If a system app had an install permission, then the app was 7532 // upgraded and we grant the permissions as runtime to all users. 7533 grant = GRANT_UPGRADE; 7534 upgradeUserIds = currentUserIds; 7535 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7536 // If users changed since the last permissions update for a 7537 // system app, we grant the permission as runtime to the new users. 7538 grant = GRANT_UPGRADE; 7539 upgradeUserIds = currentUserIds; 7540 for (int userId : updatedUserIds) { 7541 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7542 } 7543 } else { 7544 // Otherwise, we grant the permission as runtime if the app 7545 // already had it, i.e. we preserve runtime permissions. 7546 grant = GRANT_RUNTIME; 7547 } 7548 } else if (origPermissions.hasInstallPermission(bp.name)) { 7549 // For legacy apps that became modern, install becomes runtime. 7550 grant = GRANT_UPGRADE; 7551 upgradeUserIds = currentUserIds; 7552 } else if (replace) { 7553 // For upgraded modern apps keep runtime permissions unchanged. 7554 grant = GRANT_RUNTIME; 7555 } 7556 } break; 7557 7558 case PermissionInfo.PROTECTION_SIGNATURE: { 7559 // For all apps signature permissions are install time ones. 7560 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7561 if (allowedSig) { 7562 grant = GRANT_INSTALL; 7563 } 7564 } break; 7565 } 7566 7567 if (DEBUG_INSTALL) { 7568 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7569 } 7570 7571 if (grant != GRANT_DENIED) { 7572 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7573 // If this is an existing, non-system package, then 7574 // we can't add any new permissions to it. 7575 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7576 // Except... if this is a permission that was added 7577 // to the platform (note: need to only do this when 7578 // updating the platform). 7579 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7580 grant = GRANT_DENIED; 7581 } 7582 } 7583 } 7584 7585 switch (grant) { 7586 case GRANT_INSTALL: { 7587 // Grant an install permission. 7588 if (permissionsState.grantInstallPermission(bp) != 7589 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7590 changedInstallPermission = true; 7591 } 7592 } break; 7593 7594 case GRANT_RUNTIME: { 7595 // Grant previously granted runtime permissions. 7596 for (int userId : UserManagerService.getInstance().getUserIds()) { 7597 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7598 if (permissionsState.grantRuntimePermission(bp, userId) == 7599 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7600 // If we cannot put the permission as it was, we have to write. 7601 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7602 changedRuntimePermissionUserIds, userId); 7603 } 7604 } 7605 } 7606 } break; 7607 7608 case GRANT_UPGRADE: { 7609 // Grant runtime permissions for a previously held install permission. 7610 permissionsState.revokeInstallPermission(bp); 7611 for (int userId : upgradeUserIds) { 7612 if (permissionsState.grantRuntimePermission(bp, userId) != 7613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7614 // If we granted the permission, we have to write. 7615 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7616 changedRuntimePermissionUserIds, userId); 7617 } 7618 } 7619 } break; 7620 7621 default: { 7622 if (packageOfInterest == null 7623 || packageOfInterest.equals(pkg.packageName)) { 7624 Slog.w(TAG, "Not granting permission " + perm 7625 + " to package " + pkg.packageName 7626 + " because it was previously installed without"); 7627 } 7628 } break; 7629 } 7630 } else { 7631 if (permissionsState.revokeInstallPermission(bp) != 7632 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7633 changedInstallPermission = true; 7634 Slog.i(TAG, "Un-granting permission " + perm 7635 + " from package " + pkg.packageName 7636 + " (protectionLevel=" + bp.protectionLevel 7637 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7638 + ")"); 7639 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7640 // Don't print warning for app op permissions, since it is fine for them 7641 // not to be granted, there is a UI for the user to decide. 7642 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7643 Slog.w(TAG, "Not granting permission " + perm 7644 + " to package " + pkg.packageName 7645 + " (protectionLevel=" + bp.protectionLevel 7646 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7647 + ")"); 7648 } 7649 } 7650 } 7651 } 7652 7653 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7654 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7655 // This is the first that we have heard about this package, so the 7656 // permissions we have now selected are fixed until explicitly 7657 // changed. 7658 ps.installPermissionsFixed = true; 7659 } 7660 7661 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7662 7663 // Persist the runtime permissions state for users with changes. 7664 if (RUNTIME_PERMISSIONS_ENABLED) { 7665 for (int userId : changedRuntimePermissionUserIds) { 7666 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7667 } 7668 } 7669 } 7670 7671 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7672 boolean allowed = false; 7673 final int NP = PackageParser.NEW_PERMISSIONS.length; 7674 for (int ip=0; ip<NP; ip++) { 7675 final PackageParser.NewPermissionInfo npi 7676 = PackageParser.NEW_PERMISSIONS[ip]; 7677 if (npi.name.equals(perm) 7678 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7679 allowed = true; 7680 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7681 + pkg.packageName); 7682 break; 7683 } 7684 } 7685 return allowed; 7686 } 7687 7688 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7689 BasePermission bp, PermissionsState origPermissions) { 7690 boolean allowed; 7691 allowed = (compareSignatures( 7692 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7693 == PackageManager.SIGNATURE_MATCH) 7694 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7695 == PackageManager.SIGNATURE_MATCH); 7696 if (!allowed && (bp.protectionLevel 7697 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7698 if (isSystemApp(pkg)) { 7699 // For updated system applications, a system permission 7700 // is granted only if it had been defined by the original application. 7701 if (pkg.isUpdatedSystemApp()) { 7702 final PackageSetting sysPs = mSettings 7703 .getDisabledSystemPkgLPr(pkg.packageName); 7704 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7705 // If the original was granted this permission, we take 7706 // that grant decision as read and propagate it to the 7707 // update. 7708 if (sysPs.isPrivileged()) { 7709 allowed = true; 7710 } 7711 } else { 7712 // The system apk may have been updated with an older 7713 // version of the one on the data partition, but which 7714 // granted a new system permission that it didn't have 7715 // before. In this case we do want to allow the app to 7716 // now get the new permission if the ancestral apk is 7717 // privileged to get it. 7718 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7719 for (int j=0; 7720 j<sysPs.pkg.requestedPermissions.size(); j++) { 7721 if (perm.equals( 7722 sysPs.pkg.requestedPermissions.get(j))) { 7723 allowed = true; 7724 break; 7725 } 7726 } 7727 } 7728 } 7729 } else { 7730 allowed = isPrivilegedApp(pkg); 7731 } 7732 } 7733 } 7734 if (!allowed && (bp.protectionLevel 7735 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7736 // For development permissions, a development permission 7737 // is granted only if it was already granted. 7738 allowed = origPermissions.hasInstallPermission(perm); 7739 } 7740 return allowed; 7741 } 7742 7743 final class ActivityIntentResolver 7744 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7745 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7746 boolean defaultOnly, int userId) { 7747 if (!sUserManager.exists(userId)) return null; 7748 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7749 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7750 } 7751 7752 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7753 int userId) { 7754 if (!sUserManager.exists(userId)) return null; 7755 mFlags = flags; 7756 return super.queryIntent(intent, resolvedType, 7757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7758 } 7759 7760 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7761 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7762 if (!sUserManager.exists(userId)) return null; 7763 if (packageActivities == null) { 7764 return null; 7765 } 7766 mFlags = flags; 7767 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7768 final int N = packageActivities.size(); 7769 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7770 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7771 7772 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7773 for (int i = 0; i < N; ++i) { 7774 intentFilters = packageActivities.get(i).intents; 7775 if (intentFilters != null && intentFilters.size() > 0) { 7776 PackageParser.ActivityIntentInfo[] array = 7777 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7778 intentFilters.toArray(array); 7779 listCut.add(array); 7780 } 7781 } 7782 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7783 } 7784 7785 public final void addActivity(PackageParser.Activity a, String type) { 7786 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7787 mActivities.put(a.getComponentName(), a); 7788 if (DEBUG_SHOW_INFO) 7789 Log.v( 7790 TAG, " " + type + " " + 7791 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7792 if (DEBUG_SHOW_INFO) 7793 Log.v(TAG, " Class=" + a.info.name); 7794 final int NI = a.intents.size(); 7795 for (int j=0; j<NI; j++) { 7796 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7797 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7798 intent.setPriority(0); 7799 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7800 + a.className + " with priority > 0, forcing to 0"); 7801 } 7802 if (DEBUG_SHOW_INFO) { 7803 Log.v(TAG, " IntentFilter:"); 7804 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7805 } 7806 if (!intent.debugCheck()) { 7807 Log.w(TAG, "==> For Activity " + a.info.name); 7808 } 7809 addFilter(intent); 7810 } 7811 } 7812 7813 public final void removeActivity(PackageParser.Activity a, String type) { 7814 mActivities.remove(a.getComponentName()); 7815 if (DEBUG_SHOW_INFO) { 7816 Log.v(TAG, " " + type + " " 7817 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7818 : a.info.name) + ":"); 7819 Log.v(TAG, " Class=" + a.info.name); 7820 } 7821 final int NI = a.intents.size(); 7822 for (int j=0; j<NI; j++) { 7823 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7824 if (DEBUG_SHOW_INFO) { 7825 Log.v(TAG, " IntentFilter:"); 7826 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7827 } 7828 removeFilter(intent); 7829 } 7830 } 7831 7832 @Override 7833 protected boolean allowFilterResult( 7834 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7835 ActivityInfo filterAi = filter.activity.info; 7836 for (int i=dest.size()-1; i>=0; i--) { 7837 ActivityInfo destAi = dest.get(i).activityInfo; 7838 if (destAi.name == filterAi.name 7839 && destAi.packageName == filterAi.packageName) { 7840 return false; 7841 } 7842 } 7843 return true; 7844 } 7845 7846 @Override 7847 protected ActivityIntentInfo[] newArray(int size) { 7848 return new ActivityIntentInfo[size]; 7849 } 7850 7851 @Override 7852 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7853 if (!sUserManager.exists(userId)) return true; 7854 PackageParser.Package p = filter.activity.owner; 7855 if (p != null) { 7856 PackageSetting ps = (PackageSetting)p.mExtras; 7857 if (ps != null) { 7858 // System apps are never considered stopped for purposes of 7859 // filtering, because there may be no way for the user to 7860 // actually re-launch them. 7861 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7862 && ps.getStopped(userId); 7863 } 7864 } 7865 return false; 7866 } 7867 7868 @Override 7869 protected boolean isPackageForFilter(String packageName, 7870 PackageParser.ActivityIntentInfo info) { 7871 return packageName.equals(info.activity.owner.packageName); 7872 } 7873 7874 @Override 7875 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7876 int match, int userId) { 7877 if (!sUserManager.exists(userId)) return null; 7878 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7879 return null; 7880 } 7881 final PackageParser.Activity activity = info.activity; 7882 if (mSafeMode && (activity.info.applicationInfo.flags 7883 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7884 return null; 7885 } 7886 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7887 if (ps == null) { 7888 return null; 7889 } 7890 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7891 ps.readUserState(userId), userId); 7892 if (ai == null) { 7893 return null; 7894 } 7895 final ResolveInfo res = new ResolveInfo(); 7896 res.activityInfo = ai; 7897 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7898 res.filter = info; 7899 } 7900 if (info != null) { 7901 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7902 } 7903 res.priority = info.getPriority(); 7904 res.preferredOrder = activity.owner.mPreferredOrder; 7905 //System.out.println("Result: " + res.activityInfo.className + 7906 // " = " + res.priority); 7907 res.match = match; 7908 res.isDefault = info.hasDefault; 7909 res.labelRes = info.labelRes; 7910 res.nonLocalizedLabel = info.nonLocalizedLabel; 7911 if (userNeedsBadging(userId)) { 7912 res.noResourceId = true; 7913 } else { 7914 res.icon = info.icon; 7915 } 7916 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7917 return res; 7918 } 7919 7920 @Override 7921 protected void sortResults(List<ResolveInfo> results) { 7922 Collections.sort(results, mResolvePrioritySorter); 7923 } 7924 7925 @Override 7926 protected void dumpFilter(PrintWriter out, String prefix, 7927 PackageParser.ActivityIntentInfo filter) { 7928 out.print(prefix); out.print( 7929 Integer.toHexString(System.identityHashCode(filter.activity))); 7930 out.print(' '); 7931 filter.activity.printComponentShortName(out); 7932 out.print(" filter "); 7933 out.println(Integer.toHexString(System.identityHashCode(filter))); 7934 } 7935 7936 @Override 7937 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7938 return filter.activity; 7939 } 7940 7941 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7942 PackageParser.Activity activity = (PackageParser.Activity)label; 7943 out.print(prefix); out.print( 7944 Integer.toHexString(System.identityHashCode(activity))); 7945 out.print(' '); 7946 activity.printComponentShortName(out); 7947 if (count > 1) { 7948 out.print(" ("); out.print(count); out.print(" filters)"); 7949 } 7950 out.println(); 7951 } 7952 7953// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7954// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7955// final List<ResolveInfo> retList = Lists.newArrayList(); 7956// while (i.hasNext()) { 7957// final ResolveInfo resolveInfo = i.next(); 7958// if (isEnabledLP(resolveInfo.activityInfo)) { 7959// retList.add(resolveInfo); 7960// } 7961// } 7962// return retList; 7963// } 7964 7965 // Keys are String (activity class name), values are Activity. 7966 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7967 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7968 private int mFlags; 7969 } 7970 7971 private final class ServiceIntentResolver 7972 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7973 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7974 boolean defaultOnly, int userId) { 7975 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7976 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7977 } 7978 7979 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7980 int userId) { 7981 if (!sUserManager.exists(userId)) return null; 7982 mFlags = flags; 7983 return super.queryIntent(intent, resolvedType, 7984 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7985 } 7986 7987 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7988 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7989 if (!sUserManager.exists(userId)) return null; 7990 if (packageServices == null) { 7991 return null; 7992 } 7993 mFlags = flags; 7994 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7995 final int N = packageServices.size(); 7996 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7997 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7998 7999 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8000 for (int i = 0; i < N; ++i) { 8001 intentFilters = packageServices.get(i).intents; 8002 if (intentFilters != null && intentFilters.size() > 0) { 8003 PackageParser.ServiceIntentInfo[] array = 8004 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8005 intentFilters.toArray(array); 8006 listCut.add(array); 8007 } 8008 } 8009 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8010 } 8011 8012 public final void addService(PackageParser.Service s) { 8013 mServices.put(s.getComponentName(), s); 8014 if (DEBUG_SHOW_INFO) { 8015 Log.v(TAG, " " 8016 + (s.info.nonLocalizedLabel != null 8017 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8018 Log.v(TAG, " Class=" + s.info.name); 8019 } 8020 final int NI = s.intents.size(); 8021 int j; 8022 for (j=0; j<NI; j++) { 8023 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8024 if (DEBUG_SHOW_INFO) { 8025 Log.v(TAG, " IntentFilter:"); 8026 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8027 } 8028 if (!intent.debugCheck()) { 8029 Log.w(TAG, "==> For Service " + s.info.name); 8030 } 8031 addFilter(intent); 8032 } 8033 } 8034 8035 public final void removeService(PackageParser.Service s) { 8036 mServices.remove(s.getComponentName()); 8037 if (DEBUG_SHOW_INFO) { 8038 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8039 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8040 Log.v(TAG, " Class=" + s.info.name); 8041 } 8042 final int NI = s.intents.size(); 8043 int j; 8044 for (j=0; j<NI; j++) { 8045 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8046 if (DEBUG_SHOW_INFO) { 8047 Log.v(TAG, " IntentFilter:"); 8048 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8049 } 8050 removeFilter(intent); 8051 } 8052 } 8053 8054 @Override 8055 protected boolean allowFilterResult( 8056 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8057 ServiceInfo filterSi = filter.service.info; 8058 for (int i=dest.size()-1; i>=0; i--) { 8059 ServiceInfo destAi = dest.get(i).serviceInfo; 8060 if (destAi.name == filterSi.name 8061 && destAi.packageName == filterSi.packageName) { 8062 return false; 8063 } 8064 } 8065 return true; 8066 } 8067 8068 @Override 8069 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8070 return new PackageParser.ServiceIntentInfo[size]; 8071 } 8072 8073 @Override 8074 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8075 if (!sUserManager.exists(userId)) return true; 8076 PackageParser.Package p = filter.service.owner; 8077 if (p != null) { 8078 PackageSetting ps = (PackageSetting)p.mExtras; 8079 if (ps != null) { 8080 // System apps are never considered stopped for purposes of 8081 // filtering, because there may be no way for the user to 8082 // actually re-launch them. 8083 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8084 && ps.getStopped(userId); 8085 } 8086 } 8087 return false; 8088 } 8089 8090 @Override 8091 protected boolean isPackageForFilter(String packageName, 8092 PackageParser.ServiceIntentInfo info) { 8093 return packageName.equals(info.service.owner.packageName); 8094 } 8095 8096 @Override 8097 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8098 int match, int userId) { 8099 if (!sUserManager.exists(userId)) return null; 8100 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8101 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8102 return null; 8103 } 8104 final PackageParser.Service service = info.service; 8105 if (mSafeMode && (service.info.applicationInfo.flags 8106 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8107 return null; 8108 } 8109 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8110 if (ps == null) { 8111 return null; 8112 } 8113 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8114 ps.readUserState(userId), userId); 8115 if (si == null) { 8116 return null; 8117 } 8118 final ResolveInfo res = new ResolveInfo(); 8119 res.serviceInfo = si; 8120 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8121 res.filter = filter; 8122 } 8123 res.priority = info.getPriority(); 8124 res.preferredOrder = service.owner.mPreferredOrder; 8125 res.match = match; 8126 res.isDefault = info.hasDefault; 8127 res.labelRes = info.labelRes; 8128 res.nonLocalizedLabel = info.nonLocalizedLabel; 8129 res.icon = info.icon; 8130 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8131 return res; 8132 } 8133 8134 @Override 8135 protected void sortResults(List<ResolveInfo> results) { 8136 Collections.sort(results, mResolvePrioritySorter); 8137 } 8138 8139 @Override 8140 protected void dumpFilter(PrintWriter out, String prefix, 8141 PackageParser.ServiceIntentInfo filter) { 8142 out.print(prefix); out.print( 8143 Integer.toHexString(System.identityHashCode(filter.service))); 8144 out.print(' '); 8145 filter.service.printComponentShortName(out); 8146 out.print(" filter "); 8147 out.println(Integer.toHexString(System.identityHashCode(filter))); 8148 } 8149 8150 @Override 8151 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8152 return filter.service; 8153 } 8154 8155 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8156 PackageParser.Service service = (PackageParser.Service)label; 8157 out.print(prefix); out.print( 8158 Integer.toHexString(System.identityHashCode(service))); 8159 out.print(' '); 8160 service.printComponentShortName(out); 8161 if (count > 1) { 8162 out.print(" ("); out.print(count); out.print(" filters)"); 8163 } 8164 out.println(); 8165 } 8166 8167// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8168// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8169// final List<ResolveInfo> retList = Lists.newArrayList(); 8170// while (i.hasNext()) { 8171// final ResolveInfo resolveInfo = (ResolveInfo) i; 8172// if (isEnabledLP(resolveInfo.serviceInfo)) { 8173// retList.add(resolveInfo); 8174// } 8175// } 8176// return retList; 8177// } 8178 8179 // Keys are String (activity class name), values are Activity. 8180 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8181 = new ArrayMap<ComponentName, PackageParser.Service>(); 8182 private int mFlags; 8183 }; 8184 8185 private final class ProviderIntentResolver 8186 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8187 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8188 boolean defaultOnly, int userId) { 8189 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8190 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8191 } 8192 8193 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8194 int userId) { 8195 if (!sUserManager.exists(userId)) 8196 return null; 8197 mFlags = flags; 8198 return super.queryIntent(intent, resolvedType, 8199 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8200 } 8201 8202 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8203 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8204 if (!sUserManager.exists(userId)) 8205 return null; 8206 if (packageProviders == null) { 8207 return null; 8208 } 8209 mFlags = flags; 8210 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8211 final int N = packageProviders.size(); 8212 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8213 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8214 8215 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8216 for (int i = 0; i < N; ++i) { 8217 intentFilters = packageProviders.get(i).intents; 8218 if (intentFilters != null && intentFilters.size() > 0) { 8219 PackageParser.ProviderIntentInfo[] array = 8220 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8221 intentFilters.toArray(array); 8222 listCut.add(array); 8223 } 8224 } 8225 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8226 } 8227 8228 public final void addProvider(PackageParser.Provider p) { 8229 if (mProviders.containsKey(p.getComponentName())) { 8230 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8231 return; 8232 } 8233 8234 mProviders.put(p.getComponentName(), p); 8235 if (DEBUG_SHOW_INFO) { 8236 Log.v(TAG, " " 8237 + (p.info.nonLocalizedLabel != null 8238 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8239 Log.v(TAG, " Class=" + p.info.name); 8240 } 8241 final int NI = p.intents.size(); 8242 int j; 8243 for (j = 0; j < NI; j++) { 8244 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8245 if (DEBUG_SHOW_INFO) { 8246 Log.v(TAG, " IntentFilter:"); 8247 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8248 } 8249 if (!intent.debugCheck()) { 8250 Log.w(TAG, "==> For Provider " + p.info.name); 8251 } 8252 addFilter(intent); 8253 } 8254 } 8255 8256 public final void removeProvider(PackageParser.Provider p) { 8257 mProviders.remove(p.getComponentName()); 8258 if (DEBUG_SHOW_INFO) { 8259 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8260 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8261 Log.v(TAG, " Class=" + p.info.name); 8262 } 8263 final int NI = p.intents.size(); 8264 int j; 8265 for (j = 0; j < NI; j++) { 8266 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8267 if (DEBUG_SHOW_INFO) { 8268 Log.v(TAG, " IntentFilter:"); 8269 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8270 } 8271 removeFilter(intent); 8272 } 8273 } 8274 8275 @Override 8276 protected boolean allowFilterResult( 8277 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8278 ProviderInfo filterPi = filter.provider.info; 8279 for (int i = dest.size() - 1; i >= 0; i--) { 8280 ProviderInfo destPi = dest.get(i).providerInfo; 8281 if (destPi.name == filterPi.name 8282 && destPi.packageName == filterPi.packageName) { 8283 return false; 8284 } 8285 } 8286 return true; 8287 } 8288 8289 @Override 8290 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8291 return new PackageParser.ProviderIntentInfo[size]; 8292 } 8293 8294 @Override 8295 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8296 if (!sUserManager.exists(userId)) 8297 return true; 8298 PackageParser.Package p = filter.provider.owner; 8299 if (p != null) { 8300 PackageSetting ps = (PackageSetting) p.mExtras; 8301 if (ps != null) { 8302 // System apps are never considered stopped for purposes of 8303 // filtering, because there may be no way for the user to 8304 // actually re-launch them. 8305 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8306 && ps.getStopped(userId); 8307 } 8308 } 8309 return false; 8310 } 8311 8312 @Override 8313 protected boolean isPackageForFilter(String packageName, 8314 PackageParser.ProviderIntentInfo info) { 8315 return packageName.equals(info.provider.owner.packageName); 8316 } 8317 8318 @Override 8319 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8320 int match, int userId) { 8321 if (!sUserManager.exists(userId)) 8322 return null; 8323 final PackageParser.ProviderIntentInfo info = filter; 8324 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8325 return null; 8326 } 8327 final PackageParser.Provider provider = info.provider; 8328 if (mSafeMode && (provider.info.applicationInfo.flags 8329 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8330 return null; 8331 } 8332 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8333 if (ps == null) { 8334 return null; 8335 } 8336 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8337 ps.readUserState(userId), userId); 8338 if (pi == null) { 8339 return null; 8340 } 8341 final ResolveInfo res = new ResolveInfo(); 8342 res.providerInfo = pi; 8343 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8344 res.filter = filter; 8345 } 8346 res.priority = info.getPriority(); 8347 res.preferredOrder = provider.owner.mPreferredOrder; 8348 res.match = match; 8349 res.isDefault = info.hasDefault; 8350 res.labelRes = info.labelRes; 8351 res.nonLocalizedLabel = info.nonLocalizedLabel; 8352 res.icon = info.icon; 8353 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8354 return res; 8355 } 8356 8357 @Override 8358 protected void sortResults(List<ResolveInfo> results) { 8359 Collections.sort(results, mResolvePrioritySorter); 8360 } 8361 8362 @Override 8363 protected void dumpFilter(PrintWriter out, String prefix, 8364 PackageParser.ProviderIntentInfo filter) { 8365 out.print(prefix); 8366 out.print( 8367 Integer.toHexString(System.identityHashCode(filter.provider))); 8368 out.print(' '); 8369 filter.provider.printComponentShortName(out); 8370 out.print(" filter "); 8371 out.println(Integer.toHexString(System.identityHashCode(filter))); 8372 } 8373 8374 @Override 8375 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8376 return filter.provider; 8377 } 8378 8379 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8380 PackageParser.Provider provider = (PackageParser.Provider)label; 8381 out.print(prefix); out.print( 8382 Integer.toHexString(System.identityHashCode(provider))); 8383 out.print(' '); 8384 provider.printComponentShortName(out); 8385 if (count > 1) { 8386 out.print(" ("); out.print(count); out.print(" filters)"); 8387 } 8388 out.println(); 8389 } 8390 8391 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8392 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8393 private int mFlags; 8394 }; 8395 8396 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8397 new Comparator<ResolveInfo>() { 8398 public int compare(ResolveInfo r1, ResolveInfo r2) { 8399 int v1 = r1.priority; 8400 int v2 = r2.priority; 8401 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8402 if (v1 != v2) { 8403 return (v1 > v2) ? -1 : 1; 8404 } 8405 v1 = r1.preferredOrder; 8406 v2 = r2.preferredOrder; 8407 if (v1 != v2) { 8408 return (v1 > v2) ? -1 : 1; 8409 } 8410 if (r1.isDefault != r2.isDefault) { 8411 return r1.isDefault ? -1 : 1; 8412 } 8413 v1 = r1.match; 8414 v2 = r2.match; 8415 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8416 if (v1 != v2) { 8417 return (v1 > v2) ? -1 : 1; 8418 } 8419 if (r1.system != r2.system) { 8420 return r1.system ? -1 : 1; 8421 } 8422 return 0; 8423 } 8424 }; 8425 8426 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8427 new Comparator<ProviderInfo>() { 8428 public int compare(ProviderInfo p1, ProviderInfo p2) { 8429 final int v1 = p1.initOrder; 8430 final int v2 = p2.initOrder; 8431 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8432 } 8433 }; 8434 8435 static final void sendPackageBroadcast(String action, String pkg, 8436 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8437 int[] userIds) { 8438 IActivityManager am = ActivityManagerNative.getDefault(); 8439 if (am != null) { 8440 try { 8441 if (userIds == null) { 8442 userIds = am.getRunningUserIds(); 8443 } 8444 for (int id : userIds) { 8445 final Intent intent = new Intent(action, 8446 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8447 if (extras != null) { 8448 intent.putExtras(extras); 8449 } 8450 if (targetPkg != null) { 8451 intent.setPackage(targetPkg); 8452 } 8453 // Modify the UID when posting to other users 8454 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8455 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8456 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8457 intent.putExtra(Intent.EXTRA_UID, uid); 8458 } 8459 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8460 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8461 if (DEBUG_BROADCASTS) { 8462 RuntimeException here = new RuntimeException("here"); 8463 here.fillInStackTrace(); 8464 Slog.d(TAG, "Sending to user " + id + ": " 8465 + intent.toShortString(false, true, false, false) 8466 + " " + intent.getExtras(), here); 8467 } 8468 am.broadcastIntent(null, intent, null, finishedReceiver, 8469 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8470 finishedReceiver != null, false, id); 8471 } 8472 } catch (RemoteException ex) { 8473 } 8474 } 8475 } 8476 8477 /** 8478 * Check if the external storage media is available. This is true if there 8479 * is a mounted external storage medium or if the external storage is 8480 * emulated. 8481 */ 8482 private boolean isExternalMediaAvailable() { 8483 return mMediaMounted || Environment.isExternalStorageEmulated(); 8484 } 8485 8486 @Override 8487 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8488 // writer 8489 synchronized (mPackages) { 8490 if (!isExternalMediaAvailable()) { 8491 // If the external storage is no longer mounted at this point, 8492 // the caller may not have been able to delete all of this 8493 // packages files and can not delete any more. Bail. 8494 return null; 8495 } 8496 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8497 if (lastPackage != null) { 8498 pkgs.remove(lastPackage); 8499 } 8500 if (pkgs.size() > 0) { 8501 return pkgs.get(0); 8502 } 8503 } 8504 return null; 8505 } 8506 8507 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8508 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8509 userId, andCode ? 1 : 0, packageName); 8510 if (mSystemReady) { 8511 msg.sendToTarget(); 8512 } else { 8513 if (mPostSystemReadyMessages == null) { 8514 mPostSystemReadyMessages = new ArrayList<>(); 8515 } 8516 mPostSystemReadyMessages.add(msg); 8517 } 8518 } 8519 8520 void startCleaningPackages() { 8521 // reader 8522 synchronized (mPackages) { 8523 if (!isExternalMediaAvailable()) { 8524 return; 8525 } 8526 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8527 return; 8528 } 8529 } 8530 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8531 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8532 IActivityManager am = ActivityManagerNative.getDefault(); 8533 if (am != null) { 8534 try { 8535 am.startService(null, intent, null, UserHandle.USER_OWNER); 8536 } catch (RemoteException e) { 8537 } 8538 } 8539 } 8540 8541 @Override 8542 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8543 int installFlags, String installerPackageName, VerificationParams verificationParams, 8544 String packageAbiOverride) { 8545 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8546 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8547 } 8548 8549 @Override 8550 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8551 int installFlags, String installerPackageName, VerificationParams verificationParams, 8552 String packageAbiOverride, int userId) { 8553 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8554 8555 final int callingUid = Binder.getCallingUid(); 8556 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8557 8558 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8559 try { 8560 if (observer != null) { 8561 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8562 } 8563 } catch (RemoteException re) { 8564 } 8565 return; 8566 } 8567 8568 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8569 installFlags |= PackageManager.INSTALL_FROM_ADB; 8570 8571 } else { 8572 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8573 // about installerPackageName. 8574 8575 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8576 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8577 } 8578 8579 UserHandle user; 8580 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8581 user = UserHandle.ALL; 8582 } else { 8583 user = new UserHandle(userId); 8584 } 8585 8586 // Only system components can circumvent runtime permissions when installing. 8587 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8588 && mContext.checkCallingOrSelfPermission(Manifest.permission 8589 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8590 throw new SecurityException("You need the " 8591 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8592 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8593 } 8594 8595 verificationParams.setInstallerUid(callingUid); 8596 8597 final File originFile = new File(originPath); 8598 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8599 8600 final Message msg = mHandler.obtainMessage(INIT_COPY); 8601 msg.obj = new InstallParams(origin, observer, installFlags, 8602 installerPackageName, null, verificationParams, user, packageAbiOverride); 8603 mHandler.sendMessage(msg); 8604 } 8605 8606 void installStage(String packageName, File stagedDir, String stagedCid, 8607 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8608 String installerPackageName, int installerUid, UserHandle user) { 8609 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8610 params.referrerUri, installerUid, null); 8611 8612 final OriginInfo origin; 8613 if (stagedDir != null) { 8614 origin = OriginInfo.fromStagedFile(stagedDir); 8615 } else { 8616 origin = OriginInfo.fromStagedContainer(stagedCid); 8617 } 8618 8619 final Message msg = mHandler.obtainMessage(INIT_COPY); 8620 msg.obj = new InstallParams(origin, observer, params.installFlags, 8621 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8622 mHandler.sendMessage(msg); 8623 } 8624 8625 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8626 Bundle extras = new Bundle(1); 8627 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8628 8629 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8630 packageName, extras, null, null, new int[] {userId}); 8631 try { 8632 IActivityManager am = ActivityManagerNative.getDefault(); 8633 final boolean isSystem = 8634 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8635 if (isSystem && am.isUserRunning(userId, false)) { 8636 // The just-installed/enabled app is bundled on the system, so presumed 8637 // to be able to run automatically without needing an explicit launch. 8638 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8639 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8640 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8641 .setPackage(packageName); 8642 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8643 android.app.AppOpsManager.OP_NONE, false, false, userId); 8644 } 8645 } catch (RemoteException e) { 8646 // shouldn't happen 8647 Slog.w(TAG, "Unable to bootstrap installed package", e); 8648 } 8649 } 8650 8651 @Override 8652 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8653 int userId) { 8654 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8655 PackageSetting pkgSetting; 8656 final int uid = Binder.getCallingUid(); 8657 enforceCrossUserPermission(uid, userId, true, true, 8658 "setApplicationHiddenSetting for user " + userId); 8659 8660 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8661 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8662 return false; 8663 } 8664 8665 long callingId = Binder.clearCallingIdentity(); 8666 try { 8667 boolean sendAdded = false; 8668 boolean sendRemoved = false; 8669 // writer 8670 synchronized (mPackages) { 8671 pkgSetting = mSettings.mPackages.get(packageName); 8672 if (pkgSetting == null) { 8673 return false; 8674 } 8675 if (pkgSetting.getHidden(userId) != hidden) { 8676 pkgSetting.setHidden(hidden, userId); 8677 mSettings.writePackageRestrictionsLPr(userId); 8678 if (hidden) { 8679 sendRemoved = true; 8680 } else { 8681 sendAdded = true; 8682 } 8683 } 8684 } 8685 if (sendAdded) { 8686 sendPackageAddedForUser(packageName, pkgSetting, userId); 8687 return true; 8688 } 8689 if (sendRemoved) { 8690 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8691 "hiding pkg"); 8692 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8693 } 8694 } finally { 8695 Binder.restoreCallingIdentity(callingId); 8696 } 8697 return false; 8698 } 8699 8700 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8701 int userId) { 8702 final PackageRemovedInfo info = new PackageRemovedInfo(); 8703 info.removedPackage = packageName; 8704 info.removedUsers = new int[] {userId}; 8705 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8706 info.sendBroadcast(false, false, false); 8707 } 8708 8709 /** 8710 * Returns true if application is not found or there was an error. Otherwise it returns 8711 * the hidden state of the package for the given user. 8712 */ 8713 @Override 8714 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8715 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8716 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8717 false, "getApplicationHidden for user " + userId); 8718 PackageSetting pkgSetting; 8719 long callingId = Binder.clearCallingIdentity(); 8720 try { 8721 // writer 8722 synchronized (mPackages) { 8723 pkgSetting = mSettings.mPackages.get(packageName); 8724 if (pkgSetting == null) { 8725 return true; 8726 } 8727 return pkgSetting.getHidden(userId); 8728 } 8729 } finally { 8730 Binder.restoreCallingIdentity(callingId); 8731 } 8732 } 8733 8734 /** 8735 * @hide 8736 */ 8737 @Override 8738 public int installExistingPackageAsUser(String packageName, int userId) { 8739 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8740 null); 8741 PackageSetting pkgSetting; 8742 final int uid = Binder.getCallingUid(); 8743 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8744 + userId); 8745 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8746 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8747 } 8748 8749 long callingId = Binder.clearCallingIdentity(); 8750 try { 8751 boolean sendAdded = false; 8752 8753 // writer 8754 synchronized (mPackages) { 8755 pkgSetting = mSettings.mPackages.get(packageName); 8756 if (pkgSetting == null) { 8757 return PackageManager.INSTALL_FAILED_INVALID_URI; 8758 } 8759 if (!pkgSetting.getInstalled(userId)) { 8760 pkgSetting.setInstalled(true, userId); 8761 pkgSetting.setHidden(false, userId); 8762 mSettings.writePackageRestrictionsLPr(userId); 8763 sendAdded = true; 8764 } 8765 } 8766 8767 if (sendAdded) { 8768 sendPackageAddedForUser(packageName, pkgSetting, userId); 8769 } 8770 } finally { 8771 Binder.restoreCallingIdentity(callingId); 8772 } 8773 8774 return PackageManager.INSTALL_SUCCEEDED; 8775 } 8776 8777 boolean isUserRestricted(int userId, String restrictionKey) { 8778 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8779 if (restrictions.getBoolean(restrictionKey, false)) { 8780 Log.w(TAG, "User is restricted: " + restrictionKey); 8781 return true; 8782 } 8783 return false; 8784 } 8785 8786 @Override 8787 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8788 mContext.enforceCallingOrSelfPermission( 8789 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8790 "Only package verification agents can verify applications"); 8791 8792 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8793 final PackageVerificationResponse response = new PackageVerificationResponse( 8794 verificationCode, Binder.getCallingUid()); 8795 msg.arg1 = id; 8796 msg.obj = response; 8797 mHandler.sendMessage(msg); 8798 } 8799 8800 @Override 8801 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8802 long millisecondsToDelay) { 8803 mContext.enforceCallingOrSelfPermission( 8804 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8805 "Only package verification agents can extend verification timeouts"); 8806 8807 final PackageVerificationState state = mPendingVerification.get(id); 8808 final PackageVerificationResponse response = new PackageVerificationResponse( 8809 verificationCodeAtTimeout, Binder.getCallingUid()); 8810 8811 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8812 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8813 } 8814 if (millisecondsToDelay < 0) { 8815 millisecondsToDelay = 0; 8816 } 8817 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8818 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8819 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8820 } 8821 8822 if ((state != null) && !state.timeoutExtended()) { 8823 state.extendTimeout(); 8824 8825 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8826 msg.arg1 = id; 8827 msg.obj = response; 8828 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8829 } 8830 } 8831 8832 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8833 int verificationCode, UserHandle user) { 8834 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8835 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8836 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8837 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8838 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8839 8840 mContext.sendBroadcastAsUser(intent, user, 8841 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8842 } 8843 8844 private ComponentName matchComponentForVerifier(String packageName, 8845 List<ResolveInfo> receivers) { 8846 ActivityInfo targetReceiver = null; 8847 8848 final int NR = receivers.size(); 8849 for (int i = 0; i < NR; i++) { 8850 final ResolveInfo info = receivers.get(i); 8851 if (info.activityInfo == null) { 8852 continue; 8853 } 8854 8855 if (packageName.equals(info.activityInfo.packageName)) { 8856 targetReceiver = info.activityInfo; 8857 break; 8858 } 8859 } 8860 8861 if (targetReceiver == null) { 8862 return null; 8863 } 8864 8865 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8866 } 8867 8868 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8869 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8870 if (pkgInfo.verifiers.length == 0) { 8871 return null; 8872 } 8873 8874 final int N = pkgInfo.verifiers.length; 8875 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8876 for (int i = 0; i < N; i++) { 8877 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8878 8879 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8880 receivers); 8881 if (comp == null) { 8882 continue; 8883 } 8884 8885 final int verifierUid = getUidForVerifier(verifierInfo); 8886 if (verifierUid == -1) { 8887 continue; 8888 } 8889 8890 if (DEBUG_VERIFY) { 8891 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8892 + " with the correct signature"); 8893 } 8894 sufficientVerifiers.add(comp); 8895 verificationState.addSufficientVerifier(verifierUid); 8896 } 8897 8898 return sufficientVerifiers; 8899 } 8900 8901 private int getUidForVerifier(VerifierInfo verifierInfo) { 8902 synchronized (mPackages) { 8903 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8904 if (pkg == null) { 8905 return -1; 8906 } else if (pkg.mSignatures.length != 1) { 8907 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8908 + " has more than one signature; ignoring"); 8909 return -1; 8910 } 8911 8912 /* 8913 * If the public key of the package's signature does not match 8914 * our expected public key, then this is a different package and 8915 * we should skip. 8916 */ 8917 8918 final byte[] expectedPublicKey; 8919 try { 8920 final Signature verifierSig = pkg.mSignatures[0]; 8921 final PublicKey publicKey = verifierSig.getPublicKey(); 8922 expectedPublicKey = publicKey.getEncoded(); 8923 } catch (CertificateException e) { 8924 return -1; 8925 } 8926 8927 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8928 8929 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8930 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8931 + " does not have the expected public key; ignoring"); 8932 return -1; 8933 } 8934 8935 return pkg.applicationInfo.uid; 8936 } 8937 } 8938 8939 @Override 8940 public void finishPackageInstall(int token) { 8941 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8942 8943 if (DEBUG_INSTALL) { 8944 Slog.v(TAG, "BM finishing package install for " + token); 8945 } 8946 8947 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8948 mHandler.sendMessage(msg); 8949 } 8950 8951 /** 8952 * Get the verification agent timeout. 8953 * 8954 * @return verification timeout in milliseconds 8955 */ 8956 private long getVerificationTimeout() { 8957 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8958 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8959 DEFAULT_VERIFICATION_TIMEOUT); 8960 } 8961 8962 /** 8963 * Get the default verification agent response code. 8964 * 8965 * @return default verification response code 8966 */ 8967 private int getDefaultVerificationResponse() { 8968 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8969 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8970 DEFAULT_VERIFICATION_RESPONSE); 8971 } 8972 8973 /** 8974 * Check whether or not package verification has been enabled. 8975 * 8976 * @return true if verification should be performed 8977 */ 8978 private boolean isVerificationEnabled(int userId, int installFlags) { 8979 if (!DEFAULT_VERIFY_ENABLE) { 8980 return false; 8981 } 8982 8983 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8984 8985 // Check if installing from ADB 8986 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8987 // Do not run verification in a test harness environment 8988 if (ActivityManager.isRunningInTestHarness()) { 8989 return false; 8990 } 8991 if (ensureVerifyAppsEnabled) { 8992 return true; 8993 } 8994 // Check if the developer does not want package verification for ADB installs 8995 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8996 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8997 return false; 8998 } 8999 } 9000 9001 if (ensureVerifyAppsEnabled) { 9002 return true; 9003 } 9004 9005 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9006 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9007 } 9008 9009 @Override 9010 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9011 throws RemoteException { 9012 mContext.enforceCallingOrSelfPermission( 9013 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9014 "Only intentfilter verification agents can verify applications"); 9015 9016 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9017 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9018 Binder.getCallingUid(), verificationCode, failedDomains); 9019 msg.arg1 = id; 9020 msg.obj = response; 9021 mHandler.sendMessage(msg); 9022 } 9023 9024 @Override 9025 public int getIntentVerificationStatus(String packageName, int userId) { 9026 synchronized (mPackages) { 9027 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9028 } 9029 } 9030 9031 @Override 9032 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9033 boolean result = false; 9034 synchronized (mPackages) { 9035 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9036 } 9037 scheduleWritePackageRestrictionsLocked(userId); 9038 return result; 9039 } 9040 9041 @Override 9042 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9043 synchronized (mPackages) { 9044 return mSettings.getIntentFilterVerificationsLPr(packageName); 9045 } 9046 } 9047 9048 @Override 9049 public List<IntentFilter> getAllIntentFilters(String packageName) { 9050 if (TextUtils.isEmpty(packageName)) { 9051 return Collections.<IntentFilter>emptyList(); 9052 } 9053 synchronized (mPackages) { 9054 PackageParser.Package pkg = mPackages.get(packageName); 9055 if (pkg == null || pkg.activities == null) { 9056 return Collections.<IntentFilter>emptyList(); 9057 } 9058 final int count = pkg.activities.size(); 9059 ArrayList<IntentFilter> result = new ArrayList<>(); 9060 for (int n=0; n<count; n++) { 9061 PackageParser.Activity activity = pkg.activities.get(n); 9062 if (activity.intents != null || activity.intents.size() > 0) { 9063 result.addAll(activity.intents); 9064 } 9065 } 9066 return result; 9067 } 9068 } 9069 9070 @Override 9071 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9072 synchronized (mPackages) { 9073 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9074 } 9075 } 9076 9077 @Override 9078 public String getDefaultBrowserPackageName(int userId) { 9079 synchronized (mPackages) { 9080 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9081 } 9082 } 9083 9084 /** 9085 * Get the "allow unknown sources" setting. 9086 * 9087 * @return the current "allow unknown sources" setting 9088 */ 9089 private int getUnknownSourcesSettings() { 9090 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9091 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9092 -1); 9093 } 9094 9095 @Override 9096 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9097 final int uid = Binder.getCallingUid(); 9098 // writer 9099 synchronized (mPackages) { 9100 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9101 if (targetPackageSetting == null) { 9102 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9103 } 9104 9105 PackageSetting installerPackageSetting; 9106 if (installerPackageName != null) { 9107 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9108 if (installerPackageSetting == null) { 9109 throw new IllegalArgumentException("Unknown installer package: " 9110 + installerPackageName); 9111 } 9112 } else { 9113 installerPackageSetting = null; 9114 } 9115 9116 Signature[] callerSignature; 9117 Object obj = mSettings.getUserIdLPr(uid); 9118 if (obj != null) { 9119 if (obj instanceof SharedUserSetting) { 9120 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9121 } else if (obj instanceof PackageSetting) { 9122 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9123 } else { 9124 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9125 } 9126 } else { 9127 throw new SecurityException("Unknown calling uid " + uid); 9128 } 9129 9130 // Verify: can't set installerPackageName to a package that is 9131 // not signed with the same cert as the caller. 9132 if (installerPackageSetting != null) { 9133 if (compareSignatures(callerSignature, 9134 installerPackageSetting.signatures.mSignatures) 9135 != PackageManager.SIGNATURE_MATCH) { 9136 throw new SecurityException( 9137 "Caller does not have same cert as new installer package " 9138 + installerPackageName); 9139 } 9140 } 9141 9142 // Verify: if target already has an installer package, it must 9143 // be signed with the same cert as the caller. 9144 if (targetPackageSetting.installerPackageName != null) { 9145 PackageSetting setting = mSettings.mPackages.get( 9146 targetPackageSetting.installerPackageName); 9147 // If the currently set package isn't valid, then it's always 9148 // okay to change it. 9149 if (setting != null) { 9150 if (compareSignatures(callerSignature, 9151 setting.signatures.mSignatures) 9152 != PackageManager.SIGNATURE_MATCH) { 9153 throw new SecurityException( 9154 "Caller does not have same cert as old installer package " 9155 + targetPackageSetting.installerPackageName); 9156 } 9157 } 9158 } 9159 9160 // Okay! 9161 targetPackageSetting.installerPackageName = installerPackageName; 9162 scheduleWriteSettingsLocked(); 9163 } 9164 } 9165 9166 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9167 // Queue up an async operation since the package installation may take a little while. 9168 mHandler.post(new Runnable() { 9169 public void run() { 9170 mHandler.removeCallbacks(this); 9171 // Result object to be returned 9172 PackageInstalledInfo res = new PackageInstalledInfo(); 9173 res.returnCode = currentStatus; 9174 res.uid = -1; 9175 res.pkg = null; 9176 res.removedInfo = new PackageRemovedInfo(); 9177 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9178 args.doPreInstall(res.returnCode); 9179 synchronized (mInstallLock) { 9180 installPackageLI(args, res); 9181 } 9182 args.doPostInstall(res.returnCode, res.uid); 9183 } 9184 9185 // A restore should be performed at this point if (a) the install 9186 // succeeded, (b) the operation is not an update, and (c) the new 9187 // package has not opted out of backup participation. 9188 final boolean update = res.removedInfo.removedPackage != null; 9189 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9190 boolean doRestore = !update 9191 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9192 9193 // Set up the post-install work request bookkeeping. This will be used 9194 // and cleaned up by the post-install event handling regardless of whether 9195 // there's a restore pass performed. Token values are >= 1. 9196 int token; 9197 if (mNextInstallToken < 0) mNextInstallToken = 1; 9198 token = mNextInstallToken++; 9199 9200 PostInstallData data = new PostInstallData(args, res); 9201 mRunningInstalls.put(token, data); 9202 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9203 9204 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9205 // Pass responsibility to the Backup Manager. It will perform a 9206 // restore if appropriate, then pass responsibility back to the 9207 // Package Manager to run the post-install observer callbacks 9208 // and broadcasts. 9209 IBackupManager bm = IBackupManager.Stub.asInterface( 9210 ServiceManager.getService(Context.BACKUP_SERVICE)); 9211 if (bm != null) { 9212 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9213 + " to BM for possible restore"); 9214 try { 9215 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9216 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9217 } else { 9218 doRestore = false; 9219 } 9220 } catch (RemoteException e) { 9221 // can't happen; the backup manager is local 9222 } catch (Exception e) { 9223 Slog.e(TAG, "Exception trying to enqueue restore", e); 9224 doRestore = false; 9225 } 9226 } else { 9227 Slog.e(TAG, "Backup Manager not found!"); 9228 doRestore = false; 9229 } 9230 } 9231 9232 if (!doRestore) { 9233 // No restore possible, or the Backup Manager was mysteriously not 9234 // available -- just fire the post-install work request directly. 9235 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9236 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9237 mHandler.sendMessage(msg); 9238 } 9239 } 9240 }); 9241 } 9242 9243 private abstract class HandlerParams { 9244 private static final int MAX_RETRIES = 4; 9245 9246 /** 9247 * Number of times startCopy() has been attempted and had a non-fatal 9248 * error. 9249 */ 9250 private int mRetries = 0; 9251 9252 /** User handle for the user requesting the information or installation. */ 9253 private final UserHandle mUser; 9254 9255 HandlerParams(UserHandle user) { 9256 mUser = user; 9257 } 9258 9259 UserHandle getUser() { 9260 return mUser; 9261 } 9262 9263 final boolean startCopy() { 9264 boolean res; 9265 try { 9266 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9267 9268 if (++mRetries > MAX_RETRIES) { 9269 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9270 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9271 handleServiceError(); 9272 return false; 9273 } else { 9274 handleStartCopy(); 9275 res = true; 9276 } 9277 } catch (RemoteException e) { 9278 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9279 mHandler.sendEmptyMessage(MCS_RECONNECT); 9280 res = false; 9281 } 9282 handleReturnCode(); 9283 return res; 9284 } 9285 9286 final void serviceError() { 9287 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9288 handleServiceError(); 9289 handleReturnCode(); 9290 } 9291 9292 abstract void handleStartCopy() throws RemoteException; 9293 abstract void handleServiceError(); 9294 abstract void handleReturnCode(); 9295 } 9296 9297 class MeasureParams extends HandlerParams { 9298 private final PackageStats mStats; 9299 private boolean mSuccess; 9300 9301 private final IPackageStatsObserver mObserver; 9302 9303 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9304 super(new UserHandle(stats.userHandle)); 9305 mObserver = observer; 9306 mStats = stats; 9307 } 9308 9309 @Override 9310 public String toString() { 9311 return "MeasureParams{" 9312 + Integer.toHexString(System.identityHashCode(this)) 9313 + " " + mStats.packageName + "}"; 9314 } 9315 9316 @Override 9317 void handleStartCopy() throws RemoteException { 9318 synchronized (mInstallLock) { 9319 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9320 } 9321 9322 if (mSuccess) { 9323 final boolean mounted; 9324 if (Environment.isExternalStorageEmulated()) { 9325 mounted = true; 9326 } else { 9327 final String status = Environment.getExternalStorageState(); 9328 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9329 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9330 } 9331 9332 if (mounted) { 9333 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9334 9335 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9336 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9337 9338 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9339 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9340 9341 // Always subtract cache size, since it's a subdirectory 9342 mStats.externalDataSize -= mStats.externalCacheSize; 9343 9344 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9345 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9346 9347 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9348 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9349 } 9350 } 9351 } 9352 9353 @Override 9354 void handleReturnCode() { 9355 if (mObserver != null) { 9356 try { 9357 mObserver.onGetStatsCompleted(mStats, mSuccess); 9358 } catch (RemoteException e) { 9359 Slog.i(TAG, "Observer no longer exists."); 9360 } 9361 } 9362 } 9363 9364 @Override 9365 void handleServiceError() { 9366 Slog.e(TAG, "Could not measure application " + mStats.packageName 9367 + " external storage"); 9368 } 9369 } 9370 9371 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9372 throws RemoteException { 9373 long result = 0; 9374 for (File path : paths) { 9375 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9376 } 9377 return result; 9378 } 9379 9380 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9381 for (File path : paths) { 9382 try { 9383 mcs.clearDirectory(path.getAbsolutePath()); 9384 } catch (RemoteException e) { 9385 } 9386 } 9387 } 9388 9389 static class OriginInfo { 9390 /** 9391 * Location where install is coming from, before it has been 9392 * copied/renamed into place. This could be a single monolithic APK 9393 * file, or a cluster directory. This location may be untrusted. 9394 */ 9395 final File file; 9396 final String cid; 9397 9398 /** 9399 * Flag indicating that {@link #file} or {@link #cid} has already been 9400 * staged, meaning downstream users don't need to defensively copy the 9401 * contents. 9402 */ 9403 final boolean staged; 9404 9405 /** 9406 * Flag indicating that {@link #file} or {@link #cid} is an already 9407 * installed app that is being moved. 9408 */ 9409 final boolean existing; 9410 9411 final String resolvedPath; 9412 final File resolvedFile; 9413 9414 static OriginInfo fromNothing() { 9415 return new OriginInfo(null, null, false, false); 9416 } 9417 9418 static OriginInfo fromUntrustedFile(File file) { 9419 return new OriginInfo(file, null, false, false); 9420 } 9421 9422 static OriginInfo fromExistingFile(File file) { 9423 return new OriginInfo(file, null, false, true); 9424 } 9425 9426 static OriginInfo fromStagedFile(File file) { 9427 return new OriginInfo(file, null, true, false); 9428 } 9429 9430 static OriginInfo fromStagedContainer(String cid) { 9431 return new OriginInfo(null, cid, true, false); 9432 } 9433 9434 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9435 this.file = file; 9436 this.cid = cid; 9437 this.staged = staged; 9438 this.existing = existing; 9439 9440 if (cid != null) { 9441 resolvedPath = PackageHelper.getSdDir(cid); 9442 resolvedFile = new File(resolvedPath); 9443 } else if (file != null) { 9444 resolvedPath = file.getAbsolutePath(); 9445 resolvedFile = file; 9446 } else { 9447 resolvedPath = null; 9448 resolvedFile = null; 9449 } 9450 } 9451 } 9452 9453 class InstallParams extends HandlerParams { 9454 final OriginInfo origin; 9455 final IPackageInstallObserver2 observer; 9456 int installFlags; 9457 final String installerPackageName; 9458 final String volumeUuid; 9459 final VerificationParams verificationParams; 9460 private InstallArgs mArgs; 9461 private int mRet; 9462 final String packageAbiOverride; 9463 9464 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9465 String installerPackageName, String volumeUuid, 9466 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9467 super(user); 9468 this.origin = origin; 9469 this.observer = observer; 9470 this.installFlags = installFlags; 9471 this.installerPackageName = installerPackageName; 9472 this.volumeUuid = volumeUuid; 9473 this.verificationParams = verificationParams; 9474 this.packageAbiOverride = packageAbiOverride; 9475 } 9476 9477 @Override 9478 public String toString() { 9479 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9480 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9481 } 9482 9483 public ManifestDigest getManifestDigest() { 9484 if (verificationParams == null) { 9485 return null; 9486 } 9487 return verificationParams.getManifestDigest(); 9488 } 9489 9490 private int installLocationPolicy(PackageInfoLite pkgLite) { 9491 String packageName = pkgLite.packageName; 9492 int installLocation = pkgLite.installLocation; 9493 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9494 // reader 9495 synchronized (mPackages) { 9496 PackageParser.Package pkg = mPackages.get(packageName); 9497 if (pkg != null) { 9498 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9499 // Check for downgrading. 9500 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9501 try { 9502 checkDowngrade(pkg, pkgLite); 9503 } catch (PackageManagerException e) { 9504 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9505 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9506 } 9507 } 9508 // Check for updated system application. 9509 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9510 if (onSd) { 9511 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9512 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9513 } 9514 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9515 } else { 9516 if (onSd) { 9517 // Install flag overrides everything. 9518 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9519 } 9520 // If current upgrade specifies particular preference 9521 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9522 // Application explicitly specified internal. 9523 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9524 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9525 // App explictly prefers external. Let policy decide 9526 } else { 9527 // Prefer previous location 9528 if (isExternal(pkg)) { 9529 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9530 } 9531 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9532 } 9533 } 9534 } else { 9535 // Invalid install. Return error code 9536 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9537 } 9538 } 9539 } 9540 // All the special cases have been taken care of. 9541 // Return result based on recommended install location. 9542 if (onSd) { 9543 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9544 } 9545 return pkgLite.recommendedInstallLocation; 9546 } 9547 9548 /* 9549 * Invoke remote method to get package information and install 9550 * location values. Override install location based on default 9551 * policy if needed and then create install arguments based 9552 * on the install location. 9553 */ 9554 public void handleStartCopy() throws RemoteException { 9555 int ret = PackageManager.INSTALL_SUCCEEDED; 9556 9557 // If we're already staged, we've firmly committed to an install location 9558 if (origin.staged) { 9559 if (origin.file != null) { 9560 installFlags |= PackageManager.INSTALL_INTERNAL; 9561 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9562 } else if (origin.cid != null) { 9563 installFlags |= PackageManager.INSTALL_EXTERNAL; 9564 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9565 } else { 9566 throw new IllegalStateException("Invalid stage location"); 9567 } 9568 } 9569 9570 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9571 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9572 9573 PackageInfoLite pkgLite = null; 9574 9575 if (onInt && onSd) { 9576 // Check if both bits are set. 9577 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9578 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9579 } else { 9580 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9581 packageAbiOverride); 9582 9583 /* 9584 * If we have too little free space, try to free cache 9585 * before giving up. 9586 */ 9587 if (!origin.staged && pkgLite.recommendedInstallLocation 9588 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9589 // TODO: focus freeing disk space on the target device 9590 final StorageManager storage = StorageManager.from(mContext); 9591 final long lowThreshold = storage.getStorageLowBytes( 9592 Environment.getDataDirectory()); 9593 9594 final long sizeBytes = mContainerService.calculateInstalledSize( 9595 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9596 9597 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9598 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9599 installFlags, packageAbiOverride); 9600 } 9601 9602 /* 9603 * The cache free must have deleted the file we 9604 * downloaded to install. 9605 * 9606 * TODO: fix the "freeCache" call to not delete 9607 * the file we care about. 9608 */ 9609 if (pkgLite.recommendedInstallLocation 9610 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9611 pkgLite.recommendedInstallLocation 9612 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9613 } 9614 } 9615 } 9616 9617 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9618 int loc = pkgLite.recommendedInstallLocation; 9619 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9620 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9621 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9622 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9624 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9625 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9626 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9627 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9628 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9629 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9630 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9631 } else { 9632 // Override with defaults if needed. 9633 loc = installLocationPolicy(pkgLite); 9634 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9635 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9636 } else if (!onSd && !onInt) { 9637 // Override install location with flags 9638 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9639 // Set the flag to install on external media. 9640 installFlags |= PackageManager.INSTALL_EXTERNAL; 9641 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9642 } else { 9643 // Make sure the flag for installing on external 9644 // media is unset 9645 installFlags |= PackageManager.INSTALL_INTERNAL; 9646 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9647 } 9648 } 9649 } 9650 } 9651 9652 final InstallArgs args = createInstallArgs(this); 9653 mArgs = args; 9654 9655 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9656 /* 9657 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9658 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9659 */ 9660 int userIdentifier = getUser().getIdentifier(); 9661 if (userIdentifier == UserHandle.USER_ALL 9662 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9663 userIdentifier = UserHandle.USER_OWNER; 9664 } 9665 9666 /* 9667 * Determine if we have any installed package verifiers. If we 9668 * do, then we'll defer to them to verify the packages. 9669 */ 9670 final int requiredUid = mRequiredVerifierPackage == null ? -1 9671 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9672 if (!origin.existing && requiredUid != -1 9673 && isVerificationEnabled(userIdentifier, installFlags)) { 9674 final Intent verification = new Intent( 9675 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9676 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9677 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9678 PACKAGE_MIME_TYPE); 9679 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9680 9681 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9682 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9683 0 /* TODO: Which userId? */); 9684 9685 if (DEBUG_VERIFY) { 9686 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9687 + verification.toString() + " with " + pkgLite.verifiers.length 9688 + " optional verifiers"); 9689 } 9690 9691 final int verificationId = mPendingVerificationToken++; 9692 9693 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9694 9695 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9696 installerPackageName); 9697 9698 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9699 installFlags); 9700 9701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9702 pkgLite.packageName); 9703 9704 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9705 pkgLite.versionCode); 9706 9707 if (verificationParams != null) { 9708 if (verificationParams.getVerificationURI() != null) { 9709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9710 verificationParams.getVerificationURI()); 9711 } 9712 if (verificationParams.getOriginatingURI() != null) { 9713 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9714 verificationParams.getOriginatingURI()); 9715 } 9716 if (verificationParams.getReferrer() != null) { 9717 verification.putExtra(Intent.EXTRA_REFERRER, 9718 verificationParams.getReferrer()); 9719 } 9720 if (verificationParams.getOriginatingUid() >= 0) { 9721 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9722 verificationParams.getOriginatingUid()); 9723 } 9724 if (verificationParams.getInstallerUid() >= 0) { 9725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9726 verificationParams.getInstallerUid()); 9727 } 9728 } 9729 9730 final PackageVerificationState verificationState = new PackageVerificationState( 9731 requiredUid, args); 9732 9733 mPendingVerification.append(verificationId, verificationState); 9734 9735 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9736 receivers, verificationState); 9737 9738 /* 9739 * If any sufficient verifiers were listed in the package 9740 * manifest, attempt to ask them. 9741 */ 9742 if (sufficientVerifiers != null) { 9743 final int N = sufficientVerifiers.size(); 9744 if (N == 0) { 9745 Slog.i(TAG, "Additional verifiers required, but none installed."); 9746 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9747 } else { 9748 for (int i = 0; i < N; i++) { 9749 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9750 9751 final Intent sufficientIntent = new Intent(verification); 9752 sufficientIntent.setComponent(verifierComponent); 9753 9754 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9755 } 9756 } 9757 } 9758 9759 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9760 mRequiredVerifierPackage, receivers); 9761 if (ret == PackageManager.INSTALL_SUCCEEDED 9762 && mRequiredVerifierPackage != null) { 9763 /* 9764 * Send the intent to the required verification agent, 9765 * but only start the verification timeout after the 9766 * target BroadcastReceivers have run. 9767 */ 9768 verification.setComponent(requiredVerifierComponent); 9769 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9770 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9771 new BroadcastReceiver() { 9772 @Override 9773 public void onReceive(Context context, Intent intent) { 9774 final Message msg = mHandler 9775 .obtainMessage(CHECK_PENDING_VERIFICATION); 9776 msg.arg1 = verificationId; 9777 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9778 } 9779 }, null, 0, null, null); 9780 9781 /* 9782 * We don't want the copy to proceed until verification 9783 * succeeds, so null out this field. 9784 */ 9785 mArgs = null; 9786 } 9787 } else { 9788 /* 9789 * No package verification is enabled, so immediately start 9790 * the remote call to initiate copy using temporary file. 9791 */ 9792 ret = args.copyApk(mContainerService, true); 9793 } 9794 } 9795 9796 mRet = ret; 9797 } 9798 9799 @Override 9800 void handleReturnCode() { 9801 // If mArgs is null, then MCS couldn't be reached. When it 9802 // reconnects, it will try again to install. At that point, this 9803 // will succeed. 9804 if (mArgs != null) { 9805 processPendingInstall(mArgs, mRet); 9806 } 9807 } 9808 9809 @Override 9810 void handleServiceError() { 9811 mArgs = createInstallArgs(this); 9812 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9813 } 9814 9815 public boolean isForwardLocked() { 9816 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9817 } 9818 } 9819 9820 /** 9821 * Used during creation of InstallArgs 9822 * 9823 * @param installFlags package installation flags 9824 * @return true if should be installed on external storage 9825 */ 9826 private static boolean installOnExternalAsec(int installFlags) { 9827 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9828 return false; 9829 } 9830 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9831 return true; 9832 } 9833 return false; 9834 } 9835 9836 /** 9837 * Used during creation of InstallArgs 9838 * 9839 * @param installFlags package installation flags 9840 * @return true if should be installed as forward locked 9841 */ 9842 private static boolean installForwardLocked(int installFlags) { 9843 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9844 } 9845 9846 private InstallArgs createInstallArgs(InstallParams params) { 9847 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9848 return new AsecInstallArgs(params); 9849 } else { 9850 return new FileInstallArgs(params); 9851 } 9852 } 9853 9854 /** 9855 * Create args that describe an existing installed package. Typically used 9856 * when cleaning up old installs, or used as a move source. 9857 */ 9858 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9859 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9860 final boolean isInAsec; 9861 if (installOnExternalAsec(installFlags)) { 9862 /* Apps on SD card are always in ASEC containers. */ 9863 isInAsec = true; 9864 } else if (installForwardLocked(installFlags) 9865 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9866 /* 9867 * Forward-locked apps are only in ASEC containers if they're the 9868 * new style 9869 */ 9870 isInAsec = true; 9871 } else { 9872 isInAsec = false; 9873 } 9874 9875 if (isInAsec) { 9876 return new AsecInstallArgs(codePath, instructionSets, 9877 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9878 } else { 9879 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9880 instructionSets); 9881 } 9882 } 9883 9884 static abstract class InstallArgs { 9885 /** @see InstallParams#origin */ 9886 final OriginInfo origin; 9887 9888 final IPackageInstallObserver2 observer; 9889 // Always refers to PackageManager flags only 9890 final int installFlags; 9891 final String installerPackageName; 9892 final String volumeUuid; 9893 final ManifestDigest manifestDigest; 9894 final UserHandle user; 9895 final String abiOverride; 9896 9897 // The list of instruction sets supported by this app. This is currently 9898 // only used during the rmdex() phase to clean up resources. We can get rid of this 9899 // if we move dex files under the common app path. 9900 /* nullable */ String[] instructionSets; 9901 9902 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9903 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9904 UserHandle user, String[] instructionSets, String abiOverride) { 9905 this.origin = origin; 9906 this.installFlags = installFlags; 9907 this.observer = observer; 9908 this.installerPackageName = installerPackageName; 9909 this.volumeUuid = volumeUuid; 9910 this.manifestDigest = manifestDigest; 9911 this.user = user; 9912 this.instructionSets = instructionSets; 9913 this.abiOverride = abiOverride; 9914 } 9915 9916 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9917 abstract int doPreInstall(int status); 9918 9919 /** 9920 * Rename package into final resting place. All paths on the given 9921 * scanned package should be updated to reflect the rename. 9922 */ 9923 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9924 abstract int doPostInstall(int status, int uid); 9925 9926 /** @see PackageSettingBase#codePathString */ 9927 abstract String getCodePath(); 9928 /** @see PackageSettingBase#resourcePathString */ 9929 abstract String getResourcePath(); 9930 abstract String getLegacyNativeLibraryPath(); 9931 9932 // Need installer lock especially for dex file removal. 9933 abstract void cleanUpResourcesLI(); 9934 abstract boolean doPostDeleteLI(boolean delete); 9935 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9936 9937 /** 9938 * Called before the source arguments are copied. This is used mostly 9939 * for MoveParams when it needs to read the source file to put it in the 9940 * destination. 9941 */ 9942 int doPreCopy() { 9943 return PackageManager.INSTALL_SUCCEEDED; 9944 } 9945 9946 /** 9947 * Called after the source arguments are copied. This is used mostly for 9948 * MoveParams when it needs to read the source file to put it in the 9949 * destination. 9950 * 9951 * @return 9952 */ 9953 int doPostCopy(int uid) { 9954 return PackageManager.INSTALL_SUCCEEDED; 9955 } 9956 9957 protected boolean isFwdLocked() { 9958 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9959 } 9960 9961 protected boolean isExternalAsec() { 9962 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9963 } 9964 9965 UserHandle getUser() { 9966 return user; 9967 } 9968 } 9969 9970 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9971 if (!allCodePaths.isEmpty()) { 9972 if (instructionSets == null) { 9973 throw new IllegalStateException("instructionSet == null"); 9974 } 9975 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9976 for (String codePath : allCodePaths) { 9977 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9978 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9979 if (retCode < 0) { 9980 Slog.w(TAG, "Couldn't remove dex file for package: " 9981 + " at location " + codePath + ", retcode=" + retCode); 9982 // we don't consider this to be a failure of the core package deletion 9983 } 9984 } 9985 } 9986 } 9987 } 9988 9989 /** 9990 * Logic to handle installation of non-ASEC applications, including copying 9991 * and renaming logic. 9992 */ 9993 class FileInstallArgs extends InstallArgs { 9994 private File codeFile; 9995 private File resourceFile; 9996 private File legacyNativeLibraryPath; 9997 9998 // Example topology: 9999 // /data/app/com.example/base.apk 10000 // /data/app/com.example/split_foo.apk 10001 // /data/app/com.example/lib/arm/libfoo.so 10002 // /data/app/com.example/lib/arm64/libfoo.so 10003 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10004 10005 /** New install */ 10006 FileInstallArgs(InstallParams params) { 10007 super(params.origin, params.observer, params.installFlags, 10008 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10009 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10010 if (isFwdLocked()) { 10011 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10012 } 10013 } 10014 10015 /** Existing install */ 10016 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10017 String[] instructionSets) { 10018 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10019 this.codeFile = (codePath != null) ? new File(codePath) : null; 10020 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10021 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10022 new File(legacyNativeLibraryPath) : null; 10023 } 10024 10025 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10026 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10027 isFwdLocked(), abiOverride); 10028 10029 final StorageManager storage = StorageManager.from(mContext); 10030 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10031 } 10032 10033 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10034 if (origin.staged) { 10035 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10036 codeFile = origin.file; 10037 resourceFile = origin.file; 10038 return PackageManager.INSTALL_SUCCEEDED; 10039 } 10040 10041 try { 10042 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10043 codeFile = tempDir; 10044 resourceFile = tempDir; 10045 } catch (IOException e) { 10046 Slog.w(TAG, "Failed to create copy file: " + e); 10047 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10048 } 10049 10050 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10051 @Override 10052 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10053 if (!FileUtils.isValidExtFilename(name)) { 10054 throw new IllegalArgumentException("Invalid filename: " + name); 10055 } 10056 try { 10057 final File file = new File(codeFile, name); 10058 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10059 O_RDWR | O_CREAT, 0644); 10060 Os.chmod(file.getAbsolutePath(), 0644); 10061 return new ParcelFileDescriptor(fd); 10062 } catch (ErrnoException e) { 10063 throw new RemoteException("Failed to open: " + e.getMessage()); 10064 } 10065 } 10066 }; 10067 10068 int ret = PackageManager.INSTALL_SUCCEEDED; 10069 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10070 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10071 Slog.e(TAG, "Failed to copy package"); 10072 return ret; 10073 } 10074 10075 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10076 NativeLibraryHelper.Handle handle = null; 10077 try { 10078 handle = NativeLibraryHelper.Handle.create(codeFile); 10079 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10080 abiOverride); 10081 } catch (IOException e) { 10082 Slog.e(TAG, "Copying native libraries failed", e); 10083 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10084 } finally { 10085 IoUtils.closeQuietly(handle); 10086 } 10087 10088 return ret; 10089 } 10090 10091 int doPreInstall(int status) { 10092 if (status != PackageManager.INSTALL_SUCCEEDED) { 10093 cleanUp(); 10094 } 10095 return status; 10096 } 10097 10098 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10099 if (status != PackageManager.INSTALL_SUCCEEDED) { 10100 cleanUp(); 10101 return false; 10102 } else { 10103 final File targetDir = codeFile.getParentFile(); 10104 final File beforeCodeFile = codeFile; 10105 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10106 10107 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10108 try { 10109 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10110 } catch (ErrnoException e) { 10111 Slog.d(TAG, "Failed to rename", e); 10112 return false; 10113 } 10114 10115 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10116 Slog.d(TAG, "Failed to restorecon"); 10117 return false; 10118 } 10119 10120 // Reflect the rename internally 10121 codeFile = afterCodeFile; 10122 resourceFile = afterCodeFile; 10123 10124 // Reflect the rename in scanned details 10125 pkg.codePath = afterCodeFile.getAbsolutePath(); 10126 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10127 pkg.baseCodePath); 10128 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10129 pkg.splitCodePaths); 10130 10131 // Reflect the rename in app info 10132 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10133 pkg.applicationInfo.setCodePath(pkg.codePath); 10134 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10135 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10136 pkg.applicationInfo.setResourcePath(pkg.codePath); 10137 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10138 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10139 10140 return true; 10141 } 10142 } 10143 10144 int doPostInstall(int status, int uid) { 10145 if (status != PackageManager.INSTALL_SUCCEEDED) { 10146 cleanUp(); 10147 } 10148 return status; 10149 } 10150 10151 @Override 10152 String getCodePath() { 10153 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10154 } 10155 10156 @Override 10157 String getResourcePath() { 10158 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10159 } 10160 10161 @Override 10162 String getLegacyNativeLibraryPath() { 10163 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10164 } 10165 10166 private boolean cleanUp() { 10167 if (codeFile == null || !codeFile.exists()) { 10168 return false; 10169 } 10170 10171 if (codeFile.isDirectory()) { 10172 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10173 } else { 10174 codeFile.delete(); 10175 } 10176 10177 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10178 resourceFile.delete(); 10179 } 10180 10181 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10182 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10183 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10184 } 10185 legacyNativeLibraryPath.delete(); 10186 } 10187 10188 return true; 10189 } 10190 10191 void cleanUpResourcesLI() { 10192 // Try enumerating all code paths before deleting 10193 List<String> allCodePaths = Collections.EMPTY_LIST; 10194 if (codeFile != null && codeFile.exists()) { 10195 try { 10196 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10197 allCodePaths = pkg.getAllCodePaths(); 10198 } catch (PackageParserException e) { 10199 // Ignored; we tried our best 10200 } 10201 } 10202 10203 cleanUp(); 10204 removeDexFiles(allCodePaths, instructionSets); 10205 } 10206 10207 boolean doPostDeleteLI(boolean delete) { 10208 // XXX err, shouldn't we respect the delete flag? 10209 cleanUpResourcesLI(); 10210 return true; 10211 } 10212 } 10213 10214 private boolean isAsecExternal(String cid) { 10215 final String asecPath = PackageHelper.getSdFilesystem(cid); 10216 return !asecPath.startsWith(mAsecInternalPath); 10217 } 10218 10219 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10220 PackageManagerException { 10221 if (copyRet < 0) { 10222 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10223 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10224 throw new PackageManagerException(copyRet, message); 10225 } 10226 } 10227 } 10228 10229 /** 10230 * Extract the MountService "container ID" from the full code path of an 10231 * .apk. 10232 */ 10233 static String cidFromCodePath(String fullCodePath) { 10234 int eidx = fullCodePath.lastIndexOf("/"); 10235 String subStr1 = fullCodePath.substring(0, eidx); 10236 int sidx = subStr1.lastIndexOf("/"); 10237 return subStr1.substring(sidx+1, eidx); 10238 } 10239 10240 /** 10241 * Logic to handle installation of ASEC applications, including copying and 10242 * renaming logic. 10243 */ 10244 class AsecInstallArgs extends InstallArgs { 10245 static final String RES_FILE_NAME = "pkg.apk"; 10246 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10247 10248 String cid; 10249 String packagePath; 10250 String resourcePath; 10251 String legacyNativeLibraryDir; 10252 10253 /** New install */ 10254 AsecInstallArgs(InstallParams params) { 10255 super(params.origin, params.observer, params.installFlags, 10256 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10257 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10258 } 10259 10260 /** Existing install */ 10261 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10262 boolean isExternal, boolean isForwardLocked) { 10263 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10264 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10265 instructionSets, null); 10266 // Hackily pretend we're still looking at a full code path 10267 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10268 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10269 } 10270 10271 // Extract cid from fullCodePath 10272 int eidx = fullCodePath.lastIndexOf("/"); 10273 String subStr1 = fullCodePath.substring(0, eidx); 10274 int sidx = subStr1.lastIndexOf("/"); 10275 cid = subStr1.substring(sidx+1, eidx); 10276 setMountPath(subStr1); 10277 } 10278 10279 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10280 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10281 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10282 instructionSets, null); 10283 this.cid = cid; 10284 setMountPath(PackageHelper.getSdDir(cid)); 10285 } 10286 10287 void createCopyFile() { 10288 cid = mInstallerService.allocateExternalStageCidLegacy(); 10289 } 10290 10291 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10292 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10293 abiOverride); 10294 10295 final File target; 10296 if (isExternalAsec()) { 10297 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10298 } else { 10299 target = Environment.getDataDirectory(); 10300 } 10301 10302 final StorageManager storage = StorageManager.from(mContext); 10303 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10304 } 10305 10306 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10307 if (origin.staged) { 10308 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10309 cid = origin.cid; 10310 setMountPath(PackageHelper.getSdDir(cid)); 10311 return PackageManager.INSTALL_SUCCEEDED; 10312 } 10313 10314 if (temp) { 10315 createCopyFile(); 10316 } else { 10317 /* 10318 * Pre-emptively destroy the container since it's destroyed if 10319 * copying fails due to it existing anyway. 10320 */ 10321 PackageHelper.destroySdDir(cid); 10322 } 10323 10324 final String newMountPath = imcs.copyPackageToContainer( 10325 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10326 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10327 10328 if (newMountPath != null) { 10329 setMountPath(newMountPath); 10330 return PackageManager.INSTALL_SUCCEEDED; 10331 } else { 10332 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10333 } 10334 } 10335 10336 @Override 10337 String getCodePath() { 10338 return packagePath; 10339 } 10340 10341 @Override 10342 String getResourcePath() { 10343 return resourcePath; 10344 } 10345 10346 @Override 10347 String getLegacyNativeLibraryPath() { 10348 return legacyNativeLibraryDir; 10349 } 10350 10351 int doPreInstall(int status) { 10352 if (status != PackageManager.INSTALL_SUCCEEDED) { 10353 // Destroy container 10354 PackageHelper.destroySdDir(cid); 10355 } else { 10356 boolean mounted = PackageHelper.isContainerMounted(cid); 10357 if (!mounted) { 10358 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10359 Process.SYSTEM_UID); 10360 if (newMountPath != null) { 10361 setMountPath(newMountPath); 10362 } else { 10363 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10364 } 10365 } 10366 } 10367 return status; 10368 } 10369 10370 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10371 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10372 String newMountPath = null; 10373 if (PackageHelper.isContainerMounted(cid)) { 10374 // Unmount the container 10375 if (!PackageHelper.unMountSdDir(cid)) { 10376 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10377 return false; 10378 } 10379 } 10380 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10381 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10382 " which might be stale. Will try to clean up."); 10383 // Clean up the stale container and proceed to recreate. 10384 if (!PackageHelper.destroySdDir(newCacheId)) { 10385 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10386 return false; 10387 } 10388 // Successfully cleaned up stale container. Try to rename again. 10389 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10390 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10391 + " inspite of cleaning it up."); 10392 return false; 10393 } 10394 } 10395 if (!PackageHelper.isContainerMounted(newCacheId)) { 10396 Slog.w(TAG, "Mounting container " + newCacheId); 10397 newMountPath = PackageHelper.mountSdDir(newCacheId, 10398 getEncryptKey(), Process.SYSTEM_UID); 10399 } else { 10400 newMountPath = PackageHelper.getSdDir(newCacheId); 10401 } 10402 if (newMountPath == null) { 10403 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10404 return false; 10405 } 10406 Log.i(TAG, "Succesfully renamed " + cid + 10407 " to " + newCacheId + 10408 " at new path: " + newMountPath); 10409 cid = newCacheId; 10410 10411 final File beforeCodeFile = new File(packagePath); 10412 setMountPath(newMountPath); 10413 final File afterCodeFile = new File(packagePath); 10414 10415 // Reflect the rename in scanned details 10416 pkg.codePath = afterCodeFile.getAbsolutePath(); 10417 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10418 pkg.baseCodePath); 10419 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10420 pkg.splitCodePaths); 10421 10422 // Reflect the rename in app info 10423 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10424 pkg.applicationInfo.setCodePath(pkg.codePath); 10425 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10426 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10427 pkg.applicationInfo.setResourcePath(pkg.codePath); 10428 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10429 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10430 10431 return true; 10432 } 10433 10434 private void setMountPath(String mountPath) { 10435 final File mountFile = new File(mountPath); 10436 10437 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10438 if (monolithicFile.exists()) { 10439 packagePath = monolithicFile.getAbsolutePath(); 10440 if (isFwdLocked()) { 10441 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10442 } else { 10443 resourcePath = packagePath; 10444 } 10445 } else { 10446 packagePath = mountFile.getAbsolutePath(); 10447 resourcePath = packagePath; 10448 } 10449 10450 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10451 } 10452 10453 int doPostInstall(int status, int uid) { 10454 if (status != PackageManager.INSTALL_SUCCEEDED) { 10455 cleanUp(); 10456 } else { 10457 final int groupOwner; 10458 final String protectedFile; 10459 if (isFwdLocked()) { 10460 groupOwner = UserHandle.getSharedAppGid(uid); 10461 protectedFile = RES_FILE_NAME; 10462 } else { 10463 groupOwner = -1; 10464 protectedFile = null; 10465 } 10466 10467 if (uid < Process.FIRST_APPLICATION_UID 10468 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10469 Slog.e(TAG, "Failed to finalize " + cid); 10470 PackageHelper.destroySdDir(cid); 10471 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10472 } 10473 10474 boolean mounted = PackageHelper.isContainerMounted(cid); 10475 if (!mounted) { 10476 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10477 } 10478 } 10479 return status; 10480 } 10481 10482 private void cleanUp() { 10483 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10484 10485 // Destroy secure container 10486 PackageHelper.destroySdDir(cid); 10487 } 10488 10489 private List<String> getAllCodePaths() { 10490 final File codeFile = new File(getCodePath()); 10491 if (codeFile != null && codeFile.exists()) { 10492 try { 10493 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10494 return pkg.getAllCodePaths(); 10495 } catch (PackageParserException e) { 10496 // Ignored; we tried our best 10497 } 10498 } 10499 return Collections.EMPTY_LIST; 10500 } 10501 10502 void cleanUpResourcesLI() { 10503 // Enumerate all code paths before deleting 10504 cleanUpResourcesLI(getAllCodePaths()); 10505 } 10506 10507 private void cleanUpResourcesLI(List<String> allCodePaths) { 10508 cleanUp(); 10509 removeDexFiles(allCodePaths, instructionSets); 10510 } 10511 10512 10513 10514 String getPackageName() { 10515 return getAsecPackageName(cid); 10516 } 10517 10518 boolean doPostDeleteLI(boolean delete) { 10519 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10520 final List<String> allCodePaths = getAllCodePaths(); 10521 boolean mounted = PackageHelper.isContainerMounted(cid); 10522 if (mounted) { 10523 // Unmount first 10524 if (PackageHelper.unMountSdDir(cid)) { 10525 mounted = false; 10526 } 10527 } 10528 if (!mounted && delete) { 10529 cleanUpResourcesLI(allCodePaths); 10530 } 10531 return !mounted; 10532 } 10533 10534 @Override 10535 int doPreCopy() { 10536 if (isFwdLocked()) { 10537 if (!PackageHelper.fixSdPermissions(cid, 10538 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10539 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10540 } 10541 } 10542 10543 return PackageManager.INSTALL_SUCCEEDED; 10544 } 10545 10546 @Override 10547 int doPostCopy(int uid) { 10548 if (isFwdLocked()) { 10549 if (uid < Process.FIRST_APPLICATION_UID 10550 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10551 RES_FILE_NAME)) { 10552 Slog.e(TAG, "Failed to finalize " + cid); 10553 PackageHelper.destroySdDir(cid); 10554 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10555 } 10556 } 10557 10558 return PackageManager.INSTALL_SUCCEEDED; 10559 } 10560 } 10561 10562 static String getAsecPackageName(String packageCid) { 10563 int idx = packageCid.lastIndexOf("-"); 10564 if (idx == -1) { 10565 return packageCid; 10566 } 10567 return packageCid.substring(0, idx); 10568 } 10569 10570 // Utility method used to create code paths based on package name and available index. 10571 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10572 String idxStr = ""; 10573 int idx = 1; 10574 // Fall back to default value of idx=1 if prefix is not 10575 // part of oldCodePath 10576 if (oldCodePath != null) { 10577 String subStr = oldCodePath; 10578 // Drop the suffix right away 10579 if (suffix != null && subStr.endsWith(suffix)) { 10580 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10581 } 10582 // If oldCodePath already contains prefix find out the 10583 // ending index to either increment or decrement. 10584 int sidx = subStr.lastIndexOf(prefix); 10585 if (sidx != -1) { 10586 subStr = subStr.substring(sidx + prefix.length()); 10587 if (subStr != null) { 10588 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10589 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10590 } 10591 try { 10592 idx = Integer.parseInt(subStr); 10593 if (idx <= 1) { 10594 idx++; 10595 } else { 10596 idx--; 10597 } 10598 } catch(NumberFormatException e) { 10599 } 10600 } 10601 } 10602 } 10603 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10604 return prefix + idxStr; 10605 } 10606 10607 private File getNextCodePath(File targetDir, String packageName) { 10608 int suffix = 1; 10609 File result; 10610 do { 10611 result = new File(targetDir, packageName + "-" + suffix); 10612 suffix++; 10613 } while (result.exists()); 10614 return result; 10615 } 10616 10617 // Utility method that returns the relative package path with respect 10618 // to the installation directory. Like say for /data/data/com.test-1.apk 10619 // string com.test-1 is returned. 10620 static String deriveCodePathName(String codePath) { 10621 if (codePath == null) { 10622 return null; 10623 } 10624 final File codeFile = new File(codePath); 10625 final String name = codeFile.getName(); 10626 if (codeFile.isDirectory()) { 10627 return name; 10628 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10629 final int lastDot = name.lastIndexOf('.'); 10630 return name.substring(0, lastDot); 10631 } else { 10632 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10633 return null; 10634 } 10635 } 10636 10637 class PackageInstalledInfo { 10638 String name; 10639 int uid; 10640 // The set of users that originally had this package installed. 10641 int[] origUsers; 10642 // The set of users that now have this package installed. 10643 int[] newUsers; 10644 PackageParser.Package pkg; 10645 int returnCode; 10646 String returnMsg; 10647 PackageRemovedInfo removedInfo; 10648 10649 public void setError(int code, String msg) { 10650 returnCode = code; 10651 returnMsg = msg; 10652 Slog.w(TAG, msg); 10653 } 10654 10655 public void setError(String msg, PackageParserException e) { 10656 returnCode = e.error; 10657 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10658 Slog.w(TAG, msg, e); 10659 } 10660 10661 public void setError(String msg, PackageManagerException e) { 10662 returnCode = e.error; 10663 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10664 Slog.w(TAG, msg, e); 10665 } 10666 10667 // In some error cases we want to convey more info back to the observer 10668 String origPackage; 10669 String origPermission; 10670 } 10671 10672 /* 10673 * Install a non-existing package. 10674 */ 10675 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10676 UserHandle user, String installerPackageName, String volumeUuid, 10677 PackageInstalledInfo res) { 10678 // Remember this for later, in case we need to rollback this install 10679 String pkgName = pkg.packageName; 10680 10681 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10682 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10683 UserHandle.USER_OWNER).exists(); 10684 synchronized(mPackages) { 10685 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10686 // A package with the same name is already installed, though 10687 // it has been renamed to an older name. The package we 10688 // are trying to install should be installed as an update to 10689 // the existing one, but that has not been requested, so bail. 10690 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10691 + " without first uninstalling package running as " 10692 + mSettings.mRenamedPackages.get(pkgName)); 10693 return; 10694 } 10695 if (mPackages.containsKey(pkgName)) { 10696 // Don't allow installation over an existing package with the same name. 10697 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10698 + " without first uninstalling."); 10699 return; 10700 } 10701 } 10702 10703 try { 10704 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10705 System.currentTimeMillis(), user); 10706 10707 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10708 // delete the partially installed application. the data directory will have to be 10709 // restored if it was already existing 10710 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10711 // remove package from internal structures. Note that we want deletePackageX to 10712 // delete the package data and cache directories that it created in 10713 // scanPackageLocked, unless those directories existed before we even tried to 10714 // install. 10715 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10716 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10717 res.removedInfo, true); 10718 } 10719 10720 } catch (PackageManagerException e) { 10721 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10722 } 10723 } 10724 10725 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10726 // Upgrade keysets are being used. Determine if new package has a superset of the 10727 // required keys. 10728 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10729 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10730 for (int i = 0; i < upgradeKeySets.length; i++) { 10731 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10732 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10733 return true; 10734 } 10735 } 10736 return false; 10737 } 10738 10739 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10740 UserHandle user, String installerPackageName, String volumeUuid, 10741 PackageInstalledInfo res) { 10742 PackageParser.Package oldPackage; 10743 String pkgName = pkg.packageName; 10744 int[] allUsers; 10745 boolean[] perUserInstalled; 10746 10747 // First find the old package info and check signatures 10748 synchronized(mPackages) { 10749 oldPackage = mPackages.get(pkgName); 10750 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10751 PackageSetting ps = mSettings.mPackages.get(pkgName); 10752 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10753 // default to original signature matching 10754 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10755 != PackageManager.SIGNATURE_MATCH) { 10756 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10757 "New package has a different signature: " + pkgName); 10758 return; 10759 } 10760 } else { 10761 if(!checkUpgradeKeySetLP(ps, pkg)) { 10762 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10763 "New package not signed by keys specified by upgrade-keysets: " 10764 + pkgName); 10765 return; 10766 } 10767 } 10768 10769 // In case of rollback, remember per-user/profile install state 10770 allUsers = sUserManager.getUserIds(); 10771 perUserInstalled = new boolean[allUsers.length]; 10772 for (int i = 0; i < allUsers.length; i++) { 10773 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10774 } 10775 } 10776 10777 boolean sysPkg = (isSystemApp(oldPackage)); 10778 if (sysPkg) { 10779 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10780 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10781 } else { 10782 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10783 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10784 } 10785 } 10786 10787 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10788 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10789 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10790 String volumeUuid, PackageInstalledInfo res) { 10791 String pkgName = deletedPackage.packageName; 10792 boolean deletedPkg = true; 10793 boolean updatedSettings = false; 10794 10795 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10796 + deletedPackage); 10797 long origUpdateTime; 10798 if (pkg.mExtras != null) { 10799 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10800 } else { 10801 origUpdateTime = 0; 10802 } 10803 10804 // First delete the existing package while retaining the data directory 10805 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10806 res.removedInfo, true)) { 10807 // If the existing package wasn't successfully deleted 10808 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10809 deletedPkg = false; 10810 } else { 10811 // Successfully deleted the old package; proceed with replace. 10812 10813 // If deleted package lived in a container, give users a chance to 10814 // relinquish resources before killing. 10815 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10816 if (DEBUG_INSTALL) { 10817 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10818 } 10819 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10820 final ArrayList<String> pkgList = new ArrayList<String>(1); 10821 pkgList.add(deletedPackage.applicationInfo.packageName); 10822 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10823 } 10824 10825 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10826 try { 10827 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10828 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10829 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10830 perUserInstalled, res, user); 10831 updatedSettings = true; 10832 } catch (PackageManagerException e) { 10833 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10834 } 10835 } 10836 10837 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10838 // remove package from internal structures. Note that we want deletePackageX to 10839 // delete the package data and cache directories that it created in 10840 // scanPackageLocked, unless those directories existed before we even tried to 10841 // install. 10842 if(updatedSettings) { 10843 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10844 deletePackageLI( 10845 pkgName, null, true, allUsers, perUserInstalled, 10846 PackageManager.DELETE_KEEP_DATA, 10847 res.removedInfo, true); 10848 } 10849 // Since we failed to install the new package we need to restore the old 10850 // package that we deleted. 10851 if (deletedPkg) { 10852 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10853 File restoreFile = new File(deletedPackage.codePath); 10854 // Parse old package 10855 boolean oldExternal = isExternal(deletedPackage); 10856 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10857 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10858 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10859 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10860 try { 10861 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10862 } catch (PackageManagerException e) { 10863 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10864 + e.getMessage()); 10865 return; 10866 } 10867 // Restore of old package succeeded. Update permissions. 10868 // writer 10869 synchronized (mPackages) { 10870 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10871 UPDATE_PERMISSIONS_ALL); 10872 // can downgrade to reader 10873 mSettings.writeLPr(); 10874 } 10875 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10876 } 10877 } 10878 } 10879 10880 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10881 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10882 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10883 String volumeUuid, PackageInstalledInfo res) { 10884 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10885 + ", old=" + deletedPackage); 10886 boolean disabledSystem = false; 10887 boolean updatedSettings = false; 10888 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10889 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10890 != 0) { 10891 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10892 } 10893 String packageName = deletedPackage.packageName; 10894 if (packageName == null) { 10895 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10896 "Attempt to delete null packageName."); 10897 return; 10898 } 10899 PackageParser.Package oldPkg; 10900 PackageSetting oldPkgSetting; 10901 // reader 10902 synchronized (mPackages) { 10903 oldPkg = mPackages.get(packageName); 10904 oldPkgSetting = mSettings.mPackages.get(packageName); 10905 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10906 (oldPkgSetting == null)) { 10907 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10908 "Couldn't find package:" + packageName + " information"); 10909 return; 10910 } 10911 } 10912 10913 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10914 10915 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10916 res.removedInfo.removedPackage = packageName; 10917 // Remove existing system package 10918 removePackageLI(oldPkgSetting, true); 10919 // writer 10920 synchronized (mPackages) { 10921 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10922 if (!disabledSystem && deletedPackage != null) { 10923 // We didn't need to disable the .apk as a current system package, 10924 // which means we are replacing another update that is already 10925 // installed. We need to make sure to delete the older one's .apk. 10926 res.removedInfo.args = createInstallArgsForExisting(0, 10927 deletedPackage.applicationInfo.getCodePath(), 10928 deletedPackage.applicationInfo.getResourcePath(), 10929 deletedPackage.applicationInfo.nativeLibraryRootDir, 10930 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10931 } else { 10932 res.removedInfo.args = null; 10933 } 10934 } 10935 10936 // Successfully disabled the old package. Now proceed with re-installation 10937 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 10938 10939 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10940 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10941 10942 PackageParser.Package newPackage = null; 10943 try { 10944 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10945 if (newPackage.mExtras != null) { 10946 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10947 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10948 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10949 10950 // is the update attempting to change shared user? that isn't going to work... 10951 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10952 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10953 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10954 + " to " + newPkgSetting.sharedUser); 10955 updatedSettings = true; 10956 } 10957 } 10958 10959 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10960 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10961 perUserInstalled, res, user); 10962 updatedSettings = true; 10963 } 10964 10965 } catch (PackageManagerException e) { 10966 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10967 } 10968 10969 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10970 // Re installation failed. Restore old information 10971 // Remove new pkg information 10972 if (newPackage != null) { 10973 removeInstalledPackageLI(newPackage, true); 10974 } 10975 // Add back the old system package 10976 try { 10977 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10978 } catch (PackageManagerException e) { 10979 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10980 } 10981 // Restore the old system information in Settings 10982 synchronized (mPackages) { 10983 if (disabledSystem) { 10984 mSettings.enableSystemPackageLPw(packageName); 10985 } 10986 if (updatedSettings) { 10987 mSettings.setInstallerPackageName(packageName, 10988 oldPkgSetting.installerPackageName); 10989 } 10990 mSettings.writeLPr(); 10991 } 10992 } 10993 } 10994 10995 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10996 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10997 UserHandle user) { 10998 String pkgName = newPackage.packageName; 10999 synchronized (mPackages) { 11000 //write settings. the installStatus will be incomplete at this stage. 11001 //note that the new package setting would have already been 11002 //added to mPackages. It hasn't been persisted yet. 11003 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11004 mSettings.writeLPr(); 11005 } 11006 11007 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11008 11009 synchronized (mPackages) { 11010 updatePermissionsLPw(newPackage.packageName, newPackage, 11011 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11012 ? UPDATE_PERMISSIONS_ALL : 0)); 11013 // For system-bundled packages, we assume that installing an upgraded version 11014 // of the package implies that the user actually wants to run that new code, 11015 // so we enable the package. 11016 PackageSetting ps = mSettings.mPackages.get(pkgName); 11017 if (ps != null) { 11018 if (isSystemApp(newPackage)) { 11019 // NB: implicit assumption that system package upgrades apply to all users 11020 if (DEBUG_INSTALL) { 11021 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11022 } 11023 if (res.origUsers != null) { 11024 for (int userHandle : res.origUsers) { 11025 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11026 userHandle, installerPackageName); 11027 } 11028 } 11029 // Also convey the prior install/uninstall state 11030 if (allUsers != null && perUserInstalled != null) { 11031 for (int i = 0; i < allUsers.length; i++) { 11032 if (DEBUG_INSTALL) { 11033 Slog.d(TAG, " user " + allUsers[i] 11034 + " => " + perUserInstalled[i]); 11035 } 11036 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11037 } 11038 // these install state changes will be persisted in the 11039 // upcoming call to mSettings.writeLPr(). 11040 } 11041 } 11042 // It's implied that when a user requests installation, they want the app to be 11043 // installed and enabled. 11044 int userId = user.getIdentifier(); 11045 if (userId != UserHandle.USER_ALL) { 11046 ps.setInstalled(true, userId); 11047 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11048 } 11049 } 11050 res.name = pkgName; 11051 res.uid = newPackage.applicationInfo.uid; 11052 res.pkg = newPackage; 11053 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11054 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11055 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11056 //to update install status 11057 mSettings.writeLPr(); 11058 } 11059 } 11060 11061 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11062 final int installFlags = args.installFlags; 11063 final String installerPackageName = args.installerPackageName; 11064 final String volumeUuid = args.volumeUuid; 11065 final File tmpPackageFile = new File(args.getCodePath()); 11066 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11067 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11068 || (args.volumeUuid != null)); 11069 boolean replace = false; 11070 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11071 // Result object to be returned 11072 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11073 11074 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11075 // Retrieve PackageSettings and parse package 11076 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11077 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11078 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11079 PackageParser pp = new PackageParser(); 11080 pp.setSeparateProcesses(mSeparateProcesses); 11081 pp.setDisplayMetrics(mMetrics); 11082 11083 final PackageParser.Package pkg; 11084 try { 11085 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11086 } catch (PackageParserException e) { 11087 res.setError("Failed parse during installPackageLI", e); 11088 return; 11089 } 11090 11091 // Mark that we have an install time CPU ABI override. 11092 pkg.cpuAbiOverride = args.abiOverride; 11093 11094 String pkgName = res.name = pkg.packageName; 11095 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11096 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11097 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11098 return; 11099 } 11100 } 11101 11102 try { 11103 pp.collectCertificates(pkg, parseFlags); 11104 pp.collectManifestDigest(pkg); 11105 } catch (PackageParserException e) { 11106 res.setError("Failed collect during installPackageLI", e); 11107 return; 11108 } 11109 11110 /* If the installer passed in a manifest digest, compare it now. */ 11111 if (args.manifestDigest != null) { 11112 if (DEBUG_INSTALL) { 11113 final String parsedManifest = pkg.manifestDigest == null ? "null" 11114 : pkg.manifestDigest.toString(); 11115 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11116 + parsedManifest); 11117 } 11118 11119 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11120 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11121 return; 11122 } 11123 } else if (DEBUG_INSTALL) { 11124 final String parsedManifest = pkg.manifestDigest == null 11125 ? "null" : pkg.manifestDigest.toString(); 11126 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11127 } 11128 11129 // Get rid of all references to package scan path via parser. 11130 pp = null; 11131 String oldCodePath = null; 11132 boolean systemApp = false; 11133 synchronized (mPackages) { 11134 // Check if installing already existing package 11135 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11136 String oldName = mSettings.mRenamedPackages.get(pkgName); 11137 if (pkg.mOriginalPackages != null 11138 && pkg.mOriginalPackages.contains(oldName) 11139 && mPackages.containsKey(oldName)) { 11140 // This package is derived from an original package, 11141 // and this device has been updating from that original 11142 // name. We must continue using the original name, so 11143 // rename the new package here. 11144 pkg.setPackageName(oldName); 11145 pkgName = pkg.packageName; 11146 replace = true; 11147 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11148 + oldName + " pkgName=" + pkgName); 11149 } else if (mPackages.containsKey(pkgName)) { 11150 // This package, under its official name, already exists 11151 // on the device; we should replace it. 11152 replace = true; 11153 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11154 } 11155 } 11156 11157 PackageSetting ps = mSettings.mPackages.get(pkgName); 11158 if (ps != null) { 11159 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11160 11161 // Quick sanity check that we're signed correctly if updating; 11162 // we'll check this again later when scanning, but we want to 11163 // bail early here before tripping over redefined permissions. 11164 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11165 try { 11166 verifySignaturesLP(ps, pkg); 11167 } catch (PackageManagerException e) { 11168 res.setError(e.error, e.getMessage()); 11169 return; 11170 } 11171 } else { 11172 if (!checkUpgradeKeySetLP(ps, pkg)) { 11173 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11174 + pkg.packageName + " upgrade keys do not match the " 11175 + "previously installed version"); 11176 return; 11177 } 11178 } 11179 11180 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11181 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11182 systemApp = (ps.pkg.applicationInfo.flags & 11183 ApplicationInfo.FLAG_SYSTEM) != 0; 11184 } 11185 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11186 } 11187 11188 // Check whether the newly-scanned package wants to define an already-defined perm 11189 int N = pkg.permissions.size(); 11190 for (int i = N-1; i >= 0; i--) { 11191 PackageParser.Permission perm = pkg.permissions.get(i); 11192 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11193 if (bp != null) { 11194 // If the defining package is signed with our cert, it's okay. This 11195 // also includes the "updating the same package" case, of course. 11196 // "updating same package" could also involve key-rotation. 11197 final boolean sigsOk; 11198 if (!bp.sourcePackage.equals(pkg.packageName) 11199 || !(bp.packageSetting instanceof PackageSetting) 11200 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11201 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11202 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11203 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11204 } else { 11205 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11206 } 11207 if (!sigsOk) { 11208 // If the owning package is the system itself, we log but allow 11209 // install to proceed; we fail the install on all other permission 11210 // redefinitions. 11211 if (!bp.sourcePackage.equals("android")) { 11212 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11213 + pkg.packageName + " attempting to redeclare permission " 11214 + perm.info.name + " already owned by " + bp.sourcePackage); 11215 res.origPermission = perm.info.name; 11216 res.origPackage = bp.sourcePackage; 11217 return; 11218 } else { 11219 Slog.w(TAG, "Package " + pkg.packageName 11220 + " attempting to redeclare system permission " 11221 + perm.info.name + "; ignoring new declaration"); 11222 pkg.permissions.remove(i); 11223 } 11224 } 11225 } 11226 } 11227 11228 } 11229 11230 if (systemApp && onExternal) { 11231 // Disable updates to system apps on sdcard 11232 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11233 "Cannot install updates to system apps on sdcard"); 11234 return; 11235 } 11236 11237 // If app directory is not writable, dexopt will be called after the rename 11238 if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11239 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11240 scanFlags |= SCAN_NO_DEX; 11241 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11242 int result = mPackageDexOptimizer 11243 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11244 false /* defer */, false /* inclDependencies */); 11245 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11246 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11247 return; 11248 } 11249 } 11250 11251 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11252 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11253 return; 11254 } 11255 11256 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11257 11258 if (replace) { 11259 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11260 installerPackageName, volumeUuid, res); 11261 } else { 11262 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11263 args.user, installerPackageName, volumeUuid, res); 11264 } 11265 synchronized (mPackages) { 11266 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11267 if (ps != null) { 11268 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11269 } 11270 } 11271 } 11272 11273 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11274 if (mIntentFilterVerifierComponent == null) { 11275 Slog.d(TAG, "No IntentFilter verification will not be done as " 11276 + "there is no IntentFilterVerifier available!"); 11277 return; 11278 } 11279 11280 final int verifierUid = getPackageUid( 11281 mIntentFilterVerifierComponent.getPackageName(), 11282 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11283 11284 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11285 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11286 msg.obj = pkg; 11287 msg.arg1 = userId; 11288 msg.arg2 = verifierUid; 11289 11290 mHandler.sendMessage(msg); 11291 } 11292 11293 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11294 PackageParser.Package pkg) { 11295 int size = pkg.activities.size(); 11296 if (size == 0) { 11297 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11298 return; 11299 } 11300 11301 final boolean hasDomainURLs = hasDomainURLs(pkg); 11302 if (!hasDomainURLs) { 11303 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11304 return; 11305 } 11306 11307 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11308 + " Activities needs verification ..."); 11309 11310 final int verificationId = mIntentFilterVerificationToken++; 11311 int count = 0; 11312 final String packageName = pkg.packageName; 11313 ArrayList<String> allHosts = new ArrayList<>(); 11314 11315 synchronized (mPackages) { 11316 for (PackageParser.Activity a : pkg.activities) { 11317 for (ActivityIntentInfo filter : a.intents) { 11318 boolean needsFilterVerification = filter.needsVerification(); 11319 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11320 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11321 mIntentFilterVerifier.addOneIntentFilterVerification( 11322 verifierUid, userId, verificationId, filter, packageName); 11323 count++; 11324 } else if (!needsFilterVerification) { 11325 Slog.d(TAG, "No verification needed for IntentFilter:" 11326 + filter.toString()); 11327 if (hasValidDomains(filter)) { 11328 allHosts.addAll(filter.getHostsList()); 11329 } 11330 } else { 11331 Slog.d(TAG, "Verification already done for IntentFilter:" 11332 + filter.toString()); 11333 } 11334 } 11335 } 11336 } 11337 11338 if (count > 0) { 11339 mIntentFilterVerifier.startVerifications(userId); 11340 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11341 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11342 } else { 11343 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11344 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11345 packageName, allHosts) != null) { 11346 scheduleWriteSettingsLocked(); 11347 } 11348 } 11349 } 11350 11351 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11352 final ComponentName cn = filter.activity.getComponentName(); 11353 final String packageName = cn.getPackageName(); 11354 11355 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11356 packageName); 11357 if (ivi == null) { 11358 return true; 11359 } 11360 int status = ivi.getStatus(); 11361 switch (status) { 11362 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11363 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11364 return true; 11365 11366 default: 11367 // Nothing to do 11368 return false; 11369 } 11370 } 11371 11372 private static boolean isMultiArch(PackageSetting ps) { 11373 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11374 } 11375 11376 private static boolean isMultiArch(ApplicationInfo info) { 11377 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11378 } 11379 11380 private static boolean isExternal(PackageParser.Package pkg) { 11381 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11382 } 11383 11384 private static boolean isExternal(PackageSetting ps) { 11385 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11386 } 11387 11388 private static boolean isExternal(ApplicationInfo info) { 11389 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11390 } 11391 11392 private static boolean isSystemApp(PackageParser.Package pkg) { 11393 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11394 } 11395 11396 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11397 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11398 } 11399 11400 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11401 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11402 } 11403 11404 private static boolean isSystemApp(PackageSetting ps) { 11405 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11406 } 11407 11408 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11409 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11410 } 11411 11412 private int packageFlagsToInstallFlags(PackageSetting ps) { 11413 int installFlags = 0; 11414 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11415 // This existing package was an external ASEC install when we have 11416 // the external flag without a UUID 11417 installFlags |= PackageManager.INSTALL_EXTERNAL; 11418 } 11419 if (ps.isForwardLocked()) { 11420 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11421 } 11422 return installFlags; 11423 } 11424 11425 private void deleteTempPackageFiles() { 11426 final FilenameFilter filter = new FilenameFilter() { 11427 public boolean accept(File dir, String name) { 11428 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11429 } 11430 }; 11431 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11432 file.delete(); 11433 } 11434 } 11435 11436 @Override 11437 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11438 int flags) { 11439 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11440 flags); 11441 } 11442 11443 @Override 11444 public void deletePackage(final String packageName, 11445 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11446 mContext.enforceCallingOrSelfPermission( 11447 android.Manifest.permission.DELETE_PACKAGES, null); 11448 final int uid = Binder.getCallingUid(); 11449 if (UserHandle.getUserId(uid) != userId) { 11450 mContext.enforceCallingPermission( 11451 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11452 "deletePackage for user " + userId); 11453 } 11454 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11455 try { 11456 observer.onPackageDeleted(packageName, 11457 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11458 } catch (RemoteException re) { 11459 } 11460 return; 11461 } 11462 11463 boolean uninstallBlocked = false; 11464 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11465 int[] users = sUserManager.getUserIds(); 11466 for (int i = 0; i < users.length; ++i) { 11467 if (getBlockUninstallForUser(packageName, users[i])) { 11468 uninstallBlocked = true; 11469 break; 11470 } 11471 } 11472 } else { 11473 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11474 } 11475 if (uninstallBlocked) { 11476 try { 11477 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11478 null); 11479 } catch (RemoteException re) { 11480 } 11481 return; 11482 } 11483 11484 if (DEBUG_REMOVE) { 11485 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11486 } 11487 // Queue up an async operation since the package deletion may take a little while. 11488 mHandler.post(new Runnable() { 11489 public void run() { 11490 mHandler.removeCallbacks(this); 11491 final int returnCode = deletePackageX(packageName, userId, flags); 11492 if (observer != null) { 11493 try { 11494 observer.onPackageDeleted(packageName, returnCode, null); 11495 } catch (RemoteException e) { 11496 Log.i(TAG, "Observer no longer exists."); 11497 } //end catch 11498 } //end if 11499 } //end run 11500 }); 11501 } 11502 11503 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11504 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11505 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11506 try { 11507 if (dpm != null) { 11508 if (dpm.isDeviceOwner(packageName)) { 11509 return true; 11510 } 11511 int[] users; 11512 if (userId == UserHandle.USER_ALL) { 11513 users = sUserManager.getUserIds(); 11514 } else { 11515 users = new int[]{userId}; 11516 } 11517 for (int i = 0; i < users.length; ++i) { 11518 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11519 return true; 11520 } 11521 } 11522 } 11523 } catch (RemoteException e) { 11524 } 11525 return false; 11526 } 11527 11528 /** 11529 * This method is an internal method that could be get invoked either 11530 * to delete an installed package or to clean up a failed installation. 11531 * After deleting an installed package, a broadcast is sent to notify any 11532 * listeners that the package has been installed. For cleaning up a failed 11533 * installation, the broadcast is not necessary since the package's 11534 * installation wouldn't have sent the initial broadcast either 11535 * The key steps in deleting a package are 11536 * deleting the package information in internal structures like mPackages, 11537 * deleting the packages base directories through installd 11538 * updating mSettings to reflect current status 11539 * persisting settings for later use 11540 * sending a broadcast if necessary 11541 */ 11542 private int deletePackageX(String packageName, int userId, int flags) { 11543 final PackageRemovedInfo info = new PackageRemovedInfo(); 11544 final boolean res; 11545 11546 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11547 ? UserHandle.ALL : new UserHandle(userId); 11548 11549 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11550 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11551 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11552 } 11553 11554 boolean removedForAllUsers = false; 11555 boolean systemUpdate = false; 11556 11557 // for the uninstall-updates case and restricted profiles, remember the per- 11558 // userhandle installed state 11559 int[] allUsers; 11560 boolean[] perUserInstalled; 11561 synchronized (mPackages) { 11562 PackageSetting ps = mSettings.mPackages.get(packageName); 11563 allUsers = sUserManager.getUserIds(); 11564 perUserInstalled = new boolean[allUsers.length]; 11565 for (int i = 0; i < allUsers.length; i++) { 11566 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11567 } 11568 } 11569 11570 synchronized (mInstallLock) { 11571 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11572 res = deletePackageLI(packageName, removeForUser, 11573 true, allUsers, perUserInstalled, 11574 flags | REMOVE_CHATTY, info, true); 11575 systemUpdate = info.isRemovedPackageSystemUpdate; 11576 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11577 removedForAllUsers = true; 11578 } 11579 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11580 + " removedForAllUsers=" + removedForAllUsers); 11581 } 11582 11583 if (res) { 11584 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11585 11586 // If the removed package was a system update, the old system package 11587 // was re-enabled; we need to broadcast this information 11588 if (systemUpdate) { 11589 Bundle extras = new Bundle(1); 11590 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11591 ? info.removedAppId : info.uid); 11592 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11593 11594 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11595 extras, null, null, null); 11596 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11597 extras, null, null, null); 11598 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11599 null, packageName, null, null); 11600 } 11601 } 11602 // Force a gc here. 11603 Runtime.getRuntime().gc(); 11604 // Delete the resources here after sending the broadcast to let 11605 // other processes clean up before deleting resources. 11606 if (info.args != null) { 11607 synchronized (mInstallLock) { 11608 info.args.doPostDeleteLI(true); 11609 } 11610 } 11611 11612 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11613 } 11614 11615 static class PackageRemovedInfo { 11616 String removedPackage; 11617 int uid = -1; 11618 int removedAppId = -1; 11619 int[] removedUsers = null; 11620 boolean isRemovedPackageSystemUpdate = false; 11621 // Clean up resources deleted packages. 11622 InstallArgs args = null; 11623 11624 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11625 Bundle extras = new Bundle(1); 11626 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11627 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11628 if (replacing) { 11629 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11630 } 11631 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11632 if (removedPackage != null) { 11633 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11634 extras, null, null, removedUsers); 11635 if (fullRemove && !replacing) { 11636 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11637 extras, null, null, removedUsers); 11638 } 11639 } 11640 if (removedAppId >= 0) { 11641 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11642 removedUsers); 11643 } 11644 } 11645 } 11646 11647 /* 11648 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11649 * flag is not set, the data directory is removed as well. 11650 * make sure this flag is set for partially installed apps. If not its meaningless to 11651 * delete a partially installed application. 11652 */ 11653 private void removePackageDataLI(PackageSetting ps, 11654 int[] allUserHandles, boolean[] perUserInstalled, 11655 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11656 String packageName = ps.name; 11657 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11658 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11659 // Retrieve object to delete permissions for shared user later on 11660 final PackageSetting deletedPs; 11661 // reader 11662 synchronized (mPackages) { 11663 deletedPs = mSettings.mPackages.get(packageName); 11664 if (outInfo != null) { 11665 outInfo.removedPackage = packageName; 11666 outInfo.removedUsers = deletedPs != null 11667 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11668 : null; 11669 } 11670 } 11671 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11672 removeDataDirsLI(ps.volumeUuid, packageName); 11673 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11674 } 11675 // writer 11676 synchronized (mPackages) { 11677 if (deletedPs != null) { 11678 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11679 if (outInfo != null) { 11680 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11681 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11682 } 11683 updatePermissionsLPw(deletedPs.name, null, 0); 11684 if (deletedPs.sharedUser != null) { 11685 // Remove permissions associated with package. Since runtime 11686 // permissions are per user we have to kill the removed package 11687 // or packages running under the shared user of the removed 11688 // package if revoking the permissions requested only by the removed 11689 // package is successful and this causes a change in gids. 11690 for (int userId : UserManagerService.getInstance().getUserIds()) { 11691 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11692 userId); 11693 if (userIdToKill == UserHandle.USER_ALL 11694 || userIdToKill >= UserHandle.USER_OWNER) { 11695 // If gids changed for this user, kill all affected packages. 11696 mHandler.post(new Runnable() { 11697 @Override 11698 public void run() { 11699 // This has to happen with no lock held. 11700 killSettingPackagesForUser(deletedPs, userIdToKill, 11701 KILL_APP_REASON_GIDS_CHANGED); 11702 } 11703 }); 11704 break; 11705 } 11706 } 11707 } 11708 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11709 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11710 } 11711 // make sure to preserve per-user disabled state if this removal was just 11712 // a downgrade of a system app to the factory package 11713 if (allUserHandles != null && perUserInstalled != null) { 11714 if (DEBUG_REMOVE) { 11715 Slog.d(TAG, "Propagating install state across downgrade"); 11716 } 11717 for (int i = 0; i < allUserHandles.length; i++) { 11718 if (DEBUG_REMOVE) { 11719 Slog.d(TAG, " user " + allUserHandles[i] 11720 + " => " + perUserInstalled[i]); 11721 } 11722 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11723 } 11724 } 11725 } 11726 // can downgrade to reader 11727 if (writeSettings) { 11728 // Save settings now 11729 mSettings.writeLPr(); 11730 } 11731 } 11732 if (outInfo != null) { 11733 // A user ID was deleted here. Go through all users and remove it 11734 // from KeyStore. 11735 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11736 } 11737 } 11738 11739 static boolean locationIsPrivileged(File path) { 11740 try { 11741 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11742 .getCanonicalPath(); 11743 return path.getCanonicalPath().startsWith(privilegedAppDir); 11744 } catch (IOException e) { 11745 Slog.e(TAG, "Unable to access code path " + path); 11746 } 11747 return false; 11748 } 11749 11750 /* 11751 * Tries to delete system package. 11752 */ 11753 private boolean deleteSystemPackageLI(PackageSetting newPs, 11754 int[] allUserHandles, boolean[] perUserInstalled, 11755 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11756 final boolean applyUserRestrictions 11757 = (allUserHandles != null) && (perUserInstalled != null); 11758 PackageSetting disabledPs = null; 11759 // Confirm if the system package has been updated 11760 // An updated system app can be deleted. This will also have to restore 11761 // the system pkg from system partition 11762 // reader 11763 synchronized (mPackages) { 11764 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11765 } 11766 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11767 + " disabledPs=" + disabledPs); 11768 if (disabledPs == null) { 11769 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11770 return false; 11771 } else if (DEBUG_REMOVE) { 11772 Slog.d(TAG, "Deleting system pkg from data partition"); 11773 } 11774 if (DEBUG_REMOVE) { 11775 if (applyUserRestrictions) { 11776 Slog.d(TAG, "Remembering install states:"); 11777 for (int i = 0; i < allUserHandles.length; i++) { 11778 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11779 } 11780 } 11781 } 11782 // Delete the updated package 11783 outInfo.isRemovedPackageSystemUpdate = true; 11784 if (disabledPs.versionCode < newPs.versionCode) { 11785 // Delete data for downgrades 11786 flags &= ~PackageManager.DELETE_KEEP_DATA; 11787 } else { 11788 // Preserve data by setting flag 11789 flags |= PackageManager.DELETE_KEEP_DATA; 11790 } 11791 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11792 allUserHandles, perUserInstalled, outInfo, writeSettings); 11793 if (!ret) { 11794 return false; 11795 } 11796 // writer 11797 synchronized (mPackages) { 11798 // Reinstate the old system package 11799 mSettings.enableSystemPackageLPw(newPs.name); 11800 // Remove any native libraries from the upgraded package. 11801 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11802 } 11803 // Install the system package 11804 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11805 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11806 if (locationIsPrivileged(disabledPs.codePath)) { 11807 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11808 } 11809 11810 final PackageParser.Package newPkg; 11811 try { 11812 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11813 } catch (PackageManagerException e) { 11814 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11815 return false; 11816 } 11817 11818 // writer 11819 synchronized (mPackages) { 11820 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11821 updatePermissionsLPw(newPkg.packageName, newPkg, 11822 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11823 if (applyUserRestrictions) { 11824 if (DEBUG_REMOVE) { 11825 Slog.d(TAG, "Propagating install state across reinstall"); 11826 } 11827 for (int i = 0; i < allUserHandles.length; i++) { 11828 if (DEBUG_REMOVE) { 11829 Slog.d(TAG, " user " + allUserHandles[i] 11830 + " => " + perUserInstalled[i]); 11831 } 11832 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11833 } 11834 // Regardless of writeSettings we need to ensure that this restriction 11835 // state propagation is persisted 11836 mSettings.writeAllUsersPackageRestrictionsLPr(); 11837 } 11838 // can downgrade to reader here 11839 if (writeSettings) { 11840 mSettings.writeLPr(); 11841 } 11842 } 11843 return true; 11844 } 11845 11846 private boolean deleteInstalledPackageLI(PackageSetting ps, 11847 boolean deleteCodeAndResources, int flags, 11848 int[] allUserHandles, boolean[] perUserInstalled, 11849 PackageRemovedInfo outInfo, boolean writeSettings) { 11850 if (outInfo != null) { 11851 outInfo.uid = ps.appId; 11852 } 11853 11854 // Delete package data from internal structures and also remove data if flag is set 11855 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11856 11857 // Delete application code and resources 11858 if (deleteCodeAndResources && (outInfo != null)) { 11859 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11860 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11861 getAppDexInstructionSets(ps)); 11862 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11863 } 11864 return true; 11865 } 11866 11867 @Override 11868 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11869 int userId) { 11870 mContext.enforceCallingOrSelfPermission( 11871 android.Manifest.permission.DELETE_PACKAGES, null); 11872 synchronized (mPackages) { 11873 PackageSetting ps = mSettings.mPackages.get(packageName); 11874 if (ps == null) { 11875 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11876 return false; 11877 } 11878 if (!ps.getInstalled(userId)) { 11879 // Can't block uninstall for an app that is not installed or enabled. 11880 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11881 return false; 11882 } 11883 ps.setBlockUninstall(blockUninstall, userId); 11884 mSettings.writePackageRestrictionsLPr(userId); 11885 } 11886 return true; 11887 } 11888 11889 @Override 11890 public boolean getBlockUninstallForUser(String packageName, int userId) { 11891 synchronized (mPackages) { 11892 PackageSetting ps = mSettings.mPackages.get(packageName); 11893 if (ps == null) { 11894 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11895 return false; 11896 } 11897 return ps.getBlockUninstall(userId); 11898 } 11899 } 11900 11901 /* 11902 * This method handles package deletion in general 11903 */ 11904 private boolean deletePackageLI(String packageName, UserHandle user, 11905 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11906 int flags, PackageRemovedInfo outInfo, 11907 boolean writeSettings) { 11908 if (packageName == null) { 11909 Slog.w(TAG, "Attempt to delete null packageName."); 11910 return false; 11911 } 11912 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11913 PackageSetting ps; 11914 boolean dataOnly = false; 11915 int removeUser = -1; 11916 int appId = -1; 11917 synchronized (mPackages) { 11918 ps = mSettings.mPackages.get(packageName); 11919 if (ps == null) { 11920 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11921 return false; 11922 } 11923 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11924 && user.getIdentifier() != UserHandle.USER_ALL) { 11925 // The caller is asking that the package only be deleted for a single 11926 // user. To do this, we just mark its uninstalled state and delete 11927 // its data. If this is a system app, we only allow this to happen if 11928 // they have set the special DELETE_SYSTEM_APP which requests different 11929 // semantics than normal for uninstalling system apps. 11930 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11931 ps.setUserState(user.getIdentifier(), 11932 COMPONENT_ENABLED_STATE_DEFAULT, 11933 false, //installed 11934 true, //stopped 11935 true, //notLaunched 11936 false, //hidden 11937 null, null, null, 11938 false, // blockUninstall 11939 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11940 if (!isSystemApp(ps)) { 11941 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11942 // Other user still have this package installed, so all 11943 // we need to do is clear this user's data and save that 11944 // it is uninstalled. 11945 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11946 removeUser = user.getIdentifier(); 11947 appId = ps.appId; 11948 scheduleWritePackageRestrictionsLocked(removeUser); 11949 } else { 11950 // We need to set it back to 'installed' so the uninstall 11951 // broadcasts will be sent correctly. 11952 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11953 ps.setInstalled(true, user.getIdentifier()); 11954 } 11955 } else { 11956 // This is a system app, so we assume that the 11957 // other users still have this package installed, so all 11958 // we need to do is clear this user's data and save that 11959 // it is uninstalled. 11960 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11961 removeUser = user.getIdentifier(); 11962 appId = ps.appId; 11963 scheduleWritePackageRestrictionsLocked(removeUser); 11964 } 11965 } 11966 } 11967 11968 if (removeUser >= 0) { 11969 // From above, we determined that we are deleting this only 11970 // for a single user. Continue the work here. 11971 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11972 if (outInfo != null) { 11973 outInfo.removedPackage = packageName; 11974 outInfo.removedAppId = appId; 11975 outInfo.removedUsers = new int[] {removeUser}; 11976 } 11977 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 11978 removeKeystoreDataIfNeeded(removeUser, appId); 11979 schedulePackageCleaning(packageName, removeUser, false); 11980 synchronized (mPackages) { 11981 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 11982 scheduleWritePackageRestrictionsLocked(removeUser); 11983 } 11984 } 11985 return true; 11986 } 11987 11988 if (dataOnly) { 11989 // Delete application data first 11990 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11991 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11992 return true; 11993 } 11994 11995 boolean ret = false; 11996 if (isSystemApp(ps)) { 11997 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11998 // When an updated system application is deleted we delete the existing resources as well and 11999 // fall back to existing code in system partition 12000 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12001 flags, outInfo, writeSettings); 12002 } else { 12003 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12004 // Kill application pre-emptively especially for apps on sd. 12005 killApplication(packageName, ps.appId, "uninstall pkg"); 12006 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12007 allUserHandles, perUserInstalled, 12008 outInfo, writeSettings); 12009 } 12010 12011 return ret; 12012 } 12013 12014 private final class ClearStorageConnection implements ServiceConnection { 12015 IMediaContainerService mContainerService; 12016 12017 @Override 12018 public void onServiceConnected(ComponentName name, IBinder service) { 12019 synchronized (this) { 12020 mContainerService = IMediaContainerService.Stub.asInterface(service); 12021 notifyAll(); 12022 } 12023 } 12024 12025 @Override 12026 public void onServiceDisconnected(ComponentName name) { 12027 } 12028 } 12029 12030 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12031 final boolean mounted; 12032 if (Environment.isExternalStorageEmulated()) { 12033 mounted = true; 12034 } else { 12035 final String status = Environment.getExternalStorageState(); 12036 12037 mounted = status.equals(Environment.MEDIA_MOUNTED) 12038 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12039 } 12040 12041 if (!mounted) { 12042 return; 12043 } 12044 12045 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12046 int[] users; 12047 if (userId == UserHandle.USER_ALL) { 12048 users = sUserManager.getUserIds(); 12049 } else { 12050 users = new int[] { userId }; 12051 } 12052 final ClearStorageConnection conn = new ClearStorageConnection(); 12053 if (mContext.bindServiceAsUser( 12054 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12055 try { 12056 for (int curUser : users) { 12057 long timeout = SystemClock.uptimeMillis() + 5000; 12058 synchronized (conn) { 12059 long now = SystemClock.uptimeMillis(); 12060 while (conn.mContainerService == null && now < timeout) { 12061 try { 12062 conn.wait(timeout - now); 12063 } catch (InterruptedException e) { 12064 } 12065 } 12066 } 12067 if (conn.mContainerService == null) { 12068 return; 12069 } 12070 12071 final UserEnvironment userEnv = new UserEnvironment(curUser); 12072 clearDirectory(conn.mContainerService, 12073 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12074 if (allData) { 12075 clearDirectory(conn.mContainerService, 12076 userEnv.buildExternalStorageAppDataDirs(packageName)); 12077 clearDirectory(conn.mContainerService, 12078 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12079 } 12080 } 12081 } finally { 12082 mContext.unbindService(conn); 12083 } 12084 } 12085 } 12086 12087 @Override 12088 public void clearApplicationUserData(final String packageName, 12089 final IPackageDataObserver observer, final int userId) { 12090 mContext.enforceCallingOrSelfPermission( 12091 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12092 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12093 // Queue up an async operation since the package deletion may take a little while. 12094 mHandler.post(new Runnable() { 12095 public void run() { 12096 mHandler.removeCallbacks(this); 12097 final boolean succeeded; 12098 synchronized (mInstallLock) { 12099 succeeded = clearApplicationUserDataLI(packageName, userId); 12100 } 12101 clearExternalStorageDataSync(packageName, userId, true); 12102 if (succeeded) { 12103 // invoke DeviceStorageMonitor's update method to clear any notifications 12104 DeviceStorageMonitorInternal 12105 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12106 if (dsm != null) { 12107 dsm.checkMemory(); 12108 } 12109 } 12110 if(observer != null) { 12111 try { 12112 observer.onRemoveCompleted(packageName, succeeded); 12113 } catch (RemoteException e) { 12114 Log.i(TAG, "Observer no longer exists."); 12115 } 12116 } //end if observer 12117 } //end run 12118 }); 12119 } 12120 12121 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12122 if (packageName == null) { 12123 Slog.w(TAG, "Attempt to delete null packageName."); 12124 return false; 12125 } 12126 12127 // Try finding details about the requested package 12128 PackageParser.Package pkg; 12129 synchronized (mPackages) { 12130 pkg = mPackages.get(packageName); 12131 if (pkg == null) { 12132 final PackageSetting ps = mSettings.mPackages.get(packageName); 12133 if (ps != null) { 12134 pkg = ps.pkg; 12135 } 12136 } 12137 } 12138 12139 if (pkg == null) { 12140 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12141 } 12142 12143 // Always delete data directories for package, even if we found no other 12144 // record of app. This helps users recover from UID mismatches without 12145 // resorting to a full data wipe. 12146 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12147 if (retCode < 0) { 12148 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12149 return false; 12150 } 12151 12152 if (pkg == null) { 12153 return false; 12154 } 12155 12156 if (pkg != null && pkg.applicationInfo != null) { 12157 final int appId = pkg.applicationInfo.uid; 12158 removeKeystoreDataIfNeeded(userId, appId); 12159 } 12160 12161 // Create a native library symlink only if we have native libraries 12162 // and if the native libraries are 32 bit libraries. We do not provide 12163 // this symlink for 64 bit libraries. 12164 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12165 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12166 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12167 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12168 nativeLibPath, userId) < 0) { 12169 Slog.w(TAG, "Failed linking native library dir"); 12170 return false; 12171 } 12172 } 12173 12174 return true; 12175 } 12176 12177 /** 12178 * Remove entries from the keystore daemon. Will only remove it if the 12179 * {@code appId} is valid. 12180 */ 12181 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12182 if (appId < 0) { 12183 return; 12184 } 12185 12186 final KeyStore keyStore = KeyStore.getInstance(); 12187 if (keyStore != null) { 12188 if (userId == UserHandle.USER_ALL) { 12189 for (final int individual : sUserManager.getUserIds()) { 12190 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12191 } 12192 } else { 12193 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12194 } 12195 } else { 12196 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12197 } 12198 } 12199 12200 @Override 12201 public void deleteApplicationCacheFiles(final String packageName, 12202 final IPackageDataObserver observer) { 12203 mContext.enforceCallingOrSelfPermission( 12204 android.Manifest.permission.DELETE_CACHE_FILES, null); 12205 // Queue up an async operation since the package deletion may take a little while. 12206 final int userId = UserHandle.getCallingUserId(); 12207 mHandler.post(new Runnable() { 12208 public void run() { 12209 mHandler.removeCallbacks(this); 12210 final boolean succeded; 12211 synchronized (mInstallLock) { 12212 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12213 } 12214 clearExternalStorageDataSync(packageName, userId, false); 12215 if(observer != null) { 12216 try { 12217 observer.onRemoveCompleted(packageName, succeded); 12218 } catch (RemoteException e) { 12219 Log.i(TAG, "Observer no longer exists."); 12220 } 12221 } //end if observer 12222 } //end run 12223 }); 12224 } 12225 12226 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12227 if (packageName == null) { 12228 Slog.w(TAG, "Attempt to delete null packageName."); 12229 return false; 12230 } 12231 PackageParser.Package p; 12232 synchronized (mPackages) { 12233 p = mPackages.get(packageName); 12234 } 12235 if (p == null) { 12236 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12237 return false; 12238 } 12239 final ApplicationInfo applicationInfo = p.applicationInfo; 12240 if (applicationInfo == null) { 12241 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12242 return false; 12243 } 12244 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12245 if (retCode < 0) { 12246 Slog.w(TAG, "Couldn't remove cache files for package: " 12247 + packageName + " u" + userId); 12248 return false; 12249 } 12250 return true; 12251 } 12252 12253 @Override 12254 public void getPackageSizeInfo(final String packageName, int userHandle, 12255 final IPackageStatsObserver observer) { 12256 mContext.enforceCallingOrSelfPermission( 12257 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12258 if (packageName == null) { 12259 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12260 } 12261 12262 PackageStats stats = new PackageStats(packageName, userHandle); 12263 12264 /* 12265 * Queue up an async operation since the package measurement may take a 12266 * little while. 12267 */ 12268 Message msg = mHandler.obtainMessage(INIT_COPY); 12269 msg.obj = new MeasureParams(stats, observer); 12270 mHandler.sendMessage(msg); 12271 } 12272 12273 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12274 PackageStats pStats) { 12275 if (packageName == null) { 12276 Slog.w(TAG, "Attempt to get size of null packageName."); 12277 return false; 12278 } 12279 PackageParser.Package p; 12280 boolean dataOnly = false; 12281 String libDirRoot = null; 12282 String asecPath = null; 12283 PackageSetting ps = null; 12284 synchronized (mPackages) { 12285 p = mPackages.get(packageName); 12286 ps = mSettings.mPackages.get(packageName); 12287 if(p == null) { 12288 dataOnly = true; 12289 if((ps == null) || (ps.pkg == null)) { 12290 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12291 return false; 12292 } 12293 p = ps.pkg; 12294 } 12295 if (ps != null) { 12296 libDirRoot = ps.legacyNativeLibraryPathString; 12297 } 12298 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12299 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12300 if (secureContainerId != null) { 12301 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12302 } 12303 } 12304 } 12305 String publicSrcDir = null; 12306 if(!dataOnly) { 12307 final ApplicationInfo applicationInfo = p.applicationInfo; 12308 if (applicationInfo == null) { 12309 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12310 return false; 12311 } 12312 if (p.isForwardLocked()) { 12313 publicSrcDir = applicationInfo.getBaseResourcePath(); 12314 } 12315 } 12316 // TODO: extend to measure size of split APKs 12317 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12318 // not just the first level. 12319 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12320 // just the primary. 12321 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12322 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12323 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12324 if (res < 0) { 12325 return false; 12326 } 12327 12328 // Fix-up for forward-locked applications in ASEC containers. 12329 if (!isExternal(p)) { 12330 pStats.codeSize += pStats.externalCodeSize; 12331 pStats.externalCodeSize = 0L; 12332 } 12333 12334 return true; 12335 } 12336 12337 12338 @Override 12339 public void addPackageToPreferred(String packageName) { 12340 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12341 } 12342 12343 @Override 12344 public void removePackageFromPreferred(String packageName) { 12345 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12346 } 12347 12348 @Override 12349 public List<PackageInfo> getPreferredPackages(int flags) { 12350 return new ArrayList<PackageInfo>(); 12351 } 12352 12353 private int getUidTargetSdkVersionLockedLPr(int uid) { 12354 Object obj = mSettings.getUserIdLPr(uid); 12355 if (obj instanceof SharedUserSetting) { 12356 final SharedUserSetting sus = (SharedUserSetting) obj; 12357 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12358 final Iterator<PackageSetting> it = sus.packages.iterator(); 12359 while (it.hasNext()) { 12360 final PackageSetting ps = it.next(); 12361 if (ps.pkg != null) { 12362 int v = ps.pkg.applicationInfo.targetSdkVersion; 12363 if (v < vers) vers = v; 12364 } 12365 } 12366 return vers; 12367 } else if (obj instanceof PackageSetting) { 12368 final PackageSetting ps = (PackageSetting) obj; 12369 if (ps.pkg != null) { 12370 return ps.pkg.applicationInfo.targetSdkVersion; 12371 } 12372 } 12373 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12374 } 12375 12376 @Override 12377 public void addPreferredActivity(IntentFilter filter, int match, 12378 ComponentName[] set, ComponentName activity, int userId) { 12379 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12380 "Adding preferred"); 12381 } 12382 12383 private void addPreferredActivityInternal(IntentFilter filter, int match, 12384 ComponentName[] set, ComponentName activity, boolean always, int userId, 12385 String opname) { 12386 // writer 12387 int callingUid = Binder.getCallingUid(); 12388 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12389 if (filter.countActions() == 0) { 12390 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12391 return; 12392 } 12393 synchronized (mPackages) { 12394 if (mContext.checkCallingOrSelfPermission( 12395 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12396 != PackageManager.PERMISSION_GRANTED) { 12397 if (getUidTargetSdkVersionLockedLPr(callingUid) 12398 < Build.VERSION_CODES.FROYO) { 12399 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12400 + callingUid); 12401 return; 12402 } 12403 mContext.enforceCallingOrSelfPermission( 12404 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12405 } 12406 12407 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12408 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12409 + userId + ":"); 12410 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12411 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12412 scheduleWritePackageRestrictionsLocked(userId); 12413 } 12414 } 12415 12416 @Override 12417 public void replacePreferredActivity(IntentFilter filter, int match, 12418 ComponentName[] set, ComponentName activity, int userId) { 12419 if (filter.countActions() != 1) { 12420 throw new IllegalArgumentException( 12421 "replacePreferredActivity expects filter to have only 1 action."); 12422 } 12423 if (filter.countDataAuthorities() != 0 12424 || filter.countDataPaths() != 0 12425 || filter.countDataSchemes() > 1 12426 || filter.countDataTypes() != 0) { 12427 throw new IllegalArgumentException( 12428 "replacePreferredActivity expects filter to have no data authorities, " + 12429 "paths, or types; and at most one scheme."); 12430 } 12431 12432 final int callingUid = Binder.getCallingUid(); 12433 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12434 synchronized (mPackages) { 12435 if (mContext.checkCallingOrSelfPermission( 12436 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12437 != PackageManager.PERMISSION_GRANTED) { 12438 if (getUidTargetSdkVersionLockedLPr(callingUid) 12439 < Build.VERSION_CODES.FROYO) { 12440 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12441 + Binder.getCallingUid()); 12442 return; 12443 } 12444 mContext.enforceCallingOrSelfPermission( 12445 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12446 } 12447 12448 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12449 if (pir != null) { 12450 // Get all of the existing entries that exactly match this filter. 12451 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12452 if (existing != null && existing.size() == 1) { 12453 PreferredActivity cur = existing.get(0); 12454 if (DEBUG_PREFERRED) { 12455 Slog.i(TAG, "Checking replace of preferred:"); 12456 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12457 if (!cur.mPref.mAlways) { 12458 Slog.i(TAG, " -- CUR; not mAlways!"); 12459 } else { 12460 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12461 Slog.i(TAG, " -- CUR: mSet=" 12462 + Arrays.toString(cur.mPref.mSetComponents)); 12463 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12464 Slog.i(TAG, " -- NEW: mMatch=" 12465 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12466 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12467 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12468 } 12469 } 12470 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12471 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12472 && cur.mPref.sameSet(set)) { 12473 // Setting the preferred activity to what it happens to be already 12474 if (DEBUG_PREFERRED) { 12475 Slog.i(TAG, "Replacing with same preferred activity " 12476 + cur.mPref.mShortComponent + " for user " 12477 + userId + ":"); 12478 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12479 } 12480 return; 12481 } 12482 } 12483 12484 if (existing != null) { 12485 if (DEBUG_PREFERRED) { 12486 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12487 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12488 } 12489 for (int i = 0; i < existing.size(); i++) { 12490 PreferredActivity pa = existing.get(i); 12491 if (DEBUG_PREFERRED) { 12492 Slog.i(TAG, "Removing existing preferred activity " 12493 + pa.mPref.mComponent + ":"); 12494 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12495 } 12496 pir.removeFilter(pa); 12497 } 12498 } 12499 } 12500 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12501 "Replacing preferred"); 12502 } 12503 } 12504 12505 @Override 12506 public void clearPackagePreferredActivities(String packageName) { 12507 final int uid = Binder.getCallingUid(); 12508 // writer 12509 synchronized (mPackages) { 12510 PackageParser.Package pkg = mPackages.get(packageName); 12511 if (pkg == null || pkg.applicationInfo.uid != uid) { 12512 if (mContext.checkCallingOrSelfPermission( 12513 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12514 != PackageManager.PERMISSION_GRANTED) { 12515 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12516 < Build.VERSION_CODES.FROYO) { 12517 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12518 + Binder.getCallingUid()); 12519 return; 12520 } 12521 mContext.enforceCallingOrSelfPermission( 12522 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12523 } 12524 } 12525 12526 int user = UserHandle.getCallingUserId(); 12527 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12528 scheduleWritePackageRestrictionsLocked(user); 12529 } 12530 } 12531 } 12532 12533 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12534 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12535 ArrayList<PreferredActivity> removed = null; 12536 boolean changed = false; 12537 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12538 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12539 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12540 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12541 continue; 12542 } 12543 Iterator<PreferredActivity> it = pir.filterIterator(); 12544 while (it.hasNext()) { 12545 PreferredActivity pa = it.next(); 12546 // Mark entry for removal only if it matches the package name 12547 // and the entry is of type "always". 12548 if (packageName == null || 12549 (pa.mPref.mComponent.getPackageName().equals(packageName) 12550 && pa.mPref.mAlways)) { 12551 if (removed == null) { 12552 removed = new ArrayList<PreferredActivity>(); 12553 } 12554 removed.add(pa); 12555 } 12556 } 12557 if (removed != null) { 12558 for (int j=0; j<removed.size(); j++) { 12559 PreferredActivity pa = removed.get(j); 12560 pir.removeFilter(pa); 12561 } 12562 changed = true; 12563 } 12564 } 12565 return changed; 12566 } 12567 12568 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12569 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12570 if (userId == UserHandle.USER_ALL) { 12571 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12572 for (int oneUserId : sUserManager.getUserIds()) { 12573 scheduleWritePackageRestrictionsLocked(oneUserId); 12574 } 12575 } else { 12576 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12577 scheduleWritePackageRestrictionsLocked(userId); 12578 } 12579 } 12580 12581 @Override 12582 public void resetPreferredActivities(int userId) { 12583 /* TODO: Actually use userId. Why is it being passed in? */ 12584 mContext.enforceCallingOrSelfPermission( 12585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12586 // writer 12587 synchronized (mPackages) { 12588 int user = UserHandle.getCallingUserId(); 12589 clearPackagePreferredActivitiesLPw(null, user); 12590 mSettings.readDefaultPreferredAppsLPw(this, user); 12591 scheduleWritePackageRestrictionsLocked(user); 12592 } 12593 } 12594 12595 @Override 12596 public int getPreferredActivities(List<IntentFilter> outFilters, 12597 List<ComponentName> outActivities, String packageName) { 12598 12599 int num = 0; 12600 final int userId = UserHandle.getCallingUserId(); 12601 // reader 12602 synchronized (mPackages) { 12603 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12604 if (pir != null) { 12605 final Iterator<PreferredActivity> it = pir.filterIterator(); 12606 while (it.hasNext()) { 12607 final PreferredActivity pa = it.next(); 12608 if (packageName == null 12609 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12610 && pa.mPref.mAlways)) { 12611 if (outFilters != null) { 12612 outFilters.add(new IntentFilter(pa)); 12613 } 12614 if (outActivities != null) { 12615 outActivities.add(pa.mPref.mComponent); 12616 } 12617 } 12618 } 12619 } 12620 } 12621 12622 return num; 12623 } 12624 12625 @Override 12626 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12627 int userId) { 12628 int callingUid = Binder.getCallingUid(); 12629 if (callingUid != Process.SYSTEM_UID) { 12630 throw new SecurityException( 12631 "addPersistentPreferredActivity can only be run by the system"); 12632 } 12633 if (filter.countActions() == 0) { 12634 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12635 return; 12636 } 12637 synchronized (mPackages) { 12638 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12639 " :"); 12640 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12641 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12642 new PersistentPreferredActivity(filter, activity)); 12643 scheduleWritePackageRestrictionsLocked(userId); 12644 } 12645 } 12646 12647 @Override 12648 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12649 int callingUid = Binder.getCallingUid(); 12650 if (callingUid != Process.SYSTEM_UID) { 12651 throw new SecurityException( 12652 "clearPackagePersistentPreferredActivities can only be run by the system"); 12653 } 12654 ArrayList<PersistentPreferredActivity> removed = null; 12655 boolean changed = false; 12656 synchronized (mPackages) { 12657 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12658 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12659 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12660 .valueAt(i); 12661 if (userId != thisUserId) { 12662 continue; 12663 } 12664 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12665 while (it.hasNext()) { 12666 PersistentPreferredActivity ppa = it.next(); 12667 // Mark entry for removal only if it matches the package name. 12668 if (ppa.mComponent.getPackageName().equals(packageName)) { 12669 if (removed == null) { 12670 removed = new ArrayList<PersistentPreferredActivity>(); 12671 } 12672 removed.add(ppa); 12673 } 12674 } 12675 if (removed != null) { 12676 for (int j=0; j<removed.size(); j++) { 12677 PersistentPreferredActivity ppa = removed.get(j); 12678 ppir.removeFilter(ppa); 12679 } 12680 changed = true; 12681 } 12682 } 12683 12684 if (changed) { 12685 scheduleWritePackageRestrictionsLocked(userId); 12686 } 12687 } 12688 } 12689 12690 /** 12691 * Non-Binder method, support for the backup/restore mechanism: write the 12692 * full set of preferred activities in its canonical XML format. Returns true 12693 * on success; false otherwise. 12694 */ 12695 @Override 12696 public byte[] getPreferredActivityBackup(int userId) { 12697 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12698 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12699 } 12700 12701 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12702 try { 12703 final XmlSerializer serializer = new FastXmlSerializer(); 12704 serializer.setOutput(dataStream, "utf-8"); 12705 serializer.startDocument(null, true); 12706 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12707 12708 synchronized (mPackages) { 12709 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12710 } 12711 12712 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12713 serializer.endDocument(); 12714 serializer.flush(); 12715 } catch (Exception e) { 12716 if (DEBUG_BACKUP) { 12717 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12718 } 12719 return null; 12720 } 12721 12722 return dataStream.toByteArray(); 12723 } 12724 12725 @Override 12726 public void restorePreferredActivities(byte[] backup, int userId) { 12727 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12728 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12729 } 12730 12731 try { 12732 final XmlPullParser parser = Xml.newPullParser(); 12733 parser.setInput(new ByteArrayInputStream(backup), null); 12734 12735 int type; 12736 while ((type = parser.next()) != XmlPullParser.START_TAG 12737 && type != XmlPullParser.END_DOCUMENT) { 12738 } 12739 if (type != XmlPullParser.START_TAG) { 12740 // oops didn't find a start tag?! 12741 if (DEBUG_BACKUP) { 12742 Slog.e(TAG, "Didn't find start tag during restore"); 12743 } 12744 return; 12745 } 12746 12747 // this is supposed to be TAG_PREFERRED_BACKUP 12748 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12749 if (DEBUG_BACKUP) { 12750 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12751 } 12752 return; 12753 } 12754 12755 // skip interfering stuff, then we're aligned with the backing implementation 12756 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12757 synchronized (mPackages) { 12758 mSettings.readPreferredActivitiesLPw(parser, userId); 12759 } 12760 } catch (Exception e) { 12761 if (DEBUG_BACKUP) { 12762 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12763 } 12764 } 12765 } 12766 12767 @Override 12768 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12769 int sourceUserId, int targetUserId, int flags) { 12770 mContext.enforceCallingOrSelfPermission( 12771 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12772 int callingUid = Binder.getCallingUid(); 12773 enforceOwnerRights(ownerPackage, callingUid); 12774 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12775 if (intentFilter.countActions() == 0) { 12776 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12777 return; 12778 } 12779 synchronized (mPackages) { 12780 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12781 ownerPackage, targetUserId, flags); 12782 CrossProfileIntentResolver resolver = 12783 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12784 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12785 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12786 if (existing != null) { 12787 int size = existing.size(); 12788 for (int i = 0; i < size; i++) { 12789 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12790 return; 12791 } 12792 } 12793 } 12794 resolver.addFilter(newFilter); 12795 scheduleWritePackageRestrictionsLocked(sourceUserId); 12796 } 12797 } 12798 12799 @Override 12800 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12801 mContext.enforceCallingOrSelfPermission( 12802 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12803 int callingUid = Binder.getCallingUid(); 12804 enforceOwnerRights(ownerPackage, callingUid); 12805 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12806 synchronized (mPackages) { 12807 CrossProfileIntentResolver resolver = 12808 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12809 ArraySet<CrossProfileIntentFilter> set = 12810 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12811 for (CrossProfileIntentFilter filter : set) { 12812 if (filter.getOwnerPackage().equals(ownerPackage)) { 12813 resolver.removeFilter(filter); 12814 } 12815 } 12816 scheduleWritePackageRestrictionsLocked(sourceUserId); 12817 } 12818 } 12819 12820 // Enforcing that callingUid is owning pkg on userId 12821 private void enforceOwnerRights(String pkg, int callingUid) { 12822 // The system owns everything. 12823 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12824 return; 12825 } 12826 int callingUserId = UserHandle.getUserId(callingUid); 12827 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12828 if (pi == null) { 12829 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12830 + callingUserId); 12831 } 12832 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12833 throw new SecurityException("Calling uid " + callingUid 12834 + " does not own package " + pkg); 12835 } 12836 } 12837 12838 @Override 12839 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12840 Intent intent = new Intent(Intent.ACTION_MAIN); 12841 intent.addCategory(Intent.CATEGORY_HOME); 12842 12843 final int callingUserId = UserHandle.getCallingUserId(); 12844 List<ResolveInfo> list = queryIntentActivities(intent, null, 12845 PackageManager.GET_META_DATA, callingUserId); 12846 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12847 true, false, false, callingUserId); 12848 12849 allHomeCandidates.clear(); 12850 if (list != null) { 12851 for (ResolveInfo ri : list) { 12852 allHomeCandidates.add(ri); 12853 } 12854 } 12855 return (preferred == null || preferred.activityInfo == null) 12856 ? null 12857 : new ComponentName(preferred.activityInfo.packageName, 12858 preferred.activityInfo.name); 12859 } 12860 12861 @Override 12862 public void setApplicationEnabledSetting(String appPackageName, 12863 int newState, int flags, int userId, String callingPackage) { 12864 if (!sUserManager.exists(userId)) return; 12865 if (callingPackage == null) { 12866 callingPackage = Integer.toString(Binder.getCallingUid()); 12867 } 12868 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12869 } 12870 12871 @Override 12872 public void setComponentEnabledSetting(ComponentName componentName, 12873 int newState, int flags, int userId) { 12874 if (!sUserManager.exists(userId)) return; 12875 setEnabledSetting(componentName.getPackageName(), 12876 componentName.getClassName(), newState, flags, userId, null); 12877 } 12878 12879 private void setEnabledSetting(final String packageName, String className, int newState, 12880 final int flags, int userId, String callingPackage) { 12881 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12882 || newState == COMPONENT_ENABLED_STATE_ENABLED 12883 || newState == COMPONENT_ENABLED_STATE_DISABLED 12884 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12885 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12886 throw new IllegalArgumentException("Invalid new component state: " 12887 + newState); 12888 } 12889 PackageSetting pkgSetting; 12890 final int uid = Binder.getCallingUid(); 12891 final int permission = mContext.checkCallingOrSelfPermission( 12892 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12893 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12894 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12895 boolean sendNow = false; 12896 boolean isApp = (className == null); 12897 String componentName = isApp ? packageName : className; 12898 int packageUid = -1; 12899 ArrayList<String> components; 12900 12901 // writer 12902 synchronized (mPackages) { 12903 pkgSetting = mSettings.mPackages.get(packageName); 12904 if (pkgSetting == null) { 12905 if (className == null) { 12906 throw new IllegalArgumentException( 12907 "Unknown package: " + packageName); 12908 } 12909 throw new IllegalArgumentException( 12910 "Unknown component: " + packageName 12911 + "/" + className); 12912 } 12913 // Allow root and verify that userId is not being specified by a different user 12914 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12915 throw new SecurityException( 12916 "Permission Denial: attempt to change component state from pid=" 12917 + Binder.getCallingPid() 12918 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12919 } 12920 if (className == null) { 12921 // We're dealing with an application/package level state change 12922 if (pkgSetting.getEnabled(userId) == newState) { 12923 // Nothing to do 12924 return; 12925 } 12926 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12927 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12928 // Don't care about who enables an app. 12929 callingPackage = null; 12930 } 12931 pkgSetting.setEnabled(newState, userId, callingPackage); 12932 // pkgSetting.pkg.mSetEnabled = newState; 12933 } else { 12934 // We're dealing with a component level state change 12935 // First, verify that this is a valid class name. 12936 PackageParser.Package pkg = pkgSetting.pkg; 12937 if (pkg == null || !pkg.hasComponentClassName(className)) { 12938 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12939 throw new IllegalArgumentException("Component class " + className 12940 + " does not exist in " + packageName); 12941 } else { 12942 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12943 + className + " does not exist in " + packageName); 12944 } 12945 } 12946 switch (newState) { 12947 case COMPONENT_ENABLED_STATE_ENABLED: 12948 if (!pkgSetting.enableComponentLPw(className, userId)) { 12949 return; 12950 } 12951 break; 12952 case COMPONENT_ENABLED_STATE_DISABLED: 12953 if (!pkgSetting.disableComponentLPw(className, userId)) { 12954 return; 12955 } 12956 break; 12957 case COMPONENT_ENABLED_STATE_DEFAULT: 12958 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12959 return; 12960 } 12961 break; 12962 default: 12963 Slog.e(TAG, "Invalid new component state: " + newState); 12964 return; 12965 } 12966 } 12967 scheduleWritePackageRestrictionsLocked(userId); 12968 components = mPendingBroadcasts.get(userId, packageName); 12969 final boolean newPackage = components == null; 12970 if (newPackage) { 12971 components = new ArrayList<String>(); 12972 } 12973 if (!components.contains(componentName)) { 12974 components.add(componentName); 12975 } 12976 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12977 sendNow = true; 12978 // Purge entry from pending broadcast list if another one exists already 12979 // since we are sending one right away. 12980 mPendingBroadcasts.remove(userId, packageName); 12981 } else { 12982 if (newPackage) { 12983 mPendingBroadcasts.put(userId, packageName, components); 12984 } 12985 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12986 // Schedule a message 12987 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12988 } 12989 } 12990 } 12991 12992 long callingId = Binder.clearCallingIdentity(); 12993 try { 12994 if (sendNow) { 12995 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12996 sendPackageChangedBroadcast(packageName, 12997 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12998 } 12999 } finally { 13000 Binder.restoreCallingIdentity(callingId); 13001 } 13002 } 13003 13004 private void sendPackageChangedBroadcast(String packageName, 13005 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13006 if (DEBUG_INSTALL) 13007 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13008 + componentNames); 13009 Bundle extras = new Bundle(4); 13010 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13011 String nameList[] = new String[componentNames.size()]; 13012 componentNames.toArray(nameList); 13013 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13014 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13015 extras.putInt(Intent.EXTRA_UID, packageUid); 13016 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13017 new int[] {UserHandle.getUserId(packageUid)}); 13018 } 13019 13020 @Override 13021 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13022 if (!sUserManager.exists(userId)) return; 13023 final int uid = Binder.getCallingUid(); 13024 final int permission = mContext.checkCallingOrSelfPermission( 13025 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13026 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13027 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13028 // writer 13029 synchronized (mPackages) { 13030 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13031 uid, userId)) { 13032 scheduleWritePackageRestrictionsLocked(userId); 13033 } 13034 } 13035 } 13036 13037 @Override 13038 public String getInstallerPackageName(String packageName) { 13039 // reader 13040 synchronized (mPackages) { 13041 return mSettings.getInstallerPackageNameLPr(packageName); 13042 } 13043 } 13044 13045 @Override 13046 public int getApplicationEnabledSetting(String packageName, int userId) { 13047 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13048 int uid = Binder.getCallingUid(); 13049 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13050 // reader 13051 synchronized (mPackages) { 13052 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13053 } 13054 } 13055 13056 @Override 13057 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13058 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13059 int uid = Binder.getCallingUid(); 13060 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13061 // reader 13062 synchronized (mPackages) { 13063 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13064 } 13065 } 13066 13067 @Override 13068 public void enterSafeMode() { 13069 enforceSystemOrRoot("Only the system can request entering safe mode"); 13070 13071 if (!mSystemReady) { 13072 mSafeMode = true; 13073 } 13074 } 13075 13076 @Override 13077 public void systemReady() { 13078 mSystemReady = true; 13079 13080 // Read the compatibilty setting when the system is ready. 13081 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13082 mContext.getContentResolver(), 13083 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13084 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13085 if (DEBUG_SETTINGS) { 13086 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13087 } 13088 13089 synchronized (mPackages) { 13090 // Verify that all of the preferred activity components actually 13091 // exist. It is possible for applications to be updated and at 13092 // that point remove a previously declared activity component that 13093 // had been set as a preferred activity. We try to clean this up 13094 // the next time we encounter that preferred activity, but it is 13095 // possible for the user flow to never be able to return to that 13096 // situation so here we do a sanity check to make sure we haven't 13097 // left any junk around. 13098 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13099 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13100 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13101 removed.clear(); 13102 for (PreferredActivity pa : pir.filterSet()) { 13103 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13104 removed.add(pa); 13105 } 13106 } 13107 if (removed.size() > 0) { 13108 for (int r=0; r<removed.size(); r++) { 13109 PreferredActivity pa = removed.get(r); 13110 Slog.w(TAG, "Removing dangling preferred activity: " 13111 + pa.mPref.mComponent); 13112 pir.removeFilter(pa); 13113 } 13114 mSettings.writePackageRestrictionsLPr( 13115 mSettings.mPreferredActivities.keyAt(i)); 13116 } 13117 } 13118 } 13119 sUserManager.systemReady(); 13120 13121 // Kick off any messages waiting for system ready 13122 if (mPostSystemReadyMessages != null) { 13123 for (Message msg : mPostSystemReadyMessages) { 13124 msg.sendToTarget(); 13125 } 13126 mPostSystemReadyMessages = null; 13127 } 13128 13129 // Watch for external volumes that come and go over time 13130 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13131 storage.registerListener(mStorageListener); 13132 13133 mInstallerService.systemReady(); 13134 } 13135 13136 @Override 13137 public boolean isSafeMode() { 13138 return mSafeMode; 13139 } 13140 13141 @Override 13142 public boolean hasSystemUidErrors() { 13143 return mHasSystemUidErrors; 13144 } 13145 13146 static String arrayToString(int[] array) { 13147 StringBuffer buf = new StringBuffer(128); 13148 buf.append('['); 13149 if (array != null) { 13150 for (int i=0; i<array.length; i++) { 13151 if (i > 0) buf.append(", "); 13152 buf.append(array[i]); 13153 } 13154 } 13155 buf.append(']'); 13156 return buf.toString(); 13157 } 13158 13159 static class DumpState { 13160 public static final int DUMP_LIBS = 1 << 0; 13161 public static final int DUMP_FEATURES = 1 << 1; 13162 public static final int DUMP_RESOLVERS = 1 << 2; 13163 public static final int DUMP_PERMISSIONS = 1 << 3; 13164 public static final int DUMP_PACKAGES = 1 << 4; 13165 public static final int DUMP_SHARED_USERS = 1 << 5; 13166 public static final int DUMP_MESSAGES = 1 << 6; 13167 public static final int DUMP_PROVIDERS = 1 << 7; 13168 public static final int DUMP_VERIFIERS = 1 << 8; 13169 public static final int DUMP_PREFERRED = 1 << 9; 13170 public static final int DUMP_PREFERRED_XML = 1 << 10; 13171 public static final int DUMP_KEYSETS = 1 << 11; 13172 public static final int DUMP_VERSION = 1 << 12; 13173 public static final int DUMP_INSTALLS = 1 << 13; 13174 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13175 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13176 13177 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13178 13179 private int mTypes; 13180 13181 private int mOptions; 13182 13183 private boolean mTitlePrinted; 13184 13185 private SharedUserSetting mSharedUser; 13186 13187 public boolean isDumping(int type) { 13188 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13189 return true; 13190 } 13191 13192 return (mTypes & type) != 0; 13193 } 13194 13195 public void setDump(int type) { 13196 mTypes |= type; 13197 } 13198 13199 public boolean isOptionEnabled(int option) { 13200 return (mOptions & option) != 0; 13201 } 13202 13203 public void setOptionEnabled(int option) { 13204 mOptions |= option; 13205 } 13206 13207 public boolean onTitlePrinted() { 13208 final boolean printed = mTitlePrinted; 13209 mTitlePrinted = true; 13210 return printed; 13211 } 13212 13213 public boolean getTitlePrinted() { 13214 return mTitlePrinted; 13215 } 13216 13217 public void setTitlePrinted(boolean enabled) { 13218 mTitlePrinted = enabled; 13219 } 13220 13221 public SharedUserSetting getSharedUser() { 13222 return mSharedUser; 13223 } 13224 13225 public void setSharedUser(SharedUserSetting user) { 13226 mSharedUser = user; 13227 } 13228 } 13229 13230 @Override 13231 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13232 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13233 != PackageManager.PERMISSION_GRANTED) { 13234 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13235 + Binder.getCallingPid() 13236 + ", uid=" + Binder.getCallingUid() 13237 + " without permission " 13238 + android.Manifest.permission.DUMP); 13239 return; 13240 } 13241 13242 DumpState dumpState = new DumpState(); 13243 boolean fullPreferred = false; 13244 boolean checkin = false; 13245 13246 String packageName = null; 13247 13248 int opti = 0; 13249 while (opti < args.length) { 13250 String opt = args[opti]; 13251 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13252 break; 13253 } 13254 opti++; 13255 13256 if ("-a".equals(opt)) { 13257 // Right now we only know how to print all. 13258 } else if ("-h".equals(opt)) { 13259 pw.println("Package manager dump options:"); 13260 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13261 pw.println(" --checkin: dump for a checkin"); 13262 pw.println(" -f: print details of intent filters"); 13263 pw.println(" -h: print this help"); 13264 pw.println(" cmd may be one of:"); 13265 pw.println(" l[ibraries]: list known shared libraries"); 13266 pw.println(" f[ibraries]: list device features"); 13267 pw.println(" k[eysets]: print known keysets"); 13268 pw.println(" r[esolvers]: dump intent resolvers"); 13269 pw.println(" perm[issions]: dump permissions"); 13270 pw.println(" pref[erred]: print preferred package settings"); 13271 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13272 pw.println(" prov[iders]: dump content providers"); 13273 pw.println(" p[ackages]: dump installed packages"); 13274 pw.println(" s[hared-users]: dump shared user IDs"); 13275 pw.println(" m[essages]: print collected runtime messages"); 13276 pw.println(" v[erifiers]: print package verifier info"); 13277 pw.println(" version: print database version info"); 13278 pw.println(" write: write current settings now"); 13279 pw.println(" <package.name>: info about given package"); 13280 pw.println(" installs: details about install sessions"); 13281 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13282 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13283 return; 13284 } else if ("--checkin".equals(opt)) { 13285 checkin = true; 13286 } else if ("-f".equals(opt)) { 13287 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13288 } else { 13289 pw.println("Unknown argument: " + opt + "; use -h for help"); 13290 } 13291 } 13292 13293 // Is the caller requesting to dump a particular piece of data? 13294 if (opti < args.length) { 13295 String cmd = args[opti]; 13296 opti++; 13297 // Is this a package name? 13298 if ("android".equals(cmd) || cmd.contains(".")) { 13299 packageName = cmd; 13300 // When dumping a single package, we always dump all of its 13301 // filter information since the amount of data will be reasonable. 13302 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13303 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13304 dumpState.setDump(DumpState.DUMP_LIBS); 13305 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13306 dumpState.setDump(DumpState.DUMP_FEATURES); 13307 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13308 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13309 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13310 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13311 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13312 dumpState.setDump(DumpState.DUMP_PREFERRED); 13313 } else if ("preferred-xml".equals(cmd)) { 13314 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13315 if (opti < args.length && "--full".equals(args[opti])) { 13316 fullPreferred = true; 13317 opti++; 13318 } 13319 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13320 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13321 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13322 dumpState.setDump(DumpState.DUMP_PACKAGES); 13323 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13324 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13325 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13326 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13327 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13328 dumpState.setDump(DumpState.DUMP_MESSAGES); 13329 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13330 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13331 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13332 || "intent-filter-verifiers".equals(cmd)) { 13333 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13334 } else if ("version".equals(cmd)) { 13335 dumpState.setDump(DumpState.DUMP_VERSION); 13336 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13337 dumpState.setDump(DumpState.DUMP_KEYSETS); 13338 } else if ("installs".equals(cmd)) { 13339 dumpState.setDump(DumpState.DUMP_INSTALLS); 13340 } else if ("write".equals(cmd)) { 13341 synchronized (mPackages) { 13342 mSettings.writeLPr(); 13343 pw.println("Settings written."); 13344 return; 13345 } 13346 } 13347 } 13348 13349 if (checkin) { 13350 pw.println("vers,1"); 13351 } 13352 13353 // reader 13354 synchronized (mPackages) { 13355 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13356 if (!checkin) { 13357 if (dumpState.onTitlePrinted()) 13358 pw.println(); 13359 pw.println("Database versions:"); 13360 pw.print(" SDK Version:"); 13361 pw.print(" internal="); 13362 pw.print(mSettings.mInternalSdkPlatform); 13363 pw.print(" external="); 13364 pw.println(mSettings.mExternalSdkPlatform); 13365 pw.print(" DB Version:"); 13366 pw.print(" internal="); 13367 pw.print(mSettings.mInternalDatabaseVersion); 13368 pw.print(" external="); 13369 pw.println(mSettings.mExternalDatabaseVersion); 13370 } 13371 } 13372 13373 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13374 if (!checkin) { 13375 if (dumpState.onTitlePrinted()) 13376 pw.println(); 13377 pw.println("Verifiers:"); 13378 pw.print(" Required: "); 13379 pw.print(mRequiredVerifierPackage); 13380 pw.print(" (uid="); 13381 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13382 pw.println(")"); 13383 } else if (mRequiredVerifierPackage != null) { 13384 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13385 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13386 } 13387 } 13388 13389 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13390 packageName == null) { 13391 if (mIntentFilterVerifierComponent != null) { 13392 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13393 if (!checkin) { 13394 if (dumpState.onTitlePrinted()) 13395 pw.println(); 13396 pw.println("Intent Filter Verifier:"); 13397 pw.print(" Using: "); 13398 pw.print(verifierPackageName); 13399 pw.print(" (uid="); 13400 pw.print(getPackageUid(verifierPackageName, 0)); 13401 pw.println(")"); 13402 } else if (verifierPackageName != null) { 13403 pw.print("ifv,"); pw.print(verifierPackageName); 13404 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13405 } 13406 } else { 13407 pw.println(); 13408 pw.println("No Intent Filter Verifier available!"); 13409 } 13410 } 13411 13412 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13413 boolean printedHeader = false; 13414 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13415 while (it.hasNext()) { 13416 String name = it.next(); 13417 SharedLibraryEntry ent = mSharedLibraries.get(name); 13418 if (!checkin) { 13419 if (!printedHeader) { 13420 if (dumpState.onTitlePrinted()) 13421 pw.println(); 13422 pw.println("Libraries:"); 13423 printedHeader = true; 13424 } 13425 pw.print(" "); 13426 } else { 13427 pw.print("lib,"); 13428 } 13429 pw.print(name); 13430 if (!checkin) { 13431 pw.print(" -> "); 13432 } 13433 if (ent.path != null) { 13434 if (!checkin) { 13435 pw.print("(jar) "); 13436 pw.print(ent.path); 13437 } else { 13438 pw.print(",jar,"); 13439 pw.print(ent.path); 13440 } 13441 } else { 13442 if (!checkin) { 13443 pw.print("(apk) "); 13444 pw.print(ent.apk); 13445 } else { 13446 pw.print(",apk,"); 13447 pw.print(ent.apk); 13448 } 13449 } 13450 pw.println(); 13451 } 13452 } 13453 13454 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13455 if (dumpState.onTitlePrinted()) 13456 pw.println(); 13457 if (!checkin) { 13458 pw.println("Features:"); 13459 } 13460 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13461 while (it.hasNext()) { 13462 String name = it.next(); 13463 if (!checkin) { 13464 pw.print(" "); 13465 } else { 13466 pw.print("feat,"); 13467 } 13468 pw.println(name); 13469 } 13470 } 13471 13472 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13473 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13474 : "Activity Resolver Table:", " ", packageName, 13475 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13476 dumpState.setTitlePrinted(true); 13477 } 13478 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13479 : "Receiver Resolver Table:", " ", packageName, 13480 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13481 dumpState.setTitlePrinted(true); 13482 } 13483 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13484 : "Service Resolver Table:", " ", packageName, 13485 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13486 dumpState.setTitlePrinted(true); 13487 } 13488 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13489 : "Provider Resolver Table:", " ", packageName, 13490 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13491 dumpState.setTitlePrinted(true); 13492 } 13493 } 13494 13495 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13496 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13497 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13498 int user = mSettings.mPreferredActivities.keyAt(i); 13499 if (pir.dump(pw, 13500 dumpState.getTitlePrinted() 13501 ? "\nPreferred Activities User " + user + ":" 13502 : "Preferred Activities User " + user + ":", " ", 13503 packageName, true, false)) { 13504 dumpState.setTitlePrinted(true); 13505 } 13506 } 13507 } 13508 13509 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13510 pw.flush(); 13511 FileOutputStream fout = new FileOutputStream(fd); 13512 BufferedOutputStream str = new BufferedOutputStream(fout); 13513 XmlSerializer serializer = new FastXmlSerializer(); 13514 try { 13515 serializer.setOutput(str, "utf-8"); 13516 serializer.startDocument(null, true); 13517 serializer.setFeature( 13518 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13519 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13520 serializer.endDocument(); 13521 serializer.flush(); 13522 } catch (IllegalArgumentException e) { 13523 pw.println("Failed writing: " + e); 13524 } catch (IllegalStateException e) { 13525 pw.println("Failed writing: " + e); 13526 } catch (IOException e) { 13527 pw.println("Failed writing: " + e); 13528 } 13529 } 13530 13531 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13532 pw.println(); 13533 int count = mSettings.mPackages.size(); 13534 if (count == 0) { 13535 pw.println("No domain preferred apps!"); 13536 pw.println(); 13537 } else { 13538 final String prefix = " "; 13539 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13540 if (allPackageSettings.size() == 0) { 13541 pw.println("No domain preferred apps!"); 13542 pw.println(); 13543 } else { 13544 pw.println("Domain preferred apps status:"); 13545 pw.println(); 13546 count = 0; 13547 for (PackageSetting ps : allPackageSettings) { 13548 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13549 if (ivi == null || ivi.getPackageName() == null) continue; 13550 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13551 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13552 pw.println(prefix + "Status: " + ivi.getStatusString()); 13553 pw.println(); 13554 count++; 13555 } 13556 if (count == 0) { 13557 pw.println(prefix + "No domain preferred app status!"); 13558 pw.println(); 13559 } 13560 for (int userId : sUserManager.getUserIds()) { 13561 pw.println("Domain preferred apps for User " + userId + ":"); 13562 pw.println(); 13563 count = 0; 13564 for (PackageSetting ps : allPackageSettings) { 13565 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13566 if (ivi == null || ivi.getPackageName() == null) { 13567 continue; 13568 } 13569 final int status = ps.getDomainVerificationStatusForUser(userId); 13570 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13571 continue; 13572 } 13573 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13574 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13575 String statusStr = IntentFilterVerificationInfo. 13576 getStatusStringFromValue(status); 13577 pw.println(prefix + "Status: " + statusStr); 13578 pw.println(); 13579 count++; 13580 } 13581 if (count == 0) { 13582 pw.println(prefix + "No domain preferred apps!"); 13583 pw.println(); 13584 } 13585 } 13586 } 13587 } 13588 } 13589 13590 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13591 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13592 if (packageName == null) { 13593 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13594 if (iperm == 0) { 13595 if (dumpState.onTitlePrinted()) 13596 pw.println(); 13597 pw.println("AppOp Permissions:"); 13598 } 13599 pw.print(" AppOp Permission "); 13600 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13601 pw.println(":"); 13602 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13603 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13604 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13605 } 13606 } 13607 } 13608 } 13609 13610 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13611 boolean printedSomething = false; 13612 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13613 if (packageName != null && !packageName.equals(p.info.packageName)) { 13614 continue; 13615 } 13616 if (!printedSomething) { 13617 if (dumpState.onTitlePrinted()) 13618 pw.println(); 13619 pw.println("Registered ContentProviders:"); 13620 printedSomething = true; 13621 } 13622 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13623 pw.print(" "); pw.println(p.toString()); 13624 } 13625 printedSomething = false; 13626 for (Map.Entry<String, PackageParser.Provider> entry : 13627 mProvidersByAuthority.entrySet()) { 13628 PackageParser.Provider p = entry.getValue(); 13629 if (packageName != null && !packageName.equals(p.info.packageName)) { 13630 continue; 13631 } 13632 if (!printedSomething) { 13633 if (dumpState.onTitlePrinted()) 13634 pw.println(); 13635 pw.println("ContentProvider Authorities:"); 13636 printedSomething = true; 13637 } 13638 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13639 pw.print(" "); pw.println(p.toString()); 13640 if (p.info != null && p.info.applicationInfo != null) { 13641 final String appInfo = p.info.applicationInfo.toString(); 13642 pw.print(" applicationInfo="); pw.println(appInfo); 13643 } 13644 } 13645 } 13646 13647 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13648 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13649 } 13650 13651 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13652 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13653 } 13654 13655 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13656 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13657 } 13658 13659 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13660 // XXX should handle packageName != null by dumping only install data that 13661 // the given package is involved with. 13662 if (dumpState.onTitlePrinted()) pw.println(); 13663 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13664 } 13665 13666 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13667 if (dumpState.onTitlePrinted()) pw.println(); 13668 mSettings.dumpReadMessagesLPr(pw, dumpState); 13669 13670 pw.println(); 13671 pw.println("Package warning messages:"); 13672 BufferedReader in = null; 13673 String line = null; 13674 try { 13675 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13676 while ((line = in.readLine()) != null) { 13677 if (line.contains("ignored: updated version")) continue; 13678 pw.println(line); 13679 } 13680 } catch (IOException ignored) { 13681 } finally { 13682 IoUtils.closeQuietly(in); 13683 } 13684 } 13685 13686 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13687 BufferedReader in = null; 13688 String line = null; 13689 try { 13690 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13691 while ((line = in.readLine()) != null) { 13692 if (line.contains("ignored: updated version")) continue; 13693 pw.print("msg,"); 13694 pw.println(line); 13695 } 13696 } catch (IOException ignored) { 13697 } finally { 13698 IoUtils.closeQuietly(in); 13699 } 13700 } 13701 } 13702 } 13703 13704 // ------- apps on sdcard specific code ------- 13705 static final boolean DEBUG_SD_INSTALL = false; 13706 13707 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13708 13709 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13710 13711 private boolean mMediaMounted = false; 13712 13713 static String getEncryptKey() { 13714 try { 13715 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13716 SD_ENCRYPTION_KEYSTORE_NAME); 13717 if (sdEncKey == null) { 13718 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13719 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13720 if (sdEncKey == null) { 13721 Slog.e(TAG, "Failed to create encryption keys"); 13722 return null; 13723 } 13724 } 13725 return sdEncKey; 13726 } catch (NoSuchAlgorithmException nsae) { 13727 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13728 return null; 13729 } catch (IOException ioe) { 13730 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13731 return null; 13732 } 13733 } 13734 13735 /* 13736 * Update media status on PackageManager. 13737 */ 13738 @Override 13739 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13740 int callingUid = Binder.getCallingUid(); 13741 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13742 throw new SecurityException("Media status can only be updated by the system"); 13743 } 13744 // reader; this apparently protects mMediaMounted, but should probably 13745 // be a different lock in that case. 13746 synchronized (mPackages) { 13747 Log.i(TAG, "Updating external media status from " 13748 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13749 + (mediaStatus ? "mounted" : "unmounted")); 13750 if (DEBUG_SD_INSTALL) 13751 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13752 + ", mMediaMounted=" + mMediaMounted); 13753 if (mediaStatus == mMediaMounted) { 13754 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13755 : 0, -1); 13756 mHandler.sendMessage(msg); 13757 return; 13758 } 13759 mMediaMounted = mediaStatus; 13760 } 13761 // Queue up an async operation since the package installation may take a 13762 // little while. 13763 mHandler.post(new Runnable() { 13764 public void run() { 13765 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13766 } 13767 }); 13768 } 13769 13770 /** 13771 * Called by MountService when the initial ASECs to scan are available. 13772 * Should block until all the ASEC containers are finished being scanned. 13773 */ 13774 public void scanAvailableAsecs() { 13775 updateExternalMediaStatusInner(true, false, false); 13776 if (mShouldRestoreconData) { 13777 SELinuxMMAC.setRestoreconDone(); 13778 mShouldRestoreconData = false; 13779 } 13780 } 13781 13782 /* 13783 * Collect information of applications on external media, map them against 13784 * existing containers and update information based on current mount status. 13785 * Please note that we always have to report status if reportStatus has been 13786 * set to true especially when unloading packages. 13787 */ 13788 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13789 boolean externalStorage) { 13790 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13791 int[] uidArr = EmptyArray.INT; 13792 13793 final String[] list = PackageHelper.getSecureContainerList(); 13794 if (ArrayUtils.isEmpty(list)) { 13795 Log.i(TAG, "No secure containers found"); 13796 } else { 13797 // Process list of secure containers and categorize them 13798 // as active or stale based on their package internal state. 13799 13800 // reader 13801 synchronized (mPackages) { 13802 for (String cid : list) { 13803 // Leave stages untouched for now; installer service owns them 13804 if (PackageInstallerService.isStageName(cid)) continue; 13805 13806 if (DEBUG_SD_INSTALL) 13807 Log.i(TAG, "Processing container " + cid); 13808 String pkgName = getAsecPackageName(cid); 13809 if (pkgName == null) { 13810 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13811 continue; 13812 } 13813 if (DEBUG_SD_INSTALL) 13814 Log.i(TAG, "Looking for pkg : " + pkgName); 13815 13816 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13817 if (ps == null) { 13818 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13819 continue; 13820 } 13821 13822 /* 13823 * Skip packages that are not external if we're unmounting 13824 * external storage. 13825 */ 13826 if (externalStorage && !isMounted && !isExternal(ps)) { 13827 continue; 13828 } 13829 13830 final AsecInstallArgs args = new AsecInstallArgs(cid, 13831 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13832 // The package status is changed only if the code path 13833 // matches between settings and the container id. 13834 if (ps.codePathString != null 13835 && ps.codePathString.startsWith(args.getCodePath())) { 13836 if (DEBUG_SD_INSTALL) { 13837 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13838 + " at code path: " + ps.codePathString); 13839 } 13840 13841 // We do have a valid package installed on sdcard 13842 processCids.put(args, ps.codePathString); 13843 final int uid = ps.appId; 13844 if (uid != -1) { 13845 uidArr = ArrayUtils.appendInt(uidArr, uid); 13846 } 13847 } else { 13848 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13849 + ps.codePathString); 13850 } 13851 } 13852 } 13853 13854 Arrays.sort(uidArr); 13855 } 13856 13857 // Process packages with valid entries. 13858 if (isMounted) { 13859 if (DEBUG_SD_INSTALL) 13860 Log.i(TAG, "Loading packages"); 13861 loadMediaPackages(processCids, uidArr); 13862 startCleaningPackages(); 13863 mInstallerService.onSecureContainersAvailable(); 13864 } else { 13865 if (DEBUG_SD_INSTALL) 13866 Log.i(TAG, "Unloading packages"); 13867 unloadMediaPackages(processCids, uidArr, reportStatus); 13868 } 13869 } 13870 13871 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13872 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13873 final int size = infos.size(); 13874 final String[] packageNames = new String[size]; 13875 final int[] packageUids = new int[size]; 13876 for (int i = 0; i < size; i++) { 13877 final ApplicationInfo info = infos.get(i); 13878 packageNames[i] = info.packageName; 13879 packageUids[i] = info.uid; 13880 } 13881 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13882 finishedReceiver); 13883 } 13884 13885 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13886 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13887 sendResourcesChangedBroadcast(mediaStatus, replacing, 13888 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13889 } 13890 13891 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13892 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13893 int size = pkgList.length; 13894 if (size > 0) { 13895 // Send broadcasts here 13896 Bundle extras = new Bundle(); 13897 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13898 if (uidArr != null) { 13899 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13900 } 13901 if (replacing) { 13902 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13903 } 13904 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13905 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13906 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13907 } 13908 } 13909 13910 /* 13911 * Look at potentially valid container ids from processCids If package 13912 * information doesn't match the one on record or package scanning fails, 13913 * the cid is added to list of removeCids. We currently don't delete stale 13914 * containers. 13915 */ 13916 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13917 ArrayList<String> pkgList = new ArrayList<String>(); 13918 Set<AsecInstallArgs> keys = processCids.keySet(); 13919 13920 for (AsecInstallArgs args : keys) { 13921 String codePath = processCids.get(args); 13922 if (DEBUG_SD_INSTALL) 13923 Log.i(TAG, "Loading container : " + args.cid); 13924 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13925 try { 13926 // Make sure there are no container errors first. 13927 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13928 Slog.e(TAG, "Failed to mount cid : " + args.cid 13929 + " when installing from sdcard"); 13930 continue; 13931 } 13932 // Check code path here. 13933 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13934 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13935 + " does not match one in settings " + codePath); 13936 continue; 13937 } 13938 // Parse package 13939 int parseFlags = mDefParseFlags; 13940 if (args.isExternalAsec()) { 13941 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13942 } 13943 if (args.isFwdLocked()) { 13944 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13945 } 13946 13947 synchronized (mInstallLock) { 13948 PackageParser.Package pkg = null; 13949 try { 13950 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13951 } catch (PackageManagerException e) { 13952 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13953 } 13954 // Scan the package 13955 if (pkg != null) { 13956 /* 13957 * TODO why is the lock being held? doPostInstall is 13958 * called in other places without the lock. This needs 13959 * to be straightened out. 13960 */ 13961 // writer 13962 synchronized (mPackages) { 13963 retCode = PackageManager.INSTALL_SUCCEEDED; 13964 pkgList.add(pkg.packageName); 13965 // Post process args 13966 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13967 pkg.applicationInfo.uid); 13968 } 13969 } else { 13970 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13971 } 13972 } 13973 13974 } finally { 13975 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13976 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13977 } 13978 } 13979 } 13980 // writer 13981 synchronized (mPackages) { 13982 // If the platform SDK has changed since the last time we booted, 13983 // we need to re-grant app permission to catch any new ones that 13984 // appear. This is really a hack, and means that apps can in some 13985 // cases get permissions that the user didn't initially explicitly 13986 // allow... it would be nice to have some better way to handle 13987 // this situation. 13988 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13989 if (regrantPermissions) 13990 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13991 + mSdkVersion + "; regranting permissions for external storage"); 13992 mSettings.mExternalSdkPlatform = mSdkVersion; 13993 13994 // Make sure group IDs have been assigned, and any permission 13995 // changes in other apps are accounted for 13996 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13997 | (regrantPermissions 13998 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13999 : 0)); 14000 14001 mSettings.updateExternalDatabaseVersion(); 14002 14003 // can downgrade to reader 14004 // Persist settings 14005 mSettings.writeLPr(); 14006 } 14007 // Send a broadcast to let everyone know we are done processing 14008 if (pkgList.size() > 0) { 14009 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14010 } 14011 } 14012 14013 /* 14014 * Utility method to unload a list of specified containers 14015 */ 14016 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14017 // Just unmount all valid containers. 14018 for (AsecInstallArgs arg : cidArgs) { 14019 synchronized (mInstallLock) { 14020 arg.doPostDeleteLI(false); 14021 } 14022 } 14023 } 14024 14025 /* 14026 * Unload packages mounted on external media. This involves deleting package 14027 * data from internal structures, sending broadcasts about diabled packages, 14028 * gc'ing to free up references, unmounting all secure containers 14029 * corresponding to packages on external media, and posting a 14030 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14031 * that we always have to post this message if status has been requested no 14032 * matter what. 14033 */ 14034 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14035 final boolean reportStatus) { 14036 if (DEBUG_SD_INSTALL) 14037 Log.i(TAG, "unloading media packages"); 14038 ArrayList<String> pkgList = new ArrayList<String>(); 14039 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14040 final Set<AsecInstallArgs> keys = processCids.keySet(); 14041 for (AsecInstallArgs args : keys) { 14042 String pkgName = args.getPackageName(); 14043 if (DEBUG_SD_INSTALL) 14044 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14045 // Delete package internally 14046 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14047 synchronized (mInstallLock) { 14048 boolean res = deletePackageLI(pkgName, null, false, null, null, 14049 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14050 if (res) { 14051 pkgList.add(pkgName); 14052 } else { 14053 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14054 failedList.add(args); 14055 } 14056 } 14057 } 14058 14059 // reader 14060 synchronized (mPackages) { 14061 // We didn't update the settings after removing each package; 14062 // write them now for all packages. 14063 mSettings.writeLPr(); 14064 } 14065 14066 // We have to absolutely send UPDATED_MEDIA_STATUS only 14067 // after confirming that all the receivers processed the ordered 14068 // broadcast when packages get disabled, force a gc to clean things up. 14069 // and unload all the containers. 14070 if (pkgList.size() > 0) { 14071 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14072 new IIntentReceiver.Stub() { 14073 public void performReceive(Intent intent, int resultCode, String data, 14074 Bundle extras, boolean ordered, boolean sticky, 14075 int sendingUser) throws RemoteException { 14076 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14077 reportStatus ? 1 : 0, 1, keys); 14078 mHandler.sendMessage(msg); 14079 } 14080 }); 14081 } else { 14082 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14083 keys); 14084 mHandler.sendMessage(msg); 14085 } 14086 } 14087 14088 private void loadPrivatePackages(VolumeInfo vol) { 14089 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14090 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14091 synchronized (mPackages) { 14092 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14093 for (PackageSetting ps : packages) { 14094 synchronized (mInstallLock) { 14095 final PackageParser.Package pkg; 14096 try { 14097 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14098 loaded.add(pkg.applicationInfo); 14099 } catch (PackageManagerException e) { 14100 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14101 } 14102 } 14103 } 14104 14105 // TODO: regrant any permissions that changed based since original install 14106 14107 mSettings.writeLPr(); 14108 } 14109 14110 Slog.d(TAG, "Loaded packages " + loaded); 14111 sendResourcesChangedBroadcast(true, false, loaded, null); 14112 } 14113 14114 private void unloadPrivatePackages(VolumeInfo vol) { 14115 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14116 synchronized (mPackages) { 14117 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14118 for (PackageSetting ps : packages) { 14119 if (ps.pkg == null) continue; 14120 synchronized (mInstallLock) { 14121 final ApplicationInfo info = ps.pkg.applicationInfo; 14122 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14123 if (deletePackageLI(ps.name, null, false, null, null, 14124 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14125 unloaded.add(info); 14126 } else { 14127 Slog.w(TAG, "Failed to unload " + ps.codePath); 14128 } 14129 } 14130 } 14131 14132 mSettings.writeLPr(); 14133 } 14134 14135 Slog.d(TAG, "Unloaded packages " + unloaded); 14136 sendResourcesChangedBroadcast(false, false, unloaded, null); 14137 } 14138 14139 @Override 14140 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14141 final int flags) { 14142 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14143 14144 final int installFlags; 14145 if ((flags & MOVE_INTERNAL) != 0) { 14146 installFlags = INSTALL_INTERNAL; 14147 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14148 installFlags = INSTALL_EXTERNAL; 14149 } else { 14150 throw new IllegalArgumentException("Unsupported move flags " + flags); 14151 } 14152 14153 try { 14154 movePackageInternal(packageName, null, installFlags, false, observer); 14155 } catch (PackageManagerException e) { 14156 Slog.d(TAG, "Failed to move " + packageName, e); 14157 try { 14158 observer.packageMoved(packageName, e.error); 14159 } catch (RemoteException ignored) { 14160 } 14161 } 14162 } 14163 14164 @Override 14165 public void movePackageAndData(final String packageName, final String volumeUuid, 14166 final IPackageMoveObserver observer) { 14167 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14168 try { 14169 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14170 } catch (PackageManagerException e) { 14171 Slog.d(TAG, "Failed to move " + packageName, e); 14172 try { 14173 observer.packageMoved(packageName, e.error); 14174 } catch (RemoteException ignored) { 14175 } 14176 } 14177 } 14178 14179 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14180 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14181 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14182 14183 final String currentVolumeUuid; 14184 final File codeFile; 14185 final String installerPackageName; 14186 final String packageAbiOverride; 14187 final int appId; 14188 final String seinfo; 14189 14190 // reader 14191 synchronized (mPackages) { 14192 final PackageParser.Package pkg = mPackages.get(packageName); 14193 final PackageSetting ps = mSettings.mPackages.get(packageName); 14194 if (pkg == null || ps == null) { 14195 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14196 } 14197 14198 if (pkg.applicationInfo.isSystemApp()) { 14199 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14200 "Cannot move system application"); 14201 } else if (pkg.mOperationPending) { 14202 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14203 "Attempt to move package which has pending operations"); 14204 } 14205 14206 // TODO: yell if already in desired location 14207 14208 pkg.mOperationPending = true; 14209 14210 currentVolumeUuid = ps.volumeUuid; 14211 codeFile = new File(pkg.codePath); 14212 installerPackageName = ps.installerPackageName; 14213 packageAbiOverride = ps.cpuAbiOverrideString; 14214 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14215 seinfo = pkg.applicationInfo.seinfo; 14216 } 14217 14218 if (andData) { 14219 Slog.d(TAG, "Moving " + packageName + " private data from " + currentVolumeUuid + " to " 14220 + volumeUuid); 14221 synchronized (mInstallLock) { 14222 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14223 seinfo) != 0) { 14224 synchronized (mPackages) { 14225 final PackageParser.Package pkg = mPackages.get(packageName); 14226 if (pkg != null) { 14227 pkg.mOperationPending = false; 14228 } 14229 } 14230 14231 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14232 "Failed to move private data"); 14233 } 14234 } 14235 } 14236 14237 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14238 @Override 14239 public void onUserActionRequired(Intent intent) throws RemoteException { 14240 throw new IllegalStateException(); 14241 } 14242 14243 @Override 14244 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14245 Bundle extras) throws RemoteException { 14246 Slog.d(TAG, "Install result for move: " 14247 + PackageManager.installStatusToString(returnCode, msg)); 14248 14249 // We usually have a new package now after the install, but if 14250 // we failed we need to clear the pending flag on the original 14251 // package object. 14252 synchronized (mPackages) { 14253 final PackageParser.Package pkg = mPackages.get(packageName); 14254 if (pkg != null) { 14255 pkg.mOperationPending = false; 14256 } 14257 } 14258 14259 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14260 switch (status) { 14261 case PackageInstaller.STATUS_SUCCESS: 14262 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14263 break; 14264 case PackageInstaller.STATUS_FAILURE_STORAGE: 14265 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14266 break; 14267 default: 14268 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14269 break; 14270 } 14271 } 14272 }; 14273 14274 // Treat a move like reinstalling an existing app, which ensures that we 14275 // process everythign uniformly, like unpacking native libraries. 14276 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14277 14278 final Message msg = mHandler.obtainMessage(INIT_COPY); 14279 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14280 msg.obj = new InstallParams(origin, installObserver, installFlags, 14281 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14282 mHandler.sendMessage(msg); 14283 } 14284 14285 @Override 14286 public boolean setInstallLocation(int loc) { 14287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14288 null); 14289 if (getInstallLocation() == loc) { 14290 return true; 14291 } 14292 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14293 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14294 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14295 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14296 return true; 14297 } 14298 return false; 14299 } 14300 14301 @Override 14302 public int getInstallLocation() { 14303 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14304 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14305 PackageHelper.APP_INSTALL_AUTO); 14306 } 14307 14308 /** Called by UserManagerService */ 14309 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14310 mDirtyUsers.remove(userHandle); 14311 mSettings.removeUserLPw(userHandle); 14312 mPendingBroadcasts.remove(userHandle); 14313 if (mInstaller != null) { 14314 // Technically, we shouldn't be doing this with the package lock 14315 // held. However, this is very rare, and there is already so much 14316 // other disk I/O going on, that we'll let it slide for now. 14317 final StorageManager storage = StorageManager.from(mContext); 14318 final List<VolumeInfo> vols = storage.getVolumes(); 14319 for (VolumeInfo vol : vols) { 14320 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14321 final String volumeUuid = vol.getFsUuid(); 14322 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14323 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14324 } 14325 } 14326 } 14327 mUserNeedsBadging.delete(userHandle); 14328 removeUnusedPackagesLILPw(userManager, userHandle); 14329 } 14330 14331 /** 14332 * We're removing userHandle and would like to remove any downloaded packages 14333 * that are no longer in use by any other user. 14334 * @param userHandle the user being removed 14335 */ 14336 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14337 final boolean DEBUG_CLEAN_APKS = false; 14338 int [] users = userManager.getUserIdsLPr(); 14339 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14340 while (psit.hasNext()) { 14341 PackageSetting ps = psit.next(); 14342 if (ps.pkg == null) { 14343 continue; 14344 } 14345 final String packageName = ps.pkg.packageName; 14346 // Skip over if system app 14347 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14348 continue; 14349 } 14350 if (DEBUG_CLEAN_APKS) { 14351 Slog.i(TAG, "Checking package " + packageName); 14352 } 14353 boolean keep = false; 14354 for (int i = 0; i < users.length; i++) { 14355 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14356 keep = true; 14357 if (DEBUG_CLEAN_APKS) { 14358 Slog.i(TAG, " Keeping package " + packageName + " for user " 14359 + users[i]); 14360 } 14361 break; 14362 } 14363 } 14364 if (!keep) { 14365 if (DEBUG_CLEAN_APKS) { 14366 Slog.i(TAG, " Removing package " + packageName); 14367 } 14368 mHandler.post(new Runnable() { 14369 public void run() { 14370 deletePackageX(packageName, userHandle, 0); 14371 } //end run 14372 }); 14373 } 14374 } 14375 } 14376 14377 /** Called by UserManagerService */ 14378 void createNewUserLILPw(int userHandle, File path) { 14379 if (mInstaller != null) { 14380 mInstaller.createUserConfig(userHandle); 14381 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14382 } 14383 } 14384 14385 void newUserCreatedLILPw(int userHandle) { 14386 // Adding a user requires updating runtime permissions for system apps. 14387 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14388 } 14389 14390 @Override 14391 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14392 mContext.enforceCallingOrSelfPermission( 14393 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14394 "Only package verification agents can read the verifier device identity"); 14395 14396 synchronized (mPackages) { 14397 return mSettings.getVerifierDeviceIdentityLPw(); 14398 } 14399 } 14400 14401 @Override 14402 public void setPermissionEnforced(String permission, boolean enforced) { 14403 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14404 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14405 synchronized (mPackages) { 14406 if (mSettings.mReadExternalStorageEnforced == null 14407 || mSettings.mReadExternalStorageEnforced != enforced) { 14408 mSettings.mReadExternalStorageEnforced = enforced; 14409 mSettings.writeLPr(); 14410 } 14411 } 14412 // kill any non-foreground processes so we restart them and 14413 // grant/revoke the GID. 14414 final IActivityManager am = ActivityManagerNative.getDefault(); 14415 if (am != null) { 14416 final long token = Binder.clearCallingIdentity(); 14417 try { 14418 am.killProcessesBelowForeground("setPermissionEnforcement"); 14419 } catch (RemoteException e) { 14420 } finally { 14421 Binder.restoreCallingIdentity(token); 14422 } 14423 } 14424 } else { 14425 throw new IllegalArgumentException("No selective enforcement for " + permission); 14426 } 14427 } 14428 14429 @Override 14430 @Deprecated 14431 public boolean isPermissionEnforced(String permission) { 14432 return true; 14433 } 14434 14435 @Override 14436 public boolean isStorageLow() { 14437 final long token = Binder.clearCallingIdentity(); 14438 try { 14439 final DeviceStorageMonitorInternal 14440 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14441 if (dsm != null) { 14442 return dsm.isMemoryLow(); 14443 } else { 14444 return false; 14445 } 14446 } finally { 14447 Binder.restoreCallingIdentity(token); 14448 } 14449 } 14450 14451 @Override 14452 public IPackageInstaller getPackageInstaller() { 14453 return mInstallerService; 14454 } 14455 14456 private boolean userNeedsBadging(int userId) { 14457 int index = mUserNeedsBadging.indexOfKey(userId); 14458 if (index < 0) { 14459 final UserInfo userInfo; 14460 final long token = Binder.clearCallingIdentity(); 14461 try { 14462 userInfo = sUserManager.getUserInfo(userId); 14463 } finally { 14464 Binder.restoreCallingIdentity(token); 14465 } 14466 final boolean b; 14467 if (userInfo != null && userInfo.isManagedProfile()) { 14468 b = true; 14469 } else { 14470 b = false; 14471 } 14472 mUserNeedsBadging.put(userId, b); 14473 return b; 14474 } 14475 return mUserNeedsBadging.valueAt(index); 14476 } 14477 14478 @Override 14479 public KeySet getKeySetByAlias(String packageName, String alias) { 14480 if (packageName == null || alias == null) { 14481 return null; 14482 } 14483 synchronized(mPackages) { 14484 final PackageParser.Package pkg = mPackages.get(packageName); 14485 if (pkg == null) { 14486 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14487 throw new IllegalArgumentException("Unknown package: " + packageName); 14488 } 14489 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14490 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14491 } 14492 } 14493 14494 @Override 14495 public KeySet getSigningKeySet(String packageName) { 14496 if (packageName == null) { 14497 return null; 14498 } 14499 synchronized(mPackages) { 14500 final PackageParser.Package pkg = mPackages.get(packageName); 14501 if (pkg == null) { 14502 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14503 throw new IllegalArgumentException("Unknown package: " + packageName); 14504 } 14505 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14506 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14507 throw new SecurityException("May not access signing KeySet of other apps."); 14508 } 14509 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14510 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14511 } 14512 } 14513 14514 @Override 14515 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14516 if (packageName == null || ks == null) { 14517 return false; 14518 } 14519 synchronized(mPackages) { 14520 final PackageParser.Package pkg = mPackages.get(packageName); 14521 if (pkg == null) { 14522 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14523 throw new IllegalArgumentException("Unknown package: " + packageName); 14524 } 14525 IBinder ksh = ks.getToken(); 14526 if (ksh instanceof KeySetHandle) { 14527 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14528 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14529 } 14530 return false; 14531 } 14532 } 14533 14534 @Override 14535 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14536 if (packageName == null || ks == null) { 14537 return false; 14538 } 14539 synchronized(mPackages) { 14540 final PackageParser.Package pkg = mPackages.get(packageName); 14541 if (pkg == null) { 14542 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14543 throw new IllegalArgumentException("Unknown package: " + packageName); 14544 } 14545 IBinder ksh = ks.getToken(); 14546 if (ksh instanceof KeySetHandle) { 14547 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14548 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14549 } 14550 return false; 14551 } 14552 } 14553 14554 public void getUsageStatsIfNoPackageUsageInfo() { 14555 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14556 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14557 if (usm == null) { 14558 throw new IllegalStateException("UsageStatsManager must be initialized"); 14559 } 14560 long now = System.currentTimeMillis(); 14561 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14562 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14563 String packageName = entry.getKey(); 14564 PackageParser.Package pkg = mPackages.get(packageName); 14565 if (pkg == null) { 14566 continue; 14567 } 14568 UsageStats usage = entry.getValue(); 14569 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14570 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14571 } 14572 } 14573 } 14574 14575 /** 14576 * Check and throw if the given before/after packages would be considered a 14577 * downgrade. 14578 */ 14579 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14580 throws PackageManagerException { 14581 if (after.versionCode < before.mVersionCode) { 14582 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14583 "Update version code " + after.versionCode + " is older than current " 14584 + before.mVersionCode); 14585 } else if (after.versionCode == before.mVersionCode) { 14586 if (after.baseRevisionCode < before.baseRevisionCode) { 14587 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14588 "Update base revision code " + after.baseRevisionCode 14589 + " is older than current " + before.baseRevisionCode); 14590 } 14591 14592 if (!ArrayUtils.isEmpty(after.splitNames)) { 14593 for (int i = 0; i < after.splitNames.length; i++) { 14594 final String splitName = after.splitNames[i]; 14595 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14596 if (j != -1) { 14597 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14598 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14599 "Update split " + splitName + " revision code " 14600 + after.splitRevisionCodes[i] + " is older than current " 14601 + before.splitRevisionCodes[j]); 14602 } 14603 } 14604 } 14605 } 14606 } 14607 } 14608} 14609