PackageManagerService.java revision e012a235569fe307d165dfd0784ae847d0b13739
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_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 51import static android.content.pm.PackageParser.isApkFile; 52import static android.os.Process.PACKAGE_INFO_GID; 53import static android.os.Process.SYSTEM_UID; 54import static android.system.OsConstants.O_CREAT; 55import static android.system.OsConstants.O_RDWR; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 59import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 60import static com.android.internal.util.ArrayUtils.appendInt; 61import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 62import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 63import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 64import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 65import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 66 67import android.Manifest; 68import android.content.pm.IntentFilterVerificationInfo; 69import android.util.ArrayMap; 70 71import com.android.internal.R; 72import com.android.internal.app.IMediaContainerService; 73import com.android.internal.app.ResolverActivity; 74import com.android.internal.content.NativeLibraryHelper; 75import com.android.internal.content.PackageHelper; 76import com.android.internal.os.IParcelFileDescriptorFactory; 77import com.android.internal.util.ArrayUtils; 78import com.android.internal.util.FastPrintWriter; 79import com.android.internal.util.FastXmlSerializer; 80import com.android.internal.util.IndentingPrintWriter; 81import com.android.server.EventLogTags; 82import com.android.server.IntentResolver; 83import com.android.server.LocalServices; 84import com.android.server.ServiceThread; 85import com.android.server.SystemConfig; 86import com.android.server.Watchdog; 87import com.android.server.pm.Settings.DatabaseVersion; 88import com.android.server.storage.DeviceStorageMonitorInternal; 89 90import org.xmlpull.v1.XmlPullParser; 91import org.xmlpull.v1.XmlSerializer; 92 93import android.app.ActivityManager; 94import android.app.ActivityManagerNative; 95import android.app.AppGlobals; 96import android.app.IActivityManager; 97import android.app.admin.IDevicePolicyManager; 98import android.app.backup.IBackupManager; 99import android.app.usage.UsageStats; 100import android.app.usage.UsageStatsManager; 101import android.content.BroadcastReceiver; 102import android.content.ComponentName; 103import android.content.Context; 104import android.content.IIntentReceiver; 105import android.content.Intent; 106import android.content.IntentFilter; 107import android.content.IntentSender; 108import android.content.IntentSender.SendIntentException; 109import android.content.ServiceConnection; 110import android.content.pm.ActivityInfo; 111import android.content.pm.ApplicationInfo; 112import android.content.pm.FeatureInfo; 113import android.content.pm.IPackageDataObserver; 114import android.content.pm.IPackageDeleteObserver; 115import android.content.pm.IPackageDeleteObserver2; 116import android.content.pm.IPackageInstallObserver2; 117import android.content.pm.IPackageInstaller; 118import android.content.pm.IPackageManager; 119import android.content.pm.IPackageMoveObserver; 120import android.content.pm.IPackageStatsObserver; 121import android.content.pm.InstrumentationInfo; 122import android.content.pm.KeySet; 123import android.content.pm.ManifestDigest; 124import android.content.pm.PackageCleanItem; 125import android.content.pm.PackageInfo; 126import android.content.pm.PackageInfoLite; 127import android.content.pm.PackageInstaller; 128import android.content.pm.PackageManager; 129import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageParser; 134import android.content.pm.PackageStats; 135import android.content.pm.PackageUserState; 136import android.content.pm.ParceledListSlice; 137import android.content.pm.PermissionGroupInfo; 138import android.content.pm.PermissionInfo; 139import android.content.pm.ProviderInfo; 140import android.content.pm.ResolveInfo; 141import android.content.pm.ServiceInfo; 142import android.content.pm.Signature; 143import android.content.pm.UserInfo; 144import android.content.pm.VerificationParams; 145import android.content.pm.VerifierDeviceIdentity; 146import android.content.pm.VerifierInfo; 147import android.content.res.Resources; 148import android.hardware.display.DisplayManager; 149import android.net.Uri; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.storage.IMountService; 156import android.os.storage.StorageEventListener; 157import android.os.storage.StorageManager; 158import android.os.storage.VolumeInfo; 159import android.os.Debug; 160import android.os.FileUtils; 161import android.os.Handler; 162import android.os.IBinder; 163import android.os.Looper; 164import android.os.Message; 165import android.os.Parcel; 166import android.os.ParcelFileDescriptor; 167import android.os.Process; 168import android.os.RemoteException; 169import android.os.SELinux; 170import android.os.ServiceManager; 171import android.os.SystemClock; 172import android.os.SystemProperties; 173import android.os.UserHandle; 174import android.os.UserManager; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArraySet; 183import android.util.AtomicFile; 184import android.util.DisplayMetrics; 185import android.util.EventLog; 186import android.util.ExceptionUtils; 187import android.util.Log; 188import android.util.LogPrinter; 189import android.util.PrintStreamPrinter; 190import android.util.Slog; 191import android.util.SparseArray; 192import android.util.SparseBooleanArray; 193import android.util.Xml; 194import android.view.Display; 195 196import java.io.BufferedInputStream; 197import java.io.BufferedOutputStream; 198import java.io.BufferedReader; 199import java.io.ByteArrayInputStream; 200import java.io.ByteArrayOutputStream; 201import java.io.File; 202import java.io.FileDescriptor; 203import java.io.FileNotFoundException; 204import java.io.FileOutputStream; 205import java.io.FileReader; 206import java.io.FilenameFilter; 207import java.io.IOException; 208import java.io.InputStream; 209import java.io.PrintWriter; 210import java.nio.charset.StandardCharsets; 211import java.security.NoSuchAlgorithmException; 212import java.security.PublicKey; 213import java.security.cert.CertificateEncodingException; 214import java.security.cert.CertificateException; 215import java.text.SimpleDateFormat; 216import java.util.ArrayList; 217import java.util.Arrays; 218import java.util.Collection; 219import java.util.Collections; 220import java.util.Comparator; 221import java.util.Date; 222import java.util.Iterator; 223import java.util.List; 224import java.util.Map; 225import java.util.Objects; 226import java.util.Set; 227import java.util.concurrent.atomic.AtomicBoolean; 228import java.util.concurrent.atomic.AtomicLong; 229 230import dalvik.system.DexFile; 231import dalvik.system.VMRuntime; 232 233import libcore.io.IoUtils; 234import libcore.util.EmptyArray; 235 236/** 237 * Keep track of all those .apks everywhere. 238 * 239 * This is very central to the platform's security; please run the unit 240 * tests whenever making modifications here: 241 * 242mmm frameworks/base/tests/AndroidTests 243adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 244adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 245 * 246 * {@hide} 247 */ 248public class PackageManagerService extends IPackageManager.Stub { 249 static final String TAG = "PackageManager"; 250 static final boolean DEBUG_SETTINGS = false; 251 static final boolean DEBUG_PREFERRED = false; 252 static final boolean DEBUG_UPGRADE = false; 253 private static final boolean DEBUG_BACKUP = true; 254 private static final boolean DEBUG_INSTALL = false; 255 private static final boolean DEBUG_REMOVE = false; 256 private static final boolean DEBUG_BROADCASTS = false; 257 private static final boolean DEBUG_SHOW_INFO = false; 258 private static final boolean DEBUG_PACKAGE_INFO = false; 259 private static final boolean DEBUG_INTENT_MATCHING = false; 260 private static final boolean DEBUG_PACKAGE_SCANNING = false; 261 private static final boolean DEBUG_VERIFY = false; 262 private static final boolean DEBUG_DEXOPT = false; 263 private static final boolean DEBUG_ABI_SELECTION = false; 264 265 static final boolean RUNTIME_PERMISSIONS_ENABLED = 266 SystemProperties.getInt("ro.runtime.permissions.enabled", 0) == 1; 267 268 private static final int RADIO_UID = Process.PHONE_UID; 269 private static final int LOG_UID = Process.LOG_UID; 270 private static final int NFC_UID = Process.NFC_UID; 271 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 272 private static final int SHELL_UID = Process.SHELL_UID; 273 274 // Cap the size of permission trees that 3rd party apps can define 275 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 276 277 // Suffix used during package installation when copying/moving 278 // package apks to install directory. 279 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 280 281 static final int SCAN_NO_DEX = 1<<1; 282 static final int SCAN_FORCE_DEX = 1<<2; 283 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 284 static final int SCAN_NEW_INSTALL = 1<<4; 285 static final int SCAN_NO_PATHS = 1<<5; 286 static final int SCAN_UPDATE_TIME = 1<<6; 287 static final int SCAN_DEFER_DEX = 1<<7; 288 static final int SCAN_BOOTING = 1<<8; 289 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 290 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 291 static final int SCAN_REPLACING = 1<<11; 292 static final int SCAN_REQUIRE_KNOWN = 1<<12; 293 294 static final int REMOVE_CHATTY = 1<<16; 295 296 /** 297 * Timeout (in milliseconds) after which the watchdog should declare that 298 * our handler thread is wedged. The usual default for such things is one 299 * minute but we sometimes do very lengthy I/O operations on this thread, 300 * such as installing multi-gigabyte applications, so ours needs to be longer. 301 */ 302 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 303 304 /** 305 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 306 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 307 * settings entry if available, otherwise we use the hardcoded default. If it's been 308 * more than this long since the last fstrim, we force one during the boot sequence. 309 * 310 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 311 * one gets run at the next available charging+idle time. This final mandatory 312 * no-fstrim check kicks in only of the other scheduling criteria is never met. 313 */ 314 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 315 316 /** 317 * Whether verification is enabled by default. 318 */ 319 private static final boolean DEFAULT_VERIFY_ENABLE = true; 320 321 /** 322 * The default maximum time to wait for the verification agent to return in 323 * milliseconds. 324 */ 325 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 326 327 /** 328 * The default response for package verification timeout. 329 * 330 * This can be either PackageManager.VERIFICATION_ALLOW or 331 * PackageManager.VERIFICATION_REJECT. 332 */ 333 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 334 335 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 336 337 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 338 DEFAULT_CONTAINER_PACKAGE, 339 "com.android.defcontainer.DefaultContainerService"); 340 341 private static final String KILL_APP_REASON_GIDS_CHANGED = 342 "permission grant or revoke changed gids"; 343 344 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 345 "permissions revoked"; 346 347 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 348 349 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 350 351 /** Permission grant: not grant the permission. */ 352 private static final int GRANT_DENIED = 1; 353 354 /** Permission grant: grant the permission as an install permission. */ 355 private static final int GRANT_INSTALL = 2; 356 357 /** Permission grant: grant the permission as a runtime one. */ 358 private static final int GRANT_RUNTIME = 3; 359 360 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 361 private static final int GRANT_UPGRADE = 4; 362 363 final ServiceThread mHandlerThread; 364 365 final PackageHandler mHandler; 366 367 /** 368 * Messages for {@link #mHandler} that need to wait for system ready before 369 * being dispatched. 370 */ 371 private ArrayList<Message> mPostSystemReadyMessages; 372 373 final int mSdkVersion = Build.VERSION.SDK_INT; 374 375 final Context mContext; 376 final boolean mFactoryTest; 377 final boolean mOnlyCore; 378 final boolean mLazyDexOpt; 379 final long mDexOptLRUThresholdInMills; 380 final DisplayMetrics mMetrics; 381 final int mDefParseFlags; 382 final String[] mSeparateProcesses; 383 final boolean mIsUpgrade; 384 385 // This is where all application persistent data goes. 386 final File mAppDataDir; 387 388 // This is where all application persistent data goes for secondary users. 389 final File mUserAppDataDir; 390 391 /** The location for ASEC container files on internal storage. */ 392 final String mAsecInternalPath; 393 394 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 395 // LOCK HELD. Can be called with mInstallLock held. 396 final Installer mInstaller; 397 398 /** Directory where installed third-party apps stored */ 399 final File mAppInstallDir; 400 401 /** 402 * Directory to which applications installed internally have their 403 * 32 bit native libraries copied. 404 */ 405 private File mAppLib32InstallDir; 406 407 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 408 // apps. 409 final File mDrmAppPrivateInstallDir; 410 411 // ---------------------------------------------------------------- 412 413 // Lock for state used when installing and doing other long running 414 // operations. Methods that must be called with this lock held have 415 // the suffix "LI". 416 final Object mInstallLock = new Object(); 417 418 // ---------------------------------------------------------------- 419 420 // Keys are String (package name), values are Package. This also serves 421 // as the lock for the global state. Methods that must be called with 422 // this lock held have the prefix "LP". 423 final ArrayMap<String, PackageParser.Package> mPackages = 424 new ArrayMap<String, PackageParser.Package>(); 425 426 // Tracks available target package names -> overlay package paths. 427 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 428 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 429 430 final Settings mSettings; 431 boolean mRestoredSettings; 432 433 // System configuration read by SystemConfig. 434 final int[] mGlobalGids; 435 final SparseArray<ArraySet<String>> mSystemPermissions; 436 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 437 438 // If mac_permissions.xml was found for seinfo labeling. 439 boolean mFoundPolicyFile; 440 441 // If a recursive restorecon of /data/data/<pkg> is needed. 442 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 443 444 public static final class SharedLibraryEntry { 445 public final String path; 446 public final String apk; 447 448 SharedLibraryEntry(String _path, String _apk) { 449 path = _path; 450 apk = _apk; 451 } 452 } 453 454 // Currently known shared libraries. 455 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 456 new ArrayMap<String, SharedLibraryEntry>(); 457 458 // All available activities, for your resolving pleasure. 459 final ActivityIntentResolver mActivities = 460 new ActivityIntentResolver(); 461 462 // All available receivers, for your resolving pleasure. 463 final ActivityIntentResolver mReceivers = 464 new ActivityIntentResolver(); 465 466 // All available services, for your resolving pleasure. 467 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 468 469 // All available providers, for your resolving pleasure. 470 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 471 472 // Mapping from provider base names (first directory in content URI codePath) 473 // to the provider information. 474 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 475 new ArrayMap<String, PackageParser.Provider>(); 476 477 // Mapping from instrumentation class names to info about them. 478 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 479 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 480 481 // Mapping from permission names to info about them. 482 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 483 new ArrayMap<String, PackageParser.PermissionGroup>(); 484 485 // Packages whose data we have transfered into another package, thus 486 // should no longer exist. 487 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 488 489 // Broadcast actions that are only available to the system. 490 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 491 492 /** List of packages waiting for verification. */ 493 final SparseArray<PackageVerificationState> mPendingVerification 494 = new SparseArray<PackageVerificationState>(); 495 496 /** Set of packages associated with each app op permission. */ 497 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 498 499 final PackageInstallerService mInstallerService; 500 501 private final PackageDexOptimizer mPackageDexOptimizer; 502 // Cache of users who need badging. 503 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 504 505 /** Token for keys in mPendingVerification. */ 506 private int mPendingVerificationToken = 0; 507 508 volatile boolean mSystemReady; 509 volatile boolean mSafeMode; 510 volatile boolean mHasSystemUidErrors; 511 512 ApplicationInfo mAndroidApplication; 513 final ActivityInfo mResolveActivity = new ActivityInfo(); 514 final ResolveInfo mResolveInfo = new ResolveInfo(); 515 ComponentName mResolveComponentName; 516 PackageParser.Package mPlatformPackage; 517 ComponentName mCustomResolverComponentName; 518 519 boolean mResolverReplaced = false; 520 521 private final ComponentName mIntentFilterVerifierComponent; 522 private int mIntentFilterVerificationToken = 0; 523 524 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 525 = new SparseArray<IntentFilterVerificationState>(); 526 527 private interface IntentFilterVerifier<T extends IntentFilter> { 528 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 529 T filter, String packageName); 530 void startVerifications(int userId); 531 void receiveVerificationResponse(int verificationId); 532 } 533 534 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 535 private Context mContext; 536 private ComponentName mIntentFilterVerifierComponent; 537 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 538 539 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 540 mContext = context; 541 mIntentFilterVerifierComponent = verifierComponent; 542 } 543 544 private String getDefaultScheme() { 545 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 546 return IntentFilter.SCHEME_HTTP; 547 } 548 549 @Override 550 public void startVerifications(int userId) { 551 // Launch verifications requests 552 int count = mCurrentIntentFilterVerifications.size(); 553 for (int n=0; n<count; n++) { 554 int verificationId = mCurrentIntentFilterVerifications.get(n); 555 final IntentFilterVerificationState ivs = 556 mIntentFilterVerificationStates.get(verificationId); 557 558 String packageName = ivs.getPackageName(); 559 boolean modified = false; 560 561 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 562 final int filterCount = filters.size(); 563 for (int m=0; m<filterCount; m++) { 564 PackageParser.ActivityIntentInfo filter = filters.get(m); 565 synchronized (mPackages) { 566 modified = mSettings.createIntentFilterVerificationIfNeededLPw( 567 packageName, filter.getHosts()); 568 } 569 } 570 synchronized (mPackages) { 571 if (modified) { 572 scheduleWriteSettingsLocked(); 573 } 574 } 575 sendVerificationRequest(userId, verificationId, ivs); 576 } 577 mCurrentIntentFilterVerifications.clear(); 578 } 579 580 private void sendVerificationRequest(int userId, int verificationId, 581 IntentFilterVerificationState ivs) { 582 583 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 584 verificationIntent.putExtra( 585 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 586 verificationId); 587 verificationIntent.putExtra( 588 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 589 getDefaultScheme()); 590 verificationIntent.putExtra( 591 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 592 ivs.getHostsString()); 593 verificationIntent.putExtra( 594 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 595 ivs.getPackageName()); 596 verificationIntent.setComponent(mIntentFilterVerifierComponent); 597 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 598 599 UserHandle user = new UserHandle(userId); 600 mContext.sendBroadcastAsUser(verificationIntent, user); 601 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 602 } 603 604 public void receiveVerificationResponse(int verificationId) { 605 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 606 607 final boolean verified = ivs.isVerified(); 608 609 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 610 final int count = filters.size(); 611 for (int n=0; n<count; n++) { 612 PackageParser.ActivityIntentInfo filter = filters.get(n); 613 filter.setVerified(verified); 614 615 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 616 + verified + " and hosts:" + ivs.getHostsString()); 617 } 618 619 mIntentFilterVerificationStates.remove(verificationId); 620 621 final String packageName = ivs.getPackageName(); 622 IntentFilterVerificationInfo ivi = null; 623 624 synchronized (mPackages) { 625 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 626 } 627 if (ivi == null) { 628 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 629 + verificationId + " packageName:" + packageName); 630 return; 631 } 632 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 633 + verificationId); 634 635 synchronized (mPackages) { 636 if (verified) { 637 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 638 } else { 639 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 640 } 641 scheduleWriteSettingsLocked(); 642 643 final int userId = ivs.getUserId(); 644 if (userId != UserHandle.USER_ALL) { 645 final int userStatus = 646 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 647 648 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 649 boolean needUpdate = false; 650 651 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 652 // already been set by the User thru the Disambiguation dialog 653 switch (userStatus) { 654 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 655 if (verified) { 656 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 657 } else { 658 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 659 } 660 needUpdate = true; 661 break; 662 663 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 664 if (verified) { 665 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 666 needUpdate = true; 667 } 668 break; 669 670 default: 671 // Nothing to do 672 } 673 674 if (needUpdate) { 675 mSettings.updateIntentFilterVerificationStatusLPw( 676 packageName, updatedStatus, userId); 677 scheduleWritePackageRestrictionsLocked(userId); 678 } 679 } 680 } 681 } 682 683 @Override 684 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 685 ActivityIntentInfo filter, String packageName) { 686 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 687 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 688 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 689 return false; 690 } 691 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 692 if (ivs == null) { 693 ivs = createDomainVerificationState(verifierId, userId, verificationId, 694 packageName); 695 } 696 ArrayList<String> hosts = filter.getHostsList(); 697 if (!hasValidHosts(hosts)) { 698 return false; 699 } 700 ivs.addFilter(filter); 701 return true; 702 } 703 704 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 705 int userId, int verificationId, String packageName) { 706 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 707 verifierId, userId, packageName); 708 ivs.setPendingState(); 709 synchronized (mPackages) { 710 mIntentFilterVerificationStates.append(verificationId, ivs); 711 mCurrentIntentFilterVerifications.add(verificationId); 712 } 713 return ivs; 714 } 715 716 private boolean hasValidHosts(ArrayList<String> hosts) { 717 if (hosts.size() == 0) { 718 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 719 return false; 720 } 721 String hostEndBase = null; 722 for (String host : hosts) { 723 String[] hostParts = host.split("\\."); 724 // Should be at minimum a host like "example.com" 725 if (hostParts.length < 2) { 726 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 727 return false; 728 } 729 // Verify that we have the same ending domain 730 int length = hostParts.length; 731 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 732 if (hostEndBase == null) { 733 hostEndBase = hostEnd; 734 } 735 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 736 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 737 return false; 738 } 739 } 740 return true; 741 } 742 } 743 744 private IntentFilterVerifier mIntentFilterVerifier; 745 746 // Set of pending broadcasts for aggregating enable/disable of components. 747 static class PendingPackageBroadcasts { 748 // for each user id, a map of <package name -> components within that package> 749 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 750 751 public PendingPackageBroadcasts() { 752 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 753 } 754 755 public ArrayList<String> get(int userId, String packageName) { 756 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 757 return packages.get(packageName); 758 } 759 760 public void put(int userId, String packageName, ArrayList<String> components) { 761 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 762 packages.put(packageName, components); 763 } 764 765 public void remove(int userId, String packageName) { 766 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 767 if (packages != null) { 768 packages.remove(packageName); 769 } 770 } 771 772 public void remove(int userId) { 773 mUidMap.remove(userId); 774 } 775 776 public int userIdCount() { 777 return mUidMap.size(); 778 } 779 780 public int userIdAt(int n) { 781 return mUidMap.keyAt(n); 782 } 783 784 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 785 return mUidMap.get(userId); 786 } 787 788 public int size() { 789 // total number of pending broadcast entries across all userIds 790 int num = 0; 791 for (int i = 0; i< mUidMap.size(); i++) { 792 num += mUidMap.valueAt(i).size(); 793 } 794 return num; 795 } 796 797 public void clear() { 798 mUidMap.clear(); 799 } 800 801 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 802 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 803 if (map == null) { 804 map = new ArrayMap<String, ArrayList<String>>(); 805 mUidMap.put(userId, map); 806 } 807 return map; 808 } 809 } 810 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 811 812 // Service Connection to remote media container service to copy 813 // package uri's from external media onto secure containers 814 // or internal storage. 815 private IMediaContainerService mContainerService = null; 816 817 static final int SEND_PENDING_BROADCAST = 1; 818 static final int MCS_BOUND = 3; 819 static final int END_COPY = 4; 820 static final int INIT_COPY = 5; 821 static final int MCS_UNBIND = 6; 822 static final int START_CLEANING_PACKAGE = 7; 823 static final int FIND_INSTALL_LOC = 8; 824 static final int POST_INSTALL = 9; 825 static final int MCS_RECONNECT = 10; 826 static final int MCS_GIVE_UP = 11; 827 static final int UPDATED_MEDIA_STATUS = 12; 828 static final int WRITE_SETTINGS = 13; 829 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 830 static final int PACKAGE_VERIFIED = 15; 831 static final int CHECK_PENDING_VERIFICATION = 16; 832 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 833 static final int INTENT_FILTER_VERIFIED = 18; 834 835 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 836 837 // Delay time in millisecs 838 static final int BROADCAST_DELAY = 10 * 1000; 839 840 static UserManagerService sUserManager; 841 842 // Stores a list of users whose package restrictions file needs to be updated 843 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 844 845 final private DefaultContainerConnection mDefContainerConn = 846 new DefaultContainerConnection(); 847 class DefaultContainerConnection implements ServiceConnection { 848 public void onServiceConnected(ComponentName name, IBinder service) { 849 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 850 IMediaContainerService imcs = 851 IMediaContainerService.Stub.asInterface(service); 852 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 853 } 854 855 public void onServiceDisconnected(ComponentName name) { 856 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 857 } 858 }; 859 860 // Recordkeeping of restore-after-install operations that are currently in flight 861 // between the Package Manager and the Backup Manager 862 class PostInstallData { 863 public InstallArgs args; 864 public PackageInstalledInfo res; 865 866 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 867 args = _a; 868 res = _r; 869 } 870 }; 871 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 872 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 873 874 // backup/restore of preferred activity state 875 private static final String TAG_PREFERRED_BACKUP = "pa"; 876 877 private final String mRequiredVerifierPackage; 878 879 private final PackageUsage mPackageUsage = new PackageUsage(); 880 881 private class PackageUsage { 882 private static final int WRITE_INTERVAL 883 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 884 885 private final Object mFileLock = new Object(); 886 private final AtomicLong mLastWritten = new AtomicLong(0); 887 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 888 889 private boolean mIsHistoricalPackageUsageAvailable = true; 890 891 boolean isHistoricalPackageUsageAvailable() { 892 return mIsHistoricalPackageUsageAvailable; 893 } 894 895 void write(boolean force) { 896 if (force) { 897 writeInternal(); 898 return; 899 } 900 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 901 && !DEBUG_DEXOPT) { 902 return; 903 } 904 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 905 new Thread("PackageUsage_DiskWriter") { 906 @Override 907 public void run() { 908 try { 909 writeInternal(); 910 } finally { 911 mBackgroundWriteRunning.set(false); 912 } 913 } 914 }.start(); 915 } 916 } 917 918 private void writeInternal() { 919 synchronized (mPackages) { 920 synchronized (mFileLock) { 921 AtomicFile file = getFile(); 922 FileOutputStream f = null; 923 try { 924 f = file.startWrite(); 925 BufferedOutputStream out = new BufferedOutputStream(f); 926 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 927 StringBuilder sb = new StringBuilder(); 928 for (PackageParser.Package pkg : mPackages.values()) { 929 if (pkg.mLastPackageUsageTimeInMills == 0) { 930 continue; 931 } 932 sb.setLength(0); 933 sb.append(pkg.packageName); 934 sb.append(' '); 935 sb.append((long)pkg.mLastPackageUsageTimeInMills); 936 sb.append('\n'); 937 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 938 } 939 out.flush(); 940 file.finishWrite(f); 941 } catch (IOException e) { 942 if (f != null) { 943 file.failWrite(f); 944 } 945 Log.e(TAG, "Failed to write package usage times", e); 946 } 947 } 948 } 949 mLastWritten.set(SystemClock.elapsedRealtime()); 950 } 951 952 void readLP() { 953 synchronized (mFileLock) { 954 AtomicFile file = getFile(); 955 BufferedInputStream in = null; 956 try { 957 in = new BufferedInputStream(file.openRead()); 958 StringBuffer sb = new StringBuffer(); 959 while (true) { 960 String packageName = readToken(in, sb, ' '); 961 if (packageName == null) { 962 break; 963 } 964 String timeInMillisString = readToken(in, sb, '\n'); 965 if (timeInMillisString == null) { 966 throw new IOException("Failed to find last usage time for package " 967 + packageName); 968 } 969 PackageParser.Package pkg = mPackages.get(packageName); 970 if (pkg == null) { 971 continue; 972 } 973 long timeInMillis; 974 try { 975 timeInMillis = Long.parseLong(timeInMillisString.toString()); 976 } catch (NumberFormatException e) { 977 throw new IOException("Failed to parse " + timeInMillisString 978 + " as a long.", e); 979 } 980 pkg.mLastPackageUsageTimeInMills = timeInMillis; 981 } 982 } catch (FileNotFoundException expected) { 983 mIsHistoricalPackageUsageAvailable = false; 984 } catch (IOException e) { 985 Log.w(TAG, "Failed to read package usage times", e); 986 } finally { 987 IoUtils.closeQuietly(in); 988 } 989 } 990 mLastWritten.set(SystemClock.elapsedRealtime()); 991 } 992 993 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 994 throws IOException { 995 sb.setLength(0); 996 while (true) { 997 int ch = in.read(); 998 if (ch == -1) { 999 if (sb.length() == 0) { 1000 return null; 1001 } 1002 throw new IOException("Unexpected EOF"); 1003 } 1004 if (ch == endOfToken) { 1005 return sb.toString(); 1006 } 1007 sb.append((char)ch); 1008 } 1009 } 1010 1011 private AtomicFile getFile() { 1012 File dataDir = Environment.getDataDirectory(); 1013 File systemDir = new File(dataDir, "system"); 1014 File fname = new File(systemDir, "package-usage.list"); 1015 return new AtomicFile(fname); 1016 } 1017 } 1018 1019 class PackageHandler extends Handler { 1020 private boolean mBound = false; 1021 final ArrayList<HandlerParams> mPendingInstalls = 1022 new ArrayList<HandlerParams>(); 1023 1024 private boolean connectToService() { 1025 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1026 " DefaultContainerService"); 1027 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1028 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1029 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1030 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1031 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1032 mBound = true; 1033 return true; 1034 } 1035 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1036 return false; 1037 } 1038 1039 private void disconnectService() { 1040 mContainerService = null; 1041 mBound = false; 1042 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1043 mContext.unbindService(mDefContainerConn); 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 } 1046 1047 PackageHandler(Looper looper) { 1048 super(looper); 1049 } 1050 1051 public void handleMessage(Message msg) { 1052 try { 1053 doHandleMessage(msg); 1054 } finally { 1055 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1056 } 1057 } 1058 1059 void doHandleMessage(Message msg) { 1060 switch (msg.what) { 1061 case INIT_COPY: { 1062 HandlerParams params = (HandlerParams) msg.obj; 1063 int idx = mPendingInstalls.size(); 1064 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1065 // If a bind was already initiated we dont really 1066 // need to do anything. The pending install 1067 // will be processed later on. 1068 if (!mBound) { 1069 // If this is the only one pending we might 1070 // have to bind to the service again. 1071 if (!connectToService()) { 1072 Slog.e(TAG, "Failed to bind to media container service"); 1073 params.serviceError(); 1074 return; 1075 } else { 1076 // Once we bind to the service, the first 1077 // pending request will be processed. 1078 mPendingInstalls.add(idx, params); 1079 } 1080 } else { 1081 mPendingInstalls.add(idx, params); 1082 // Already bound to the service. Just make 1083 // sure we trigger off processing the first request. 1084 if (idx == 0) { 1085 mHandler.sendEmptyMessage(MCS_BOUND); 1086 } 1087 } 1088 break; 1089 } 1090 case MCS_BOUND: { 1091 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1092 if (msg.obj != null) { 1093 mContainerService = (IMediaContainerService) msg.obj; 1094 } 1095 if (mContainerService == null) { 1096 // Something seriously wrong. Bail out 1097 Slog.e(TAG, "Cannot bind to media container service"); 1098 for (HandlerParams params : mPendingInstalls) { 1099 // Indicate service bind error 1100 params.serviceError(); 1101 } 1102 mPendingInstalls.clear(); 1103 } else if (mPendingInstalls.size() > 0) { 1104 HandlerParams params = mPendingInstalls.get(0); 1105 if (params != null) { 1106 if (params.startCopy()) { 1107 // We are done... look for more work or to 1108 // go idle. 1109 if (DEBUG_SD_INSTALL) Log.i(TAG, 1110 "Checking for more work or unbind..."); 1111 // Delete pending install 1112 if (mPendingInstalls.size() > 0) { 1113 mPendingInstalls.remove(0); 1114 } 1115 if (mPendingInstalls.size() == 0) { 1116 if (mBound) { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, 1118 "Posting delayed MCS_UNBIND"); 1119 removeMessages(MCS_UNBIND); 1120 Message ubmsg = obtainMessage(MCS_UNBIND); 1121 // Unbind after a little delay, to avoid 1122 // continual thrashing. 1123 sendMessageDelayed(ubmsg, 10000); 1124 } 1125 } else { 1126 // There are more pending requests in queue. 1127 // Just post MCS_BOUND message to trigger processing 1128 // of next pending install. 1129 if (DEBUG_SD_INSTALL) Log.i(TAG, 1130 "Posting MCS_BOUND for next work"); 1131 mHandler.sendEmptyMessage(MCS_BOUND); 1132 } 1133 } 1134 } 1135 } else { 1136 // Should never happen ideally. 1137 Slog.w(TAG, "Empty queue"); 1138 } 1139 break; 1140 } 1141 case MCS_RECONNECT: { 1142 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1143 if (mPendingInstalls.size() > 0) { 1144 if (mBound) { 1145 disconnectService(); 1146 } 1147 if (!connectToService()) { 1148 Slog.e(TAG, "Failed to bind to media container service"); 1149 for (HandlerParams params : mPendingInstalls) { 1150 // Indicate service bind error 1151 params.serviceError(); 1152 } 1153 mPendingInstalls.clear(); 1154 } 1155 } 1156 break; 1157 } 1158 case MCS_UNBIND: { 1159 // If there is no actual work left, then time to unbind. 1160 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1161 1162 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1163 if (mBound) { 1164 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1165 1166 disconnectService(); 1167 } 1168 } else if (mPendingInstalls.size() > 0) { 1169 // There are more pending requests in queue. 1170 // Just post MCS_BOUND message to trigger processing 1171 // of next pending install. 1172 mHandler.sendEmptyMessage(MCS_BOUND); 1173 } 1174 1175 break; 1176 } 1177 case MCS_GIVE_UP: { 1178 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1179 mPendingInstalls.remove(0); 1180 break; 1181 } 1182 case SEND_PENDING_BROADCAST: { 1183 String packages[]; 1184 ArrayList<String> components[]; 1185 int size = 0; 1186 int uids[]; 1187 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1188 synchronized (mPackages) { 1189 if (mPendingBroadcasts == null) { 1190 return; 1191 } 1192 size = mPendingBroadcasts.size(); 1193 if (size <= 0) { 1194 // Nothing to be done. Just return 1195 return; 1196 } 1197 packages = new String[size]; 1198 components = new ArrayList[size]; 1199 uids = new int[size]; 1200 int i = 0; // filling out the above arrays 1201 1202 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1203 int packageUserId = mPendingBroadcasts.userIdAt(n); 1204 Iterator<Map.Entry<String, ArrayList<String>>> it 1205 = mPendingBroadcasts.packagesForUserId(packageUserId) 1206 .entrySet().iterator(); 1207 while (it.hasNext() && i < size) { 1208 Map.Entry<String, ArrayList<String>> ent = it.next(); 1209 packages[i] = ent.getKey(); 1210 components[i] = ent.getValue(); 1211 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1212 uids[i] = (ps != null) 1213 ? UserHandle.getUid(packageUserId, ps.appId) 1214 : -1; 1215 i++; 1216 } 1217 } 1218 size = i; 1219 mPendingBroadcasts.clear(); 1220 } 1221 // Send broadcasts 1222 for (int i = 0; i < size; i++) { 1223 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1224 } 1225 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1226 break; 1227 } 1228 case START_CLEANING_PACKAGE: { 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1230 final String packageName = (String)msg.obj; 1231 final int userId = msg.arg1; 1232 final boolean andCode = msg.arg2 != 0; 1233 synchronized (mPackages) { 1234 if (userId == UserHandle.USER_ALL) { 1235 int[] users = sUserManager.getUserIds(); 1236 for (int user : users) { 1237 mSettings.addPackageToCleanLPw( 1238 new PackageCleanItem(user, packageName, andCode)); 1239 } 1240 } else { 1241 mSettings.addPackageToCleanLPw( 1242 new PackageCleanItem(userId, packageName, andCode)); 1243 } 1244 } 1245 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1246 startCleaningPackages(); 1247 } break; 1248 case POST_INSTALL: { 1249 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1250 PostInstallData data = mRunningInstalls.get(msg.arg1); 1251 mRunningInstalls.delete(msg.arg1); 1252 boolean deleteOld = false; 1253 1254 if (data != null) { 1255 InstallArgs args = data.args; 1256 PackageInstalledInfo res = data.res; 1257 1258 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1259 res.removedInfo.sendBroadcast(false, true, false); 1260 Bundle extras = new Bundle(1); 1261 extras.putInt(Intent.EXTRA_UID, res.uid); 1262 1263 // Now that we successfully installed the package, grant runtime 1264 // permissions if requested before broadcasting the install. 1265 if ((args.installFlags 1266 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1267 grantRequestedRuntimePermissions(res.pkg, 1268 args.user.getIdentifier()); 1269 } 1270 1271 // Determine the set of users who are adding this 1272 // package for the first time vs. those who are seeing 1273 // an update. 1274 int[] firstUsers; 1275 int[] updateUsers = new int[0]; 1276 if (res.origUsers == null || res.origUsers.length == 0) { 1277 firstUsers = res.newUsers; 1278 } else { 1279 firstUsers = new int[0]; 1280 for (int i=0; i<res.newUsers.length; i++) { 1281 int user = res.newUsers[i]; 1282 boolean isNew = true; 1283 for (int j=0; j<res.origUsers.length; j++) { 1284 if (res.origUsers[j] == user) { 1285 isNew = false; 1286 break; 1287 } 1288 } 1289 if (isNew) { 1290 int[] newFirst = new int[firstUsers.length+1]; 1291 System.arraycopy(firstUsers, 0, newFirst, 0, 1292 firstUsers.length); 1293 newFirst[firstUsers.length] = user; 1294 firstUsers = newFirst; 1295 } else { 1296 int[] newUpdate = new int[updateUsers.length+1]; 1297 System.arraycopy(updateUsers, 0, newUpdate, 0, 1298 updateUsers.length); 1299 newUpdate[updateUsers.length] = user; 1300 updateUsers = newUpdate; 1301 } 1302 } 1303 } 1304 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1305 res.pkg.applicationInfo.packageName, 1306 extras, null, null, firstUsers); 1307 final boolean update = res.removedInfo.removedPackage != null; 1308 if (update) { 1309 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1310 } 1311 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1312 res.pkg.applicationInfo.packageName, 1313 extras, null, null, updateUsers); 1314 if (update) { 1315 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1316 res.pkg.applicationInfo.packageName, 1317 extras, null, null, updateUsers); 1318 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1319 null, null, 1320 res.pkg.applicationInfo.packageName, null, updateUsers); 1321 1322 // treat asec-hosted packages like removable media on upgrade 1323 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1324 if (DEBUG_INSTALL) { 1325 Slog.i(TAG, "upgrading pkg " + res.pkg 1326 + " is ASEC-hosted -> AVAILABLE"); 1327 } 1328 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1329 ArrayList<String> pkgList = new ArrayList<String>(1); 1330 pkgList.add(res.pkg.applicationInfo.packageName); 1331 sendResourcesChangedBroadcast(true, true, 1332 pkgList,uidArray, null); 1333 } 1334 } 1335 if (res.removedInfo.args != null) { 1336 // Remove the replaced package's older resources safely now 1337 deleteOld = true; 1338 } 1339 1340 // Log current value of "unknown sources" setting 1341 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1342 getUnknownSourcesSettings()); 1343 } 1344 // Force a gc to clear up things 1345 Runtime.getRuntime().gc(); 1346 // We delete after a gc for applications on sdcard. 1347 if (deleteOld) { 1348 synchronized (mInstallLock) { 1349 res.removedInfo.args.doPostDeleteLI(true); 1350 } 1351 } 1352 if (args.observer != null) { 1353 try { 1354 Bundle extras = extrasForInstallResult(res); 1355 args.observer.onPackageInstalled(res.name, res.returnCode, 1356 res.returnMsg, extras); 1357 } catch (RemoteException e) { 1358 Slog.i(TAG, "Observer no longer exists."); 1359 } 1360 } 1361 } else { 1362 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1363 } 1364 } break; 1365 case UPDATED_MEDIA_STATUS: { 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1367 boolean reportStatus = msg.arg1 == 1; 1368 boolean doGc = msg.arg2 == 1; 1369 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1370 if (doGc) { 1371 // Force a gc to clear up stale containers. 1372 Runtime.getRuntime().gc(); 1373 } 1374 if (msg.obj != null) { 1375 @SuppressWarnings("unchecked") 1376 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1377 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1378 // Unload containers 1379 unloadAllContainers(args); 1380 } 1381 if (reportStatus) { 1382 try { 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1384 PackageHelper.getMountService().finishMediaUpdate(); 1385 } catch (RemoteException e) { 1386 Log.e(TAG, "MountService not running?"); 1387 } 1388 } 1389 } break; 1390 case WRITE_SETTINGS: { 1391 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1392 synchronized (mPackages) { 1393 removeMessages(WRITE_SETTINGS); 1394 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1395 mSettings.writeLPr(); 1396 mDirtyUsers.clear(); 1397 } 1398 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1399 } break; 1400 case WRITE_PACKAGE_RESTRICTIONS: { 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 synchronized (mPackages) { 1403 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1404 for (int userId : mDirtyUsers) { 1405 mSettings.writePackageRestrictionsLPr(userId); 1406 } 1407 mDirtyUsers.clear(); 1408 } 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1410 } break; 1411 case CHECK_PENDING_VERIFICATION: { 1412 final int verificationId = msg.arg1; 1413 final PackageVerificationState state = mPendingVerification.get(verificationId); 1414 1415 if ((state != null) && !state.timeoutExtended()) { 1416 final InstallArgs args = state.getInstallArgs(); 1417 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1418 1419 Slog.i(TAG, "Verification timed out for " + originUri); 1420 mPendingVerification.remove(verificationId); 1421 1422 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1423 1424 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1425 Slog.i(TAG, "Continuing with installation of " + originUri); 1426 state.setVerifierResponse(Binder.getCallingUid(), 1427 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1428 broadcastPackageVerified(verificationId, originUri, 1429 PackageManager.VERIFICATION_ALLOW, 1430 state.getInstallArgs().getUser()); 1431 try { 1432 ret = args.copyApk(mContainerService, true); 1433 } catch (RemoteException e) { 1434 Slog.e(TAG, "Could not contact the ContainerService"); 1435 } 1436 } else { 1437 broadcastPackageVerified(verificationId, originUri, 1438 PackageManager.VERIFICATION_REJECT, 1439 state.getInstallArgs().getUser()); 1440 } 1441 1442 processPendingInstall(args, ret); 1443 mHandler.sendEmptyMessage(MCS_UNBIND); 1444 } 1445 break; 1446 } 1447 case PACKAGE_VERIFIED: { 1448 final int verificationId = msg.arg1; 1449 1450 final PackageVerificationState state = mPendingVerification.get(verificationId); 1451 if (state == null) { 1452 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1453 break; 1454 } 1455 1456 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1457 1458 state.setVerifierResponse(response.callerUid, response.code); 1459 1460 if (state.isVerificationComplete()) { 1461 mPendingVerification.remove(verificationId); 1462 1463 final InstallArgs args = state.getInstallArgs(); 1464 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1465 1466 int ret; 1467 if (state.isInstallAllowed()) { 1468 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1469 broadcastPackageVerified(verificationId, originUri, 1470 response.code, state.getInstallArgs().getUser()); 1471 try { 1472 ret = args.copyApk(mContainerService, true); 1473 } catch (RemoteException e) { 1474 Slog.e(TAG, "Could not contact the ContainerService"); 1475 } 1476 } else { 1477 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1478 } 1479 1480 processPendingInstall(args, ret); 1481 1482 mHandler.sendEmptyMessage(MCS_UNBIND); 1483 } 1484 1485 break; 1486 } 1487 case START_INTENT_FILTER_VERIFICATIONS: { 1488 int userId = msg.arg1; 1489 int verifierUid = msg.arg2; 1490 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1491 1492 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1493 break; 1494 } 1495 case INTENT_FILTER_VERIFIED: { 1496 final int verificationId = msg.arg1; 1497 1498 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1499 verificationId); 1500 if (state == null) { 1501 Slog.w(TAG, "Invalid IntentFilter verification token " 1502 + verificationId + " received"); 1503 break; 1504 } 1505 1506 final int userId = state.getUserId(); 1507 1508 Slog.d(TAG, "Processing IntentFilter verification with token:" 1509 + verificationId + " and userId:" + userId); 1510 1511 final IntentFilterVerificationResponse response = 1512 (IntentFilterVerificationResponse) msg.obj; 1513 1514 state.setVerifierResponse(response.callerUid, response.code); 1515 1516 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1517 + " and userId:" + userId 1518 + " is settings verifier response with response code:" 1519 + response.code); 1520 1521 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1522 Slog.d(TAG, "Domains failing verification: " 1523 + response.getFailedDomainsString()); 1524 } 1525 1526 if (state.isVerificationComplete()) { 1527 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1528 } else { 1529 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1530 + " was not said to be complete"); 1531 } 1532 1533 break; 1534 } 1535 } 1536 } 1537 } 1538 1539 private StorageEventListener mStorageListener = new StorageEventListener() { 1540 @Override 1541 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1542 Slog.v(TAG, vol.toString()); 1543 1544 // TODO: when private volume shows up, look for packages there too 1545 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1546 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1547 updateExternalMediaStatus(true, false); 1548 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1549 updateExternalMediaStatus(false, false); 1550 } 1551 } 1552 } 1553 }; 1554 1555 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1556 if (userId >= UserHandle.USER_OWNER) { 1557 grantRequestedRuntimePermissionsForUser(pkg, userId); 1558 } else if (userId == UserHandle.USER_ALL) { 1559 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1560 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1561 } 1562 } 1563 } 1564 1565 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1566 SettingBase sb = (SettingBase) pkg.mExtras; 1567 if (sb == null) { 1568 return; 1569 } 1570 1571 PermissionsState permissionsState = sb.getPermissionsState(); 1572 1573 for (String permission : pkg.requestedPermissions) { 1574 BasePermission bp = mSettings.mPermissions.get(permission); 1575 if (bp != null && bp.isRuntime()) { 1576 permissionsState.grantRuntimePermission(bp, userId); 1577 } 1578 } 1579 } 1580 1581 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1582 Bundle extras = null; 1583 switch (res.returnCode) { 1584 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1585 extras = new Bundle(); 1586 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1587 res.origPermission); 1588 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1589 res.origPackage); 1590 break; 1591 } 1592 } 1593 return extras; 1594 } 1595 1596 void scheduleWriteSettingsLocked() { 1597 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1598 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1599 } 1600 } 1601 1602 void scheduleWritePackageRestrictionsLocked(int userId) { 1603 if (!sUserManager.exists(userId)) return; 1604 mDirtyUsers.add(userId); 1605 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1606 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1607 } 1608 } 1609 1610 public static PackageManagerService main(Context context, Installer installer, 1611 boolean factoryTest, boolean onlyCore) { 1612 PackageManagerService m = new PackageManagerService(context, installer, 1613 factoryTest, onlyCore); 1614 ServiceManager.addService("package", m); 1615 return m; 1616 } 1617 1618 static String[] splitString(String str, char sep) { 1619 int count = 1; 1620 int i = 0; 1621 while ((i=str.indexOf(sep, i)) >= 0) { 1622 count++; 1623 i++; 1624 } 1625 1626 String[] res = new String[count]; 1627 i=0; 1628 count = 0; 1629 int lastI=0; 1630 while ((i=str.indexOf(sep, i)) >= 0) { 1631 res[count] = str.substring(lastI, i); 1632 count++; 1633 i++; 1634 lastI = i; 1635 } 1636 res[count] = str.substring(lastI, str.length()); 1637 return res; 1638 } 1639 1640 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1641 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1642 Context.DISPLAY_SERVICE); 1643 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1644 } 1645 1646 public PackageManagerService(Context context, Installer installer, 1647 boolean factoryTest, boolean onlyCore) { 1648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1649 SystemClock.uptimeMillis()); 1650 1651 if (mSdkVersion <= 0) { 1652 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1653 } 1654 1655 mContext = context; 1656 mFactoryTest = factoryTest; 1657 mOnlyCore = onlyCore; 1658 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1659 mMetrics = new DisplayMetrics(); 1660 mSettings = new Settings(mPackages); 1661 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1662 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1663 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1664 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1665 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1666 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1667 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1668 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1669 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1670 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1671 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 1674 // TODO: add a property to control this? 1675 long dexOptLRUThresholdInMinutes; 1676 if (mLazyDexOpt) { 1677 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1678 } else { 1679 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1680 } 1681 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1682 1683 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1684 if (separateProcesses != null && separateProcesses.length() > 0) { 1685 if ("*".equals(separateProcesses)) { 1686 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1687 mSeparateProcesses = null; 1688 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1689 } else { 1690 mDefParseFlags = 0; 1691 mSeparateProcesses = separateProcesses.split(","); 1692 Slog.w(TAG, "Running with debug.separate_processes: " 1693 + separateProcesses); 1694 } 1695 } else { 1696 mDefParseFlags = 0; 1697 mSeparateProcesses = null; 1698 } 1699 1700 mInstaller = installer; 1701 mPackageDexOptimizer = new PackageDexOptimizer(this); 1702 1703 getDefaultDisplayMetrics(context, mMetrics); 1704 1705 SystemConfig systemConfig = SystemConfig.getInstance(); 1706 mGlobalGids = systemConfig.getGlobalGids(); 1707 mSystemPermissions = systemConfig.getSystemPermissions(); 1708 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1709 1710 synchronized (mInstallLock) { 1711 // writer 1712 synchronized (mPackages) { 1713 mHandlerThread = new ServiceThread(TAG, 1714 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1715 mHandlerThread.start(); 1716 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1717 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1718 1719 File dataDir = Environment.getDataDirectory(); 1720 mAppDataDir = new File(dataDir, "data"); 1721 mAppInstallDir = new File(dataDir, "app"); 1722 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1723 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1724 mUserAppDataDir = new File(dataDir, "user"); 1725 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1726 1727 sUserManager = new UserManagerService(context, this, 1728 mInstallLock, mPackages); 1729 1730 // Propagate permission configuration in to package manager. 1731 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1732 = systemConfig.getPermissions(); 1733 for (int i=0; i<permConfig.size(); i++) { 1734 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1735 BasePermission bp = mSettings.mPermissions.get(perm.name); 1736 if (bp == null) { 1737 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1738 mSettings.mPermissions.put(perm.name, bp); 1739 } 1740 if (perm.gids != null) { 1741 bp.setGids(perm.gids, perm.perUser); 1742 } 1743 } 1744 1745 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1746 for (int i=0; i<libConfig.size(); i++) { 1747 mSharedLibraries.put(libConfig.keyAt(i), 1748 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1749 } 1750 1751 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1752 1753 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1754 mSdkVersion, mOnlyCore); 1755 1756 String customResolverActivity = Resources.getSystem().getString( 1757 R.string.config_customResolverActivity); 1758 if (TextUtils.isEmpty(customResolverActivity)) { 1759 customResolverActivity = null; 1760 } else { 1761 mCustomResolverComponentName = ComponentName.unflattenFromString( 1762 customResolverActivity); 1763 } 1764 1765 long startTime = SystemClock.uptimeMillis(); 1766 1767 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1768 startTime); 1769 1770 // Set flag to monitor and not change apk file paths when 1771 // scanning install directories. 1772 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1773 1774 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1775 1776 /** 1777 * Add everything in the in the boot class path to the 1778 * list of process files because dexopt will have been run 1779 * if necessary during zygote startup. 1780 */ 1781 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1782 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1783 1784 if (bootClassPath != null) { 1785 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1786 for (String element : bootClassPathElements) { 1787 alreadyDexOpted.add(element); 1788 } 1789 } else { 1790 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1791 } 1792 1793 if (systemServerClassPath != null) { 1794 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1795 for (String element : systemServerClassPathElements) { 1796 alreadyDexOpted.add(element); 1797 } 1798 } else { 1799 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1800 } 1801 1802 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1803 final String[] dexCodeInstructionSets = 1804 getDexCodeInstructionSets( 1805 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1806 1807 /** 1808 * Ensure all external libraries have had dexopt run on them. 1809 */ 1810 if (mSharedLibraries.size() > 0) { 1811 // NOTE: For now, we're compiling these system "shared libraries" 1812 // (and framework jars) into all available architectures. It's possible 1813 // to compile them only when we come across an app that uses them (there's 1814 // already logic for that in scanPackageLI) but that adds some complexity. 1815 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1816 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1817 final String lib = libEntry.path; 1818 if (lib == null) { 1819 continue; 1820 } 1821 1822 try { 1823 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1824 dexCodeInstructionSet, 1825 false); 1826 if (dexoptRequired != DexFile.UP_TO_DATE) { 1827 alreadyDexOpted.add(lib); 1828 1829 // The list of "shared libraries" we have at this point is 1830 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1831 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1832 } else { 1833 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1834 } 1835 } 1836 } catch (FileNotFoundException e) { 1837 Slog.w(TAG, "Library not found: " + lib); 1838 } catch (IOException e) { 1839 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1840 + e.getMessage()); 1841 } 1842 } 1843 } 1844 } 1845 1846 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1847 1848 // Gross hack for now: we know this file doesn't contain any 1849 // code, so don't dexopt it to avoid the resulting log spew. 1850 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1851 1852 // Gross hack for now: we know this file is only part of 1853 // the boot class path for art, so don't dexopt it to 1854 // avoid the resulting log spew. 1855 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1856 1857 /** 1858 * And there are a number of commands implemented in Java, which 1859 * we currently need to do the dexopt on so that they can be 1860 * run from a non-root shell. 1861 */ 1862 String[] frameworkFiles = frameworkDir.list(); 1863 if (frameworkFiles != null) { 1864 // TODO: We could compile these only for the most preferred ABI. We should 1865 // first double check that the dex files for these commands are not referenced 1866 // by other system apps. 1867 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1868 for (int i=0; i<frameworkFiles.length; i++) { 1869 File libPath = new File(frameworkDir, frameworkFiles[i]); 1870 String path = libPath.getPath(); 1871 // Skip the file if we already did it. 1872 if (alreadyDexOpted.contains(path)) { 1873 continue; 1874 } 1875 // Skip the file if it is not a type we want to dexopt. 1876 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1877 continue; 1878 } 1879 try { 1880 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1881 dexCodeInstructionSet, 1882 false); 1883 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1884 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1885 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1886 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1887 } 1888 } catch (FileNotFoundException e) { 1889 Slog.w(TAG, "Jar not found: " + path); 1890 } catch (IOException e) { 1891 Slog.w(TAG, "Exception reading jar: " + path, e); 1892 } 1893 } 1894 } 1895 } 1896 1897 // Collect vendor overlay packages. 1898 // (Do this before scanning any apps.) 1899 // For security and version matching reason, only consider 1900 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1901 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1902 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1903 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1904 1905 // Find base frameworks (resource packages without code). 1906 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1907 | PackageParser.PARSE_IS_SYSTEM_DIR 1908 | PackageParser.PARSE_IS_PRIVILEGED, 1909 scanFlags | SCAN_NO_DEX, 0); 1910 1911 // Collected privileged system packages. 1912 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1913 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1914 | PackageParser.PARSE_IS_SYSTEM_DIR 1915 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1916 1917 // Collect ordinary system packages. 1918 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1919 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1920 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1921 1922 // Collect all vendor packages. 1923 File vendorAppDir = new File("/vendor/app"); 1924 try { 1925 vendorAppDir = vendorAppDir.getCanonicalFile(); 1926 } catch (IOException e) { 1927 // failed to look up canonical path, continue with original one 1928 } 1929 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1931 1932 // Collect all OEM packages. 1933 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1934 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1935 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1936 1937 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1938 mInstaller.moveFiles(); 1939 1940 // Prune any system packages that no longer exist. 1941 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1942 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1943 if (!mOnlyCore) { 1944 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1945 while (psit.hasNext()) { 1946 PackageSetting ps = psit.next(); 1947 1948 /* 1949 * If this is not a system app, it can't be a 1950 * disable system app. 1951 */ 1952 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1953 continue; 1954 } 1955 1956 /* 1957 * If the package is scanned, it's not erased. 1958 */ 1959 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1960 if (scannedPkg != null) { 1961 /* 1962 * If the system app is both scanned and in the 1963 * disabled packages list, then it must have been 1964 * added via OTA. Remove it from the currently 1965 * scanned package so the previously user-installed 1966 * application can be scanned. 1967 */ 1968 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1969 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1970 + ps.name + "; removing system app. Last known codePath=" 1971 + ps.codePathString + ", installStatus=" + ps.installStatus 1972 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1973 + scannedPkg.mVersionCode); 1974 removePackageLI(ps, true); 1975 expectingBetter.put(ps.name, ps.codePath); 1976 } 1977 1978 continue; 1979 } 1980 1981 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1982 psit.remove(); 1983 logCriticalInfo(Log.WARN, "System package " + ps.name 1984 + " no longer exists; wiping its data"); 1985 removeDataDirsLI(ps.name); 1986 } else { 1987 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1988 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1989 possiblyDeletedUpdatedSystemApps.add(ps.name); 1990 } 1991 } 1992 } 1993 } 1994 1995 //look for any incomplete package installations 1996 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1997 //clean up list 1998 for(int i = 0; i < deletePkgsList.size(); i++) { 1999 //clean up here 2000 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2001 } 2002 //delete tmp files 2003 deleteTempPackageFiles(); 2004 2005 // Remove any shared userIDs that have no associated packages 2006 mSettings.pruneSharedUsersLPw(); 2007 2008 if (!mOnlyCore) { 2009 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2010 SystemClock.uptimeMillis()); 2011 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2012 2013 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2014 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2015 2016 /** 2017 * Remove disable package settings for any updated system 2018 * apps that were removed via an OTA. If they're not a 2019 * previously-updated app, remove them completely. 2020 * Otherwise, just revoke their system-level permissions. 2021 */ 2022 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2023 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2024 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2025 2026 String msg; 2027 if (deletedPkg == null) { 2028 msg = "Updated system package " + deletedAppName 2029 + " no longer exists; wiping its data"; 2030 removeDataDirsLI(deletedAppName); 2031 } else { 2032 msg = "Updated system app + " + deletedAppName 2033 + " no longer present; removing system privileges for " 2034 + deletedAppName; 2035 2036 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2037 2038 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2039 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2040 } 2041 logCriticalInfo(Log.WARN, msg); 2042 } 2043 2044 /** 2045 * Make sure all system apps that we expected to appear on 2046 * the userdata partition actually showed up. If they never 2047 * appeared, crawl back and revive the system version. 2048 */ 2049 for (int i = 0; i < expectingBetter.size(); i++) { 2050 final String packageName = expectingBetter.keyAt(i); 2051 if (!mPackages.containsKey(packageName)) { 2052 final File scanFile = expectingBetter.valueAt(i); 2053 2054 logCriticalInfo(Log.WARN, "Expected better " + packageName 2055 + " but never showed up; reverting to system"); 2056 2057 final int reparseFlags; 2058 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2059 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2060 | PackageParser.PARSE_IS_SYSTEM_DIR 2061 | PackageParser.PARSE_IS_PRIVILEGED; 2062 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2063 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR; 2065 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2066 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR; 2068 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2069 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2070 | PackageParser.PARSE_IS_SYSTEM_DIR; 2071 } else { 2072 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2073 continue; 2074 } 2075 2076 mSettings.enableSystemPackageLPw(packageName); 2077 2078 try { 2079 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2080 } catch (PackageManagerException e) { 2081 Slog.e(TAG, "Failed to parse original system package: " 2082 + e.getMessage()); 2083 } 2084 } 2085 } 2086 } 2087 2088 // Now that we know all of the shared libraries, update all clients to have 2089 // the correct library paths. 2090 updateAllSharedLibrariesLPw(); 2091 2092 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2093 // NOTE: We ignore potential failures here during a system scan (like 2094 // the rest of the commands above) because there's precious little we 2095 // can do about it. A settings error is reported, though. 2096 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2097 false /* force dexopt */, false /* defer dexopt */); 2098 } 2099 2100 // Now that we know all the packages we are keeping, 2101 // read and update their last usage times. 2102 mPackageUsage.readLP(); 2103 2104 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2105 SystemClock.uptimeMillis()); 2106 Slog.i(TAG, "Time to scan packages: " 2107 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2108 + " seconds"); 2109 2110 // If the platform SDK has changed since the last time we booted, 2111 // we need to re-grant app permission to catch any new ones that 2112 // appear. This is really a hack, and means that apps can in some 2113 // cases get permissions that the user didn't initially explicitly 2114 // allow... it would be nice to have some better way to handle 2115 // this situation. 2116 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2117 != mSdkVersion; 2118 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2119 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2120 + "; regranting permissions for internal storage"); 2121 mSettings.mInternalSdkPlatform = mSdkVersion; 2122 2123 // For now runtime permissions are toggled via a system property. 2124 if (!RUNTIME_PERMISSIONS_ENABLED) { 2125 // Remove the runtime permissions state if the feature 2126 // was disabled by flipping the system property. 2127 mSettings.deleteRuntimePermissionsFiles(); 2128 } 2129 2130 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2131 | (regrantPermissions 2132 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2133 : 0)); 2134 2135 // If this is the first boot, and it is a normal boot, then 2136 // we need to initialize the default preferred apps. 2137 if (!mRestoredSettings && !onlyCore) { 2138 mSettings.readDefaultPreferredAppsLPw(this, 0); 2139 } 2140 2141 // If this is first boot after an OTA, and a normal boot, then 2142 // we need to clear code cache directories. 2143 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2144 if (mIsUpgrade && !onlyCore) { 2145 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2146 for (String pkgName : mSettings.mPackages.keySet()) { 2147 deleteCodeCacheDirsLI(pkgName); 2148 } 2149 mSettings.mFingerprint = Build.FINGERPRINT; 2150 } 2151 2152 // All the changes are done during package scanning. 2153 mSettings.updateInternalDatabaseVersion(); 2154 2155 // can downgrade to reader 2156 mSettings.writeLPr(); 2157 2158 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2159 SystemClock.uptimeMillis()); 2160 2161 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2162 2163 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 2164 2165 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2166 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2167 mIntentFilterVerifierComponent); 2168 2169 } // synchronized (mPackages) 2170 } // synchronized (mInstallLock) 2171 2172 // Now after opening every single application zip, make sure they 2173 // are all flushed. Not really needed, but keeps things nice and 2174 // tidy. 2175 Runtime.getRuntime().gc(); 2176 } 2177 2178 @Override 2179 public boolean isFirstBoot() { 2180 return !mRestoredSettings; 2181 } 2182 2183 @Override 2184 public boolean isOnlyCoreApps() { 2185 return mOnlyCore; 2186 } 2187 2188 @Override 2189 public boolean isUpgrade() { 2190 return mIsUpgrade; 2191 } 2192 2193 private String getRequiredVerifierLPr() { 2194 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2195 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2196 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2197 2198 String requiredVerifier = null; 2199 2200 final int N = receivers.size(); 2201 for (int i = 0; i < N; i++) { 2202 final ResolveInfo info = receivers.get(i); 2203 2204 if (info.activityInfo == null) { 2205 continue; 2206 } 2207 2208 final String packageName = info.activityInfo.packageName; 2209 2210 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2211 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2212 continue; 2213 } 2214 2215 if (requiredVerifier != null) { 2216 throw new RuntimeException("There can be only one required verifier"); 2217 } 2218 2219 requiredVerifier = packageName; 2220 } 2221 2222 return requiredVerifier; 2223 } 2224 2225 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2226 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2227 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2228 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2229 2230 ComponentName verifierComponentName = null; 2231 2232 int priority = -1000; 2233 final int N = receivers.size(); 2234 for (int i = 0; i < N; i++) { 2235 final ResolveInfo info = receivers.get(i); 2236 2237 if (info.activityInfo == null) { 2238 continue; 2239 } 2240 2241 final String packageName = info.activityInfo.packageName; 2242 2243 final PackageSetting ps = mSettings.mPackages.get(packageName); 2244 if (ps == null) { 2245 continue; 2246 } 2247 2248 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2249 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2250 continue; 2251 } 2252 2253 // Select the IntentFilterVerifier with the highest priority 2254 if (priority < info.priority) { 2255 priority = info.priority; 2256 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2257 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2258 " with priority: " + info.priority); 2259 } 2260 } 2261 2262 return verifierComponentName; 2263 } 2264 2265 @Override 2266 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2267 throws RemoteException { 2268 try { 2269 return super.onTransact(code, data, reply, flags); 2270 } catch (RuntimeException e) { 2271 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2272 Slog.wtf(TAG, "Package Manager Crash", e); 2273 } 2274 throw e; 2275 } 2276 } 2277 2278 void cleanupInstallFailedPackage(PackageSetting ps) { 2279 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2280 2281 removeDataDirsLI(ps.name); 2282 if (ps.codePath != null) { 2283 if (ps.codePath.isDirectory()) { 2284 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2285 } else { 2286 ps.codePath.delete(); 2287 } 2288 } 2289 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2290 if (ps.resourcePath.isDirectory()) { 2291 FileUtils.deleteContents(ps.resourcePath); 2292 } 2293 ps.resourcePath.delete(); 2294 } 2295 mSettings.removePackageLPw(ps.name); 2296 } 2297 2298 static int[] appendInts(int[] cur, int[] add) { 2299 if (add == null) return cur; 2300 if (cur == null) return add; 2301 final int N = add.length; 2302 for (int i=0; i<N; i++) { 2303 cur = appendInt(cur, add[i]); 2304 } 2305 return cur; 2306 } 2307 2308 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2309 if (!sUserManager.exists(userId)) return null; 2310 final PackageSetting ps = (PackageSetting) p.mExtras; 2311 if (ps == null) { 2312 return null; 2313 } 2314 2315 final PermissionsState permissionsState = ps.getPermissionsState(); 2316 2317 final int[] gids = permissionsState.computeGids(userId); 2318 final Set<String> permissions = permissionsState.getPermissions(userId); 2319 final PackageUserState state = ps.readUserState(userId); 2320 2321 return PackageParser.generatePackageInfo(p, gids, flags, 2322 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2323 } 2324 2325 @Override 2326 public boolean isPackageAvailable(String packageName, int userId) { 2327 if (!sUserManager.exists(userId)) return false; 2328 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2329 synchronized (mPackages) { 2330 PackageParser.Package p = mPackages.get(packageName); 2331 if (p != null) { 2332 final PackageSetting ps = (PackageSetting) p.mExtras; 2333 if (ps != null) { 2334 final PackageUserState state = ps.readUserState(userId); 2335 if (state != null) { 2336 return PackageParser.isAvailable(state); 2337 } 2338 } 2339 } 2340 } 2341 return false; 2342 } 2343 2344 @Override 2345 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2346 if (!sUserManager.exists(userId)) return null; 2347 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2348 // reader 2349 synchronized (mPackages) { 2350 PackageParser.Package p = mPackages.get(packageName); 2351 if (DEBUG_PACKAGE_INFO) 2352 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2353 if (p != null) { 2354 return generatePackageInfo(p, flags, userId); 2355 } 2356 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2357 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2358 } 2359 } 2360 return null; 2361 } 2362 2363 @Override 2364 public String[] currentToCanonicalPackageNames(String[] names) { 2365 String[] out = new String[names.length]; 2366 // reader 2367 synchronized (mPackages) { 2368 for (int i=names.length-1; i>=0; i--) { 2369 PackageSetting ps = mSettings.mPackages.get(names[i]); 2370 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2371 } 2372 } 2373 return out; 2374 } 2375 2376 @Override 2377 public String[] canonicalToCurrentPackageNames(String[] names) { 2378 String[] out = new String[names.length]; 2379 // reader 2380 synchronized (mPackages) { 2381 for (int i=names.length-1; i>=0; i--) { 2382 String cur = mSettings.mRenamedPackages.get(names[i]); 2383 out[i] = cur != null ? cur : names[i]; 2384 } 2385 } 2386 return out; 2387 } 2388 2389 @Override 2390 public int getPackageUid(String packageName, int userId) { 2391 if (!sUserManager.exists(userId)) return -1; 2392 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2393 2394 // reader 2395 synchronized (mPackages) { 2396 PackageParser.Package p = mPackages.get(packageName); 2397 if(p != null) { 2398 return UserHandle.getUid(userId, p.applicationInfo.uid); 2399 } 2400 PackageSetting ps = mSettings.mPackages.get(packageName); 2401 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2402 return -1; 2403 } 2404 p = ps.pkg; 2405 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2406 } 2407 } 2408 2409 @Override 2410 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2411 if (!sUserManager.exists(userId)) { 2412 return null; 2413 } 2414 2415 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2416 "getPackageGids"); 2417 2418 // reader 2419 synchronized (mPackages) { 2420 PackageParser.Package p = mPackages.get(packageName); 2421 if (DEBUG_PACKAGE_INFO) { 2422 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2423 } 2424 if (p != null) { 2425 PackageSetting ps = (PackageSetting) p.mExtras; 2426 return ps.getPermissionsState().computeGids(userId); 2427 } 2428 } 2429 2430 return null; 2431 } 2432 2433 static PermissionInfo generatePermissionInfo( 2434 BasePermission bp, int flags) { 2435 if (bp.perm != null) { 2436 return PackageParser.generatePermissionInfo(bp.perm, flags); 2437 } 2438 PermissionInfo pi = new PermissionInfo(); 2439 pi.name = bp.name; 2440 pi.packageName = bp.sourcePackage; 2441 pi.nonLocalizedLabel = bp.name; 2442 pi.protectionLevel = bp.protectionLevel; 2443 return pi; 2444 } 2445 2446 @Override 2447 public PermissionInfo getPermissionInfo(String name, int flags) { 2448 // reader 2449 synchronized (mPackages) { 2450 final BasePermission p = mSettings.mPermissions.get(name); 2451 if (p != null) { 2452 return generatePermissionInfo(p, flags); 2453 } 2454 return null; 2455 } 2456 } 2457 2458 @Override 2459 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2460 // reader 2461 synchronized (mPackages) { 2462 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2463 for (BasePermission p : mSettings.mPermissions.values()) { 2464 if (group == null) { 2465 if (p.perm == null || p.perm.info.group == null) { 2466 out.add(generatePermissionInfo(p, flags)); 2467 } 2468 } else { 2469 if (p.perm != null && group.equals(p.perm.info.group)) { 2470 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2471 } 2472 } 2473 } 2474 2475 if (out.size() > 0) { 2476 return out; 2477 } 2478 return mPermissionGroups.containsKey(group) ? out : null; 2479 } 2480 } 2481 2482 @Override 2483 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2484 // reader 2485 synchronized (mPackages) { 2486 return PackageParser.generatePermissionGroupInfo( 2487 mPermissionGroups.get(name), flags); 2488 } 2489 } 2490 2491 @Override 2492 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2493 // reader 2494 synchronized (mPackages) { 2495 final int N = mPermissionGroups.size(); 2496 ArrayList<PermissionGroupInfo> out 2497 = new ArrayList<PermissionGroupInfo>(N); 2498 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2499 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2500 } 2501 return out; 2502 } 2503 } 2504 2505 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2506 int userId) { 2507 if (!sUserManager.exists(userId)) return null; 2508 PackageSetting ps = mSettings.mPackages.get(packageName); 2509 if (ps != null) { 2510 if (ps.pkg == null) { 2511 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2512 flags, userId); 2513 if (pInfo != null) { 2514 return pInfo.applicationInfo; 2515 } 2516 return null; 2517 } 2518 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2519 ps.readUserState(userId), userId); 2520 } 2521 return null; 2522 } 2523 2524 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2525 int userId) { 2526 if (!sUserManager.exists(userId)) return null; 2527 PackageSetting ps = mSettings.mPackages.get(packageName); 2528 if (ps != null) { 2529 PackageParser.Package pkg = ps.pkg; 2530 if (pkg == null) { 2531 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2532 return null; 2533 } 2534 // Only data remains, so we aren't worried about code paths 2535 pkg = new PackageParser.Package(packageName); 2536 pkg.applicationInfo.packageName = packageName; 2537 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2538 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2539 pkg.applicationInfo.dataDir = 2540 getDataPathForPackage(packageName, 0).getPath(); 2541 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2542 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2543 } 2544 return generatePackageInfo(pkg, flags, userId); 2545 } 2546 return null; 2547 } 2548 2549 @Override 2550 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2551 if (!sUserManager.exists(userId)) return null; 2552 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2553 // writer 2554 synchronized (mPackages) { 2555 PackageParser.Package p = mPackages.get(packageName); 2556 if (DEBUG_PACKAGE_INFO) Log.v( 2557 TAG, "getApplicationInfo " + packageName 2558 + ": " + p); 2559 if (p != null) { 2560 PackageSetting ps = mSettings.mPackages.get(packageName); 2561 if (ps == null) return null; 2562 // Note: isEnabledLP() does not apply here - always return info 2563 return PackageParser.generateApplicationInfo( 2564 p, flags, ps.readUserState(userId), userId); 2565 } 2566 if ("android".equals(packageName)||"system".equals(packageName)) { 2567 return mAndroidApplication; 2568 } 2569 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2570 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2571 } 2572 } 2573 return null; 2574 } 2575 2576 2577 @Override 2578 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2579 mContext.enforceCallingOrSelfPermission( 2580 android.Manifest.permission.CLEAR_APP_CACHE, null); 2581 // Queue up an async operation since clearing cache may take a little while. 2582 mHandler.post(new Runnable() { 2583 public void run() { 2584 mHandler.removeCallbacks(this); 2585 int retCode = -1; 2586 synchronized (mInstallLock) { 2587 retCode = mInstaller.freeCache(freeStorageSize); 2588 if (retCode < 0) { 2589 Slog.w(TAG, "Couldn't clear application caches"); 2590 } 2591 } 2592 if (observer != null) { 2593 try { 2594 observer.onRemoveCompleted(null, (retCode >= 0)); 2595 } catch (RemoteException e) { 2596 Slog.w(TAG, "RemoveException when invoking call back"); 2597 } 2598 } 2599 } 2600 }); 2601 } 2602 2603 @Override 2604 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2605 mContext.enforceCallingOrSelfPermission( 2606 android.Manifest.permission.CLEAR_APP_CACHE, null); 2607 // Queue up an async operation since clearing cache may take a little while. 2608 mHandler.post(new Runnable() { 2609 public void run() { 2610 mHandler.removeCallbacks(this); 2611 int retCode = -1; 2612 synchronized (mInstallLock) { 2613 retCode = mInstaller.freeCache(freeStorageSize); 2614 if (retCode < 0) { 2615 Slog.w(TAG, "Couldn't clear application caches"); 2616 } 2617 } 2618 if(pi != null) { 2619 try { 2620 // Callback via pending intent 2621 int code = (retCode >= 0) ? 1 : 0; 2622 pi.sendIntent(null, code, null, 2623 null, null); 2624 } catch (SendIntentException e1) { 2625 Slog.i(TAG, "Failed to send pending intent"); 2626 } 2627 } 2628 } 2629 }); 2630 } 2631 2632 void freeStorage(long freeStorageSize) throws IOException { 2633 synchronized (mInstallLock) { 2634 if (mInstaller.freeCache(freeStorageSize) < 0) { 2635 throw new IOException("Failed to free enough space"); 2636 } 2637 } 2638 } 2639 2640 @Override 2641 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2642 if (!sUserManager.exists(userId)) return null; 2643 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2644 synchronized (mPackages) { 2645 PackageParser.Activity a = mActivities.mActivities.get(component); 2646 2647 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2648 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2649 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2650 if (ps == null) return null; 2651 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2652 userId); 2653 } 2654 if (mResolveComponentName.equals(component)) { 2655 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2656 new PackageUserState(), userId); 2657 } 2658 } 2659 return null; 2660 } 2661 2662 @Override 2663 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2664 String resolvedType) { 2665 synchronized (mPackages) { 2666 PackageParser.Activity a = mActivities.mActivities.get(component); 2667 if (a == null) { 2668 return false; 2669 } 2670 for (int i=0; i<a.intents.size(); i++) { 2671 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2672 intent.getData(), intent.getCategories(), TAG) >= 0) { 2673 return true; 2674 } 2675 } 2676 return false; 2677 } 2678 } 2679 2680 @Override 2681 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2682 if (!sUserManager.exists(userId)) return null; 2683 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2684 synchronized (mPackages) { 2685 PackageParser.Activity a = mReceivers.mActivities.get(component); 2686 if (DEBUG_PACKAGE_INFO) Log.v( 2687 TAG, "getReceiverInfo " + component + ": " + a); 2688 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2689 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2690 if (ps == null) return null; 2691 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2692 userId); 2693 } 2694 } 2695 return null; 2696 } 2697 2698 @Override 2699 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2700 if (!sUserManager.exists(userId)) return null; 2701 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2702 synchronized (mPackages) { 2703 PackageParser.Service s = mServices.mServices.get(component); 2704 if (DEBUG_PACKAGE_INFO) Log.v( 2705 TAG, "getServiceInfo " + component + ": " + s); 2706 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2707 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2708 if (ps == null) return null; 2709 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2710 userId); 2711 } 2712 } 2713 return null; 2714 } 2715 2716 @Override 2717 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2718 if (!sUserManager.exists(userId)) return null; 2719 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2720 synchronized (mPackages) { 2721 PackageParser.Provider p = mProviders.mProviders.get(component); 2722 if (DEBUG_PACKAGE_INFO) Log.v( 2723 TAG, "getProviderInfo " + component + ": " + p); 2724 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2725 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2726 if (ps == null) return null; 2727 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2728 userId); 2729 } 2730 } 2731 return null; 2732 } 2733 2734 @Override 2735 public String[] getSystemSharedLibraryNames() { 2736 Set<String> libSet; 2737 synchronized (mPackages) { 2738 libSet = mSharedLibraries.keySet(); 2739 int size = libSet.size(); 2740 if (size > 0) { 2741 String[] libs = new String[size]; 2742 libSet.toArray(libs); 2743 return libs; 2744 } 2745 } 2746 return null; 2747 } 2748 2749 /** 2750 * @hide 2751 */ 2752 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2753 synchronized (mPackages) { 2754 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2755 if (lib != null && lib.apk != null) { 2756 return mPackages.get(lib.apk); 2757 } 2758 } 2759 return null; 2760 } 2761 2762 @Override 2763 public FeatureInfo[] getSystemAvailableFeatures() { 2764 Collection<FeatureInfo> featSet; 2765 synchronized (mPackages) { 2766 featSet = mAvailableFeatures.values(); 2767 int size = featSet.size(); 2768 if (size > 0) { 2769 FeatureInfo[] features = new FeatureInfo[size+1]; 2770 featSet.toArray(features); 2771 FeatureInfo fi = new FeatureInfo(); 2772 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2773 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2774 features[size] = fi; 2775 return features; 2776 } 2777 } 2778 return null; 2779 } 2780 2781 @Override 2782 public boolean hasSystemFeature(String name) { 2783 synchronized (mPackages) { 2784 return mAvailableFeatures.containsKey(name); 2785 } 2786 } 2787 2788 private void checkValidCaller(int uid, int userId) { 2789 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2790 return; 2791 2792 throw new SecurityException("Caller uid=" + uid 2793 + " is not privileged to communicate with user=" + userId); 2794 } 2795 2796 @Override 2797 public int checkPermission(String permName, String pkgName, int userId) { 2798 if (!sUserManager.exists(userId)) { 2799 return PackageManager.PERMISSION_DENIED; 2800 } 2801 2802 synchronized (mPackages) { 2803 final PackageParser.Package p = mPackages.get(pkgName); 2804 if (p != null && p.mExtras != null) { 2805 final PackageSetting ps = (PackageSetting) p.mExtras; 2806 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2807 return PackageManager.PERMISSION_GRANTED; 2808 } 2809 } 2810 } 2811 2812 return PackageManager.PERMISSION_DENIED; 2813 } 2814 2815 @Override 2816 public int checkUidPermission(String permName, int uid) { 2817 final int userId = UserHandle.getUserId(uid); 2818 2819 if (!sUserManager.exists(userId)) { 2820 return PackageManager.PERMISSION_DENIED; 2821 } 2822 2823 synchronized (mPackages) { 2824 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2825 if (obj != null) { 2826 final SettingBase ps = (SettingBase) obj; 2827 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2828 return PackageManager.PERMISSION_GRANTED; 2829 } 2830 } else { 2831 ArraySet<String> perms = mSystemPermissions.get(uid); 2832 if (perms != null && perms.contains(permName)) { 2833 return PackageManager.PERMISSION_GRANTED; 2834 } 2835 } 2836 } 2837 2838 return PackageManager.PERMISSION_DENIED; 2839 } 2840 2841 /** 2842 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2843 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2844 * @param checkShell TODO(yamasani): 2845 * @param message the message to log on security exception 2846 */ 2847 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2848 boolean checkShell, String message) { 2849 if (userId < 0) { 2850 throw new IllegalArgumentException("Invalid userId " + userId); 2851 } 2852 if (checkShell) { 2853 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2854 } 2855 if (userId == UserHandle.getUserId(callingUid)) return; 2856 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2857 if (requireFullPermission) { 2858 mContext.enforceCallingOrSelfPermission( 2859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2860 } else { 2861 try { 2862 mContext.enforceCallingOrSelfPermission( 2863 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2864 } catch (SecurityException se) { 2865 mContext.enforceCallingOrSelfPermission( 2866 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2867 } 2868 } 2869 } 2870 } 2871 2872 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2873 if (callingUid == Process.SHELL_UID) { 2874 if (userHandle >= 0 2875 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2876 throw new SecurityException("Shell does not have permission to access user " 2877 + userHandle); 2878 } else if (userHandle < 0) { 2879 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2880 + Debug.getCallers(3)); 2881 } 2882 } 2883 } 2884 2885 private BasePermission findPermissionTreeLP(String permName) { 2886 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2887 if (permName.startsWith(bp.name) && 2888 permName.length() > bp.name.length() && 2889 permName.charAt(bp.name.length()) == '.') { 2890 return bp; 2891 } 2892 } 2893 return null; 2894 } 2895 2896 private BasePermission checkPermissionTreeLP(String permName) { 2897 if (permName != null) { 2898 BasePermission bp = findPermissionTreeLP(permName); 2899 if (bp != null) { 2900 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2901 return bp; 2902 } 2903 throw new SecurityException("Calling uid " 2904 + Binder.getCallingUid() 2905 + " is not allowed to add to permission tree " 2906 + bp.name + " owned by uid " + bp.uid); 2907 } 2908 } 2909 throw new SecurityException("No permission tree found for " + permName); 2910 } 2911 2912 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2913 if (s1 == null) { 2914 return s2 == null; 2915 } 2916 if (s2 == null) { 2917 return false; 2918 } 2919 if (s1.getClass() != s2.getClass()) { 2920 return false; 2921 } 2922 return s1.equals(s2); 2923 } 2924 2925 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2926 if (pi1.icon != pi2.icon) return false; 2927 if (pi1.logo != pi2.logo) return false; 2928 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2929 if (!compareStrings(pi1.name, pi2.name)) return false; 2930 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2931 // We'll take care of setting this one. 2932 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2933 // These are not currently stored in settings. 2934 //if (!compareStrings(pi1.group, pi2.group)) return false; 2935 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2936 //if (pi1.labelRes != pi2.labelRes) return false; 2937 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2938 return true; 2939 } 2940 2941 int permissionInfoFootprint(PermissionInfo info) { 2942 int size = info.name.length(); 2943 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2944 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2945 return size; 2946 } 2947 2948 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2949 int size = 0; 2950 for (BasePermission perm : mSettings.mPermissions.values()) { 2951 if (perm.uid == tree.uid) { 2952 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2953 } 2954 } 2955 return size; 2956 } 2957 2958 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2959 // We calculate the max size of permissions defined by this uid and throw 2960 // if that plus the size of 'info' would exceed our stated maximum. 2961 if (tree.uid != Process.SYSTEM_UID) { 2962 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2963 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2964 throw new SecurityException("Permission tree size cap exceeded"); 2965 } 2966 } 2967 } 2968 2969 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2970 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2971 throw new SecurityException("Label must be specified in permission"); 2972 } 2973 BasePermission tree = checkPermissionTreeLP(info.name); 2974 BasePermission bp = mSettings.mPermissions.get(info.name); 2975 boolean added = bp == null; 2976 boolean changed = true; 2977 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2978 if (added) { 2979 enforcePermissionCapLocked(info, tree); 2980 bp = new BasePermission(info.name, tree.sourcePackage, 2981 BasePermission.TYPE_DYNAMIC); 2982 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2983 throw new SecurityException( 2984 "Not allowed to modify non-dynamic permission " 2985 + info.name); 2986 } else { 2987 if (bp.protectionLevel == fixedLevel 2988 && bp.perm.owner.equals(tree.perm.owner) 2989 && bp.uid == tree.uid 2990 && comparePermissionInfos(bp.perm.info, info)) { 2991 changed = false; 2992 } 2993 } 2994 bp.protectionLevel = fixedLevel; 2995 info = new PermissionInfo(info); 2996 info.protectionLevel = fixedLevel; 2997 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2998 bp.perm.info.packageName = tree.perm.info.packageName; 2999 bp.uid = tree.uid; 3000 if (added) { 3001 mSettings.mPermissions.put(info.name, bp); 3002 } 3003 if (changed) { 3004 if (!async) { 3005 mSettings.writeLPr(); 3006 } else { 3007 scheduleWriteSettingsLocked(); 3008 } 3009 } 3010 return added; 3011 } 3012 3013 @Override 3014 public boolean addPermission(PermissionInfo info) { 3015 synchronized (mPackages) { 3016 return addPermissionLocked(info, false); 3017 } 3018 } 3019 3020 @Override 3021 public boolean addPermissionAsync(PermissionInfo info) { 3022 synchronized (mPackages) { 3023 return addPermissionLocked(info, true); 3024 } 3025 } 3026 3027 @Override 3028 public void removePermission(String name) { 3029 synchronized (mPackages) { 3030 checkPermissionTreeLP(name); 3031 BasePermission bp = mSettings.mPermissions.get(name); 3032 if (bp != null) { 3033 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3034 throw new SecurityException( 3035 "Not allowed to modify non-dynamic permission " 3036 + name); 3037 } 3038 mSettings.mPermissions.remove(name); 3039 mSettings.writeLPr(); 3040 } 3041 } 3042 } 3043 3044 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3045 BasePermission bp) { 3046 int index = pkg.requestedPermissions.indexOf(bp.name); 3047 if (index == -1) { 3048 throw new SecurityException("Package " + pkg.packageName 3049 + " has not requested permission " + bp.name); 3050 } 3051 if (!bp.isRuntime()) { 3052 throw new SecurityException("Permission " + bp.name 3053 + " is not a changeable permission type"); 3054 } 3055 } 3056 3057 @Override 3058 public boolean grantPermission(String packageName, String name, int userId) { 3059 if (!RUNTIME_PERMISSIONS_ENABLED) { 3060 return false; 3061 } 3062 3063 if (!sUserManager.exists(userId)) { 3064 return false; 3065 } 3066 3067 mContext.enforceCallingOrSelfPermission( 3068 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3069 "grantPermission"); 3070 3071 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3072 "grantPermission"); 3073 3074 boolean gidsChanged = false; 3075 final SettingBase sb; 3076 3077 synchronized (mPackages) { 3078 final PackageParser.Package pkg = mPackages.get(packageName); 3079 if (pkg == null) { 3080 throw new IllegalArgumentException("Unknown package: " + packageName); 3081 } 3082 3083 final BasePermission bp = mSettings.mPermissions.get(name); 3084 if (bp == null) { 3085 throw new IllegalArgumentException("Unknown permission: " + name); 3086 } 3087 3088 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3089 3090 sb = (SettingBase) pkg.mExtras; 3091 if (sb == null) { 3092 throw new IllegalArgumentException("Unknown package: " + packageName); 3093 } 3094 3095 final PermissionsState permissionsState = sb.getPermissionsState(); 3096 3097 final int result = permissionsState.grantRuntimePermission(bp, userId); 3098 switch (result) { 3099 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3100 return false; 3101 } 3102 3103 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3104 gidsChanged = true; 3105 } break; 3106 } 3107 3108 // Not critical if that is lost - app has to request again. 3109 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3110 } 3111 3112 if (gidsChanged) { 3113 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3114 } 3115 3116 return true; 3117 } 3118 3119 @Override 3120 public boolean revokePermission(String packageName, String name, int userId) { 3121 if (!RUNTIME_PERMISSIONS_ENABLED) { 3122 return false; 3123 } 3124 3125 if (!sUserManager.exists(userId)) { 3126 return false; 3127 } 3128 3129 mContext.enforceCallingOrSelfPermission( 3130 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3131 "revokePermission"); 3132 3133 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3134 "revokePermission"); 3135 3136 final SettingBase sb; 3137 3138 synchronized (mPackages) { 3139 final PackageParser.Package pkg = mPackages.get(packageName); 3140 if (pkg == null) { 3141 throw new IllegalArgumentException("Unknown package: " + packageName); 3142 } 3143 3144 final BasePermission bp = mSettings.mPermissions.get(name); 3145 if (bp == null) { 3146 throw new IllegalArgumentException("Unknown permission: " + name); 3147 } 3148 3149 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3150 3151 sb = (SettingBase) pkg.mExtras; 3152 if (sb == null) { 3153 throw new IllegalArgumentException("Unknown package: " + packageName); 3154 } 3155 3156 final PermissionsState permissionsState = sb.getPermissionsState(); 3157 3158 if (permissionsState.revokeRuntimePermission(bp, userId) == 3159 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3160 return false; 3161 } 3162 3163 // Critical, after this call all should never have the permission. 3164 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3165 } 3166 3167 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3168 3169 return true; 3170 } 3171 3172 @Override 3173 public boolean isProtectedBroadcast(String actionName) { 3174 synchronized (mPackages) { 3175 return mProtectedBroadcasts.contains(actionName); 3176 } 3177 } 3178 3179 @Override 3180 public int checkSignatures(String pkg1, String pkg2) { 3181 synchronized (mPackages) { 3182 final PackageParser.Package p1 = mPackages.get(pkg1); 3183 final PackageParser.Package p2 = mPackages.get(pkg2); 3184 if (p1 == null || p1.mExtras == null 3185 || p2 == null || p2.mExtras == null) { 3186 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3187 } 3188 return compareSignatures(p1.mSignatures, p2.mSignatures); 3189 } 3190 } 3191 3192 @Override 3193 public int checkUidSignatures(int uid1, int uid2) { 3194 // Map to base uids. 3195 uid1 = UserHandle.getAppId(uid1); 3196 uid2 = UserHandle.getAppId(uid2); 3197 // reader 3198 synchronized (mPackages) { 3199 Signature[] s1; 3200 Signature[] s2; 3201 Object obj = mSettings.getUserIdLPr(uid1); 3202 if (obj != null) { 3203 if (obj instanceof SharedUserSetting) { 3204 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3205 } else if (obj instanceof PackageSetting) { 3206 s1 = ((PackageSetting)obj).signatures.mSignatures; 3207 } else { 3208 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3209 } 3210 } else { 3211 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3212 } 3213 obj = mSettings.getUserIdLPr(uid2); 3214 if (obj != null) { 3215 if (obj instanceof SharedUserSetting) { 3216 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3217 } else if (obj instanceof PackageSetting) { 3218 s2 = ((PackageSetting)obj).signatures.mSignatures; 3219 } else { 3220 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3221 } 3222 } else { 3223 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3224 } 3225 return compareSignatures(s1, s2); 3226 } 3227 } 3228 3229 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3230 final long identity = Binder.clearCallingIdentity(); 3231 try { 3232 if (sb instanceof SharedUserSetting) { 3233 SharedUserSetting sus = (SharedUserSetting) sb; 3234 final int packageCount = sus.packages.size(); 3235 for (int i = 0; i < packageCount; i++) { 3236 PackageSetting susPs = sus.packages.valueAt(i); 3237 if (userId == UserHandle.USER_ALL) { 3238 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3239 } else { 3240 final int uid = UserHandle.getUid(userId, susPs.appId); 3241 killUid(uid, reason); 3242 } 3243 } 3244 } else if (sb instanceof PackageSetting) { 3245 PackageSetting ps = (PackageSetting) sb; 3246 if (userId == UserHandle.USER_ALL) { 3247 killApplication(ps.pkg.packageName, ps.appId, reason); 3248 } else { 3249 final int uid = UserHandle.getUid(userId, ps.appId); 3250 killUid(uid, reason); 3251 } 3252 } 3253 } finally { 3254 Binder.restoreCallingIdentity(identity); 3255 } 3256 } 3257 3258 private static void killUid(int uid, String reason) { 3259 IActivityManager am = ActivityManagerNative.getDefault(); 3260 if (am != null) { 3261 try { 3262 am.killUid(uid, reason); 3263 } catch (RemoteException e) { 3264 /* ignore - same process */ 3265 } 3266 } 3267 } 3268 3269 /** 3270 * Compares two sets of signatures. Returns: 3271 * <br /> 3272 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3273 * <br /> 3274 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3275 * <br /> 3276 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3277 * <br /> 3278 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3279 * <br /> 3280 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3281 */ 3282 static int compareSignatures(Signature[] s1, Signature[] s2) { 3283 if (s1 == null) { 3284 return s2 == null 3285 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3286 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3287 } 3288 3289 if (s2 == null) { 3290 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3291 } 3292 3293 if (s1.length != s2.length) { 3294 return PackageManager.SIGNATURE_NO_MATCH; 3295 } 3296 3297 // Since both signature sets are of size 1, we can compare without HashSets. 3298 if (s1.length == 1) { 3299 return s1[0].equals(s2[0]) ? 3300 PackageManager.SIGNATURE_MATCH : 3301 PackageManager.SIGNATURE_NO_MATCH; 3302 } 3303 3304 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3305 for (Signature sig : s1) { 3306 set1.add(sig); 3307 } 3308 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3309 for (Signature sig : s2) { 3310 set2.add(sig); 3311 } 3312 // Make sure s2 contains all signatures in s1. 3313 if (set1.equals(set2)) { 3314 return PackageManager.SIGNATURE_MATCH; 3315 } 3316 return PackageManager.SIGNATURE_NO_MATCH; 3317 } 3318 3319 /** 3320 * If the database version for this type of package (internal storage or 3321 * external storage) is less than the version where package signatures 3322 * were updated, return true. 3323 */ 3324 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3325 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3326 DatabaseVersion.SIGNATURE_END_ENTITY)) 3327 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3328 DatabaseVersion.SIGNATURE_END_ENTITY)); 3329 } 3330 3331 /** 3332 * Used for backward compatibility to make sure any packages with 3333 * certificate chains get upgraded to the new style. {@code existingSigs} 3334 * will be in the old format (since they were stored on disk from before the 3335 * system upgrade) and {@code scannedSigs} will be in the newer format. 3336 */ 3337 private int compareSignaturesCompat(PackageSignatures existingSigs, 3338 PackageParser.Package scannedPkg) { 3339 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3340 return PackageManager.SIGNATURE_NO_MATCH; 3341 } 3342 3343 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3344 for (Signature sig : existingSigs.mSignatures) { 3345 existingSet.add(sig); 3346 } 3347 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3348 for (Signature sig : scannedPkg.mSignatures) { 3349 try { 3350 Signature[] chainSignatures = sig.getChainSignatures(); 3351 for (Signature chainSig : chainSignatures) { 3352 scannedCompatSet.add(chainSig); 3353 } 3354 } catch (CertificateEncodingException e) { 3355 scannedCompatSet.add(sig); 3356 } 3357 } 3358 /* 3359 * Make sure the expanded scanned set contains all signatures in the 3360 * existing one. 3361 */ 3362 if (scannedCompatSet.equals(existingSet)) { 3363 // Migrate the old signatures to the new scheme. 3364 existingSigs.assignSignatures(scannedPkg.mSignatures); 3365 // The new KeySets will be re-added later in the scanning process. 3366 synchronized (mPackages) { 3367 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3368 } 3369 return PackageManager.SIGNATURE_MATCH; 3370 } 3371 return PackageManager.SIGNATURE_NO_MATCH; 3372 } 3373 3374 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3375 if (isExternal(scannedPkg)) { 3376 return mSettings.isExternalDatabaseVersionOlderThan( 3377 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3378 } else { 3379 return mSettings.isInternalDatabaseVersionOlderThan( 3380 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3381 } 3382 } 3383 3384 private int compareSignaturesRecover(PackageSignatures existingSigs, 3385 PackageParser.Package scannedPkg) { 3386 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3387 return PackageManager.SIGNATURE_NO_MATCH; 3388 } 3389 3390 String msg = null; 3391 try { 3392 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3393 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3394 + scannedPkg.packageName); 3395 return PackageManager.SIGNATURE_MATCH; 3396 } 3397 } catch (CertificateException e) { 3398 msg = e.getMessage(); 3399 } 3400 3401 logCriticalInfo(Log.INFO, 3402 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3403 return PackageManager.SIGNATURE_NO_MATCH; 3404 } 3405 3406 @Override 3407 public String[] getPackagesForUid(int uid) { 3408 uid = UserHandle.getAppId(uid); 3409 // reader 3410 synchronized (mPackages) { 3411 Object obj = mSettings.getUserIdLPr(uid); 3412 if (obj instanceof SharedUserSetting) { 3413 final SharedUserSetting sus = (SharedUserSetting) obj; 3414 final int N = sus.packages.size(); 3415 final String[] res = new String[N]; 3416 final Iterator<PackageSetting> it = sus.packages.iterator(); 3417 int i = 0; 3418 while (it.hasNext()) { 3419 res[i++] = it.next().name; 3420 } 3421 return res; 3422 } else if (obj instanceof PackageSetting) { 3423 final PackageSetting ps = (PackageSetting) obj; 3424 return new String[] { ps.name }; 3425 } 3426 } 3427 return null; 3428 } 3429 3430 @Override 3431 public String getNameForUid(int uid) { 3432 // reader 3433 synchronized (mPackages) { 3434 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3435 if (obj instanceof SharedUserSetting) { 3436 final SharedUserSetting sus = (SharedUserSetting) obj; 3437 return sus.name + ":" + sus.userId; 3438 } else if (obj instanceof PackageSetting) { 3439 final PackageSetting ps = (PackageSetting) obj; 3440 return ps.name; 3441 } 3442 } 3443 return null; 3444 } 3445 3446 @Override 3447 public int getUidForSharedUser(String sharedUserName) { 3448 if(sharedUserName == null) { 3449 return -1; 3450 } 3451 // reader 3452 synchronized (mPackages) { 3453 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3454 if (suid == null) { 3455 return -1; 3456 } 3457 return suid.userId; 3458 } 3459 } 3460 3461 @Override 3462 public int getFlagsForUid(int uid) { 3463 synchronized (mPackages) { 3464 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3465 if (obj instanceof SharedUserSetting) { 3466 final SharedUserSetting sus = (SharedUserSetting) obj; 3467 return sus.pkgFlags; 3468 } else if (obj instanceof PackageSetting) { 3469 final PackageSetting ps = (PackageSetting) obj; 3470 return ps.pkgFlags; 3471 } 3472 } 3473 return 0; 3474 } 3475 3476 @Override 3477 public int getPrivateFlagsForUid(int uid) { 3478 synchronized (mPackages) { 3479 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3480 if (obj instanceof SharedUserSetting) { 3481 final SharedUserSetting sus = (SharedUserSetting) obj; 3482 return sus.pkgPrivateFlags; 3483 } else if (obj instanceof PackageSetting) { 3484 final PackageSetting ps = (PackageSetting) obj; 3485 return ps.pkgPrivateFlags; 3486 } 3487 } 3488 return 0; 3489 } 3490 3491 @Override 3492 public boolean isUidPrivileged(int uid) { 3493 uid = UserHandle.getAppId(uid); 3494 // reader 3495 synchronized (mPackages) { 3496 Object obj = mSettings.getUserIdLPr(uid); 3497 if (obj instanceof SharedUserSetting) { 3498 final SharedUserSetting sus = (SharedUserSetting) obj; 3499 final Iterator<PackageSetting> it = sus.packages.iterator(); 3500 while (it.hasNext()) { 3501 if (it.next().isPrivileged()) { 3502 return true; 3503 } 3504 } 3505 } else if (obj instanceof PackageSetting) { 3506 final PackageSetting ps = (PackageSetting) obj; 3507 return ps.isPrivileged(); 3508 } 3509 } 3510 return false; 3511 } 3512 3513 @Override 3514 public String[] getAppOpPermissionPackages(String permissionName) { 3515 synchronized (mPackages) { 3516 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3517 if (pkgs == null) { 3518 return null; 3519 } 3520 return pkgs.toArray(new String[pkgs.size()]); 3521 } 3522 } 3523 3524 @Override 3525 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3526 int flags, int userId) { 3527 if (!sUserManager.exists(userId)) return null; 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3529 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3530 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3531 } 3532 3533 @Override 3534 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3535 IntentFilter filter, int match, ComponentName activity) { 3536 final int userId = UserHandle.getCallingUserId(); 3537 if (DEBUG_PREFERRED) { 3538 Log.v(TAG, "setLastChosenActivity intent=" + intent 3539 + " resolvedType=" + resolvedType 3540 + " flags=" + flags 3541 + " filter=" + filter 3542 + " match=" + match 3543 + " activity=" + activity); 3544 filter.dump(new PrintStreamPrinter(System.out), " "); 3545 } 3546 intent.setComponent(null); 3547 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3548 // Find any earlier preferred or last chosen entries and nuke them 3549 findPreferredActivity(intent, resolvedType, 3550 flags, query, 0, false, true, false, userId); 3551 // Add the new activity as the last chosen for this filter 3552 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3553 "Setting last chosen"); 3554 } 3555 3556 @Override 3557 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3558 final int userId = UserHandle.getCallingUserId(); 3559 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3560 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3561 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3562 false, false, false, userId); 3563 } 3564 3565 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3566 int flags, List<ResolveInfo> query, int userId) { 3567 if (query != null) { 3568 final int N = query.size(); 3569 if (N == 1) { 3570 return query.get(0); 3571 } else if (N > 1) { 3572 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3573 // If there is more than one activity with the same priority, 3574 // then let the user decide between them. 3575 ResolveInfo r0 = query.get(0); 3576 ResolveInfo r1 = query.get(1); 3577 if (DEBUG_INTENT_MATCHING || debug) { 3578 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3579 + r1.activityInfo.name + "=" + r1.priority); 3580 } 3581 // If the first activity has a higher priority, or a different 3582 // default, then it is always desireable to pick it. 3583 if (r0.priority != r1.priority 3584 || r0.preferredOrder != r1.preferredOrder 3585 || r0.isDefault != r1.isDefault) { 3586 return query.get(0); 3587 } 3588 // If we have saved a preference for a preferred activity for 3589 // this Intent, use that. 3590 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3591 flags, query, r0.priority, true, false, debug, userId); 3592 if (ri != null) { 3593 return ri; 3594 } 3595 if (userId != 0) { 3596 ri = new ResolveInfo(mResolveInfo); 3597 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3598 ri.activityInfo.applicationInfo = new ApplicationInfo( 3599 ri.activityInfo.applicationInfo); 3600 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3601 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3602 return ri; 3603 } 3604 return mResolveInfo; 3605 } 3606 } 3607 return null; 3608 } 3609 3610 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3611 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3612 final int N = query.size(); 3613 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3614 .get(userId); 3615 // Get the list of persistent preferred activities that handle the intent 3616 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3617 List<PersistentPreferredActivity> pprefs = ppir != null 3618 ? ppir.queryIntent(intent, resolvedType, 3619 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3620 : null; 3621 if (pprefs != null && pprefs.size() > 0) { 3622 final int M = pprefs.size(); 3623 for (int i=0; i<M; i++) { 3624 final PersistentPreferredActivity ppa = pprefs.get(i); 3625 if (DEBUG_PREFERRED || debug) { 3626 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3627 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3628 + "\n component=" + ppa.mComponent); 3629 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3630 } 3631 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3632 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3633 if (DEBUG_PREFERRED || debug) { 3634 Slog.v(TAG, "Found persistent preferred activity:"); 3635 if (ai != null) { 3636 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3637 } else { 3638 Slog.v(TAG, " null"); 3639 } 3640 } 3641 if (ai == null) { 3642 // This previously registered persistent preferred activity 3643 // component is no longer known. Ignore it and do NOT remove it. 3644 continue; 3645 } 3646 for (int j=0; j<N; j++) { 3647 final ResolveInfo ri = query.get(j); 3648 if (!ri.activityInfo.applicationInfo.packageName 3649 .equals(ai.applicationInfo.packageName)) { 3650 continue; 3651 } 3652 if (!ri.activityInfo.name.equals(ai.name)) { 3653 continue; 3654 } 3655 // Found a persistent preference that can handle the intent. 3656 if (DEBUG_PREFERRED || debug) { 3657 Slog.v(TAG, "Returning persistent preferred activity: " + 3658 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3659 } 3660 return ri; 3661 } 3662 } 3663 } 3664 return null; 3665 } 3666 3667 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3668 List<ResolveInfo> query, int priority, boolean always, 3669 boolean removeMatches, boolean debug, int userId) { 3670 if (!sUserManager.exists(userId)) return null; 3671 // writer 3672 synchronized (mPackages) { 3673 if (intent.getSelector() != null) { 3674 intent = intent.getSelector(); 3675 } 3676 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3677 3678 // Try to find a matching persistent preferred activity. 3679 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3680 debug, userId); 3681 3682 // If a persistent preferred activity matched, use it. 3683 if (pri != null) { 3684 return pri; 3685 } 3686 3687 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3688 // Get the list of preferred activities that handle the intent 3689 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3690 List<PreferredActivity> prefs = pir != null 3691 ? pir.queryIntent(intent, resolvedType, 3692 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3693 : null; 3694 if (prefs != null && prefs.size() > 0) { 3695 boolean changed = false; 3696 try { 3697 // First figure out how good the original match set is. 3698 // We will only allow preferred activities that came 3699 // from the same match quality. 3700 int match = 0; 3701 3702 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3703 3704 final int N = query.size(); 3705 for (int j=0; j<N; j++) { 3706 final ResolveInfo ri = query.get(j); 3707 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3708 + ": 0x" + Integer.toHexString(match)); 3709 if (ri.match > match) { 3710 match = ri.match; 3711 } 3712 } 3713 3714 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3715 + Integer.toHexString(match)); 3716 3717 match &= IntentFilter.MATCH_CATEGORY_MASK; 3718 final int M = prefs.size(); 3719 for (int i=0; i<M; i++) { 3720 final PreferredActivity pa = prefs.get(i); 3721 if (DEBUG_PREFERRED || debug) { 3722 Slog.v(TAG, "Checking PreferredActivity ds=" 3723 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3724 + "\n component=" + pa.mPref.mComponent); 3725 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3726 } 3727 if (pa.mPref.mMatch != match) { 3728 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3729 + Integer.toHexString(pa.mPref.mMatch)); 3730 continue; 3731 } 3732 // If it's not an "always" type preferred activity and that's what we're 3733 // looking for, skip it. 3734 if (always && !pa.mPref.mAlways) { 3735 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3736 continue; 3737 } 3738 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3739 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3740 if (DEBUG_PREFERRED || debug) { 3741 Slog.v(TAG, "Found preferred activity:"); 3742 if (ai != null) { 3743 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3744 } else { 3745 Slog.v(TAG, " null"); 3746 } 3747 } 3748 if (ai == null) { 3749 // This previously registered preferred activity 3750 // component is no longer known. Most likely an update 3751 // to the app was installed and in the new version this 3752 // component no longer exists. Clean it up by removing 3753 // it from the preferred activities list, and skip it. 3754 Slog.w(TAG, "Removing dangling preferred activity: " 3755 + pa.mPref.mComponent); 3756 pir.removeFilter(pa); 3757 changed = true; 3758 continue; 3759 } 3760 for (int j=0; j<N; j++) { 3761 final ResolveInfo ri = query.get(j); 3762 if (!ri.activityInfo.applicationInfo.packageName 3763 .equals(ai.applicationInfo.packageName)) { 3764 continue; 3765 } 3766 if (!ri.activityInfo.name.equals(ai.name)) { 3767 continue; 3768 } 3769 3770 if (removeMatches) { 3771 pir.removeFilter(pa); 3772 changed = true; 3773 if (DEBUG_PREFERRED) { 3774 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3775 } 3776 break; 3777 } 3778 3779 // Okay we found a previously set preferred or last chosen app. 3780 // If the result set is different from when this 3781 // was created, we need to clear it and re-ask the 3782 // user their preference, if we're looking for an "always" type entry. 3783 if (always && !pa.mPref.sameSet(query)) { 3784 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3785 + intent + " type " + resolvedType); 3786 if (DEBUG_PREFERRED) { 3787 Slog.v(TAG, "Removing preferred activity since set changed " 3788 + pa.mPref.mComponent); 3789 } 3790 pir.removeFilter(pa); 3791 // Re-add the filter as a "last chosen" entry (!always) 3792 PreferredActivity lastChosen = new PreferredActivity( 3793 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3794 pir.addFilter(lastChosen); 3795 changed = true; 3796 return null; 3797 } 3798 3799 // Yay! Either the set matched or we're looking for the last chosen 3800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3801 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3802 return ri; 3803 } 3804 } 3805 } finally { 3806 if (changed) { 3807 if (DEBUG_PREFERRED) { 3808 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3809 } 3810 scheduleWritePackageRestrictionsLocked(userId); 3811 } 3812 } 3813 } 3814 } 3815 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3816 return null; 3817 } 3818 3819 /* 3820 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3821 */ 3822 @Override 3823 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3824 int targetUserId) { 3825 mContext.enforceCallingOrSelfPermission( 3826 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3827 List<CrossProfileIntentFilter> matches = 3828 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3829 if (matches != null) { 3830 int size = matches.size(); 3831 for (int i = 0; i < size; i++) { 3832 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3833 } 3834 } 3835 return false; 3836 } 3837 3838 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3839 String resolvedType, int userId) { 3840 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3841 if (resolver != null) { 3842 return resolver.queryIntent(intent, resolvedType, false, userId); 3843 } 3844 return null; 3845 } 3846 3847 @Override 3848 public List<ResolveInfo> queryIntentActivities(Intent intent, 3849 String resolvedType, int flags, int userId) { 3850 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3851 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3852 ComponentName comp = intent.getComponent(); 3853 if (comp == null) { 3854 if (intent.getSelector() != null) { 3855 intent = intent.getSelector(); 3856 comp = intent.getComponent(); 3857 } 3858 } 3859 3860 if (comp != null) { 3861 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3862 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3863 if (ai != null) { 3864 final ResolveInfo ri = new ResolveInfo(); 3865 ri.activityInfo = ai; 3866 list.add(ri); 3867 } 3868 return list; 3869 } 3870 3871 // reader 3872 synchronized (mPackages) { 3873 final String pkgName = intent.getPackage(); 3874 if (pkgName == null) { 3875 List<CrossProfileIntentFilter> matchingFilters = 3876 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3877 // Check for results that need to skip the current profile. 3878 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3879 resolvedType, flags, userId); 3880 if (resolveInfo != null) { 3881 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3882 result.add(resolveInfo); 3883 return filterIfNotPrimaryUser(result, userId); 3884 } 3885 // Check for cross profile results. 3886 resolveInfo = queryCrossProfileIntents( 3887 matchingFilters, intent, resolvedType, flags, userId); 3888 3889 // Check for results in the current profile. Adding GET_RESOLVED_FILTER flags 3890 // as we need it later 3891 List<ResolveInfo> result = mActivities.queryIntent( 3892 intent, resolvedType, flags, userId); 3893 if (resolveInfo != null) { 3894 result.add(resolveInfo); 3895 Collections.sort(result, mResolvePrioritySorter); 3896 } 3897 result = filterIfNotPrimaryUser(result, userId); 3898 if (result.size() > 1) { 3899 return filterCandidatesWithDomainPreferedActivitiesLPw(result); 3900 } 3901 3902 return result; 3903 } 3904 final PackageParser.Package pkg = mPackages.get(pkgName); 3905 if (pkg != null) { 3906 return filterIfNotPrimaryUser( 3907 mActivities.queryIntentForPackage( 3908 intent, resolvedType, flags, pkg.activities, userId), 3909 userId); 3910 } 3911 return new ArrayList<ResolveInfo>(); 3912 } 3913 } 3914 3915 /** 3916 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3917 * 3918 * @return filtered list 3919 */ 3920 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3921 if (userId == UserHandle.USER_OWNER) { 3922 return resolveInfos; 3923 } 3924 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3925 ResolveInfo info = resolveInfos.get(i); 3926 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3927 resolveInfos.remove(i); 3928 } 3929 } 3930 return resolveInfos; 3931 } 3932 3933 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPw( 3934 List<ResolveInfo> candidates) { 3935 if (DEBUG_PREFERRED) { 3936 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3937 candidates.size()); 3938 } 3939 final int userId = UserHandle.getCallingUserId(); 3940 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(candidates); 3941 synchronized (mPackages) { 3942 final int count = result.size(); 3943 for (int n = count-1; n >= 0; n--) { 3944 ResolveInfo info = result.get(n); 3945 if (!info.filterNeedsVerification) { 3946 continue; 3947 } 3948 String packageName = info.activityInfo.packageName; 3949 PackageSetting ps = mSettings.mPackages.get(packageName); 3950 if (ps != null) { 3951 // Try to get the status from User settings first 3952 int status = ps.getDomainVerificationStatusForUser(userId); 3953 // if none available, get the master status 3954 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 3955 if (ps.getIntentFilterVerificationInfo() != null) { 3956 status = ps.getIntentFilterVerificationInfo().getStatus(); 3957 } 3958 } 3959 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 3960 result.clear(); 3961 result.add(info); 3962 // We break the for loop as we are good to go 3963 break; 3964 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 3965 result.remove(n); 3966 } 3967 } 3968 } 3969 } 3970 if (DEBUG_PREFERRED) { 3971 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 3972 result.size()); 3973 } 3974 return result; 3975 } 3976 3977 private ResolveInfo querySkipCurrentProfileIntents( 3978 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3979 int flags, int sourceUserId) { 3980 if (matchingFilters != null) { 3981 int size = matchingFilters.size(); 3982 for (int i = 0; i < size; i ++) { 3983 CrossProfileIntentFilter filter = matchingFilters.get(i); 3984 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3985 // Checking if there are activities in the target user that can handle the 3986 // intent. 3987 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3988 flags, sourceUserId); 3989 if (resolveInfo != null) { 3990 return resolveInfo; 3991 } 3992 } 3993 } 3994 } 3995 return null; 3996 } 3997 3998 // Return matching ResolveInfo if any for skip current profile intent filters. 3999 private ResolveInfo queryCrossProfileIntents( 4000 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4001 int flags, int sourceUserId) { 4002 if (matchingFilters != null) { 4003 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4004 // match the same intent. For performance reasons, it is better not to 4005 // run queryIntent twice for the same userId 4006 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4007 int size = matchingFilters.size(); 4008 for (int i = 0; i < size; i++) { 4009 CrossProfileIntentFilter filter = matchingFilters.get(i); 4010 int targetUserId = filter.getTargetUserId(); 4011 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4012 && !alreadyTriedUserIds.get(targetUserId)) { 4013 // Checking if there are activities in the target user that can handle the 4014 // intent. 4015 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4016 flags, sourceUserId); 4017 if (resolveInfo != null) return resolveInfo; 4018 alreadyTriedUserIds.put(targetUserId, true); 4019 } 4020 } 4021 } 4022 return null; 4023 } 4024 4025 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4026 String resolvedType, int flags, int sourceUserId) { 4027 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4028 resolvedType, flags, filter.getTargetUserId()); 4029 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4030 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4031 } 4032 return null; 4033 } 4034 4035 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4036 int sourceUserId, int targetUserId) { 4037 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4038 String className; 4039 if (targetUserId == UserHandle.USER_OWNER) { 4040 className = FORWARD_INTENT_TO_USER_OWNER; 4041 } else { 4042 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4043 } 4044 ComponentName forwardingActivityComponentName = new ComponentName( 4045 mAndroidApplication.packageName, className); 4046 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4047 sourceUserId); 4048 if (targetUserId == UserHandle.USER_OWNER) { 4049 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4050 forwardingResolveInfo.noResourceId = true; 4051 } 4052 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4053 forwardingResolveInfo.priority = 0; 4054 forwardingResolveInfo.preferredOrder = 0; 4055 forwardingResolveInfo.match = 0; 4056 forwardingResolveInfo.isDefault = true; 4057 forwardingResolveInfo.filter = filter; 4058 forwardingResolveInfo.targetUserId = targetUserId; 4059 return forwardingResolveInfo; 4060 } 4061 4062 @Override 4063 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4064 Intent[] specifics, String[] specificTypes, Intent intent, 4065 String resolvedType, int flags, int userId) { 4066 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4067 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4068 false, "query intent activity options"); 4069 final String resultsAction = intent.getAction(); 4070 4071 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4072 | PackageManager.GET_RESOLVED_FILTER, userId); 4073 4074 if (DEBUG_INTENT_MATCHING) { 4075 Log.v(TAG, "Query " + intent + ": " + results); 4076 } 4077 4078 int specificsPos = 0; 4079 int N; 4080 4081 // todo: note that the algorithm used here is O(N^2). This 4082 // isn't a problem in our current environment, but if we start running 4083 // into situations where we have more than 5 or 10 matches then this 4084 // should probably be changed to something smarter... 4085 4086 // First we go through and resolve each of the specific items 4087 // that were supplied, taking care of removing any corresponding 4088 // duplicate items in the generic resolve list. 4089 if (specifics != null) { 4090 for (int i=0; i<specifics.length; i++) { 4091 final Intent sintent = specifics[i]; 4092 if (sintent == null) { 4093 continue; 4094 } 4095 4096 if (DEBUG_INTENT_MATCHING) { 4097 Log.v(TAG, "Specific #" + i + ": " + sintent); 4098 } 4099 4100 String action = sintent.getAction(); 4101 if (resultsAction != null && resultsAction.equals(action)) { 4102 // If this action was explicitly requested, then don't 4103 // remove things that have it. 4104 action = null; 4105 } 4106 4107 ResolveInfo ri = null; 4108 ActivityInfo ai = null; 4109 4110 ComponentName comp = sintent.getComponent(); 4111 if (comp == null) { 4112 ri = resolveIntent( 4113 sintent, 4114 specificTypes != null ? specificTypes[i] : null, 4115 flags, userId); 4116 if (ri == null) { 4117 continue; 4118 } 4119 if (ri == mResolveInfo) { 4120 // ACK! Must do something better with this. 4121 } 4122 ai = ri.activityInfo; 4123 comp = new ComponentName(ai.applicationInfo.packageName, 4124 ai.name); 4125 } else { 4126 ai = getActivityInfo(comp, flags, userId); 4127 if (ai == null) { 4128 continue; 4129 } 4130 } 4131 4132 // Look for any generic query activities that are duplicates 4133 // of this specific one, and remove them from the results. 4134 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4135 N = results.size(); 4136 int j; 4137 for (j=specificsPos; j<N; j++) { 4138 ResolveInfo sri = results.get(j); 4139 if ((sri.activityInfo.name.equals(comp.getClassName()) 4140 && sri.activityInfo.applicationInfo.packageName.equals( 4141 comp.getPackageName())) 4142 || (action != null && sri.filter.matchAction(action))) { 4143 results.remove(j); 4144 if (DEBUG_INTENT_MATCHING) Log.v( 4145 TAG, "Removing duplicate item from " + j 4146 + " due to specific " + specificsPos); 4147 if (ri == null) { 4148 ri = sri; 4149 } 4150 j--; 4151 N--; 4152 } 4153 } 4154 4155 // Add this specific item to its proper place. 4156 if (ri == null) { 4157 ri = new ResolveInfo(); 4158 ri.activityInfo = ai; 4159 } 4160 results.add(specificsPos, ri); 4161 ri.specificIndex = i; 4162 specificsPos++; 4163 } 4164 } 4165 4166 // Now we go through the remaining generic results and remove any 4167 // duplicate actions that are found here. 4168 N = results.size(); 4169 for (int i=specificsPos; i<N-1; i++) { 4170 final ResolveInfo rii = results.get(i); 4171 if (rii.filter == null) { 4172 continue; 4173 } 4174 4175 // Iterate over all of the actions of this result's intent 4176 // filter... typically this should be just one. 4177 final Iterator<String> it = rii.filter.actionsIterator(); 4178 if (it == null) { 4179 continue; 4180 } 4181 while (it.hasNext()) { 4182 final String action = it.next(); 4183 if (resultsAction != null && resultsAction.equals(action)) { 4184 // If this action was explicitly requested, then don't 4185 // remove things that have it. 4186 continue; 4187 } 4188 for (int j=i+1; j<N; j++) { 4189 final ResolveInfo rij = results.get(j); 4190 if (rij.filter != null && rij.filter.hasAction(action)) { 4191 results.remove(j); 4192 if (DEBUG_INTENT_MATCHING) Log.v( 4193 TAG, "Removing duplicate item from " + j 4194 + " due to action " + action + " at " + i); 4195 j--; 4196 N--; 4197 } 4198 } 4199 } 4200 4201 // If the caller didn't request filter information, drop it now 4202 // so we don't have to marshall/unmarshall it. 4203 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4204 rii.filter = null; 4205 } 4206 } 4207 4208 // Filter out the caller activity if so requested. 4209 if (caller != null) { 4210 N = results.size(); 4211 for (int i=0; i<N; i++) { 4212 ActivityInfo ainfo = results.get(i).activityInfo; 4213 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4214 && caller.getClassName().equals(ainfo.name)) { 4215 results.remove(i); 4216 break; 4217 } 4218 } 4219 } 4220 4221 // If the caller didn't request filter information, 4222 // drop them now so we don't have to 4223 // marshall/unmarshall it. 4224 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4225 N = results.size(); 4226 for (int i=0; i<N; i++) { 4227 results.get(i).filter = null; 4228 } 4229 } 4230 4231 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4232 return results; 4233 } 4234 4235 @Override 4236 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4237 int userId) { 4238 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4239 ComponentName comp = intent.getComponent(); 4240 if (comp == null) { 4241 if (intent.getSelector() != null) { 4242 intent = intent.getSelector(); 4243 comp = intent.getComponent(); 4244 } 4245 } 4246 if (comp != null) { 4247 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4248 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4249 if (ai != null) { 4250 ResolveInfo ri = new ResolveInfo(); 4251 ri.activityInfo = ai; 4252 list.add(ri); 4253 } 4254 return list; 4255 } 4256 4257 // reader 4258 synchronized (mPackages) { 4259 String pkgName = intent.getPackage(); 4260 if (pkgName == null) { 4261 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4262 } 4263 final PackageParser.Package pkg = mPackages.get(pkgName); 4264 if (pkg != null) { 4265 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4266 userId); 4267 } 4268 return null; 4269 } 4270 } 4271 4272 @Override 4273 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4274 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4275 if (!sUserManager.exists(userId)) return null; 4276 if (query != null) { 4277 if (query.size() >= 1) { 4278 // If there is more than one service with the same priority, 4279 // just arbitrarily pick the first one. 4280 return query.get(0); 4281 } 4282 } 4283 return null; 4284 } 4285 4286 @Override 4287 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4288 int userId) { 4289 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4290 ComponentName comp = intent.getComponent(); 4291 if (comp == null) { 4292 if (intent.getSelector() != null) { 4293 intent = intent.getSelector(); 4294 comp = intent.getComponent(); 4295 } 4296 } 4297 if (comp != null) { 4298 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4299 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4300 if (si != null) { 4301 final ResolveInfo ri = new ResolveInfo(); 4302 ri.serviceInfo = si; 4303 list.add(ri); 4304 } 4305 return list; 4306 } 4307 4308 // reader 4309 synchronized (mPackages) { 4310 String pkgName = intent.getPackage(); 4311 if (pkgName == null) { 4312 return mServices.queryIntent(intent, resolvedType, flags, userId); 4313 } 4314 final PackageParser.Package pkg = mPackages.get(pkgName); 4315 if (pkg != null) { 4316 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4317 userId); 4318 } 4319 return null; 4320 } 4321 } 4322 4323 @Override 4324 public List<ResolveInfo> queryIntentContentProviders( 4325 Intent intent, String resolvedType, int flags, int userId) { 4326 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4327 ComponentName comp = intent.getComponent(); 4328 if (comp == null) { 4329 if (intent.getSelector() != null) { 4330 intent = intent.getSelector(); 4331 comp = intent.getComponent(); 4332 } 4333 } 4334 if (comp != null) { 4335 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4336 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4337 if (pi != null) { 4338 final ResolveInfo ri = new ResolveInfo(); 4339 ri.providerInfo = pi; 4340 list.add(ri); 4341 } 4342 return list; 4343 } 4344 4345 // reader 4346 synchronized (mPackages) { 4347 String pkgName = intent.getPackage(); 4348 if (pkgName == null) { 4349 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4350 } 4351 final PackageParser.Package pkg = mPackages.get(pkgName); 4352 if (pkg != null) { 4353 return mProviders.queryIntentForPackage( 4354 intent, resolvedType, flags, pkg.providers, userId); 4355 } 4356 return null; 4357 } 4358 } 4359 4360 @Override 4361 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4362 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4363 4364 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4365 4366 // writer 4367 synchronized (mPackages) { 4368 ArrayList<PackageInfo> list; 4369 if (listUninstalled) { 4370 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4371 for (PackageSetting ps : mSettings.mPackages.values()) { 4372 PackageInfo pi; 4373 if (ps.pkg != null) { 4374 pi = generatePackageInfo(ps.pkg, flags, userId); 4375 } else { 4376 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4377 } 4378 if (pi != null) { 4379 list.add(pi); 4380 } 4381 } 4382 } else { 4383 list = new ArrayList<PackageInfo>(mPackages.size()); 4384 for (PackageParser.Package p : mPackages.values()) { 4385 PackageInfo pi = generatePackageInfo(p, flags, userId); 4386 if (pi != null) { 4387 list.add(pi); 4388 } 4389 } 4390 } 4391 4392 return new ParceledListSlice<PackageInfo>(list); 4393 } 4394 } 4395 4396 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4397 String[] permissions, boolean[] tmp, int flags, int userId) { 4398 int numMatch = 0; 4399 final PermissionsState permissionsState = ps.getPermissionsState(); 4400 for (int i=0; i<permissions.length; i++) { 4401 final String permission = permissions[i]; 4402 if (permissionsState.hasPermission(permission, userId)) { 4403 tmp[i] = true; 4404 numMatch++; 4405 } else { 4406 tmp[i] = false; 4407 } 4408 } 4409 if (numMatch == 0) { 4410 return; 4411 } 4412 PackageInfo pi; 4413 if (ps.pkg != null) { 4414 pi = generatePackageInfo(ps.pkg, flags, userId); 4415 } else { 4416 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4417 } 4418 // The above might return null in cases of uninstalled apps or install-state 4419 // skew across users/profiles. 4420 if (pi != null) { 4421 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4422 if (numMatch == permissions.length) { 4423 pi.requestedPermissions = permissions; 4424 } else { 4425 pi.requestedPermissions = new String[numMatch]; 4426 numMatch = 0; 4427 for (int i=0; i<permissions.length; i++) { 4428 if (tmp[i]) { 4429 pi.requestedPermissions[numMatch] = permissions[i]; 4430 numMatch++; 4431 } 4432 } 4433 } 4434 } 4435 list.add(pi); 4436 } 4437 } 4438 4439 @Override 4440 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4441 String[] permissions, int flags, int userId) { 4442 if (!sUserManager.exists(userId)) return null; 4443 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4444 4445 // writer 4446 synchronized (mPackages) { 4447 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4448 boolean[] tmpBools = new boolean[permissions.length]; 4449 if (listUninstalled) { 4450 for (PackageSetting ps : mSettings.mPackages.values()) { 4451 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4452 } 4453 } else { 4454 for (PackageParser.Package pkg : mPackages.values()) { 4455 PackageSetting ps = (PackageSetting)pkg.mExtras; 4456 if (ps != null) { 4457 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4458 userId); 4459 } 4460 } 4461 } 4462 4463 return new ParceledListSlice<PackageInfo>(list); 4464 } 4465 } 4466 4467 @Override 4468 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4469 if (!sUserManager.exists(userId)) return null; 4470 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4471 4472 // writer 4473 synchronized (mPackages) { 4474 ArrayList<ApplicationInfo> list; 4475 if (listUninstalled) { 4476 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4477 for (PackageSetting ps : mSettings.mPackages.values()) { 4478 ApplicationInfo ai; 4479 if (ps.pkg != null) { 4480 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4481 ps.readUserState(userId), userId); 4482 } else { 4483 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4484 } 4485 if (ai != null) { 4486 list.add(ai); 4487 } 4488 } 4489 } else { 4490 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4491 for (PackageParser.Package p : mPackages.values()) { 4492 if (p.mExtras != null) { 4493 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4494 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4495 if (ai != null) { 4496 list.add(ai); 4497 } 4498 } 4499 } 4500 } 4501 4502 return new ParceledListSlice<ApplicationInfo>(list); 4503 } 4504 } 4505 4506 public List<ApplicationInfo> getPersistentApplications(int flags) { 4507 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4508 4509 // reader 4510 synchronized (mPackages) { 4511 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4512 final int userId = UserHandle.getCallingUserId(); 4513 while (i.hasNext()) { 4514 final PackageParser.Package p = i.next(); 4515 if (p.applicationInfo != null 4516 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4517 && (!mSafeMode || isSystemApp(p))) { 4518 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4519 if (ps != null) { 4520 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4521 ps.readUserState(userId), userId); 4522 if (ai != null) { 4523 finalList.add(ai); 4524 } 4525 } 4526 } 4527 } 4528 } 4529 4530 return finalList; 4531 } 4532 4533 @Override 4534 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4535 if (!sUserManager.exists(userId)) return null; 4536 // reader 4537 synchronized (mPackages) { 4538 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4539 PackageSetting ps = provider != null 4540 ? mSettings.mPackages.get(provider.owner.packageName) 4541 : null; 4542 return ps != null 4543 && mSettings.isEnabledLPr(provider.info, flags, userId) 4544 && (!mSafeMode || (provider.info.applicationInfo.flags 4545 &ApplicationInfo.FLAG_SYSTEM) != 0) 4546 ? PackageParser.generateProviderInfo(provider, flags, 4547 ps.readUserState(userId), userId) 4548 : null; 4549 } 4550 } 4551 4552 /** 4553 * @deprecated 4554 */ 4555 @Deprecated 4556 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4557 // reader 4558 synchronized (mPackages) { 4559 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4560 .entrySet().iterator(); 4561 final int userId = UserHandle.getCallingUserId(); 4562 while (i.hasNext()) { 4563 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4564 PackageParser.Provider p = entry.getValue(); 4565 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4566 4567 if (ps != null && p.syncable 4568 && (!mSafeMode || (p.info.applicationInfo.flags 4569 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4570 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4571 ps.readUserState(userId), userId); 4572 if (info != null) { 4573 outNames.add(entry.getKey()); 4574 outInfo.add(info); 4575 } 4576 } 4577 } 4578 } 4579 } 4580 4581 @Override 4582 public List<ProviderInfo> queryContentProviders(String processName, 4583 int uid, int flags) { 4584 ArrayList<ProviderInfo> finalList = null; 4585 // reader 4586 synchronized (mPackages) { 4587 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4588 final int userId = processName != null ? 4589 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4590 while (i.hasNext()) { 4591 final PackageParser.Provider p = i.next(); 4592 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4593 if (ps != null && p.info.authority != null 4594 && (processName == null 4595 || (p.info.processName.equals(processName) 4596 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4597 && mSettings.isEnabledLPr(p.info, flags, userId) 4598 && (!mSafeMode 4599 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4600 if (finalList == null) { 4601 finalList = new ArrayList<ProviderInfo>(3); 4602 } 4603 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4604 ps.readUserState(userId), userId); 4605 if (info != null) { 4606 finalList.add(info); 4607 } 4608 } 4609 } 4610 } 4611 4612 if (finalList != null) { 4613 Collections.sort(finalList, mProviderInitOrderSorter); 4614 } 4615 4616 return finalList; 4617 } 4618 4619 @Override 4620 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4621 int flags) { 4622 // reader 4623 synchronized (mPackages) { 4624 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4625 return PackageParser.generateInstrumentationInfo(i, flags); 4626 } 4627 } 4628 4629 @Override 4630 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4631 int flags) { 4632 ArrayList<InstrumentationInfo> finalList = 4633 new ArrayList<InstrumentationInfo>(); 4634 4635 // reader 4636 synchronized (mPackages) { 4637 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4638 while (i.hasNext()) { 4639 final PackageParser.Instrumentation p = i.next(); 4640 if (targetPackage == null 4641 || targetPackage.equals(p.info.targetPackage)) { 4642 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4643 flags); 4644 if (ii != null) { 4645 finalList.add(ii); 4646 } 4647 } 4648 } 4649 } 4650 4651 return finalList; 4652 } 4653 4654 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4655 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4656 if (overlays == null) { 4657 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4658 return; 4659 } 4660 for (PackageParser.Package opkg : overlays.values()) { 4661 // Not much to do if idmap fails: we already logged the error 4662 // and we certainly don't want to abort installation of pkg simply 4663 // because an overlay didn't fit properly. For these reasons, 4664 // ignore the return value of createIdmapForPackagePairLI. 4665 createIdmapForPackagePairLI(pkg, opkg); 4666 } 4667 } 4668 4669 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4670 PackageParser.Package opkg) { 4671 if (!opkg.mTrustedOverlay) { 4672 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4673 opkg.baseCodePath + ": overlay not trusted"); 4674 return false; 4675 } 4676 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4677 if (overlaySet == null) { 4678 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4679 opkg.baseCodePath + " but target package has no known overlays"); 4680 return false; 4681 } 4682 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4683 // TODO: generate idmap for split APKs 4684 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4685 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4686 + opkg.baseCodePath); 4687 return false; 4688 } 4689 PackageParser.Package[] overlayArray = 4690 overlaySet.values().toArray(new PackageParser.Package[0]); 4691 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4692 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4693 return p1.mOverlayPriority - p2.mOverlayPriority; 4694 } 4695 }; 4696 Arrays.sort(overlayArray, cmp); 4697 4698 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4699 int i = 0; 4700 for (PackageParser.Package p : overlayArray) { 4701 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4702 } 4703 return true; 4704 } 4705 4706 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4707 final File[] files = dir.listFiles(); 4708 if (ArrayUtils.isEmpty(files)) { 4709 Log.d(TAG, "No files in app dir " + dir); 4710 return; 4711 } 4712 4713 if (DEBUG_PACKAGE_SCANNING) { 4714 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4715 + " flags=0x" + Integer.toHexString(parseFlags)); 4716 } 4717 4718 for (File file : files) { 4719 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4720 && !PackageInstallerService.isStageName(file.getName()); 4721 if (!isPackage) { 4722 // Ignore entries which are not packages 4723 continue; 4724 } 4725 try { 4726 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4727 scanFlags, currentTime, null); 4728 } catch (PackageManagerException e) { 4729 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4730 4731 // Delete invalid userdata apps 4732 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4733 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4734 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4735 if (file.isDirectory()) { 4736 mInstaller.rmPackageDir(file.getAbsolutePath()); 4737 } else { 4738 file.delete(); 4739 } 4740 } 4741 } 4742 } 4743 } 4744 4745 private static File getSettingsProblemFile() { 4746 File dataDir = Environment.getDataDirectory(); 4747 File systemDir = new File(dataDir, "system"); 4748 File fname = new File(systemDir, "uiderrors.txt"); 4749 return fname; 4750 } 4751 4752 static void reportSettingsProblem(int priority, String msg) { 4753 logCriticalInfo(priority, msg); 4754 } 4755 4756 static void logCriticalInfo(int priority, String msg) { 4757 Slog.println(priority, TAG, msg); 4758 EventLogTags.writePmCriticalInfo(msg); 4759 try { 4760 File fname = getSettingsProblemFile(); 4761 FileOutputStream out = new FileOutputStream(fname, true); 4762 PrintWriter pw = new FastPrintWriter(out); 4763 SimpleDateFormat formatter = new SimpleDateFormat(); 4764 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4765 pw.println(dateString + ": " + msg); 4766 pw.close(); 4767 FileUtils.setPermissions( 4768 fname.toString(), 4769 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4770 -1, -1); 4771 } catch (java.io.IOException e) { 4772 } 4773 } 4774 4775 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4776 PackageParser.Package pkg, File srcFile, int parseFlags) 4777 throws PackageManagerException { 4778 if (ps != null 4779 && ps.codePath.equals(srcFile) 4780 && ps.timeStamp == srcFile.lastModified() 4781 && !isCompatSignatureUpdateNeeded(pkg) 4782 && !isRecoverSignatureUpdateNeeded(pkg)) { 4783 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4784 if (ps.signatures.mSignatures != null 4785 && ps.signatures.mSignatures.length != 0 4786 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4787 // Optimization: reuse the existing cached certificates 4788 // if the package appears to be unchanged. 4789 pkg.mSignatures = ps.signatures.mSignatures; 4790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4791 synchronized (mPackages) { 4792 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4793 } 4794 return; 4795 } 4796 4797 Slog.w(TAG, "PackageSetting for " + ps.name 4798 + " is missing signatures. Collecting certs again to recover them."); 4799 } else { 4800 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4801 } 4802 4803 try { 4804 pp.collectCertificates(pkg, parseFlags); 4805 pp.collectManifestDigest(pkg); 4806 } catch (PackageParserException e) { 4807 throw PackageManagerException.from(e); 4808 } 4809 } 4810 4811 /* 4812 * Scan a package and return the newly parsed package. 4813 * Returns null in case of errors and the error code is stored in mLastScanError 4814 */ 4815 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4816 long currentTime, UserHandle user) throws PackageManagerException { 4817 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4818 parseFlags |= mDefParseFlags; 4819 PackageParser pp = new PackageParser(); 4820 pp.setSeparateProcesses(mSeparateProcesses); 4821 pp.setOnlyCoreApps(mOnlyCore); 4822 pp.setDisplayMetrics(mMetrics); 4823 4824 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4825 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4826 } 4827 4828 final PackageParser.Package pkg; 4829 try { 4830 pkg = pp.parsePackage(scanFile, parseFlags); 4831 } catch (PackageParserException e) { 4832 throw PackageManagerException.from(e); 4833 } 4834 4835 PackageSetting ps = null; 4836 PackageSetting updatedPkg; 4837 // reader 4838 synchronized (mPackages) { 4839 // Look to see if we already know about this package. 4840 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4841 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4842 // This package has been renamed to its original name. Let's 4843 // use that. 4844 ps = mSettings.peekPackageLPr(oldName); 4845 } 4846 // If there was no original package, see one for the real package name. 4847 if (ps == null) { 4848 ps = mSettings.peekPackageLPr(pkg.packageName); 4849 } 4850 // Check to see if this package could be hiding/updating a system 4851 // package. Must look for it either under the original or real 4852 // package name depending on our state. 4853 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4854 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4855 } 4856 boolean updatedPkgBetter = false; 4857 // First check if this is a system package that may involve an update 4858 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4859 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4860 // it needs to drop FLAG_PRIVILEGED. 4861 if (locationIsPrivileged(scanFile)) { 4862 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4863 } else { 4864 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4865 } 4866 4867 if (ps != null && !ps.codePath.equals(scanFile)) { 4868 // The path has changed from what was last scanned... check the 4869 // version of the new path against what we have stored to determine 4870 // what to do. 4871 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4872 if (pkg.mVersionCode <= ps.versionCode) { 4873 // The system package has been updated and the code path does not match 4874 // Ignore entry. Skip it. 4875 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4876 + " ignored: updated version " + ps.versionCode 4877 + " better than this " + pkg.mVersionCode); 4878 if (!updatedPkg.codePath.equals(scanFile)) { 4879 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4880 + ps.name + " changing from " + updatedPkg.codePathString 4881 + " to " + scanFile); 4882 updatedPkg.codePath = scanFile; 4883 updatedPkg.codePathString = scanFile.toString(); 4884 updatedPkg.resourcePath = scanFile; 4885 updatedPkg.resourcePathString = scanFile.toString(); 4886 } 4887 updatedPkg.pkg = pkg; 4888 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4889 } else { 4890 // The current app on the system partition is better than 4891 // what we have updated to on the data partition; switch 4892 // back to the system partition version. 4893 // At this point, its safely assumed that package installation for 4894 // apps in system partition will go through. If not there won't be a working 4895 // version of the app 4896 // writer 4897 synchronized (mPackages) { 4898 // Just remove the loaded entries from package lists. 4899 mPackages.remove(ps.name); 4900 } 4901 4902 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4903 + " reverting from " + ps.codePathString 4904 + ": new version " + pkg.mVersionCode 4905 + " better than installed " + ps.versionCode); 4906 4907 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4908 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4909 getAppDexInstructionSets(ps)); 4910 synchronized (mInstallLock) { 4911 args.cleanUpResourcesLI(); 4912 } 4913 synchronized (mPackages) { 4914 mSettings.enableSystemPackageLPw(ps.name); 4915 } 4916 updatedPkgBetter = true; 4917 } 4918 } 4919 } 4920 4921 if (updatedPkg != null) { 4922 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4923 // initially 4924 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4925 4926 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4927 // flag set initially 4928 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4929 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4930 } 4931 } 4932 4933 // Verify certificates against what was last scanned 4934 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4935 4936 /* 4937 * A new system app appeared, but we already had a non-system one of the 4938 * same name installed earlier. 4939 */ 4940 boolean shouldHideSystemApp = false; 4941 if (updatedPkg == null && ps != null 4942 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4943 /* 4944 * Check to make sure the signatures match first. If they don't, 4945 * wipe the installed application and its data. 4946 */ 4947 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4948 != PackageManager.SIGNATURE_MATCH) { 4949 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4950 + " signatures don't match existing userdata copy; removing"); 4951 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4952 ps = null; 4953 } else { 4954 /* 4955 * If the newly-added system app is an older version than the 4956 * already installed version, hide it. It will be scanned later 4957 * and re-added like an update. 4958 */ 4959 if (pkg.mVersionCode <= ps.versionCode) { 4960 shouldHideSystemApp = true; 4961 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4962 + " but new version " + pkg.mVersionCode + " better than installed " 4963 + ps.versionCode + "; hiding system"); 4964 } else { 4965 /* 4966 * The newly found system app is a newer version that the 4967 * one previously installed. Simply remove the 4968 * already-installed application and replace it with our own 4969 * while keeping the application data. 4970 */ 4971 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4972 + " reverting from " + ps.codePathString + ": new version " 4973 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4974 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4975 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4976 getAppDexInstructionSets(ps)); 4977 synchronized (mInstallLock) { 4978 args.cleanUpResourcesLI(); 4979 } 4980 } 4981 } 4982 } 4983 4984 // The apk is forward locked (not public) if its code and resources 4985 // are kept in different files. (except for app in either system or 4986 // vendor path). 4987 // TODO grab this value from PackageSettings 4988 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4989 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4990 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4991 } 4992 } 4993 4994 // TODO: extend to support forward-locked splits 4995 String resourcePath = null; 4996 String baseResourcePath = null; 4997 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4998 if (ps != null && ps.resourcePathString != null) { 4999 resourcePath = ps.resourcePathString; 5000 baseResourcePath = ps.resourcePathString; 5001 } else { 5002 // Should not happen at all. Just log an error. 5003 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5004 } 5005 } else { 5006 resourcePath = pkg.codePath; 5007 baseResourcePath = pkg.baseCodePath; 5008 } 5009 5010 // Set application objects path explicitly. 5011 pkg.applicationInfo.setCodePath(pkg.codePath); 5012 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5013 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5014 pkg.applicationInfo.setResourcePath(resourcePath); 5015 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5016 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5017 5018 // Note that we invoke the following method only if we are about to unpack an application 5019 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5020 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5021 5022 /* 5023 * If the system app should be overridden by a previously installed 5024 * data, hide the system app now and let the /data/app scan pick it up 5025 * again. 5026 */ 5027 if (shouldHideSystemApp) { 5028 synchronized (mPackages) { 5029 /* 5030 * We have to grant systems permissions before we hide, because 5031 * grantPermissions will assume the package update is trying to 5032 * expand its permissions. 5033 */ 5034 grantPermissionsLPw(pkg, true, pkg.packageName); 5035 mSettings.disableSystemPackageLPw(pkg.packageName); 5036 } 5037 } 5038 5039 return scannedPkg; 5040 } 5041 5042 private static String fixProcessName(String defProcessName, 5043 String processName, int uid) { 5044 if (processName == null) { 5045 return defProcessName; 5046 } 5047 return processName; 5048 } 5049 5050 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5051 throws PackageManagerException { 5052 if (pkgSetting.signatures.mSignatures != null) { 5053 // Already existing package. Make sure signatures match 5054 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5055 == PackageManager.SIGNATURE_MATCH; 5056 if (!match) { 5057 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5058 == PackageManager.SIGNATURE_MATCH; 5059 } 5060 if (!match) { 5061 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5062 == PackageManager.SIGNATURE_MATCH; 5063 } 5064 if (!match) { 5065 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5066 + pkg.packageName + " signatures do not match the " 5067 + "previously installed version; ignoring!"); 5068 } 5069 } 5070 5071 // Check for shared user signatures 5072 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5073 // Already existing package. Make sure signatures match 5074 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5075 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5076 if (!match) { 5077 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5078 == PackageManager.SIGNATURE_MATCH; 5079 } 5080 if (!match) { 5081 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5082 == PackageManager.SIGNATURE_MATCH; 5083 } 5084 if (!match) { 5085 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5086 "Package " + pkg.packageName 5087 + " has no signatures that match those in shared user " 5088 + pkgSetting.sharedUser.name + "; ignoring!"); 5089 } 5090 } 5091 } 5092 5093 /** 5094 * Enforces that only the system UID or root's UID can call a method exposed 5095 * via Binder. 5096 * 5097 * @param message used as message if SecurityException is thrown 5098 * @throws SecurityException if the caller is not system or root 5099 */ 5100 private static final void enforceSystemOrRoot(String message) { 5101 final int uid = Binder.getCallingUid(); 5102 if (uid != Process.SYSTEM_UID && uid != 0) { 5103 throw new SecurityException(message); 5104 } 5105 } 5106 5107 @Override 5108 public void performBootDexOpt() { 5109 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5110 5111 // Before everything else, see whether we need to fstrim. 5112 try { 5113 IMountService ms = PackageHelper.getMountService(); 5114 if (ms != null) { 5115 final boolean isUpgrade = isUpgrade(); 5116 boolean doTrim = isUpgrade; 5117 if (doTrim) { 5118 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5119 } else { 5120 final long interval = android.provider.Settings.Global.getLong( 5121 mContext.getContentResolver(), 5122 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5123 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5124 if (interval > 0) { 5125 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5126 if (timeSinceLast > interval) { 5127 doTrim = true; 5128 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5129 + "; running immediately"); 5130 } 5131 } 5132 } 5133 if (doTrim) { 5134 if (!isFirstBoot()) { 5135 try { 5136 ActivityManagerNative.getDefault().showBootMessage( 5137 mContext.getResources().getString( 5138 R.string.android_upgrading_fstrim), true); 5139 } catch (RemoteException e) { 5140 } 5141 } 5142 ms.runMaintenance(); 5143 } 5144 } else { 5145 Slog.e(TAG, "Mount service unavailable!"); 5146 } 5147 } catch (RemoteException e) { 5148 // Can't happen; MountService is local 5149 } 5150 5151 final ArraySet<PackageParser.Package> pkgs; 5152 synchronized (mPackages) { 5153 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5154 } 5155 5156 if (pkgs != null) { 5157 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5158 // in case the device runs out of space. 5159 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5160 // Give priority to core apps. 5161 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5162 PackageParser.Package pkg = it.next(); 5163 if (pkg.coreApp) { 5164 if (DEBUG_DEXOPT) { 5165 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5166 } 5167 sortedPkgs.add(pkg); 5168 it.remove(); 5169 } 5170 } 5171 // Give priority to system apps that listen for pre boot complete. 5172 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5173 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5174 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5175 PackageParser.Package pkg = it.next(); 5176 if (pkgNames.contains(pkg.packageName)) { 5177 if (DEBUG_DEXOPT) { 5178 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5179 } 5180 sortedPkgs.add(pkg); 5181 it.remove(); 5182 } 5183 } 5184 // Give priority to system apps. 5185 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5186 PackageParser.Package pkg = it.next(); 5187 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5188 if (DEBUG_DEXOPT) { 5189 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5190 } 5191 sortedPkgs.add(pkg); 5192 it.remove(); 5193 } 5194 } 5195 // Give priority to updated system apps. 5196 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5197 PackageParser.Package pkg = it.next(); 5198 if (pkg.isUpdatedSystemApp()) { 5199 if (DEBUG_DEXOPT) { 5200 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5201 } 5202 sortedPkgs.add(pkg); 5203 it.remove(); 5204 } 5205 } 5206 // Give priority to apps that listen for boot complete. 5207 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5208 pkgNames = getPackageNamesForIntent(intent); 5209 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5210 PackageParser.Package pkg = it.next(); 5211 if (pkgNames.contains(pkg.packageName)) { 5212 if (DEBUG_DEXOPT) { 5213 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5214 } 5215 sortedPkgs.add(pkg); 5216 it.remove(); 5217 } 5218 } 5219 // Filter out packages that aren't recently used. 5220 filterRecentlyUsedApps(pkgs); 5221 // Add all remaining apps. 5222 for (PackageParser.Package pkg : pkgs) { 5223 if (DEBUG_DEXOPT) { 5224 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5225 } 5226 sortedPkgs.add(pkg); 5227 } 5228 5229 // If we want to be lazy, filter everything that wasn't recently used. 5230 if (mLazyDexOpt) { 5231 filterRecentlyUsedApps(sortedPkgs); 5232 } 5233 5234 int i = 0; 5235 int total = sortedPkgs.size(); 5236 File dataDir = Environment.getDataDirectory(); 5237 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5238 if (lowThreshold == 0) { 5239 throw new IllegalStateException("Invalid low memory threshold"); 5240 } 5241 for (PackageParser.Package pkg : sortedPkgs) { 5242 long usableSpace = dataDir.getUsableSpace(); 5243 if (usableSpace < lowThreshold) { 5244 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5245 break; 5246 } 5247 performBootDexOpt(pkg, ++i, total); 5248 } 5249 } 5250 } 5251 5252 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5253 // Filter out packages that aren't recently used. 5254 // 5255 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5256 // should do a full dexopt. 5257 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5258 int total = pkgs.size(); 5259 int skipped = 0; 5260 long now = System.currentTimeMillis(); 5261 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5262 PackageParser.Package pkg = i.next(); 5263 long then = pkg.mLastPackageUsageTimeInMills; 5264 if (then + mDexOptLRUThresholdInMills < now) { 5265 if (DEBUG_DEXOPT) { 5266 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5267 ((then == 0) ? "never" : new Date(then))); 5268 } 5269 i.remove(); 5270 skipped++; 5271 } 5272 } 5273 if (DEBUG_DEXOPT) { 5274 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5275 } 5276 } 5277 } 5278 5279 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5280 List<ResolveInfo> ris = null; 5281 try { 5282 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5283 intent, null, 0, UserHandle.USER_OWNER); 5284 } catch (RemoteException e) { 5285 } 5286 ArraySet<String> pkgNames = new ArraySet<String>(); 5287 if (ris != null) { 5288 for (ResolveInfo ri : ris) { 5289 pkgNames.add(ri.activityInfo.packageName); 5290 } 5291 } 5292 return pkgNames; 5293 } 5294 5295 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5296 if (DEBUG_DEXOPT) { 5297 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5298 } 5299 if (!isFirstBoot()) { 5300 try { 5301 ActivityManagerNative.getDefault().showBootMessage( 5302 mContext.getResources().getString(R.string.android_upgrading_apk, 5303 curr, total), true); 5304 } catch (RemoteException e) { 5305 } 5306 } 5307 PackageParser.Package p = pkg; 5308 synchronized (mInstallLock) { 5309 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5310 false /* force dex */, false /* defer */, true /* include dependencies */); 5311 } 5312 } 5313 5314 @Override 5315 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5316 return performDexOpt(packageName, instructionSet, false); 5317 } 5318 5319 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5320 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5321 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5322 if (!dexopt && !updateUsage) { 5323 // We aren't going to dexopt or update usage, so bail early. 5324 return false; 5325 } 5326 PackageParser.Package p; 5327 final String targetInstructionSet; 5328 synchronized (mPackages) { 5329 p = mPackages.get(packageName); 5330 if (p == null) { 5331 return false; 5332 } 5333 if (updateUsage) { 5334 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5335 } 5336 mPackageUsage.write(false); 5337 if (!dexopt) { 5338 // We aren't going to dexopt, so bail early. 5339 return false; 5340 } 5341 5342 targetInstructionSet = instructionSet != null ? instructionSet : 5343 getPrimaryInstructionSet(p.applicationInfo); 5344 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5345 return false; 5346 } 5347 } 5348 5349 synchronized (mInstallLock) { 5350 final String[] instructionSets = new String[] { targetInstructionSet }; 5351 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5352 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5353 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5354 } 5355 } 5356 5357 public ArraySet<String> getPackagesThatNeedDexOpt() { 5358 ArraySet<String> pkgs = null; 5359 synchronized (mPackages) { 5360 for (PackageParser.Package p : mPackages.values()) { 5361 if (DEBUG_DEXOPT) { 5362 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5363 } 5364 if (!p.mDexOptPerformed.isEmpty()) { 5365 continue; 5366 } 5367 if (pkgs == null) { 5368 pkgs = new ArraySet<String>(); 5369 } 5370 pkgs.add(p.packageName); 5371 } 5372 } 5373 return pkgs; 5374 } 5375 5376 public void shutdown() { 5377 mPackageUsage.write(true); 5378 } 5379 5380 @Override 5381 public void forceDexOpt(String packageName) { 5382 enforceSystemOrRoot("forceDexOpt"); 5383 5384 PackageParser.Package pkg; 5385 synchronized (mPackages) { 5386 pkg = mPackages.get(packageName); 5387 if (pkg == null) { 5388 throw new IllegalArgumentException("Missing package: " + packageName); 5389 } 5390 } 5391 5392 synchronized (mInstallLock) { 5393 final String[] instructionSets = new String[] { 5394 getPrimaryInstructionSet(pkg.applicationInfo) }; 5395 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5396 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5397 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5398 throw new IllegalStateException("Failed to dexopt: " + res); 5399 } 5400 } 5401 } 5402 5403 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5404 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5405 Slog.w(TAG, "Unable to update from " + oldPkg.name 5406 + " to " + newPkg.packageName 5407 + ": old package not in system partition"); 5408 return false; 5409 } else if (mPackages.get(oldPkg.name) != null) { 5410 Slog.w(TAG, "Unable to update from " + oldPkg.name 5411 + " to " + newPkg.packageName 5412 + ": old package still exists"); 5413 return false; 5414 } 5415 return true; 5416 } 5417 5418 private File getDataPathForPackage(String packageName, int userId) { 5419 /* 5420 * Until we fully support multiple users, return the directory we 5421 * previously would have. The PackageManagerTests will need to be 5422 * revised when this is changed back.. 5423 */ 5424 if (userId == 0) { 5425 return new File(mAppDataDir, packageName); 5426 } else { 5427 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5428 + File.separator + packageName); 5429 } 5430 } 5431 5432 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5433 int[] users = sUserManager.getUserIds(); 5434 int res = mInstaller.install(packageName, uid, uid, seinfo); 5435 if (res < 0) { 5436 return res; 5437 } 5438 for (int user : users) { 5439 if (user != 0) { 5440 res = mInstaller.createUserData(packageName, 5441 UserHandle.getUid(user, uid), user, seinfo); 5442 if (res < 0) { 5443 return res; 5444 } 5445 } 5446 } 5447 return res; 5448 } 5449 5450 private int removeDataDirsLI(String packageName) { 5451 int[] users = sUserManager.getUserIds(); 5452 int res = 0; 5453 for (int user : users) { 5454 int resInner = mInstaller.remove(packageName, user); 5455 if (resInner < 0) { 5456 res = resInner; 5457 } 5458 } 5459 5460 return res; 5461 } 5462 5463 private int deleteCodeCacheDirsLI(String packageName) { 5464 int[] users = sUserManager.getUserIds(); 5465 int res = 0; 5466 for (int user : users) { 5467 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5468 if (resInner < 0) { 5469 res = resInner; 5470 } 5471 } 5472 return res; 5473 } 5474 5475 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5476 PackageParser.Package changingLib) { 5477 if (file.path != null) { 5478 usesLibraryFiles.add(file.path); 5479 return; 5480 } 5481 PackageParser.Package p = mPackages.get(file.apk); 5482 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5483 // If we are doing this while in the middle of updating a library apk, 5484 // then we need to make sure to use that new apk for determining the 5485 // dependencies here. (We haven't yet finished committing the new apk 5486 // to the package manager state.) 5487 if (p == null || p.packageName.equals(changingLib.packageName)) { 5488 p = changingLib; 5489 } 5490 } 5491 if (p != null) { 5492 usesLibraryFiles.addAll(p.getAllCodePaths()); 5493 } 5494 } 5495 5496 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5497 PackageParser.Package changingLib) throws PackageManagerException { 5498 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5499 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5500 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5501 for (int i=0; i<N; i++) { 5502 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5503 if (file == null) { 5504 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5505 "Package " + pkg.packageName + " requires unavailable shared library " 5506 + pkg.usesLibraries.get(i) + "; failing!"); 5507 } 5508 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5509 } 5510 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5511 for (int i=0; i<N; i++) { 5512 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5513 if (file == null) { 5514 Slog.w(TAG, "Package " + pkg.packageName 5515 + " desires unavailable shared library " 5516 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5517 } else { 5518 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5519 } 5520 } 5521 N = usesLibraryFiles.size(); 5522 if (N > 0) { 5523 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5524 } else { 5525 pkg.usesLibraryFiles = null; 5526 } 5527 } 5528 } 5529 5530 private static boolean hasString(List<String> list, List<String> which) { 5531 if (list == null) { 5532 return false; 5533 } 5534 for (int i=list.size()-1; i>=0; i--) { 5535 for (int j=which.size()-1; j>=0; j--) { 5536 if (which.get(j).equals(list.get(i))) { 5537 return true; 5538 } 5539 } 5540 } 5541 return false; 5542 } 5543 5544 private void updateAllSharedLibrariesLPw() { 5545 for (PackageParser.Package pkg : mPackages.values()) { 5546 try { 5547 updateSharedLibrariesLPw(pkg, null); 5548 } catch (PackageManagerException e) { 5549 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5550 } 5551 } 5552 } 5553 5554 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5555 PackageParser.Package changingPkg) { 5556 ArrayList<PackageParser.Package> res = null; 5557 for (PackageParser.Package pkg : mPackages.values()) { 5558 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5559 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5560 if (res == null) { 5561 res = new ArrayList<PackageParser.Package>(); 5562 } 5563 res.add(pkg); 5564 try { 5565 updateSharedLibrariesLPw(pkg, changingPkg); 5566 } catch (PackageManagerException e) { 5567 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5568 } 5569 } 5570 } 5571 return res; 5572 } 5573 5574 /** 5575 * Derive the value of the {@code cpuAbiOverride} based on the provided 5576 * value and an optional stored value from the package settings. 5577 */ 5578 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5579 String cpuAbiOverride = null; 5580 5581 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5582 cpuAbiOverride = null; 5583 } else if (abiOverride != null) { 5584 cpuAbiOverride = abiOverride; 5585 } else if (settings != null) { 5586 cpuAbiOverride = settings.cpuAbiOverrideString; 5587 } 5588 5589 return cpuAbiOverride; 5590 } 5591 5592 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5593 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5594 boolean success = false; 5595 try { 5596 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5597 currentTime, user); 5598 success = true; 5599 return res; 5600 } finally { 5601 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5602 removeDataDirsLI(pkg.packageName); 5603 } 5604 } 5605 } 5606 5607 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5608 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5609 final File scanFile = new File(pkg.codePath); 5610 if (pkg.applicationInfo.getCodePath() == null || 5611 pkg.applicationInfo.getResourcePath() == null) { 5612 // Bail out. The resource and code paths haven't been set. 5613 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5614 "Code and resource paths haven't been set correctly"); 5615 } 5616 5617 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5618 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5619 } else { 5620 // Only allow system apps to be flagged as core apps. 5621 pkg.coreApp = false; 5622 } 5623 5624 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5625 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5626 } 5627 5628 if (mCustomResolverComponentName != null && 5629 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5630 setUpCustomResolverActivity(pkg); 5631 } 5632 5633 if (pkg.packageName.equals("android")) { 5634 synchronized (mPackages) { 5635 if (mAndroidApplication != null) { 5636 Slog.w(TAG, "*************************************************"); 5637 Slog.w(TAG, "Core android package being redefined. Skipping."); 5638 Slog.w(TAG, " file=" + scanFile); 5639 Slog.w(TAG, "*************************************************"); 5640 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5641 "Core android package being redefined. Skipping."); 5642 } 5643 5644 // Set up information for our fall-back user intent resolution activity. 5645 mPlatformPackage = pkg; 5646 pkg.mVersionCode = mSdkVersion; 5647 mAndroidApplication = pkg.applicationInfo; 5648 5649 if (!mResolverReplaced) { 5650 mResolveActivity.applicationInfo = mAndroidApplication; 5651 mResolveActivity.name = ResolverActivity.class.getName(); 5652 mResolveActivity.packageName = mAndroidApplication.packageName; 5653 mResolveActivity.processName = "system:ui"; 5654 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5655 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5656 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5657 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5658 mResolveActivity.exported = true; 5659 mResolveActivity.enabled = true; 5660 mResolveInfo.activityInfo = mResolveActivity; 5661 mResolveInfo.priority = 0; 5662 mResolveInfo.preferredOrder = 0; 5663 mResolveInfo.match = 0; 5664 mResolveComponentName = new ComponentName( 5665 mAndroidApplication.packageName, mResolveActivity.name); 5666 } 5667 } 5668 } 5669 5670 if (DEBUG_PACKAGE_SCANNING) { 5671 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5672 Log.d(TAG, "Scanning package " + pkg.packageName); 5673 } 5674 5675 if (mPackages.containsKey(pkg.packageName) 5676 || mSharedLibraries.containsKey(pkg.packageName)) { 5677 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5678 "Application package " + pkg.packageName 5679 + " already installed. Skipping duplicate."); 5680 } 5681 5682 // If we're only installing presumed-existing packages, require that the 5683 // scanned APK is both already known and at the path previously established 5684 // for it. Previously unknown packages we pick up normally, but if we have an 5685 // a priori expectation about this package's install presence, enforce it. 5686 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5687 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5688 if (known != null) { 5689 if (DEBUG_PACKAGE_SCANNING) { 5690 Log.d(TAG, "Examining " + pkg.codePath 5691 + " and requiring known paths " + known.codePathString 5692 + " & " + known.resourcePathString); 5693 } 5694 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5695 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5696 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5697 "Application package " + pkg.packageName 5698 + " found at " + pkg.applicationInfo.getCodePath() 5699 + " but expected at " + known.codePathString + "; ignoring."); 5700 } 5701 } 5702 } 5703 5704 // Initialize package source and resource directories 5705 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5706 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5707 5708 SharedUserSetting suid = null; 5709 PackageSetting pkgSetting = null; 5710 5711 if (!isSystemApp(pkg)) { 5712 // Only system apps can use these features. 5713 pkg.mOriginalPackages = null; 5714 pkg.mRealPackage = null; 5715 pkg.mAdoptPermissions = null; 5716 } 5717 5718 // writer 5719 synchronized (mPackages) { 5720 if (pkg.mSharedUserId != null) { 5721 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5722 if (suid == null) { 5723 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5724 "Creating application package " + pkg.packageName 5725 + " for shared user failed"); 5726 } 5727 if (DEBUG_PACKAGE_SCANNING) { 5728 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5729 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5730 + "): packages=" + suid.packages); 5731 } 5732 } 5733 5734 // Check if we are renaming from an original package name. 5735 PackageSetting origPackage = null; 5736 String realName = null; 5737 if (pkg.mOriginalPackages != null) { 5738 // This package may need to be renamed to a previously 5739 // installed name. Let's check on that... 5740 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5741 if (pkg.mOriginalPackages.contains(renamed)) { 5742 // This package had originally been installed as the 5743 // original name, and we have already taken care of 5744 // transitioning to the new one. Just update the new 5745 // one to continue using the old name. 5746 realName = pkg.mRealPackage; 5747 if (!pkg.packageName.equals(renamed)) { 5748 // Callers into this function may have already taken 5749 // care of renaming the package; only do it here if 5750 // it is not already done. 5751 pkg.setPackageName(renamed); 5752 } 5753 5754 } else { 5755 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5756 if ((origPackage = mSettings.peekPackageLPr( 5757 pkg.mOriginalPackages.get(i))) != null) { 5758 // We do have the package already installed under its 5759 // original name... should we use it? 5760 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5761 // New package is not compatible with original. 5762 origPackage = null; 5763 continue; 5764 } else if (origPackage.sharedUser != null) { 5765 // Make sure uid is compatible between packages. 5766 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5767 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5768 + " to " + pkg.packageName + ": old uid " 5769 + origPackage.sharedUser.name 5770 + " differs from " + pkg.mSharedUserId); 5771 origPackage = null; 5772 continue; 5773 } 5774 } else { 5775 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5776 + pkg.packageName + " to old name " + origPackage.name); 5777 } 5778 break; 5779 } 5780 } 5781 } 5782 } 5783 5784 if (mTransferedPackages.contains(pkg.packageName)) { 5785 Slog.w(TAG, "Package " + pkg.packageName 5786 + " was transferred to another, but its .apk remains"); 5787 } 5788 5789 // Just create the setting, don't add it yet. For already existing packages 5790 // the PkgSetting exists already and doesn't have to be created. 5791 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5792 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5793 pkg.applicationInfo.primaryCpuAbi, 5794 pkg.applicationInfo.secondaryCpuAbi, 5795 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5796 user, false); 5797 if (pkgSetting == null) { 5798 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5799 "Creating application package " + pkg.packageName + " failed"); 5800 } 5801 5802 if (pkgSetting.origPackage != null) { 5803 // If we are first transitioning from an original package, 5804 // fix up the new package's name now. We need to do this after 5805 // looking up the package under its new name, so getPackageLP 5806 // can take care of fiddling things correctly. 5807 pkg.setPackageName(origPackage.name); 5808 5809 // File a report about this. 5810 String msg = "New package " + pkgSetting.realName 5811 + " renamed to replace old package " + pkgSetting.name; 5812 reportSettingsProblem(Log.WARN, msg); 5813 5814 // Make a note of it. 5815 mTransferedPackages.add(origPackage.name); 5816 5817 // No longer need to retain this. 5818 pkgSetting.origPackage = null; 5819 } 5820 5821 if (realName != null) { 5822 // Make a note of it. 5823 mTransferedPackages.add(pkg.packageName); 5824 } 5825 5826 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5827 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5828 } 5829 5830 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5831 // Check all shared libraries and map to their actual file path. 5832 // We only do this here for apps not on a system dir, because those 5833 // are the only ones that can fail an install due to this. We 5834 // will take care of the system apps by updating all of their 5835 // library paths after the scan is done. 5836 updateSharedLibrariesLPw(pkg, null); 5837 } 5838 5839 if (mFoundPolicyFile) { 5840 SELinuxMMAC.assignSeinfoValue(pkg); 5841 } 5842 5843 pkg.applicationInfo.uid = pkgSetting.appId; 5844 pkg.mExtras = pkgSetting; 5845 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5846 try { 5847 verifySignaturesLP(pkgSetting, pkg); 5848 // We just determined the app is signed correctly, so bring 5849 // over the latest parsed certs. 5850 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5851 } catch (PackageManagerException e) { 5852 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5853 throw e; 5854 } 5855 // The signature has changed, but this package is in the system 5856 // image... let's recover! 5857 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5858 // However... if this package is part of a shared user, but it 5859 // doesn't match the signature of the shared user, let's fail. 5860 // What this means is that you can't change the signatures 5861 // associated with an overall shared user, which doesn't seem all 5862 // that unreasonable. 5863 if (pkgSetting.sharedUser != null) { 5864 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5865 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5866 throw new PackageManagerException( 5867 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5868 "Signature mismatch for shared user : " 5869 + pkgSetting.sharedUser); 5870 } 5871 } 5872 // File a report about this. 5873 String msg = "System package " + pkg.packageName 5874 + " signature changed; retaining data."; 5875 reportSettingsProblem(Log.WARN, msg); 5876 } 5877 } else { 5878 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5879 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5880 + pkg.packageName + " upgrade keys do not match the " 5881 + "previously installed version"); 5882 } else { 5883 // We just determined the app is signed correctly, so bring 5884 // over the latest parsed certs. 5885 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5886 } 5887 } 5888 // Verify that this new package doesn't have any content providers 5889 // that conflict with existing packages. Only do this if the 5890 // package isn't already installed, since we don't want to break 5891 // things that are installed. 5892 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5893 final int N = pkg.providers.size(); 5894 int i; 5895 for (i=0; i<N; i++) { 5896 PackageParser.Provider p = pkg.providers.get(i); 5897 if (p.info.authority != null) { 5898 String names[] = p.info.authority.split(";"); 5899 for (int j = 0; j < names.length; j++) { 5900 if (mProvidersByAuthority.containsKey(names[j])) { 5901 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5902 final String otherPackageName = 5903 ((other != null && other.getComponentName() != null) ? 5904 other.getComponentName().getPackageName() : "?"); 5905 throw new PackageManagerException( 5906 INSTALL_FAILED_CONFLICTING_PROVIDER, 5907 "Can't install because provider name " + names[j] 5908 + " (in package " + pkg.applicationInfo.packageName 5909 + ") is already used by " + otherPackageName); 5910 } 5911 } 5912 } 5913 } 5914 } 5915 5916 if (pkg.mAdoptPermissions != null) { 5917 // This package wants to adopt ownership of permissions from 5918 // another package. 5919 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5920 final String origName = pkg.mAdoptPermissions.get(i); 5921 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5922 if (orig != null) { 5923 if (verifyPackageUpdateLPr(orig, pkg)) { 5924 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5925 + pkg.packageName); 5926 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5927 } 5928 } 5929 } 5930 } 5931 } 5932 5933 final String pkgName = pkg.packageName; 5934 5935 final long scanFileTime = scanFile.lastModified(); 5936 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5937 pkg.applicationInfo.processName = fixProcessName( 5938 pkg.applicationInfo.packageName, 5939 pkg.applicationInfo.processName, 5940 pkg.applicationInfo.uid); 5941 5942 File dataPath; 5943 if (mPlatformPackage == pkg) { 5944 // The system package is special. 5945 dataPath = new File(Environment.getDataDirectory(), "system"); 5946 5947 pkg.applicationInfo.dataDir = dataPath.getPath(); 5948 5949 } else { 5950 // This is a normal package, need to make its data directory. 5951 dataPath = getDataPathForPackage(pkg.packageName, 0); 5952 5953 boolean uidError = false; 5954 if (dataPath.exists()) { 5955 int currentUid = 0; 5956 try { 5957 StructStat stat = Os.stat(dataPath.getPath()); 5958 currentUid = stat.st_uid; 5959 } catch (ErrnoException e) { 5960 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5961 } 5962 5963 // If we have mismatched owners for the data path, we have a problem. 5964 if (currentUid != pkg.applicationInfo.uid) { 5965 boolean recovered = false; 5966 if (currentUid == 0) { 5967 // The directory somehow became owned by root. Wow. 5968 // This is probably because the system was stopped while 5969 // installd was in the middle of messing with its libs 5970 // directory. Ask installd to fix that. 5971 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5972 pkg.applicationInfo.uid); 5973 if (ret >= 0) { 5974 recovered = true; 5975 String msg = "Package " + pkg.packageName 5976 + " unexpectedly changed to uid 0; recovered to " + 5977 + pkg.applicationInfo.uid; 5978 reportSettingsProblem(Log.WARN, msg); 5979 } 5980 } 5981 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5982 || (scanFlags&SCAN_BOOTING) != 0)) { 5983 // If this is a system app, we can at least delete its 5984 // current data so the application will still work. 5985 int ret = removeDataDirsLI(pkgName); 5986 if (ret >= 0) { 5987 // TODO: Kill the processes first 5988 // Old data gone! 5989 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5990 ? "System package " : "Third party package "; 5991 String msg = prefix + pkg.packageName 5992 + " has changed from uid: " 5993 + currentUid + " to " 5994 + pkg.applicationInfo.uid + "; old data erased"; 5995 reportSettingsProblem(Log.WARN, msg); 5996 recovered = true; 5997 5998 // And now re-install the app. 5999 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6000 pkg.applicationInfo.seinfo); 6001 if (ret == -1) { 6002 // Ack should not happen! 6003 msg = prefix + pkg.packageName 6004 + " could not have data directory re-created after delete."; 6005 reportSettingsProblem(Log.WARN, msg); 6006 throw new PackageManagerException( 6007 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6008 } 6009 } 6010 if (!recovered) { 6011 mHasSystemUidErrors = true; 6012 } 6013 } else if (!recovered) { 6014 // If we allow this install to proceed, we will be broken. 6015 // Abort, abort! 6016 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6017 "scanPackageLI"); 6018 } 6019 if (!recovered) { 6020 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6021 + pkg.applicationInfo.uid + "/fs_" 6022 + currentUid; 6023 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6024 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6025 String msg = "Package " + pkg.packageName 6026 + " has mismatched uid: " 6027 + currentUid + " on disk, " 6028 + pkg.applicationInfo.uid + " in settings"; 6029 // writer 6030 synchronized (mPackages) { 6031 mSettings.mReadMessages.append(msg); 6032 mSettings.mReadMessages.append('\n'); 6033 uidError = true; 6034 if (!pkgSetting.uidError) { 6035 reportSettingsProblem(Log.ERROR, msg); 6036 } 6037 } 6038 } 6039 } 6040 pkg.applicationInfo.dataDir = dataPath.getPath(); 6041 if (mShouldRestoreconData) { 6042 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6043 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6044 pkg.applicationInfo.uid); 6045 } 6046 } else { 6047 if (DEBUG_PACKAGE_SCANNING) { 6048 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6049 Log.v(TAG, "Want this data dir: " + dataPath); 6050 } 6051 //invoke installer to do the actual installation 6052 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6053 pkg.applicationInfo.seinfo); 6054 if (ret < 0) { 6055 // Error from installer 6056 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6057 "Unable to create data dirs [errorCode=" + ret + "]"); 6058 } 6059 6060 if (dataPath.exists()) { 6061 pkg.applicationInfo.dataDir = dataPath.getPath(); 6062 } else { 6063 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6064 pkg.applicationInfo.dataDir = null; 6065 } 6066 } 6067 6068 pkgSetting.uidError = uidError; 6069 } 6070 6071 final String path = scanFile.getPath(); 6072 final String codePath = pkg.applicationInfo.getCodePath(); 6073 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6074 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6075 setBundledAppAbisAndRoots(pkg, pkgSetting); 6076 6077 // If we haven't found any native libraries for the app, check if it has 6078 // renderscript code. We'll need to force the app to 32 bit if it has 6079 // renderscript bitcode. 6080 if (pkg.applicationInfo.primaryCpuAbi == null 6081 && pkg.applicationInfo.secondaryCpuAbi == null 6082 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6083 NativeLibraryHelper.Handle handle = null; 6084 try { 6085 handle = NativeLibraryHelper.Handle.create(scanFile); 6086 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6087 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6088 } 6089 } catch (IOException ioe) { 6090 Slog.w(TAG, "Error scanning system app : " + ioe); 6091 } finally { 6092 IoUtils.closeQuietly(handle); 6093 } 6094 } 6095 6096 setNativeLibraryPaths(pkg); 6097 } else { 6098 // TODO: We can probably be smarter about this stuff. For installed apps, 6099 // we can calculate this information at install time once and for all. For 6100 // system apps, we can probably assume that this information doesn't change 6101 // after the first boot scan. As things stand, we do lots of unnecessary work. 6102 6103 // Give ourselves some initial paths; we'll come back for another 6104 // pass once we've determined ABI below. 6105 setNativeLibraryPaths(pkg); 6106 6107 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6108 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6109 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6110 6111 NativeLibraryHelper.Handle handle = null; 6112 try { 6113 handle = NativeLibraryHelper.Handle.create(scanFile); 6114 // TODO(multiArch): This can be null for apps that didn't go through the 6115 // usual installation process. We can calculate it again, like we 6116 // do during install time. 6117 // 6118 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6119 // unnecessary. 6120 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6121 6122 // Null out the abis so that they can be recalculated. 6123 pkg.applicationInfo.primaryCpuAbi = null; 6124 pkg.applicationInfo.secondaryCpuAbi = null; 6125 if (isMultiArch(pkg.applicationInfo)) { 6126 // Warn if we've set an abiOverride for multi-lib packages.. 6127 // By definition, we need to copy both 32 and 64 bit libraries for 6128 // such packages. 6129 if (pkg.cpuAbiOverride != null 6130 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6131 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6132 } 6133 6134 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6135 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6136 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6137 if (isAsec) { 6138 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6139 } else { 6140 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6141 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6142 useIsaSpecificSubdirs); 6143 } 6144 } 6145 6146 maybeThrowExceptionForMultiArchCopy( 6147 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6148 6149 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6150 if (isAsec) { 6151 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6152 } else { 6153 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6154 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6155 useIsaSpecificSubdirs); 6156 } 6157 } 6158 6159 maybeThrowExceptionForMultiArchCopy( 6160 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6161 6162 if (abi64 >= 0) { 6163 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6164 } 6165 6166 if (abi32 >= 0) { 6167 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6168 if (abi64 >= 0) { 6169 pkg.applicationInfo.secondaryCpuAbi = abi; 6170 } else { 6171 pkg.applicationInfo.primaryCpuAbi = abi; 6172 } 6173 } 6174 } else { 6175 String[] abiList = (cpuAbiOverride != null) ? 6176 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6177 6178 // Enable gross and lame hacks for apps that are built with old 6179 // SDK tools. We must scan their APKs for renderscript bitcode and 6180 // not launch them if it's present. Don't bother checking on devices 6181 // that don't have 64 bit support. 6182 boolean needsRenderScriptOverride = false; 6183 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6184 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6185 abiList = Build.SUPPORTED_32_BIT_ABIS; 6186 needsRenderScriptOverride = true; 6187 } 6188 6189 final int copyRet; 6190 if (isAsec) { 6191 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6192 } else { 6193 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6194 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6195 } 6196 6197 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6198 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6199 "Error unpackaging native libs for app, errorCode=" + copyRet); 6200 } 6201 6202 if (copyRet >= 0) { 6203 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6204 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6205 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6206 } else if (needsRenderScriptOverride) { 6207 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6208 } 6209 } 6210 } catch (IOException ioe) { 6211 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6212 } finally { 6213 IoUtils.closeQuietly(handle); 6214 } 6215 6216 // Now that we've calculated the ABIs and determined if it's an internal app, 6217 // we will go ahead and populate the nativeLibraryPath. 6218 setNativeLibraryPaths(pkg); 6219 6220 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6221 final int[] userIds = sUserManager.getUserIds(); 6222 synchronized (mInstallLock) { 6223 // Create a native library symlink only if we have native libraries 6224 // and if the native libraries are 32 bit libraries. We do not provide 6225 // this symlink for 64 bit libraries. 6226 if (pkg.applicationInfo.primaryCpuAbi != null && 6227 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6228 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6229 for (int userId : userIds) { 6230 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6231 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6232 "Failed linking native library dir (user=" + userId + ")"); 6233 } 6234 } 6235 } 6236 } 6237 } 6238 6239 // This is a special case for the "system" package, where the ABI is 6240 // dictated by the zygote configuration (and init.rc). We should keep track 6241 // of this ABI so that we can deal with "normal" applications that run under 6242 // the same UID correctly. 6243 if (mPlatformPackage == pkg) { 6244 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6245 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6246 } 6247 6248 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6249 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6250 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6251 // Copy the derived override back to the parsed package, so that we can 6252 // update the package settings accordingly. 6253 pkg.cpuAbiOverride = cpuAbiOverride; 6254 6255 if (DEBUG_ABI_SELECTION) { 6256 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6257 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6258 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6259 } 6260 6261 // Push the derived path down into PackageSettings so we know what to 6262 // clean up at uninstall time. 6263 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6264 6265 if (DEBUG_ABI_SELECTION) { 6266 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6267 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6268 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6269 } 6270 6271 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6272 // We don't do this here during boot because we can do it all 6273 // at once after scanning all existing packages. 6274 // 6275 // We also do this *before* we perform dexopt on this package, so that 6276 // we can avoid redundant dexopts, and also to make sure we've got the 6277 // code and package path correct. 6278 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6279 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6280 } 6281 6282 if ((scanFlags & SCAN_NO_DEX) == 0) { 6283 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6284 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6285 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6286 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6287 } 6288 } 6289 if (mFactoryTest && pkg.requestedPermissions.contains( 6290 android.Manifest.permission.FACTORY_TEST)) { 6291 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6292 } 6293 6294 ArrayList<PackageParser.Package> clientLibPkgs = null; 6295 6296 // writer 6297 synchronized (mPackages) { 6298 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6299 // Only system apps can add new shared libraries. 6300 if (pkg.libraryNames != null) { 6301 for (int i=0; i<pkg.libraryNames.size(); i++) { 6302 String name = pkg.libraryNames.get(i); 6303 boolean allowed = false; 6304 if (pkg.isUpdatedSystemApp()) { 6305 // New library entries can only be added through the 6306 // system image. This is important to get rid of a lot 6307 // of nasty edge cases: for example if we allowed a non- 6308 // system update of the app to add a library, then uninstalling 6309 // the update would make the library go away, and assumptions 6310 // we made such as through app install filtering would now 6311 // have allowed apps on the device which aren't compatible 6312 // with it. Better to just have the restriction here, be 6313 // conservative, and create many fewer cases that can negatively 6314 // impact the user experience. 6315 final PackageSetting sysPs = mSettings 6316 .getDisabledSystemPkgLPr(pkg.packageName); 6317 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6318 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6319 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6320 allowed = true; 6321 allowed = true; 6322 break; 6323 } 6324 } 6325 } 6326 } else { 6327 allowed = true; 6328 } 6329 if (allowed) { 6330 if (!mSharedLibraries.containsKey(name)) { 6331 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6332 } else if (!name.equals(pkg.packageName)) { 6333 Slog.w(TAG, "Package " + pkg.packageName + " library " 6334 + name + " already exists; skipping"); 6335 } 6336 } else { 6337 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6338 + name + " that is not declared on system image; skipping"); 6339 } 6340 } 6341 if ((scanFlags&SCAN_BOOTING) == 0) { 6342 // If we are not booting, we need to update any applications 6343 // that are clients of our shared library. If we are booting, 6344 // this will all be done once the scan is complete. 6345 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6346 } 6347 } 6348 } 6349 } 6350 6351 // We also need to dexopt any apps that are dependent on this library. Note that 6352 // if these fail, we should abort the install since installing the library will 6353 // result in some apps being broken. 6354 if (clientLibPkgs != null) { 6355 if ((scanFlags & SCAN_NO_DEX) == 0) { 6356 for (int i = 0; i < clientLibPkgs.size(); i++) { 6357 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6358 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6359 null /* instruction sets */, forceDex, 6360 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6361 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6362 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6363 "scanPackageLI failed to dexopt clientLibPkgs"); 6364 } 6365 } 6366 } 6367 } 6368 6369 // Request the ActivityManager to kill the process(only for existing packages) 6370 // so that we do not end up in a confused state while the user is still using the older 6371 // version of the application while the new one gets installed. 6372 if ((scanFlags & SCAN_REPLACING) != 0) { 6373 killApplication(pkg.applicationInfo.packageName, 6374 pkg.applicationInfo.uid, "update pkg"); 6375 } 6376 6377 // Also need to kill any apps that are dependent on the library. 6378 if (clientLibPkgs != null) { 6379 for (int i=0; i<clientLibPkgs.size(); i++) { 6380 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6381 killApplication(clientPkg.applicationInfo.packageName, 6382 clientPkg.applicationInfo.uid, "update lib"); 6383 } 6384 } 6385 6386 // writer 6387 synchronized (mPackages) { 6388 // We don't expect installation to fail beyond this point 6389 6390 // Add the new setting to mSettings 6391 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6392 // Add the new setting to mPackages 6393 mPackages.put(pkg.applicationInfo.packageName, pkg); 6394 // Make sure we don't accidentally delete its data. 6395 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6396 while (iter.hasNext()) { 6397 PackageCleanItem item = iter.next(); 6398 if (pkgName.equals(item.packageName)) { 6399 iter.remove(); 6400 } 6401 } 6402 6403 // Take care of first install / last update times. 6404 if (currentTime != 0) { 6405 if (pkgSetting.firstInstallTime == 0) { 6406 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6407 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6408 pkgSetting.lastUpdateTime = currentTime; 6409 } 6410 } else if (pkgSetting.firstInstallTime == 0) { 6411 // We need *something*. Take time time stamp of the file. 6412 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6413 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6414 if (scanFileTime != pkgSetting.timeStamp) { 6415 // A package on the system image has changed; consider this 6416 // to be an update. 6417 pkgSetting.lastUpdateTime = scanFileTime; 6418 } 6419 } 6420 6421 // Add the package's KeySets to the global KeySetManagerService 6422 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6423 try { 6424 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6425 if (pkg.mKeySetMapping != null) { 6426 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6427 if (pkg.mUpgradeKeySets != null) { 6428 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6429 } 6430 } 6431 } catch (NullPointerException e) { 6432 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6433 } catch (IllegalArgumentException e) { 6434 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6435 } 6436 6437 int N = pkg.providers.size(); 6438 StringBuilder r = null; 6439 int i; 6440 for (i=0; i<N; i++) { 6441 PackageParser.Provider p = pkg.providers.get(i); 6442 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6443 p.info.processName, pkg.applicationInfo.uid); 6444 mProviders.addProvider(p); 6445 p.syncable = p.info.isSyncable; 6446 if (p.info.authority != null) { 6447 String names[] = p.info.authority.split(";"); 6448 p.info.authority = null; 6449 for (int j = 0; j < names.length; j++) { 6450 if (j == 1 && p.syncable) { 6451 // We only want the first authority for a provider to possibly be 6452 // syncable, so if we already added this provider using a different 6453 // authority clear the syncable flag. We copy the provider before 6454 // changing it because the mProviders object contains a reference 6455 // to a provider that we don't want to change. 6456 // Only do this for the second authority since the resulting provider 6457 // object can be the same for all future authorities for this provider. 6458 p = new PackageParser.Provider(p); 6459 p.syncable = false; 6460 } 6461 if (!mProvidersByAuthority.containsKey(names[j])) { 6462 mProvidersByAuthority.put(names[j], p); 6463 if (p.info.authority == null) { 6464 p.info.authority = names[j]; 6465 } else { 6466 p.info.authority = p.info.authority + ";" + names[j]; 6467 } 6468 if (DEBUG_PACKAGE_SCANNING) { 6469 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6470 Log.d(TAG, "Registered content provider: " + names[j] 6471 + ", className = " + p.info.name + ", isSyncable = " 6472 + p.info.isSyncable); 6473 } 6474 } else { 6475 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6476 Slog.w(TAG, "Skipping provider name " + names[j] + 6477 " (in package " + pkg.applicationInfo.packageName + 6478 "): name already used by " 6479 + ((other != null && other.getComponentName() != null) 6480 ? other.getComponentName().getPackageName() : "?")); 6481 } 6482 } 6483 } 6484 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6485 if (r == null) { 6486 r = new StringBuilder(256); 6487 } else { 6488 r.append(' '); 6489 } 6490 r.append(p.info.name); 6491 } 6492 } 6493 if (r != null) { 6494 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6495 } 6496 6497 N = pkg.services.size(); 6498 r = null; 6499 for (i=0; i<N; i++) { 6500 PackageParser.Service s = pkg.services.get(i); 6501 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6502 s.info.processName, pkg.applicationInfo.uid); 6503 mServices.addService(s); 6504 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6505 if (r == null) { 6506 r = new StringBuilder(256); 6507 } else { 6508 r.append(' '); 6509 } 6510 r.append(s.info.name); 6511 } 6512 } 6513 if (r != null) { 6514 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6515 } 6516 6517 N = pkg.receivers.size(); 6518 r = null; 6519 for (i=0; i<N; i++) { 6520 PackageParser.Activity a = pkg.receivers.get(i); 6521 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6522 a.info.processName, pkg.applicationInfo.uid); 6523 mReceivers.addActivity(a, "receiver"); 6524 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6525 if (r == null) { 6526 r = new StringBuilder(256); 6527 } else { 6528 r.append(' '); 6529 } 6530 r.append(a.info.name); 6531 } 6532 } 6533 if (r != null) { 6534 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6535 } 6536 6537 N = pkg.activities.size(); 6538 r = null; 6539 for (i=0; i<N; i++) { 6540 PackageParser.Activity a = pkg.activities.get(i); 6541 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6542 a.info.processName, pkg.applicationInfo.uid); 6543 mActivities.addActivity(a, "activity"); 6544 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6545 if (r == null) { 6546 r = new StringBuilder(256); 6547 } else { 6548 r.append(' '); 6549 } 6550 r.append(a.info.name); 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6555 } 6556 6557 N = pkg.permissionGroups.size(); 6558 r = null; 6559 for (i=0; i<N; i++) { 6560 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6561 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6562 if (cur == null) { 6563 mPermissionGroups.put(pg.info.name, pg); 6564 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6565 if (r == null) { 6566 r = new StringBuilder(256); 6567 } else { 6568 r.append(' '); 6569 } 6570 r.append(pg.info.name); 6571 } 6572 } else { 6573 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6574 + pg.info.packageName + " ignored: original from " 6575 + cur.info.packageName); 6576 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6577 if (r == null) { 6578 r = new StringBuilder(256); 6579 } else { 6580 r.append(' '); 6581 } 6582 r.append("DUP:"); 6583 r.append(pg.info.name); 6584 } 6585 } 6586 } 6587 if (r != null) { 6588 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6589 } 6590 6591 N = pkg.permissions.size(); 6592 r = null; 6593 for (i=0; i<N; i++) { 6594 PackageParser.Permission p = pkg.permissions.get(i); 6595 ArrayMap<String, BasePermission> permissionMap = 6596 p.tree ? mSettings.mPermissionTrees 6597 : mSettings.mPermissions; 6598 p.group = mPermissionGroups.get(p.info.group); 6599 if (p.info.group == null || p.group != null) { 6600 BasePermission bp = permissionMap.get(p.info.name); 6601 6602 // Allow system apps to redefine non-system permissions 6603 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6604 final boolean currentOwnerIsSystem = (bp.perm != null 6605 && isSystemApp(bp.perm.owner)); 6606 if (isSystemApp(p.owner)) { 6607 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6608 // It's a built-in permission and no owner, take ownership now 6609 bp.packageSetting = pkgSetting; 6610 bp.perm = p; 6611 bp.uid = pkg.applicationInfo.uid; 6612 bp.sourcePackage = p.info.packageName; 6613 } else if (!currentOwnerIsSystem) { 6614 String msg = "New decl " + p.owner + " of permission " 6615 + p.info.name + " is system; overriding " + bp.sourcePackage; 6616 reportSettingsProblem(Log.WARN, msg); 6617 bp = null; 6618 } 6619 } 6620 } 6621 6622 if (bp == null) { 6623 bp = new BasePermission(p.info.name, p.info.packageName, 6624 BasePermission.TYPE_NORMAL); 6625 permissionMap.put(p.info.name, bp); 6626 } 6627 6628 if (bp.perm == null) { 6629 if (bp.sourcePackage == null 6630 || bp.sourcePackage.equals(p.info.packageName)) { 6631 BasePermission tree = findPermissionTreeLP(p.info.name); 6632 if (tree == null 6633 || tree.sourcePackage.equals(p.info.packageName)) { 6634 bp.packageSetting = pkgSetting; 6635 bp.perm = p; 6636 bp.uid = pkg.applicationInfo.uid; 6637 bp.sourcePackage = p.info.packageName; 6638 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6639 if (r == null) { 6640 r = new StringBuilder(256); 6641 } else { 6642 r.append(' '); 6643 } 6644 r.append(p.info.name); 6645 } 6646 } else { 6647 Slog.w(TAG, "Permission " + p.info.name + " from package " 6648 + p.info.packageName + " ignored: base tree " 6649 + tree.name + " is from package " 6650 + tree.sourcePackage); 6651 } 6652 } else { 6653 Slog.w(TAG, "Permission " + p.info.name + " from package " 6654 + p.info.packageName + " ignored: original from " 6655 + bp.sourcePackage); 6656 } 6657 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6658 if (r == null) { 6659 r = new StringBuilder(256); 6660 } else { 6661 r.append(' '); 6662 } 6663 r.append("DUP:"); 6664 r.append(p.info.name); 6665 } 6666 if (bp.perm == p) { 6667 bp.protectionLevel = p.info.protectionLevel; 6668 } 6669 } else { 6670 Slog.w(TAG, "Permission " + p.info.name + " from package " 6671 + p.info.packageName + " ignored: no group " 6672 + p.group); 6673 } 6674 } 6675 if (r != null) { 6676 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6677 } 6678 6679 N = pkg.instrumentation.size(); 6680 r = null; 6681 for (i=0; i<N; i++) { 6682 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6683 a.info.packageName = pkg.applicationInfo.packageName; 6684 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6685 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6686 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6687 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6688 a.info.dataDir = pkg.applicationInfo.dataDir; 6689 6690 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6691 // need other information about the application, like the ABI and what not ? 6692 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6693 mInstrumentation.put(a.getComponentName(), a); 6694 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6695 if (r == null) { 6696 r = new StringBuilder(256); 6697 } else { 6698 r.append(' '); 6699 } 6700 r.append(a.info.name); 6701 } 6702 } 6703 if (r != null) { 6704 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6705 } 6706 6707 if (pkg.protectedBroadcasts != null) { 6708 N = pkg.protectedBroadcasts.size(); 6709 for (i=0; i<N; i++) { 6710 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6711 } 6712 } 6713 6714 pkgSetting.setTimeStamp(scanFileTime); 6715 6716 // Create idmap files for pairs of (packages, overlay packages). 6717 // Note: "android", ie framework-res.apk, is handled by native layers. 6718 if (pkg.mOverlayTarget != null) { 6719 // This is an overlay package. 6720 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6721 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6722 mOverlays.put(pkg.mOverlayTarget, 6723 new ArrayMap<String, PackageParser.Package>()); 6724 } 6725 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6726 map.put(pkg.packageName, pkg); 6727 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6728 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6729 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6730 "scanPackageLI failed to createIdmap"); 6731 } 6732 } 6733 } else if (mOverlays.containsKey(pkg.packageName) && 6734 !pkg.packageName.equals("android")) { 6735 // This is a regular package, with one or more known overlay packages. 6736 createIdmapsForPackageLI(pkg); 6737 } 6738 } 6739 6740 return pkg; 6741 } 6742 6743 /** 6744 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6745 * i.e, so that all packages can be run inside a single process if required. 6746 * 6747 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6748 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6749 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6750 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6751 * updating a package that belongs to a shared user. 6752 * 6753 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6754 * adds unnecessary complexity. 6755 */ 6756 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6757 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6758 String requiredInstructionSet = null; 6759 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6760 requiredInstructionSet = VMRuntime.getInstructionSet( 6761 scannedPackage.applicationInfo.primaryCpuAbi); 6762 } 6763 6764 PackageSetting requirer = null; 6765 for (PackageSetting ps : packagesForUser) { 6766 // If packagesForUser contains scannedPackage, we skip it. This will happen 6767 // when scannedPackage is an update of an existing package. Without this check, 6768 // we will never be able to change the ABI of any package belonging to a shared 6769 // user, even if it's compatible with other packages. 6770 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6771 if (ps.primaryCpuAbiString == null) { 6772 continue; 6773 } 6774 6775 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6776 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6777 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6778 // this but there's not much we can do. 6779 String errorMessage = "Instruction set mismatch, " 6780 + ((requirer == null) ? "[caller]" : requirer) 6781 + " requires " + requiredInstructionSet + " whereas " + ps 6782 + " requires " + instructionSet; 6783 Slog.w(TAG, errorMessage); 6784 } 6785 6786 if (requiredInstructionSet == null) { 6787 requiredInstructionSet = instructionSet; 6788 requirer = ps; 6789 } 6790 } 6791 } 6792 6793 if (requiredInstructionSet != null) { 6794 String adjustedAbi; 6795 if (requirer != null) { 6796 // requirer != null implies that either scannedPackage was null or that scannedPackage 6797 // did not require an ABI, in which case we have to adjust scannedPackage to match 6798 // the ABI of the set (which is the same as requirer's ABI) 6799 adjustedAbi = requirer.primaryCpuAbiString; 6800 if (scannedPackage != null) { 6801 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6802 } 6803 } else { 6804 // requirer == null implies that we're updating all ABIs in the set to 6805 // match scannedPackage. 6806 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6807 } 6808 6809 for (PackageSetting ps : packagesForUser) { 6810 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6811 if (ps.primaryCpuAbiString != null) { 6812 continue; 6813 } 6814 6815 ps.primaryCpuAbiString = adjustedAbi; 6816 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6817 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6818 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6819 6820 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6821 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6822 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6823 ps.primaryCpuAbiString = null; 6824 ps.pkg.applicationInfo.primaryCpuAbi = null; 6825 return; 6826 } else { 6827 mInstaller.rmdex(ps.codePathString, 6828 getDexCodeInstructionSet(getPreferredInstructionSet())); 6829 } 6830 } 6831 } 6832 } 6833 } 6834 } 6835 6836 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6837 synchronized (mPackages) { 6838 mResolverReplaced = true; 6839 // Set up information for custom user intent resolution activity. 6840 mResolveActivity.applicationInfo = pkg.applicationInfo; 6841 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6842 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6843 mResolveActivity.processName = pkg.applicationInfo.packageName; 6844 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6845 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6846 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6847 mResolveActivity.theme = 0; 6848 mResolveActivity.exported = true; 6849 mResolveActivity.enabled = true; 6850 mResolveInfo.activityInfo = mResolveActivity; 6851 mResolveInfo.priority = 0; 6852 mResolveInfo.preferredOrder = 0; 6853 mResolveInfo.match = 0; 6854 mResolveComponentName = mCustomResolverComponentName; 6855 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6856 mResolveComponentName); 6857 } 6858 } 6859 6860 private static String calculateBundledApkRoot(final String codePathString) { 6861 final File codePath = new File(codePathString); 6862 final File codeRoot; 6863 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6864 codeRoot = Environment.getRootDirectory(); 6865 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6866 codeRoot = Environment.getOemDirectory(); 6867 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6868 codeRoot = Environment.getVendorDirectory(); 6869 } else { 6870 // Unrecognized code path; take its top real segment as the apk root: 6871 // e.g. /something/app/blah.apk => /something 6872 try { 6873 File f = codePath.getCanonicalFile(); 6874 File parent = f.getParentFile(); // non-null because codePath is a file 6875 File tmp; 6876 while ((tmp = parent.getParentFile()) != null) { 6877 f = parent; 6878 parent = tmp; 6879 } 6880 codeRoot = f; 6881 Slog.w(TAG, "Unrecognized code path " 6882 + codePath + " - using " + codeRoot); 6883 } catch (IOException e) { 6884 // Can't canonicalize the code path -- shenanigans? 6885 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6886 return Environment.getRootDirectory().getPath(); 6887 } 6888 } 6889 return codeRoot.getPath(); 6890 } 6891 6892 /** 6893 * Derive and set the location of native libraries for the given package, 6894 * which varies depending on where and how the package was installed. 6895 */ 6896 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6897 final ApplicationInfo info = pkg.applicationInfo; 6898 final String codePath = pkg.codePath; 6899 final File codeFile = new File(codePath); 6900 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6901 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6902 6903 info.nativeLibraryRootDir = null; 6904 info.nativeLibraryRootRequiresIsa = false; 6905 info.nativeLibraryDir = null; 6906 info.secondaryNativeLibraryDir = null; 6907 6908 if (isApkFile(codeFile)) { 6909 // Monolithic install 6910 if (bundledApp) { 6911 // If "/system/lib64/apkname" exists, assume that is the per-package 6912 // native library directory to use; otherwise use "/system/lib/apkname". 6913 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6914 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6915 getPrimaryInstructionSet(info)); 6916 6917 // This is a bundled system app so choose the path based on the ABI. 6918 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6919 // is just the default path. 6920 final String apkName = deriveCodePathName(codePath); 6921 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6922 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6923 apkName).getAbsolutePath(); 6924 6925 if (info.secondaryCpuAbi != null) { 6926 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6927 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6928 secondaryLibDir, apkName).getAbsolutePath(); 6929 } 6930 } else if (asecApp) { 6931 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6932 .getAbsolutePath(); 6933 } else { 6934 final String apkName = deriveCodePathName(codePath); 6935 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6936 .getAbsolutePath(); 6937 } 6938 6939 info.nativeLibraryRootRequiresIsa = false; 6940 info.nativeLibraryDir = info.nativeLibraryRootDir; 6941 } else { 6942 // Cluster install 6943 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6944 info.nativeLibraryRootRequiresIsa = true; 6945 6946 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6947 getPrimaryInstructionSet(info)).getAbsolutePath(); 6948 6949 if (info.secondaryCpuAbi != null) { 6950 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6951 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6952 } 6953 } 6954 } 6955 6956 /** 6957 * Calculate the abis and roots for a bundled app. These can uniquely 6958 * be determined from the contents of the system partition, i.e whether 6959 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6960 * of this information, and instead assume that the system was built 6961 * sensibly. 6962 */ 6963 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6964 PackageSetting pkgSetting) { 6965 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6966 6967 // If "/system/lib64/apkname" exists, assume that is the per-package 6968 // native library directory to use; otherwise use "/system/lib/apkname". 6969 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6970 setBundledAppAbi(pkg, apkRoot, apkName); 6971 // pkgSetting might be null during rescan following uninstall of updates 6972 // to a bundled app, so accommodate that possibility. The settings in 6973 // that case will be established later from the parsed package. 6974 // 6975 // If the settings aren't null, sync them up with what we've just derived. 6976 // note that apkRoot isn't stored in the package settings. 6977 if (pkgSetting != null) { 6978 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6979 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6980 } 6981 } 6982 6983 /** 6984 * Deduces the ABI of a bundled app and sets the relevant fields on the 6985 * parsed pkg object. 6986 * 6987 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6988 * under which system libraries are installed. 6989 * @param apkName the name of the installed package. 6990 */ 6991 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6992 final File codeFile = new File(pkg.codePath); 6993 6994 final boolean has64BitLibs; 6995 final boolean has32BitLibs; 6996 if (isApkFile(codeFile)) { 6997 // Monolithic install 6998 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6999 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7000 } else { 7001 // Cluster install 7002 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7003 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7004 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7005 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7006 has64BitLibs = (new File(rootDir, isa)).exists(); 7007 } else { 7008 has64BitLibs = false; 7009 } 7010 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7011 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7012 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7013 has32BitLibs = (new File(rootDir, isa)).exists(); 7014 } else { 7015 has32BitLibs = false; 7016 } 7017 } 7018 7019 if (has64BitLibs && !has32BitLibs) { 7020 // The package has 64 bit libs, but not 32 bit libs. Its primary 7021 // ABI should be 64 bit. We can safely assume here that the bundled 7022 // native libraries correspond to the most preferred ABI in the list. 7023 7024 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7025 pkg.applicationInfo.secondaryCpuAbi = null; 7026 } else if (has32BitLibs && !has64BitLibs) { 7027 // The package has 32 bit libs but not 64 bit libs. Its primary 7028 // ABI should be 32 bit. 7029 7030 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7031 pkg.applicationInfo.secondaryCpuAbi = null; 7032 } else if (has32BitLibs && has64BitLibs) { 7033 // The application has both 64 and 32 bit bundled libraries. We check 7034 // here that the app declares multiArch support, and warn if it doesn't. 7035 // 7036 // We will be lenient here and record both ABIs. The primary will be the 7037 // ABI that's higher on the list, i.e, a device that's configured to prefer 7038 // 64 bit apps will see a 64 bit primary ABI, 7039 7040 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7041 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7042 } 7043 7044 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7045 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7046 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7047 } else { 7048 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7049 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7050 } 7051 } else { 7052 pkg.applicationInfo.primaryCpuAbi = null; 7053 pkg.applicationInfo.secondaryCpuAbi = null; 7054 } 7055 } 7056 7057 private void killApplication(String pkgName, int appId, String reason) { 7058 // Request the ActivityManager to kill the process(only for existing packages) 7059 // so that we do not end up in a confused state while the user is still using the older 7060 // version of the application while the new one gets installed. 7061 IActivityManager am = ActivityManagerNative.getDefault(); 7062 if (am != null) { 7063 try { 7064 am.killApplicationWithAppId(pkgName, appId, reason); 7065 } catch (RemoteException e) { 7066 } 7067 } 7068 } 7069 7070 void removePackageLI(PackageSetting ps, boolean chatty) { 7071 if (DEBUG_INSTALL) { 7072 if (chatty) 7073 Log.d(TAG, "Removing package " + ps.name); 7074 } 7075 7076 // writer 7077 synchronized (mPackages) { 7078 mPackages.remove(ps.name); 7079 final PackageParser.Package pkg = ps.pkg; 7080 if (pkg != null) { 7081 cleanPackageDataStructuresLILPw(pkg, chatty); 7082 } 7083 } 7084 } 7085 7086 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7087 if (DEBUG_INSTALL) { 7088 if (chatty) 7089 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7090 } 7091 7092 // writer 7093 synchronized (mPackages) { 7094 mPackages.remove(pkg.applicationInfo.packageName); 7095 cleanPackageDataStructuresLILPw(pkg, chatty); 7096 } 7097 } 7098 7099 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7100 int N = pkg.providers.size(); 7101 StringBuilder r = null; 7102 int i; 7103 for (i=0; i<N; i++) { 7104 PackageParser.Provider p = pkg.providers.get(i); 7105 mProviders.removeProvider(p); 7106 if (p.info.authority == null) { 7107 7108 /* There was another ContentProvider with this authority when 7109 * this app was installed so this authority is null, 7110 * Ignore it as we don't have to unregister the provider. 7111 */ 7112 continue; 7113 } 7114 String names[] = p.info.authority.split(";"); 7115 for (int j = 0; j < names.length; j++) { 7116 if (mProvidersByAuthority.get(names[j]) == p) { 7117 mProvidersByAuthority.remove(names[j]); 7118 if (DEBUG_REMOVE) { 7119 if (chatty) 7120 Log.d(TAG, "Unregistered content provider: " + names[j] 7121 + ", className = " + p.info.name + ", isSyncable = " 7122 + p.info.isSyncable); 7123 } 7124 } 7125 } 7126 if (DEBUG_REMOVE && chatty) { 7127 if (r == null) { 7128 r = new StringBuilder(256); 7129 } else { 7130 r.append(' '); 7131 } 7132 r.append(p.info.name); 7133 } 7134 } 7135 if (r != null) { 7136 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7137 } 7138 7139 N = pkg.services.size(); 7140 r = null; 7141 for (i=0; i<N; i++) { 7142 PackageParser.Service s = pkg.services.get(i); 7143 mServices.removeService(s); 7144 if (chatty) { 7145 if (r == null) { 7146 r = new StringBuilder(256); 7147 } else { 7148 r.append(' '); 7149 } 7150 r.append(s.info.name); 7151 } 7152 } 7153 if (r != null) { 7154 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7155 } 7156 7157 N = pkg.receivers.size(); 7158 r = null; 7159 for (i=0; i<N; i++) { 7160 PackageParser.Activity a = pkg.receivers.get(i); 7161 mReceivers.removeActivity(a, "receiver"); 7162 if (DEBUG_REMOVE && chatty) { 7163 if (r == null) { 7164 r = new StringBuilder(256); 7165 } else { 7166 r.append(' '); 7167 } 7168 r.append(a.info.name); 7169 } 7170 } 7171 if (r != null) { 7172 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7173 } 7174 7175 N = pkg.activities.size(); 7176 r = null; 7177 for (i=0; i<N; i++) { 7178 PackageParser.Activity a = pkg.activities.get(i); 7179 mActivities.removeActivity(a, "activity"); 7180 if (DEBUG_REMOVE && chatty) { 7181 if (r == null) { 7182 r = new StringBuilder(256); 7183 } else { 7184 r.append(' '); 7185 } 7186 r.append(a.info.name); 7187 } 7188 } 7189 if (r != null) { 7190 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7191 } 7192 7193 N = pkg.permissions.size(); 7194 r = null; 7195 for (i=0; i<N; i++) { 7196 PackageParser.Permission p = pkg.permissions.get(i); 7197 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7198 if (bp == null) { 7199 bp = mSettings.mPermissionTrees.get(p.info.name); 7200 } 7201 if (bp != null && bp.perm == p) { 7202 bp.perm = null; 7203 if (DEBUG_REMOVE && chatty) { 7204 if (r == null) { 7205 r = new StringBuilder(256); 7206 } else { 7207 r.append(' '); 7208 } 7209 r.append(p.info.name); 7210 } 7211 } 7212 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7213 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7214 if (appOpPerms != null) { 7215 appOpPerms.remove(pkg.packageName); 7216 } 7217 } 7218 } 7219 if (r != null) { 7220 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7221 } 7222 7223 N = pkg.requestedPermissions.size(); 7224 r = null; 7225 for (i=0; i<N; i++) { 7226 String perm = pkg.requestedPermissions.get(i); 7227 BasePermission bp = mSettings.mPermissions.get(perm); 7228 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7229 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7230 if (appOpPerms != null) { 7231 appOpPerms.remove(pkg.packageName); 7232 if (appOpPerms.isEmpty()) { 7233 mAppOpPermissionPackages.remove(perm); 7234 } 7235 } 7236 } 7237 } 7238 if (r != null) { 7239 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7240 } 7241 7242 N = pkg.instrumentation.size(); 7243 r = null; 7244 for (i=0; i<N; i++) { 7245 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7246 mInstrumentation.remove(a.getComponentName()); 7247 if (DEBUG_REMOVE && chatty) { 7248 if (r == null) { 7249 r = new StringBuilder(256); 7250 } else { 7251 r.append(' '); 7252 } 7253 r.append(a.info.name); 7254 } 7255 } 7256 if (r != null) { 7257 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7258 } 7259 7260 r = null; 7261 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7262 // Only system apps can hold shared libraries. 7263 if (pkg.libraryNames != null) { 7264 for (i=0; i<pkg.libraryNames.size(); i++) { 7265 String name = pkg.libraryNames.get(i); 7266 SharedLibraryEntry cur = mSharedLibraries.get(name); 7267 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7268 mSharedLibraries.remove(name); 7269 if (DEBUG_REMOVE && chatty) { 7270 if (r == null) { 7271 r = new StringBuilder(256); 7272 } else { 7273 r.append(' '); 7274 } 7275 r.append(name); 7276 } 7277 } 7278 } 7279 } 7280 } 7281 if (r != null) { 7282 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7283 } 7284 } 7285 7286 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7287 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7288 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7289 return true; 7290 } 7291 } 7292 return false; 7293 } 7294 7295 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7296 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7297 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7298 7299 private void updatePermissionsLPw(String changingPkg, 7300 PackageParser.Package pkgInfo, int flags) { 7301 // Make sure there are no dangling permission trees. 7302 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7303 while (it.hasNext()) { 7304 final BasePermission bp = it.next(); 7305 if (bp.packageSetting == null) { 7306 // We may not yet have parsed the package, so just see if 7307 // we still know about its settings. 7308 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7309 } 7310 if (bp.packageSetting == null) { 7311 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7312 + " from package " + bp.sourcePackage); 7313 it.remove(); 7314 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7315 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7316 Slog.i(TAG, "Removing old permission tree: " + bp.name 7317 + " from package " + bp.sourcePackage); 7318 flags |= UPDATE_PERMISSIONS_ALL; 7319 it.remove(); 7320 } 7321 } 7322 } 7323 7324 // Make sure all dynamic permissions have been assigned to a package, 7325 // and make sure there are no dangling permissions. 7326 it = mSettings.mPermissions.values().iterator(); 7327 while (it.hasNext()) { 7328 final BasePermission bp = it.next(); 7329 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7330 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7331 + bp.name + " pkg=" + bp.sourcePackage 7332 + " info=" + bp.pendingInfo); 7333 if (bp.packageSetting == null && bp.pendingInfo != null) { 7334 final BasePermission tree = findPermissionTreeLP(bp.name); 7335 if (tree != null && tree.perm != null) { 7336 bp.packageSetting = tree.packageSetting; 7337 bp.perm = new PackageParser.Permission(tree.perm.owner, 7338 new PermissionInfo(bp.pendingInfo)); 7339 bp.perm.info.packageName = tree.perm.info.packageName; 7340 bp.perm.info.name = bp.name; 7341 bp.uid = tree.uid; 7342 } 7343 } 7344 } 7345 if (bp.packageSetting == null) { 7346 // We may not yet have parsed the package, so just see if 7347 // we still know about its settings. 7348 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7349 } 7350 if (bp.packageSetting == null) { 7351 Slog.w(TAG, "Removing dangling permission: " + bp.name 7352 + " from package " + bp.sourcePackage); 7353 it.remove(); 7354 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7355 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7356 Slog.i(TAG, "Removing old permission: " + bp.name 7357 + " from package " + bp.sourcePackage); 7358 flags |= UPDATE_PERMISSIONS_ALL; 7359 it.remove(); 7360 } 7361 } 7362 } 7363 7364 // Now update the permissions for all packages, in particular 7365 // replace the granted permissions of the system packages. 7366 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7367 for (PackageParser.Package pkg : mPackages.values()) { 7368 if (pkg != pkgInfo) { 7369 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7370 changingPkg); 7371 } 7372 } 7373 } 7374 7375 if (pkgInfo != null) { 7376 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7377 } 7378 } 7379 7380 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7381 String packageOfInterest) { 7382 // IMPORTANT: There are two types of permissions: install and runtime. 7383 // Install time permissions are granted when the app is installed to 7384 // all device users and users added in the future. Runtime permissions 7385 // are granted at runtime explicitly to specific users. Normal and signature 7386 // protected permissions are install time permissions. Dangerous permissions 7387 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7388 // otherwise they are runtime permissions. This function does not manage 7389 // runtime permissions except for the case an app targeting Lollipop MR1 7390 // being upgraded to target a newer SDK, in which case dangerous permissions 7391 // are transformed from install time to runtime ones. 7392 7393 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7394 if (ps == null) { 7395 return; 7396 } 7397 7398 PermissionsState permissionsState = ps.getPermissionsState(); 7399 PermissionsState origPermissions = permissionsState; 7400 7401 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7402 7403 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7404 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7405 7406 boolean changedInstallPermission = false; 7407 7408 if (replace) { 7409 ps.installPermissionsFixed = false; 7410 if (!ps.isSharedUser()) { 7411 origPermissions = new PermissionsState(permissionsState); 7412 permissionsState.reset(); 7413 } 7414 } 7415 7416 permissionsState.setGlobalGids(mGlobalGids); 7417 7418 final int N = pkg.requestedPermissions.size(); 7419 for (int i=0; i<N; i++) { 7420 final String name = pkg.requestedPermissions.get(i); 7421 final BasePermission bp = mSettings.mPermissions.get(name); 7422 7423 if (DEBUG_INSTALL) { 7424 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7425 } 7426 7427 if (bp == null || bp.packageSetting == null) { 7428 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7429 Slog.w(TAG, "Unknown permission " + name 7430 + " in package " + pkg.packageName); 7431 } 7432 continue; 7433 } 7434 7435 final String perm = bp.name; 7436 boolean allowedSig = false; 7437 int grant = GRANT_DENIED; 7438 7439 // Keep track of app op permissions. 7440 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7441 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7442 if (pkgs == null) { 7443 pkgs = new ArraySet<>(); 7444 mAppOpPermissionPackages.put(bp.name, pkgs); 7445 } 7446 pkgs.add(pkg.packageName); 7447 } 7448 7449 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7450 switch (level) { 7451 case PermissionInfo.PROTECTION_NORMAL: { 7452 // For all apps normal permissions are install time ones. 7453 grant = GRANT_INSTALL; 7454 } break; 7455 7456 case PermissionInfo.PROTECTION_DANGEROUS: { 7457 if (!RUNTIME_PERMISSIONS_ENABLED 7458 || pkg.applicationInfo.targetSdkVersion 7459 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7460 // For legacy apps dangerous permissions are install time ones. 7461 grant = GRANT_INSTALL; 7462 } else if (ps.isSystem()) { 7463 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7464 if (origPermissions.hasInstallPermission(bp.name)) { 7465 // If a system app had an install permission, then the app was 7466 // upgraded and we grant the permissions as runtime to all users. 7467 grant = GRANT_UPGRADE; 7468 upgradeUserIds = currentUserIds; 7469 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7470 // If users changed since the last permissions update for a 7471 // system app, we grant the permission as runtime to the new users. 7472 grant = GRANT_UPGRADE; 7473 upgradeUserIds = currentUserIds; 7474 for (int userId : updatedUserIds) { 7475 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7476 } 7477 } else { 7478 // Otherwise, we grant the permission as runtime if the app 7479 // already had it, i.e. we preserve runtime permissions. 7480 grant = GRANT_RUNTIME; 7481 } 7482 } else if (origPermissions.hasInstallPermission(bp.name)) { 7483 // For legacy apps that became modern, install becomes runtime. 7484 grant = GRANT_UPGRADE; 7485 upgradeUserIds = currentUserIds; 7486 } else if (replace) { 7487 // For upgraded modern apps keep runtime permissions unchanged. 7488 grant = GRANT_RUNTIME; 7489 } 7490 } break; 7491 7492 case PermissionInfo.PROTECTION_SIGNATURE: { 7493 // For all apps signature permissions are install time ones. 7494 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7495 if (allowedSig) { 7496 grant = GRANT_INSTALL; 7497 } 7498 } break; 7499 } 7500 7501 if (DEBUG_INSTALL) { 7502 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7503 } 7504 7505 if (grant != GRANT_DENIED) { 7506 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7507 // If this is an existing, non-system package, then 7508 // we can't add any new permissions to it. 7509 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7510 // Except... if this is a permission that was added 7511 // to the platform (note: need to only do this when 7512 // updating the platform). 7513 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7514 grant = GRANT_DENIED; 7515 } 7516 } 7517 } 7518 7519 switch (grant) { 7520 case GRANT_INSTALL: { 7521 // Grant an install permission. 7522 if (permissionsState.grantInstallPermission(bp) != 7523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7524 changedInstallPermission = true; 7525 } 7526 } break; 7527 7528 case GRANT_RUNTIME: { 7529 // Grant previously granted runtime permissions. 7530 for (int userId : UserManagerService.getInstance().getUserIds()) { 7531 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7532 if (permissionsState.grantRuntimePermission(bp, userId) == 7533 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7534 // If we cannot put the permission as it was, we have to write. 7535 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7536 changedRuntimePermissionUserIds, userId); 7537 } 7538 } 7539 } 7540 } break; 7541 7542 case GRANT_UPGRADE: { 7543 // Grant runtime permissions for a previously held install permission. 7544 permissionsState.revokeInstallPermission(bp); 7545 for (int userId : upgradeUserIds) { 7546 if (permissionsState.grantRuntimePermission(bp, userId) != 7547 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7548 // If we granted the permission, we have to write. 7549 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7550 changedRuntimePermissionUserIds, userId); 7551 } 7552 } 7553 } break; 7554 7555 default: { 7556 if (packageOfInterest == null 7557 || packageOfInterest.equals(pkg.packageName)) { 7558 Slog.w(TAG, "Not granting permission " + perm 7559 + " to package " + pkg.packageName 7560 + " because it was previously installed without"); 7561 } 7562 } break; 7563 } 7564 } else { 7565 if (permissionsState.revokeInstallPermission(bp) != 7566 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7567 changedInstallPermission = true; 7568 Slog.i(TAG, "Un-granting permission " + perm 7569 + " from package " + pkg.packageName 7570 + " (protectionLevel=" + bp.protectionLevel 7571 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7572 + ")"); 7573 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7574 // Don't print warning for app op permissions, since it is fine for them 7575 // not to be granted, there is a UI for the user to decide. 7576 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7577 Slog.w(TAG, "Not granting permission " + perm 7578 + " to package " + pkg.packageName 7579 + " (protectionLevel=" + bp.protectionLevel 7580 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7581 + ")"); 7582 } 7583 } 7584 } 7585 } 7586 7587 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7588 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7589 // This is the first that we have heard about this package, so the 7590 // permissions we have now selected are fixed until explicitly 7591 // changed. 7592 ps.installPermissionsFixed = true; 7593 } 7594 7595 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7596 7597 // Persist the runtime permissions state for users with changes. 7598 if (RUNTIME_PERMISSIONS_ENABLED) { 7599 for (int userId : changedRuntimePermissionUserIds) { 7600 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7601 } 7602 } 7603 } 7604 7605 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7606 boolean allowed = false; 7607 final int NP = PackageParser.NEW_PERMISSIONS.length; 7608 for (int ip=0; ip<NP; ip++) { 7609 final PackageParser.NewPermissionInfo npi 7610 = PackageParser.NEW_PERMISSIONS[ip]; 7611 if (npi.name.equals(perm) 7612 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7613 allowed = true; 7614 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7615 + pkg.packageName); 7616 break; 7617 } 7618 } 7619 return allowed; 7620 } 7621 7622 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7623 BasePermission bp, PermissionsState origPermissions) { 7624 boolean allowed; 7625 allowed = (compareSignatures( 7626 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7627 == PackageManager.SIGNATURE_MATCH) 7628 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7629 == PackageManager.SIGNATURE_MATCH); 7630 if (!allowed && (bp.protectionLevel 7631 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7632 if (isSystemApp(pkg)) { 7633 // For updated system applications, a system permission 7634 // is granted only if it had been defined by the original application. 7635 if (pkg.isUpdatedSystemApp()) { 7636 final PackageSetting sysPs = mSettings 7637 .getDisabledSystemPkgLPr(pkg.packageName); 7638 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7639 // If the original was granted this permission, we take 7640 // that grant decision as read and propagate it to the 7641 // update. 7642 if (sysPs.isPrivileged()) { 7643 allowed = true; 7644 } 7645 } else { 7646 // The system apk may have been updated with an older 7647 // version of the one on the data partition, but which 7648 // granted a new system permission that it didn't have 7649 // before. In this case we do want to allow the app to 7650 // now get the new permission if the ancestral apk is 7651 // privileged to get it. 7652 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7653 for (int j=0; 7654 j<sysPs.pkg.requestedPermissions.size(); j++) { 7655 if (perm.equals( 7656 sysPs.pkg.requestedPermissions.get(j))) { 7657 allowed = true; 7658 break; 7659 } 7660 } 7661 } 7662 } 7663 } else { 7664 allowed = isPrivilegedApp(pkg); 7665 } 7666 } 7667 } 7668 if (!allowed && (bp.protectionLevel 7669 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7670 // For development permissions, a development permission 7671 // is granted only if it was already granted. 7672 allowed = origPermissions.hasInstallPermission(perm); 7673 } 7674 return allowed; 7675 } 7676 7677 final class ActivityIntentResolver 7678 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7679 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7680 boolean defaultOnly, int userId) { 7681 if (!sUserManager.exists(userId)) return null; 7682 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7683 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7684 } 7685 7686 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7687 int userId) { 7688 if (!sUserManager.exists(userId)) return null; 7689 mFlags = flags; 7690 return super.queryIntent(intent, resolvedType, 7691 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7692 } 7693 7694 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7695 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7696 if (!sUserManager.exists(userId)) return null; 7697 if (packageActivities == null) { 7698 return null; 7699 } 7700 mFlags = flags; 7701 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7702 final int N = packageActivities.size(); 7703 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7704 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7705 7706 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7707 for (int i = 0; i < N; ++i) { 7708 intentFilters = packageActivities.get(i).intents; 7709 if (intentFilters != null && intentFilters.size() > 0) { 7710 PackageParser.ActivityIntentInfo[] array = 7711 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7712 intentFilters.toArray(array); 7713 listCut.add(array); 7714 } 7715 } 7716 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7717 } 7718 7719 public final void addActivity(PackageParser.Activity a, String type) { 7720 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7721 mActivities.put(a.getComponentName(), a); 7722 if (DEBUG_SHOW_INFO) 7723 Log.v( 7724 TAG, " " + type + " " + 7725 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7726 if (DEBUG_SHOW_INFO) 7727 Log.v(TAG, " Class=" + a.info.name); 7728 final int NI = a.intents.size(); 7729 for (int j=0; j<NI; j++) { 7730 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7731 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7732 intent.setPriority(0); 7733 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7734 + a.className + " with priority > 0, forcing to 0"); 7735 } 7736 if (DEBUG_SHOW_INFO) { 7737 Log.v(TAG, " IntentFilter:"); 7738 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7739 } 7740 if (!intent.debugCheck()) { 7741 Log.w(TAG, "==> For Activity " + a.info.name); 7742 } 7743 addFilter(intent); 7744 } 7745 } 7746 7747 public final void removeActivity(PackageParser.Activity a, String type) { 7748 mActivities.remove(a.getComponentName()); 7749 if (DEBUG_SHOW_INFO) { 7750 Log.v(TAG, " " + type + " " 7751 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7752 : a.info.name) + ":"); 7753 Log.v(TAG, " Class=" + a.info.name); 7754 } 7755 final int NI = a.intents.size(); 7756 for (int j=0; j<NI; j++) { 7757 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7758 if (DEBUG_SHOW_INFO) { 7759 Log.v(TAG, " IntentFilter:"); 7760 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7761 } 7762 removeFilter(intent); 7763 } 7764 } 7765 7766 @Override 7767 protected boolean allowFilterResult( 7768 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7769 ActivityInfo filterAi = filter.activity.info; 7770 for (int i=dest.size()-1; i>=0; i--) { 7771 ActivityInfo destAi = dest.get(i).activityInfo; 7772 if (destAi.name == filterAi.name 7773 && destAi.packageName == filterAi.packageName) { 7774 return false; 7775 } 7776 } 7777 return true; 7778 } 7779 7780 @Override 7781 protected ActivityIntentInfo[] newArray(int size) { 7782 return new ActivityIntentInfo[size]; 7783 } 7784 7785 @Override 7786 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7787 if (!sUserManager.exists(userId)) return true; 7788 PackageParser.Package p = filter.activity.owner; 7789 if (p != null) { 7790 PackageSetting ps = (PackageSetting)p.mExtras; 7791 if (ps != null) { 7792 // System apps are never considered stopped for purposes of 7793 // filtering, because there may be no way for the user to 7794 // actually re-launch them. 7795 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7796 && ps.getStopped(userId); 7797 } 7798 } 7799 return false; 7800 } 7801 7802 @Override 7803 protected boolean isPackageForFilter(String packageName, 7804 PackageParser.ActivityIntentInfo info) { 7805 return packageName.equals(info.activity.owner.packageName); 7806 } 7807 7808 @Override 7809 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7810 int match, int userId) { 7811 if (!sUserManager.exists(userId)) return null; 7812 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7813 return null; 7814 } 7815 final PackageParser.Activity activity = info.activity; 7816 if (mSafeMode && (activity.info.applicationInfo.flags 7817 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7818 return null; 7819 } 7820 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7821 if (ps == null) { 7822 return null; 7823 } 7824 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7825 ps.readUserState(userId), userId); 7826 if (ai == null) { 7827 return null; 7828 } 7829 final ResolveInfo res = new ResolveInfo(); 7830 res.activityInfo = ai; 7831 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7832 res.filter = info; 7833 } 7834 if (info != null) { 7835 res.filterNeedsVerification = info.needsVerification(); 7836 } 7837 res.priority = info.getPriority(); 7838 res.preferredOrder = activity.owner.mPreferredOrder; 7839 //System.out.println("Result: " + res.activityInfo.className + 7840 // " = " + res.priority); 7841 res.match = match; 7842 res.isDefault = info.hasDefault; 7843 res.labelRes = info.labelRes; 7844 res.nonLocalizedLabel = info.nonLocalizedLabel; 7845 if (userNeedsBadging(userId)) { 7846 res.noResourceId = true; 7847 } else { 7848 res.icon = info.icon; 7849 } 7850 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7851 return res; 7852 } 7853 7854 @Override 7855 protected void sortResults(List<ResolveInfo> results) { 7856 Collections.sort(results, mResolvePrioritySorter); 7857 } 7858 7859 @Override 7860 protected void dumpFilter(PrintWriter out, String prefix, 7861 PackageParser.ActivityIntentInfo filter) { 7862 out.print(prefix); out.print( 7863 Integer.toHexString(System.identityHashCode(filter.activity))); 7864 out.print(' '); 7865 filter.activity.printComponentShortName(out); 7866 out.print(" filter "); 7867 out.println(Integer.toHexString(System.identityHashCode(filter))); 7868 } 7869 7870 @Override 7871 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7872 return filter.activity; 7873 } 7874 7875 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7876 PackageParser.Activity activity = (PackageParser.Activity)label; 7877 out.print(prefix); out.print( 7878 Integer.toHexString(System.identityHashCode(activity))); 7879 out.print(' '); 7880 activity.printComponentShortName(out); 7881 if (count > 1) { 7882 out.print(" ("); out.print(count); out.print(" filters)"); 7883 } 7884 out.println(); 7885 } 7886 7887// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7888// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7889// final List<ResolveInfo> retList = Lists.newArrayList(); 7890// while (i.hasNext()) { 7891// final ResolveInfo resolveInfo = i.next(); 7892// if (isEnabledLP(resolveInfo.activityInfo)) { 7893// retList.add(resolveInfo); 7894// } 7895// } 7896// return retList; 7897// } 7898 7899 // Keys are String (activity class name), values are Activity. 7900 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7901 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7902 private int mFlags; 7903 } 7904 7905 private final class ServiceIntentResolver 7906 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7907 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7908 boolean defaultOnly, int userId) { 7909 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7910 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7911 } 7912 7913 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7914 int userId) { 7915 if (!sUserManager.exists(userId)) return null; 7916 mFlags = flags; 7917 return super.queryIntent(intent, resolvedType, 7918 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7919 } 7920 7921 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7922 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7923 if (!sUserManager.exists(userId)) return null; 7924 if (packageServices == null) { 7925 return null; 7926 } 7927 mFlags = flags; 7928 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7929 final int N = packageServices.size(); 7930 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7931 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7932 7933 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7934 for (int i = 0; i < N; ++i) { 7935 intentFilters = packageServices.get(i).intents; 7936 if (intentFilters != null && intentFilters.size() > 0) { 7937 PackageParser.ServiceIntentInfo[] array = 7938 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7939 intentFilters.toArray(array); 7940 listCut.add(array); 7941 } 7942 } 7943 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7944 } 7945 7946 public final void addService(PackageParser.Service s) { 7947 mServices.put(s.getComponentName(), s); 7948 if (DEBUG_SHOW_INFO) { 7949 Log.v(TAG, " " 7950 + (s.info.nonLocalizedLabel != null 7951 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7952 Log.v(TAG, " Class=" + s.info.name); 7953 } 7954 final int NI = s.intents.size(); 7955 int j; 7956 for (j=0; j<NI; j++) { 7957 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7958 if (DEBUG_SHOW_INFO) { 7959 Log.v(TAG, " IntentFilter:"); 7960 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7961 } 7962 if (!intent.debugCheck()) { 7963 Log.w(TAG, "==> For Service " + s.info.name); 7964 } 7965 addFilter(intent); 7966 } 7967 } 7968 7969 public final void removeService(PackageParser.Service s) { 7970 mServices.remove(s.getComponentName()); 7971 if (DEBUG_SHOW_INFO) { 7972 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7973 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7974 Log.v(TAG, " Class=" + s.info.name); 7975 } 7976 final int NI = s.intents.size(); 7977 int j; 7978 for (j=0; j<NI; j++) { 7979 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7980 if (DEBUG_SHOW_INFO) { 7981 Log.v(TAG, " IntentFilter:"); 7982 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7983 } 7984 removeFilter(intent); 7985 } 7986 } 7987 7988 @Override 7989 protected boolean allowFilterResult( 7990 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7991 ServiceInfo filterSi = filter.service.info; 7992 for (int i=dest.size()-1; i>=0; i--) { 7993 ServiceInfo destAi = dest.get(i).serviceInfo; 7994 if (destAi.name == filterSi.name 7995 && destAi.packageName == filterSi.packageName) { 7996 return false; 7997 } 7998 } 7999 return true; 8000 } 8001 8002 @Override 8003 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8004 return new PackageParser.ServiceIntentInfo[size]; 8005 } 8006 8007 @Override 8008 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8009 if (!sUserManager.exists(userId)) return true; 8010 PackageParser.Package p = filter.service.owner; 8011 if (p != null) { 8012 PackageSetting ps = (PackageSetting)p.mExtras; 8013 if (ps != null) { 8014 // System apps are never considered stopped for purposes of 8015 // filtering, because there may be no way for the user to 8016 // actually re-launch them. 8017 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8018 && ps.getStopped(userId); 8019 } 8020 } 8021 return false; 8022 } 8023 8024 @Override 8025 protected boolean isPackageForFilter(String packageName, 8026 PackageParser.ServiceIntentInfo info) { 8027 return packageName.equals(info.service.owner.packageName); 8028 } 8029 8030 @Override 8031 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8032 int match, int userId) { 8033 if (!sUserManager.exists(userId)) return null; 8034 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8035 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8036 return null; 8037 } 8038 final PackageParser.Service service = info.service; 8039 if (mSafeMode && (service.info.applicationInfo.flags 8040 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8041 return null; 8042 } 8043 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8044 if (ps == null) { 8045 return null; 8046 } 8047 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8048 ps.readUserState(userId), userId); 8049 if (si == null) { 8050 return null; 8051 } 8052 final ResolveInfo res = new ResolveInfo(); 8053 res.serviceInfo = si; 8054 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8055 res.filter = filter; 8056 } 8057 res.priority = info.getPriority(); 8058 res.preferredOrder = service.owner.mPreferredOrder; 8059 res.match = match; 8060 res.isDefault = info.hasDefault; 8061 res.labelRes = info.labelRes; 8062 res.nonLocalizedLabel = info.nonLocalizedLabel; 8063 res.icon = info.icon; 8064 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8065 return res; 8066 } 8067 8068 @Override 8069 protected void sortResults(List<ResolveInfo> results) { 8070 Collections.sort(results, mResolvePrioritySorter); 8071 } 8072 8073 @Override 8074 protected void dumpFilter(PrintWriter out, String prefix, 8075 PackageParser.ServiceIntentInfo filter) { 8076 out.print(prefix); out.print( 8077 Integer.toHexString(System.identityHashCode(filter.service))); 8078 out.print(' '); 8079 filter.service.printComponentShortName(out); 8080 out.print(" filter "); 8081 out.println(Integer.toHexString(System.identityHashCode(filter))); 8082 } 8083 8084 @Override 8085 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8086 return filter.service; 8087 } 8088 8089 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8090 PackageParser.Service service = (PackageParser.Service)label; 8091 out.print(prefix); out.print( 8092 Integer.toHexString(System.identityHashCode(service))); 8093 out.print(' '); 8094 service.printComponentShortName(out); 8095 if (count > 1) { 8096 out.print(" ("); out.print(count); out.print(" filters)"); 8097 } 8098 out.println(); 8099 } 8100 8101// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8102// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8103// final List<ResolveInfo> retList = Lists.newArrayList(); 8104// while (i.hasNext()) { 8105// final ResolveInfo resolveInfo = (ResolveInfo) i; 8106// if (isEnabledLP(resolveInfo.serviceInfo)) { 8107// retList.add(resolveInfo); 8108// } 8109// } 8110// return retList; 8111// } 8112 8113 // Keys are String (activity class name), values are Activity. 8114 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8115 = new ArrayMap<ComponentName, PackageParser.Service>(); 8116 private int mFlags; 8117 }; 8118 8119 private final class ProviderIntentResolver 8120 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8121 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8122 boolean defaultOnly, int userId) { 8123 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8124 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8125 } 8126 8127 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8128 int userId) { 8129 if (!sUserManager.exists(userId)) 8130 return null; 8131 mFlags = flags; 8132 return super.queryIntent(intent, resolvedType, 8133 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8134 } 8135 8136 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8137 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8138 if (!sUserManager.exists(userId)) 8139 return null; 8140 if (packageProviders == null) { 8141 return null; 8142 } 8143 mFlags = flags; 8144 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8145 final int N = packageProviders.size(); 8146 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8147 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8148 8149 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8150 for (int i = 0; i < N; ++i) { 8151 intentFilters = packageProviders.get(i).intents; 8152 if (intentFilters != null && intentFilters.size() > 0) { 8153 PackageParser.ProviderIntentInfo[] array = 8154 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8155 intentFilters.toArray(array); 8156 listCut.add(array); 8157 } 8158 } 8159 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8160 } 8161 8162 public final void addProvider(PackageParser.Provider p) { 8163 if (mProviders.containsKey(p.getComponentName())) { 8164 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8165 return; 8166 } 8167 8168 mProviders.put(p.getComponentName(), p); 8169 if (DEBUG_SHOW_INFO) { 8170 Log.v(TAG, " " 8171 + (p.info.nonLocalizedLabel != null 8172 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8173 Log.v(TAG, " Class=" + p.info.name); 8174 } 8175 final int NI = p.intents.size(); 8176 int j; 8177 for (j = 0; j < NI; j++) { 8178 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8179 if (DEBUG_SHOW_INFO) { 8180 Log.v(TAG, " IntentFilter:"); 8181 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8182 } 8183 if (!intent.debugCheck()) { 8184 Log.w(TAG, "==> For Provider " + p.info.name); 8185 } 8186 addFilter(intent); 8187 } 8188 } 8189 8190 public final void removeProvider(PackageParser.Provider p) { 8191 mProviders.remove(p.getComponentName()); 8192 if (DEBUG_SHOW_INFO) { 8193 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8194 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8195 Log.v(TAG, " Class=" + p.info.name); 8196 } 8197 final int NI = p.intents.size(); 8198 int j; 8199 for (j = 0; j < NI; j++) { 8200 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8201 if (DEBUG_SHOW_INFO) { 8202 Log.v(TAG, " IntentFilter:"); 8203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8204 } 8205 removeFilter(intent); 8206 } 8207 } 8208 8209 @Override 8210 protected boolean allowFilterResult( 8211 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8212 ProviderInfo filterPi = filter.provider.info; 8213 for (int i = dest.size() - 1; i >= 0; i--) { 8214 ProviderInfo destPi = dest.get(i).providerInfo; 8215 if (destPi.name == filterPi.name 8216 && destPi.packageName == filterPi.packageName) { 8217 return false; 8218 } 8219 } 8220 return true; 8221 } 8222 8223 @Override 8224 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8225 return new PackageParser.ProviderIntentInfo[size]; 8226 } 8227 8228 @Override 8229 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8230 if (!sUserManager.exists(userId)) 8231 return true; 8232 PackageParser.Package p = filter.provider.owner; 8233 if (p != null) { 8234 PackageSetting ps = (PackageSetting) p.mExtras; 8235 if (ps != null) { 8236 // System apps are never considered stopped for purposes of 8237 // filtering, because there may be no way for the user to 8238 // actually re-launch them. 8239 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8240 && ps.getStopped(userId); 8241 } 8242 } 8243 return false; 8244 } 8245 8246 @Override 8247 protected boolean isPackageForFilter(String packageName, 8248 PackageParser.ProviderIntentInfo info) { 8249 return packageName.equals(info.provider.owner.packageName); 8250 } 8251 8252 @Override 8253 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8254 int match, int userId) { 8255 if (!sUserManager.exists(userId)) 8256 return null; 8257 final PackageParser.ProviderIntentInfo info = filter; 8258 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8259 return null; 8260 } 8261 final PackageParser.Provider provider = info.provider; 8262 if (mSafeMode && (provider.info.applicationInfo.flags 8263 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8264 return null; 8265 } 8266 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8267 if (ps == null) { 8268 return null; 8269 } 8270 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8271 ps.readUserState(userId), userId); 8272 if (pi == null) { 8273 return null; 8274 } 8275 final ResolveInfo res = new ResolveInfo(); 8276 res.providerInfo = pi; 8277 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8278 res.filter = filter; 8279 } 8280 res.priority = info.getPriority(); 8281 res.preferredOrder = provider.owner.mPreferredOrder; 8282 res.match = match; 8283 res.isDefault = info.hasDefault; 8284 res.labelRes = info.labelRes; 8285 res.nonLocalizedLabel = info.nonLocalizedLabel; 8286 res.icon = info.icon; 8287 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8288 return res; 8289 } 8290 8291 @Override 8292 protected void sortResults(List<ResolveInfo> results) { 8293 Collections.sort(results, mResolvePrioritySorter); 8294 } 8295 8296 @Override 8297 protected void dumpFilter(PrintWriter out, String prefix, 8298 PackageParser.ProviderIntentInfo filter) { 8299 out.print(prefix); 8300 out.print( 8301 Integer.toHexString(System.identityHashCode(filter.provider))); 8302 out.print(' '); 8303 filter.provider.printComponentShortName(out); 8304 out.print(" filter "); 8305 out.println(Integer.toHexString(System.identityHashCode(filter))); 8306 } 8307 8308 @Override 8309 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8310 return filter.provider; 8311 } 8312 8313 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8314 PackageParser.Provider provider = (PackageParser.Provider)label; 8315 out.print(prefix); out.print( 8316 Integer.toHexString(System.identityHashCode(provider))); 8317 out.print(' '); 8318 provider.printComponentShortName(out); 8319 if (count > 1) { 8320 out.print(" ("); out.print(count); out.print(" filters)"); 8321 } 8322 out.println(); 8323 } 8324 8325 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8326 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8327 private int mFlags; 8328 }; 8329 8330 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8331 new Comparator<ResolveInfo>() { 8332 public int compare(ResolveInfo r1, ResolveInfo r2) { 8333 int v1 = r1.priority; 8334 int v2 = r2.priority; 8335 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8336 if (v1 != v2) { 8337 return (v1 > v2) ? -1 : 1; 8338 } 8339 v1 = r1.preferredOrder; 8340 v2 = r2.preferredOrder; 8341 if (v1 != v2) { 8342 return (v1 > v2) ? -1 : 1; 8343 } 8344 if (r1.isDefault != r2.isDefault) { 8345 return r1.isDefault ? -1 : 1; 8346 } 8347 v1 = r1.match; 8348 v2 = r2.match; 8349 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8350 if (v1 != v2) { 8351 return (v1 > v2) ? -1 : 1; 8352 } 8353 if (r1.system != r2.system) { 8354 return r1.system ? -1 : 1; 8355 } 8356 return 0; 8357 } 8358 }; 8359 8360 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8361 new Comparator<ProviderInfo>() { 8362 public int compare(ProviderInfo p1, ProviderInfo p2) { 8363 final int v1 = p1.initOrder; 8364 final int v2 = p2.initOrder; 8365 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8366 } 8367 }; 8368 8369 static final void sendPackageBroadcast(String action, String pkg, 8370 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8371 int[] userIds) { 8372 IActivityManager am = ActivityManagerNative.getDefault(); 8373 if (am != null) { 8374 try { 8375 if (userIds == null) { 8376 userIds = am.getRunningUserIds(); 8377 } 8378 for (int id : userIds) { 8379 final Intent intent = new Intent(action, 8380 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8381 if (extras != null) { 8382 intent.putExtras(extras); 8383 } 8384 if (targetPkg != null) { 8385 intent.setPackage(targetPkg); 8386 } 8387 // Modify the UID when posting to other users 8388 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8389 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8390 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8391 intent.putExtra(Intent.EXTRA_UID, uid); 8392 } 8393 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8394 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8395 if (DEBUG_BROADCASTS) { 8396 RuntimeException here = new RuntimeException("here"); 8397 here.fillInStackTrace(); 8398 Slog.d(TAG, "Sending to user " + id + ": " 8399 + intent.toShortString(false, true, false, false) 8400 + " " + intent.getExtras(), here); 8401 } 8402 am.broadcastIntent(null, intent, null, finishedReceiver, 8403 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8404 finishedReceiver != null, false, id); 8405 } 8406 } catch (RemoteException ex) { 8407 } 8408 } 8409 } 8410 8411 /** 8412 * Check if the external storage media is available. This is true if there 8413 * is a mounted external storage medium or if the external storage is 8414 * emulated. 8415 */ 8416 private boolean isExternalMediaAvailable() { 8417 return mMediaMounted || Environment.isExternalStorageEmulated(); 8418 } 8419 8420 @Override 8421 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8422 // writer 8423 synchronized (mPackages) { 8424 if (!isExternalMediaAvailable()) { 8425 // If the external storage is no longer mounted at this point, 8426 // the caller may not have been able to delete all of this 8427 // packages files and can not delete any more. Bail. 8428 return null; 8429 } 8430 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8431 if (lastPackage != null) { 8432 pkgs.remove(lastPackage); 8433 } 8434 if (pkgs.size() > 0) { 8435 return pkgs.get(0); 8436 } 8437 } 8438 return null; 8439 } 8440 8441 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8442 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8443 userId, andCode ? 1 : 0, packageName); 8444 if (mSystemReady) { 8445 msg.sendToTarget(); 8446 } else { 8447 if (mPostSystemReadyMessages == null) { 8448 mPostSystemReadyMessages = new ArrayList<>(); 8449 } 8450 mPostSystemReadyMessages.add(msg); 8451 } 8452 } 8453 8454 void startCleaningPackages() { 8455 // reader 8456 synchronized (mPackages) { 8457 if (!isExternalMediaAvailable()) { 8458 return; 8459 } 8460 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8461 return; 8462 } 8463 } 8464 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8465 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8466 IActivityManager am = ActivityManagerNative.getDefault(); 8467 if (am != null) { 8468 try { 8469 am.startService(null, intent, null, UserHandle.USER_OWNER); 8470 } catch (RemoteException e) { 8471 } 8472 } 8473 } 8474 8475 @Override 8476 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8477 int installFlags, String installerPackageName, VerificationParams verificationParams, 8478 String packageAbiOverride) { 8479 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8480 packageAbiOverride, UserHandle.getCallingUserId()); 8481 } 8482 8483 @Override 8484 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8485 int installFlags, String installerPackageName, VerificationParams verificationParams, 8486 String packageAbiOverride, int userId) { 8487 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8488 8489 final int callingUid = Binder.getCallingUid(); 8490 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8491 8492 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8493 try { 8494 if (observer != null) { 8495 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8496 } 8497 } catch (RemoteException re) { 8498 } 8499 return; 8500 } 8501 8502 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8503 installFlags |= PackageManager.INSTALL_FROM_ADB; 8504 8505 } else { 8506 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8507 // about installerPackageName. 8508 8509 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8510 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8511 } 8512 8513 UserHandle user; 8514 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8515 user = UserHandle.ALL; 8516 } else { 8517 user = new UserHandle(userId); 8518 } 8519 8520 verificationParams.setInstallerUid(callingUid); 8521 8522 final File originFile = new File(originPath); 8523 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8524 8525 final Message msg = mHandler.obtainMessage(INIT_COPY); 8526 msg.obj = new InstallParams(origin, observer, installFlags, 8527 installerPackageName, verificationParams, user, packageAbiOverride); 8528 mHandler.sendMessage(msg); 8529 } 8530 8531 void installStage(String packageName, File stagedDir, String stagedCid, 8532 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8533 String installerPackageName, int installerUid, UserHandle user) { 8534 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8535 params.referrerUri, installerUid, null); 8536 8537 final OriginInfo origin; 8538 if (stagedDir != null) { 8539 origin = OriginInfo.fromStagedFile(stagedDir); 8540 } else { 8541 origin = OriginInfo.fromStagedContainer(stagedCid); 8542 } 8543 8544 final Message msg = mHandler.obtainMessage(INIT_COPY); 8545 msg.obj = new InstallParams(origin, observer, params.installFlags, 8546 installerPackageName, verifParams, user, params.abiOverride); 8547 mHandler.sendMessage(msg); 8548 } 8549 8550 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8551 Bundle extras = new Bundle(1); 8552 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8553 8554 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8555 packageName, extras, null, null, new int[] {userId}); 8556 try { 8557 IActivityManager am = ActivityManagerNative.getDefault(); 8558 final boolean isSystem = 8559 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8560 if (isSystem && am.isUserRunning(userId, false)) { 8561 // The just-installed/enabled app is bundled on the system, so presumed 8562 // to be able to run automatically without needing an explicit launch. 8563 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8564 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8565 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8566 .setPackage(packageName); 8567 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8568 android.app.AppOpsManager.OP_NONE, false, false, userId); 8569 } 8570 } catch (RemoteException e) { 8571 // shouldn't happen 8572 Slog.w(TAG, "Unable to bootstrap installed package", e); 8573 } 8574 } 8575 8576 @Override 8577 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8578 int userId) { 8579 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8580 PackageSetting pkgSetting; 8581 final int uid = Binder.getCallingUid(); 8582 enforceCrossUserPermission(uid, userId, true, true, 8583 "setApplicationHiddenSetting for user " + userId); 8584 8585 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8586 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8587 return false; 8588 } 8589 8590 long callingId = Binder.clearCallingIdentity(); 8591 try { 8592 boolean sendAdded = false; 8593 boolean sendRemoved = false; 8594 // writer 8595 synchronized (mPackages) { 8596 pkgSetting = mSettings.mPackages.get(packageName); 8597 if (pkgSetting == null) { 8598 return false; 8599 } 8600 if (pkgSetting.getHidden(userId) != hidden) { 8601 pkgSetting.setHidden(hidden, userId); 8602 mSettings.writePackageRestrictionsLPr(userId); 8603 if (hidden) { 8604 sendRemoved = true; 8605 } else { 8606 sendAdded = true; 8607 } 8608 } 8609 } 8610 if (sendAdded) { 8611 sendPackageAddedForUser(packageName, pkgSetting, userId); 8612 return true; 8613 } 8614 if (sendRemoved) { 8615 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8616 "hiding pkg"); 8617 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8618 } 8619 } finally { 8620 Binder.restoreCallingIdentity(callingId); 8621 } 8622 return false; 8623 } 8624 8625 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8626 int userId) { 8627 final PackageRemovedInfo info = new PackageRemovedInfo(); 8628 info.removedPackage = packageName; 8629 info.removedUsers = new int[] {userId}; 8630 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8631 info.sendBroadcast(false, false, false); 8632 } 8633 8634 /** 8635 * Returns true if application is not found or there was an error. Otherwise it returns 8636 * the hidden state of the package for the given user. 8637 */ 8638 @Override 8639 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8640 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8641 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8642 false, "getApplicationHidden for user " + userId); 8643 PackageSetting pkgSetting; 8644 long callingId = Binder.clearCallingIdentity(); 8645 try { 8646 // writer 8647 synchronized (mPackages) { 8648 pkgSetting = mSettings.mPackages.get(packageName); 8649 if (pkgSetting == null) { 8650 return true; 8651 } 8652 return pkgSetting.getHidden(userId); 8653 } 8654 } finally { 8655 Binder.restoreCallingIdentity(callingId); 8656 } 8657 } 8658 8659 /** 8660 * @hide 8661 */ 8662 @Override 8663 public int installExistingPackageAsUser(String packageName, int userId) { 8664 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8665 null); 8666 PackageSetting pkgSetting; 8667 final int uid = Binder.getCallingUid(); 8668 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8669 + userId); 8670 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8671 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8672 } 8673 8674 long callingId = Binder.clearCallingIdentity(); 8675 try { 8676 boolean sendAdded = false; 8677 Bundle extras = new Bundle(1); 8678 8679 // writer 8680 synchronized (mPackages) { 8681 pkgSetting = mSettings.mPackages.get(packageName); 8682 if (pkgSetting == null) { 8683 return PackageManager.INSTALL_FAILED_INVALID_URI; 8684 } 8685 if (!pkgSetting.getInstalled(userId)) { 8686 pkgSetting.setInstalled(true, userId); 8687 pkgSetting.setHidden(false, userId); 8688 mSettings.writePackageRestrictionsLPr(userId); 8689 sendAdded = true; 8690 } 8691 } 8692 8693 if (sendAdded) { 8694 sendPackageAddedForUser(packageName, pkgSetting, userId); 8695 } 8696 } finally { 8697 Binder.restoreCallingIdentity(callingId); 8698 } 8699 8700 return PackageManager.INSTALL_SUCCEEDED; 8701 } 8702 8703 boolean isUserRestricted(int userId, String restrictionKey) { 8704 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8705 if (restrictions.getBoolean(restrictionKey, false)) { 8706 Log.w(TAG, "User is restricted: " + restrictionKey); 8707 return true; 8708 } 8709 return false; 8710 } 8711 8712 @Override 8713 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8714 mContext.enforceCallingOrSelfPermission( 8715 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8716 "Only package verification agents can verify applications"); 8717 8718 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8719 final PackageVerificationResponse response = new PackageVerificationResponse( 8720 verificationCode, Binder.getCallingUid()); 8721 msg.arg1 = id; 8722 msg.obj = response; 8723 mHandler.sendMessage(msg); 8724 } 8725 8726 @Override 8727 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8728 long millisecondsToDelay) { 8729 mContext.enforceCallingOrSelfPermission( 8730 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8731 "Only package verification agents can extend verification timeouts"); 8732 8733 final PackageVerificationState state = mPendingVerification.get(id); 8734 final PackageVerificationResponse response = new PackageVerificationResponse( 8735 verificationCodeAtTimeout, Binder.getCallingUid()); 8736 8737 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8738 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8739 } 8740 if (millisecondsToDelay < 0) { 8741 millisecondsToDelay = 0; 8742 } 8743 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8744 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8745 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8746 } 8747 8748 if ((state != null) && !state.timeoutExtended()) { 8749 state.extendTimeout(); 8750 8751 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8752 msg.arg1 = id; 8753 msg.obj = response; 8754 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8755 } 8756 } 8757 8758 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8759 int verificationCode, UserHandle user) { 8760 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8761 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8762 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8763 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8764 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8765 8766 mContext.sendBroadcastAsUser(intent, user, 8767 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8768 } 8769 8770 private ComponentName matchComponentForVerifier(String packageName, 8771 List<ResolveInfo> receivers) { 8772 ActivityInfo targetReceiver = null; 8773 8774 final int NR = receivers.size(); 8775 for (int i = 0; i < NR; i++) { 8776 final ResolveInfo info = receivers.get(i); 8777 if (info.activityInfo == null) { 8778 continue; 8779 } 8780 8781 if (packageName.equals(info.activityInfo.packageName)) { 8782 targetReceiver = info.activityInfo; 8783 break; 8784 } 8785 } 8786 8787 if (targetReceiver == null) { 8788 return null; 8789 } 8790 8791 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8792 } 8793 8794 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8795 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8796 if (pkgInfo.verifiers.length == 0) { 8797 return null; 8798 } 8799 8800 final int N = pkgInfo.verifiers.length; 8801 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8802 for (int i = 0; i < N; i++) { 8803 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8804 8805 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8806 receivers); 8807 if (comp == null) { 8808 continue; 8809 } 8810 8811 final int verifierUid = getUidForVerifier(verifierInfo); 8812 if (verifierUid == -1) { 8813 continue; 8814 } 8815 8816 if (DEBUG_VERIFY) { 8817 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8818 + " with the correct signature"); 8819 } 8820 sufficientVerifiers.add(comp); 8821 verificationState.addSufficientVerifier(verifierUid); 8822 } 8823 8824 return sufficientVerifiers; 8825 } 8826 8827 private int getUidForVerifier(VerifierInfo verifierInfo) { 8828 synchronized (mPackages) { 8829 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8830 if (pkg == null) { 8831 return -1; 8832 } else if (pkg.mSignatures.length != 1) { 8833 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8834 + " has more than one signature; ignoring"); 8835 return -1; 8836 } 8837 8838 /* 8839 * If the public key of the package's signature does not match 8840 * our expected public key, then this is a different package and 8841 * we should skip. 8842 */ 8843 8844 final byte[] expectedPublicKey; 8845 try { 8846 final Signature verifierSig = pkg.mSignatures[0]; 8847 final PublicKey publicKey = verifierSig.getPublicKey(); 8848 expectedPublicKey = publicKey.getEncoded(); 8849 } catch (CertificateException e) { 8850 return -1; 8851 } 8852 8853 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8854 8855 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8856 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8857 + " does not have the expected public key; ignoring"); 8858 return -1; 8859 } 8860 8861 return pkg.applicationInfo.uid; 8862 } 8863 } 8864 8865 @Override 8866 public void finishPackageInstall(int token) { 8867 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8868 8869 if (DEBUG_INSTALL) { 8870 Slog.v(TAG, "BM finishing package install for " + token); 8871 } 8872 8873 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8874 mHandler.sendMessage(msg); 8875 } 8876 8877 /** 8878 * Get the verification agent timeout. 8879 * 8880 * @return verification timeout in milliseconds 8881 */ 8882 private long getVerificationTimeout() { 8883 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8884 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8885 DEFAULT_VERIFICATION_TIMEOUT); 8886 } 8887 8888 /** 8889 * Get the default verification agent response code. 8890 * 8891 * @return default verification response code 8892 */ 8893 private int getDefaultVerificationResponse() { 8894 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8895 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8896 DEFAULT_VERIFICATION_RESPONSE); 8897 } 8898 8899 /** 8900 * Check whether or not package verification has been enabled. 8901 * 8902 * @return true if verification should be performed 8903 */ 8904 private boolean isVerificationEnabled(int userId, int installFlags) { 8905 if (!DEFAULT_VERIFY_ENABLE) { 8906 return false; 8907 } 8908 8909 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8910 8911 // Check if installing from ADB 8912 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8913 // Do not run verification in a test harness environment 8914 if (ActivityManager.isRunningInTestHarness()) { 8915 return false; 8916 } 8917 if (ensureVerifyAppsEnabled) { 8918 return true; 8919 } 8920 // Check if the developer does not want package verification for ADB installs 8921 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8922 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8923 return false; 8924 } 8925 } 8926 8927 if (ensureVerifyAppsEnabled) { 8928 return true; 8929 } 8930 8931 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8932 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8933 } 8934 8935 @Override 8936 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 8937 throws RemoteException { 8938 mContext.enforceCallingOrSelfPermission( 8939 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8940 "Only intentfilter verification agents can verify applications"); 8941 8942 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8943 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8944 Binder.getCallingUid(), verificationCode, failedDomains); 8945 msg.arg1 = id; 8946 msg.obj = response; 8947 mHandler.sendMessage(msg); 8948 } 8949 8950 @Override 8951 public int getIntentVerificationStatus(String packageName, int userId) { 8952 synchronized (mPackages) { 8953 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8954 } 8955 } 8956 8957 @Override 8958 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8959 boolean result = false; 8960 synchronized (mPackages) { 8961 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8962 } 8963 scheduleWritePackageRestrictionsLocked(userId); 8964 return result; 8965 } 8966 8967 @Override 8968 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8969 synchronized (mPackages) { 8970 return mSettings.getIntentFilterVerificationsLPr(packageName); 8971 } 8972 } 8973 8974 /** 8975 * Get the "allow unknown sources" setting. 8976 * 8977 * @return the current "allow unknown sources" setting 8978 */ 8979 private int getUnknownSourcesSettings() { 8980 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8981 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8982 -1); 8983 } 8984 8985 @Override 8986 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8987 final int uid = Binder.getCallingUid(); 8988 // writer 8989 synchronized (mPackages) { 8990 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8991 if (targetPackageSetting == null) { 8992 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8993 } 8994 8995 PackageSetting installerPackageSetting; 8996 if (installerPackageName != null) { 8997 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8998 if (installerPackageSetting == null) { 8999 throw new IllegalArgumentException("Unknown installer package: " 9000 + installerPackageName); 9001 } 9002 } else { 9003 installerPackageSetting = null; 9004 } 9005 9006 Signature[] callerSignature; 9007 Object obj = mSettings.getUserIdLPr(uid); 9008 if (obj != null) { 9009 if (obj instanceof SharedUserSetting) { 9010 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9011 } else if (obj instanceof PackageSetting) { 9012 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9013 } else { 9014 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9015 } 9016 } else { 9017 throw new SecurityException("Unknown calling uid " + uid); 9018 } 9019 9020 // Verify: can't set installerPackageName to a package that is 9021 // not signed with the same cert as the caller. 9022 if (installerPackageSetting != null) { 9023 if (compareSignatures(callerSignature, 9024 installerPackageSetting.signatures.mSignatures) 9025 != PackageManager.SIGNATURE_MATCH) { 9026 throw new SecurityException( 9027 "Caller does not have same cert as new installer package " 9028 + installerPackageName); 9029 } 9030 } 9031 9032 // Verify: if target already has an installer package, it must 9033 // be signed with the same cert as the caller. 9034 if (targetPackageSetting.installerPackageName != null) { 9035 PackageSetting setting = mSettings.mPackages.get( 9036 targetPackageSetting.installerPackageName); 9037 // If the currently set package isn't valid, then it's always 9038 // okay to change it. 9039 if (setting != null) { 9040 if (compareSignatures(callerSignature, 9041 setting.signatures.mSignatures) 9042 != PackageManager.SIGNATURE_MATCH) { 9043 throw new SecurityException( 9044 "Caller does not have same cert as old installer package " 9045 + targetPackageSetting.installerPackageName); 9046 } 9047 } 9048 } 9049 9050 // Okay! 9051 targetPackageSetting.installerPackageName = installerPackageName; 9052 scheduleWriteSettingsLocked(); 9053 } 9054 } 9055 9056 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9057 // Queue up an async operation since the package installation may take a little while. 9058 mHandler.post(new Runnable() { 9059 public void run() { 9060 mHandler.removeCallbacks(this); 9061 // Result object to be returned 9062 PackageInstalledInfo res = new PackageInstalledInfo(); 9063 res.returnCode = currentStatus; 9064 res.uid = -1; 9065 res.pkg = null; 9066 res.removedInfo = new PackageRemovedInfo(); 9067 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9068 args.doPreInstall(res.returnCode); 9069 synchronized (mInstallLock) { 9070 installPackageLI(args, res); 9071 } 9072 args.doPostInstall(res.returnCode, res.uid); 9073 } 9074 9075 // A restore should be performed at this point if (a) the install 9076 // succeeded, (b) the operation is not an update, and (c) the new 9077 // package has not opted out of backup participation. 9078 final boolean update = res.removedInfo.removedPackage != null; 9079 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9080 boolean doRestore = !update 9081 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9082 9083 // Set up the post-install work request bookkeeping. This will be used 9084 // and cleaned up by the post-install event handling regardless of whether 9085 // there's a restore pass performed. Token values are >= 1. 9086 int token; 9087 if (mNextInstallToken < 0) mNextInstallToken = 1; 9088 token = mNextInstallToken++; 9089 9090 PostInstallData data = new PostInstallData(args, res); 9091 mRunningInstalls.put(token, data); 9092 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9093 9094 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9095 // Pass responsibility to the Backup Manager. It will perform a 9096 // restore if appropriate, then pass responsibility back to the 9097 // Package Manager to run the post-install observer callbacks 9098 // and broadcasts. 9099 IBackupManager bm = IBackupManager.Stub.asInterface( 9100 ServiceManager.getService(Context.BACKUP_SERVICE)); 9101 if (bm != null) { 9102 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9103 + " to BM for possible restore"); 9104 try { 9105 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9106 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9107 } else { 9108 doRestore = false; 9109 } 9110 } catch (RemoteException e) { 9111 // can't happen; the backup manager is local 9112 } catch (Exception e) { 9113 Slog.e(TAG, "Exception trying to enqueue restore", e); 9114 doRestore = false; 9115 } 9116 } else { 9117 Slog.e(TAG, "Backup Manager not found!"); 9118 doRestore = false; 9119 } 9120 } 9121 9122 if (!doRestore) { 9123 // No restore possible, or the Backup Manager was mysteriously not 9124 // available -- just fire the post-install work request directly. 9125 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9126 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9127 mHandler.sendMessage(msg); 9128 } 9129 } 9130 }); 9131 } 9132 9133 private abstract class HandlerParams { 9134 private static final int MAX_RETRIES = 4; 9135 9136 /** 9137 * Number of times startCopy() has been attempted and had a non-fatal 9138 * error. 9139 */ 9140 private int mRetries = 0; 9141 9142 /** User handle for the user requesting the information or installation. */ 9143 private final UserHandle mUser; 9144 9145 HandlerParams(UserHandle user) { 9146 mUser = user; 9147 } 9148 9149 UserHandle getUser() { 9150 return mUser; 9151 } 9152 9153 final boolean startCopy() { 9154 boolean res; 9155 try { 9156 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9157 9158 if (++mRetries > MAX_RETRIES) { 9159 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9160 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9161 handleServiceError(); 9162 return false; 9163 } else { 9164 handleStartCopy(); 9165 res = true; 9166 } 9167 } catch (RemoteException e) { 9168 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9169 mHandler.sendEmptyMessage(MCS_RECONNECT); 9170 res = false; 9171 } 9172 handleReturnCode(); 9173 return res; 9174 } 9175 9176 final void serviceError() { 9177 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9178 handleServiceError(); 9179 handleReturnCode(); 9180 } 9181 9182 abstract void handleStartCopy() throws RemoteException; 9183 abstract void handleServiceError(); 9184 abstract void handleReturnCode(); 9185 } 9186 9187 class MeasureParams extends HandlerParams { 9188 private final PackageStats mStats; 9189 private boolean mSuccess; 9190 9191 private final IPackageStatsObserver mObserver; 9192 9193 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9194 super(new UserHandle(stats.userHandle)); 9195 mObserver = observer; 9196 mStats = stats; 9197 } 9198 9199 @Override 9200 public String toString() { 9201 return "MeasureParams{" 9202 + Integer.toHexString(System.identityHashCode(this)) 9203 + " " + mStats.packageName + "}"; 9204 } 9205 9206 @Override 9207 void handleStartCopy() throws RemoteException { 9208 synchronized (mInstallLock) { 9209 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9210 } 9211 9212 if (mSuccess) { 9213 final boolean mounted; 9214 if (Environment.isExternalStorageEmulated()) { 9215 mounted = true; 9216 } else { 9217 final String status = Environment.getExternalStorageState(); 9218 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9219 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9220 } 9221 9222 if (mounted) { 9223 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9224 9225 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9226 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9227 9228 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9229 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9230 9231 // Always subtract cache size, since it's a subdirectory 9232 mStats.externalDataSize -= mStats.externalCacheSize; 9233 9234 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9235 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9236 9237 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9238 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9239 } 9240 } 9241 } 9242 9243 @Override 9244 void handleReturnCode() { 9245 if (mObserver != null) { 9246 try { 9247 mObserver.onGetStatsCompleted(mStats, mSuccess); 9248 } catch (RemoteException e) { 9249 Slog.i(TAG, "Observer no longer exists."); 9250 } 9251 } 9252 } 9253 9254 @Override 9255 void handleServiceError() { 9256 Slog.e(TAG, "Could not measure application " + mStats.packageName 9257 + " external storage"); 9258 } 9259 } 9260 9261 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9262 throws RemoteException { 9263 long result = 0; 9264 for (File path : paths) { 9265 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9266 } 9267 return result; 9268 } 9269 9270 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9271 for (File path : paths) { 9272 try { 9273 mcs.clearDirectory(path.getAbsolutePath()); 9274 } catch (RemoteException e) { 9275 } 9276 } 9277 } 9278 9279 static class OriginInfo { 9280 /** 9281 * Location where install is coming from, before it has been 9282 * copied/renamed into place. This could be a single monolithic APK 9283 * file, or a cluster directory. This location may be untrusted. 9284 */ 9285 final File file; 9286 final String cid; 9287 9288 /** 9289 * Flag indicating that {@link #file} or {@link #cid} has already been 9290 * staged, meaning downstream users don't need to defensively copy the 9291 * contents. 9292 */ 9293 final boolean staged; 9294 9295 /** 9296 * Flag indicating that {@link #file} or {@link #cid} is an already 9297 * installed app that is being moved. 9298 */ 9299 final boolean existing; 9300 9301 final String resolvedPath; 9302 final File resolvedFile; 9303 9304 static OriginInfo fromNothing() { 9305 return new OriginInfo(null, null, false, false); 9306 } 9307 9308 static OriginInfo fromUntrustedFile(File file) { 9309 return new OriginInfo(file, null, false, false); 9310 } 9311 9312 static OriginInfo fromExistingFile(File file) { 9313 return new OriginInfo(file, null, false, true); 9314 } 9315 9316 static OriginInfo fromStagedFile(File file) { 9317 return new OriginInfo(file, null, true, false); 9318 } 9319 9320 static OriginInfo fromStagedContainer(String cid) { 9321 return new OriginInfo(null, cid, true, false); 9322 } 9323 9324 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9325 this.file = file; 9326 this.cid = cid; 9327 this.staged = staged; 9328 this.existing = existing; 9329 9330 if (cid != null) { 9331 resolvedPath = PackageHelper.getSdDir(cid); 9332 resolvedFile = new File(resolvedPath); 9333 } else if (file != null) { 9334 resolvedPath = file.getAbsolutePath(); 9335 resolvedFile = file; 9336 } else { 9337 resolvedPath = null; 9338 resolvedFile = null; 9339 } 9340 } 9341 } 9342 9343 class InstallParams extends HandlerParams { 9344 final OriginInfo origin; 9345 final IPackageInstallObserver2 observer; 9346 int installFlags; 9347 final String installerPackageName; 9348 final VerificationParams verificationParams; 9349 private InstallArgs mArgs; 9350 private int mRet; 9351 final String packageAbiOverride; 9352 9353 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9354 String installerPackageName, VerificationParams verificationParams, UserHandle user, 9355 String packageAbiOverride) { 9356 super(user); 9357 this.origin = origin; 9358 this.observer = observer; 9359 this.installFlags = installFlags; 9360 this.installerPackageName = installerPackageName; 9361 this.verificationParams = verificationParams; 9362 this.packageAbiOverride = packageAbiOverride; 9363 } 9364 9365 @Override 9366 public String toString() { 9367 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9368 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9369 } 9370 9371 public ManifestDigest getManifestDigest() { 9372 if (verificationParams == null) { 9373 return null; 9374 } 9375 return verificationParams.getManifestDigest(); 9376 } 9377 9378 private int installLocationPolicy(PackageInfoLite pkgLite) { 9379 String packageName = pkgLite.packageName; 9380 int installLocation = pkgLite.installLocation; 9381 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9382 // reader 9383 synchronized (mPackages) { 9384 PackageParser.Package pkg = mPackages.get(packageName); 9385 if (pkg != null) { 9386 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9387 // Check for downgrading. 9388 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9389 try { 9390 checkDowngrade(pkg, pkgLite); 9391 } catch (PackageManagerException e) { 9392 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9393 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9394 } 9395 } 9396 // Check for updated system application. 9397 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9398 if (onSd) { 9399 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9400 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9401 } 9402 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9403 } else { 9404 if (onSd) { 9405 // Install flag overrides everything. 9406 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9407 } 9408 // If current upgrade specifies particular preference 9409 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9410 // Application explicitly specified internal. 9411 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9412 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9413 // App explictly prefers external. Let policy decide 9414 } else { 9415 // Prefer previous location 9416 if (isExternal(pkg)) { 9417 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9418 } 9419 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9420 } 9421 } 9422 } else { 9423 // Invalid install. Return error code 9424 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9425 } 9426 } 9427 } 9428 // All the special cases have been taken care of. 9429 // Return result based on recommended install location. 9430 if (onSd) { 9431 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9432 } 9433 return pkgLite.recommendedInstallLocation; 9434 } 9435 9436 /* 9437 * Invoke remote method to get package information and install 9438 * location values. Override install location based on default 9439 * policy if needed and then create install arguments based 9440 * on the install location. 9441 */ 9442 public void handleStartCopy() throws RemoteException { 9443 int ret = PackageManager.INSTALL_SUCCEEDED; 9444 9445 // If we're already staged, we've firmly committed to an install location 9446 if (origin.staged) { 9447 if (origin.file != null) { 9448 installFlags |= PackageManager.INSTALL_INTERNAL; 9449 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9450 } else if (origin.cid != null) { 9451 installFlags |= PackageManager.INSTALL_EXTERNAL; 9452 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9453 } else { 9454 throw new IllegalStateException("Invalid stage location"); 9455 } 9456 } 9457 9458 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9459 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9460 9461 PackageInfoLite pkgLite = null; 9462 9463 if (onInt && onSd) { 9464 // Check if both bits are set. 9465 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9466 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9467 } else { 9468 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9469 packageAbiOverride); 9470 9471 /* 9472 * If we have too little free space, try to free cache 9473 * before giving up. 9474 */ 9475 if (!origin.staged && pkgLite.recommendedInstallLocation 9476 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9477 // TODO: focus freeing disk space on the target device 9478 final StorageManager storage = StorageManager.from(mContext); 9479 final long lowThreshold = storage.getStorageLowBytes( 9480 Environment.getDataDirectory()); 9481 9482 final long sizeBytes = mContainerService.calculateInstalledSize( 9483 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9484 9485 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9486 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9487 installFlags, packageAbiOverride); 9488 } 9489 9490 /* 9491 * The cache free must have deleted the file we 9492 * downloaded to install. 9493 * 9494 * TODO: fix the "freeCache" call to not delete 9495 * the file we care about. 9496 */ 9497 if (pkgLite.recommendedInstallLocation 9498 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9499 pkgLite.recommendedInstallLocation 9500 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9501 } 9502 } 9503 } 9504 9505 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9506 int loc = pkgLite.recommendedInstallLocation; 9507 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9508 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9509 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9510 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9511 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9512 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9513 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9514 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9515 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9516 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9517 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9518 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9519 } else { 9520 // Override with defaults if needed. 9521 loc = installLocationPolicy(pkgLite); 9522 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9523 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9524 } else if (!onSd && !onInt) { 9525 // Override install location with flags 9526 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9527 // Set the flag to install on external media. 9528 installFlags |= PackageManager.INSTALL_EXTERNAL; 9529 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9530 } else { 9531 // Make sure the flag for installing on external 9532 // media is unset 9533 installFlags |= PackageManager.INSTALL_INTERNAL; 9534 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9535 } 9536 } 9537 } 9538 } 9539 9540 final InstallArgs args = createInstallArgs(this); 9541 mArgs = args; 9542 9543 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9544 /* 9545 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9546 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9547 */ 9548 int userIdentifier = getUser().getIdentifier(); 9549 if (userIdentifier == UserHandle.USER_ALL 9550 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9551 userIdentifier = UserHandle.USER_OWNER; 9552 } 9553 9554 /* 9555 * Determine if we have any installed package verifiers. If we 9556 * do, then we'll defer to them to verify the packages. 9557 */ 9558 final int requiredUid = mRequiredVerifierPackage == null ? -1 9559 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9560 if (!origin.existing && requiredUid != -1 9561 && isVerificationEnabled(userIdentifier, installFlags)) { 9562 final Intent verification = new Intent( 9563 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9564 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9565 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9566 PACKAGE_MIME_TYPE); 9567 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9568 9569 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9570 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9571 0 /* TODO: Which userId? */); 9572 9573 if (DEBUG_VERIFY) { 9574 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9575 + verification.toString() + " with " + pkgLite.verifiers.length 9576 + " optional verifiers"); 9577 } 9578 9579 final int verificationId = mPendingVerificationToken++; 9580 9581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9582 9583 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9584 installerPackageName); 9585 9586 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9587 installFlags); 9588 9589 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9590 pkgLite.packageName); 9591 9592 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9593 pkgLite.versionCode); 9594 9595 if (verificationParams != null) { 9596 if (verificationParams.getVerificationURI() != null) { 9597 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9598 verificationParams.getVerificationURI()); 9599 } 9600 if (verificationParams.getOriginatingURI() != null) { 9601 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9602 verificationParams.getOriginatingURI()); 9603 } 9604 if (verificationParams.getReferrer() != null) { 9605 verification.putExtra(Intent.EXTRA_REFERRER, 9606 verificationParams.getReferrer()); 9607 } 9608 if (verificationParams.getOriginatingUid() >= 0) { 9609 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9610 verificationParams.getOriginatingUid()); 9611 } 9612 if (verificationParams.getInstallerUid() >= 0) { 9613 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9614 verificationParams.getInstallerUid()); 9615 } 9616 } 9617 9618 final PackageVerificationState verificationState = new PackageVerificationState( 9619 requiredUid, args); 9620 9621 mPendingVerification.append(verificationId, verificationState); 9622 9623 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9624 receivers, verificationState); 9625 9626 /* 9627 * If any sufficient verifiers were listed in the package 9628 * manifest, attempt to ask them. 9629 */ 9630 if (sufficientVerifiers != null) { 9631 final int N = sufficientVerifiers.size(); 9632 if (N == 0) { 9633 Slog.i(TAG, "Additional verifiers required, but none installed."); 9634 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9635 } else { 9636 for (int i = 0; i < N; i++) { 9637 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9638 9639 final Intent sufficientIntent = new Intent(verification); 9640 sufficientIntent.setComponent(verifierComponent); 9641 9642 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9643 } 9644 } 9645 } 9646 9647 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9648 mRequiredVerifierPackage, receivers); 9649 if (ret == PackageManager.INSTALL_SUCCEEDED 9650 && mRequiredVerifierPackage != null) { 9651 /* 9652 * Send the intent to the required verification agent, 9653 * but only start the verification timeout after the 9654 * target BroadcastReceivers have run. 9655 */ 9656 verification.setComponent(requiredVerifierComponent); 9657 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9658 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9659 new BroadcastReceiver() { 9660 @Override 9661 public void onReceive(Context context, Intent intent) { 9662 final Message msg = mHandler 9663 .obtainMessage(CHECK_PENDING_VERIFICATION); 9664 msg.arg1 = verificationId; 9665 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9666 } 9667 }, null, 0, null, null); 9668 9669 /* 9670 * We don't want the copy to proceed until verification 9671 * succeeds, so null out this field. 9672 */ 9673 mArgs = null; 9674 } 9675 } else { 9676 /* 9677 * No package verification is enabled, so immediately start 9678 * the remote call to initiate copy using temporary file. 9679 */ 9680 ret = args.copyApk(mContainerService, true); 9681 } 9682 } 9683 9684 mRet = ret; 9685 } 9686 9687 @Override 9688 void handleReturnCode() { 9689 // If mArgs is null, then MCS couldn't be reached. When it 9690 // reconnects, it will try again to install. At that point, this 9691 // will succeed. 9692 if (mArgs != null) { 9693 processPendingInstall(mArgs, mRet); 9694 } 9695 } 9696 9697 @Override 9698 void handleServiceError() { 9699 mArgs = createInstallArgs(this); 9700 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9701 } 9702 9703 public boolean isForwardLocked() { 9704 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9705 } 9706 } 9707 9708 /** 9709 * Used during creation of InstallArgs 9710 * 9711 * @param installFlags package installation flags 9712 * @return true if should be installed on external storage 9713 */ 9714 private static boolean installOnSd(int installFlags) { 9715 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9716 return false; 9717 } 9718 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9719 return true; 9720 } 9721 return false; 9722 } 9723 9724 /** 9725 * Used during creation of InstallArgs 9726 * 9727 * @param installFlags package installation flags 9728 * @return true if should be installed as forward locked 9729 */ 9730 private static boolean installForwardLocked(int installFlags) { 9731 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9732 } 9733 9734 private InstallArgs createInstallArgs(InstallParams params) { 9735 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9736 return new AsecInstallArgs(params); 9737 } else { 9738 return new FileInstallArgs(params); 9739 } 9740 } 9741 9742 /** 9743 * Create args that describe an existing installed package. Typically used 9744 * when cleaning up old installs, or used as a move source. 9745 */ 9746 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9747 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9748 final boolean isInAsec; 9749 if (installOnSd(installFlags)) { 9750 /* Apps on SD card are always in ASEC containers. */ 9751 isInAsec = true; 9752 } else if (installForwardLocked(installFlags) 9753 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9754 /* 9755 * Forward-locked apps are only in ASEC containers if they're the 9756 * new style 9757 */ 9758 isInAsec = true; 9759 } else { 9760 isInAsec = false; 9761 } 9762 9763 if (isInAsec) { 9764 return new AsecInstallArgs(codePath, instructionSets, 9765 installOnSd(installFlags), installForwardLocked(installFlags)); 9766 } else { 9767 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9768 instructionSets); 9769 } 9770 } 9771 9772 static abstract class InstallArgs { 9773 /** @see InstallParams#origin */ 9774 final OriginInfo origin; 9775 9776 final IPackageInstallObserver2 observer; 9777 // Always refers to PackageManager flags only 9778 final int installFlags; 9779 final String installerPackageName; 9780 final ManifestDigest manifestDigest; 9781 final UserHandle user; 9782 final String abiOverride; 9783 9784 // The list of instruction sets supported by this app. This is currently 9785 // only used during the rmdex() phase to clean up resources. We can get rid of this 9786 // if we move dex files under the common app path. 9787 /* nullable */ String[] instructionSets; 9788 9789 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9790 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9791 String[] instructionSets, String abiOverride) { 9792 this.origin = origin; 9793 this.installFlags = installFlags; 9794 this.observer = observer; 9795 this.installerPackageName = installerPackageName; 9796 this.manifestDigest = manifestDigest; 9797 this.user = user; 9798 this.instructionSets = instructionSets; 9799 this.abiOverride = abiOverride; 9800 } 9801 9802 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9803 abstract int doPreInstall(int status); 9804 9805 /** 9806 * Rename package into final resting place. All paths on the given 9807 * scanned package should be updated to reflect the rename. 9808 */ 9809 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9810 abstract int doPostInstall(int status, int uid); 9811 9812 /** @see PackageSettingBase#codePathString */ 9813 abstract String getCodePath(); 9814 /** @see PackageSettingBase#resourcePathString */ 9815 abstract String getResourcePath(); 9816 abstract String getLegacyNativeLibraryPath(); 9817 9818 // Need installer lock especially for dex file removal. 9819 abstract void cleanUpResourcesLI(); 9820 abstract boolean doPostDeleteLI(boolean delete); 9821 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9822 9823 /** 9824 * Called before the source arguments are copied. This is used mostly 9825 * for MoveParams when it needs to read the source file to put it in the 9826 * destination. 9827 */ 9828 int doPreCopy() { 9829 return PackageManager.INSTALL_SUCCEEDED; 9830 } 9831 9832 /** 9833 * Called after the source arguments are copied. This is used mostly for 9834 * MoveParams when it needs to read the source file to put it in the 9835 * destination. 9836 * 9837 * @return 9838 */ 9839 int doPostCopy(int uid) { 9840 return PackageManager.INSTALL_SUCCEEDED; 9841 } 9842 9843 protected boolean isFwdLocked() { 9844 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9845 } 9846 9847 protected boolean isExternal() { 9848 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9849 } 9850 9851 UserHandle getUser() { 9852 return user; 9853 } 9854 } 9855 9856 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9857 if (!allCodePaths.isEmpty()) { 9858 if (instructionSets == null) { 9859 throw new IllegalStateException("instructionSet == null"); 9860 } 9861 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9862 for (String codePath : allCodePaths) { 9863 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9864 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9865 if (retCode < 0) { 9866 Slog.w(TAG, "Couldn't remove dex file for package: " 9867 + " at location " + codePath + ", retcode=" + retCode); 9868 // we don't consider this to be a failure of the core package deletion 9869 } 9870 } 9871 } 9872 } 9873 } 9874 9875 /** 9876 * Logic to handle installation of non-ASEC applications, including copying 9877 * and renaming logic. 9878 */ 9879 class FileInstallArgs extends InstallArgs { 9880 private File codeFile; 9881 private File resourceFile; 9882 private File legacyNativeLibraryPath; 9883 9884 // Example topology: 9885 // /data/app/com.example/base.apk 9886 // /data/app/com.example/split_foo.apk 9887 // /data/app/com.example/lib/arm/libfoo.so 9888 // /data/app/com.example/lib/arm64/libfoo.so 9889 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9890 9891 /** New install */ 9892 FileInstallArgs(InstallParams params) { 9893 super(params.origin, params.observer, params.installFlags, 9894 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9895 null /* instruction sets */, params.packageAbiOverride); 9896 if (isFwdLocked()) { 9897 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9898 } 9899 } 9900 9901 /** Existing install */ 9902 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9903 String[] instructionSets) { 9904 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9905 this.codeFile = (codePath != null) ? new File(codePath) : null; 9906 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9907 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9908 new File(legacyNativeLibraryPath) : null; 9909 } 9910 9911 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9912 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9913 isFwdLocked(), abiOverride); 9914 9915 final StorageManager storage = StorageManager.from(mContext); 9916 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9917 } 9918 9919 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9920 if (origin.staged) { 9921 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9922 codeFile = origin.file; 9923 resourceFile = origin.file; 9924 return PackageManager.INSTALL_SUCCEEDED; 9925 } 9926 9927 try { 9928 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9929 codeFile = tempDir; 9930 resourceFile = tempDir; 9931 } catch (IOException e) { 9932 Slog.w(TAG, "Failed to create copy file: " + e); 9933 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9934 } 9935 9936 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9937 @Override 9938 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9939 if (!FileUtils.isValidExtFilename(name)) { 9940 throw new IllegalArgumentException("Invalid filename: " + name); 9941 } 9942 try { 9943 final File file = new File(codeFile, name); 9944 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9945 O_RDWR | O_CREAT, 0644); 9946 Os.chmod(file.getAbsolutePath(), 0644); 9947 return new ParcelFileDescriptor(fd); 9948 } catch (ErrnoException e) { 9949 throw new RemoteException("Failed to open: " + e.getMessage()); 9950 } 9951 } 9952 }; 9953 9954 int ret = PackageManager.INSTALL_SUCCEEDED; 9955 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9956 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9957 Slog.e(TAG, "Failed to copy package"); 9958 return ret; 9959 } 9960 9961 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9962 NativeLibraryHelper.Handle handle = null; 9963 try { 9964 handle = NativeLibraryHelper.Handle.create(codeFile); 9965 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9966 abiOverride); 9967 } catch (IOException e) { 9968 Slog.e(TAG, "Copying native libraries failed", e); 9969 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9970 } finally { 9971 IoUtils.closeQuietly(handle); 9972 } 9973 9974 return ret; 9975 } 9976 9977 int doPreInstall(int status) { 9978 if (status != PackageManager.INSTALL_SUCCEEDED) { 9979 cleanUp(); 9980 } 9981 return status; 9982 } 9983 9984 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9985 if (status != PackageManager.INSTALL_SUCCEEDED) { 9986 cleanUp(); 9987 return false; 9988 } else { 9989 final File beforeCodeFile = codeFile; 9990 final File afterCodeFile = getNextCodePath(pkg.packageName); 9991 9992 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9993 try { 9994 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9995 } catch (ErrnoException e) { 9996 Slog.d(TAG, "Failed to rename", e); 9997 return false; 9998 } 9999 10000 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10001 Slog.d(TAG, "Failed to restorecon"); 10002 return false; 10003 } 10004 10005 // Reflect the rename internally 10006 codeFile = afterCodeFile; 10007 resourceFile = afterCodeFile; 10008 10009 // Reflect the rename in scanned details 10010 pkg.codePath = afterCodeFile.getAbsolutePath(); 10011 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10012 pkg.baseCodePath); 10013 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10014 pkg.splitCodePaths); 10015 10016 // Reflect the rename in app info 10017 pkg.applicationInfo.setCodePath(pkg.codePath); 10018 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10019 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10020 pkg.applicationInfo.setResourcePath(pkg.codePath); 10021 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10022 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10023 10024 return true; 10025 } 10026 } 10027 10028 int doPostInstall(int status, int uid) { 10029 if (status != PackageManager.INSTALL_SUCCEEDED) { 10030 cleanUp(); 10031 } 10032 return status; 10033 } 10034 10035 @Override 10036 String getCodePath() { 10037 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10038 } 10039 10040 @Override 10041 String getResourcePath() { 10042 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10043 } 10044 10045 @Override 10046 String getLegacyNativeLibraryPath() { 10047 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10048 } 10049 10050 private boolean cleanUp() { 10051 if (codeFile == null || !codeFile.exists()) { 10052 return false; 10053 } 10054 10055 if (codeFile.isDirectory()) { 10056 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10057 } else { 10058 codeFile.delete(); 10059 } 10060 10061 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10062 resourceFile.delete(); 10063 } 10064 10065 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10066 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10067 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10068 } 10069 legacyNativeLibraryPath.delete(); 10070 } 10071 10072 return true; 10073 } 10074 10075 void cleanUpResourcesLI() { 10076 // Try enumerating all code paths before deleting 10077 List<String> allCodePaths = Collections.EMPTY_LIST; 10078 if (codeFile != null && codeFile.exists()) { 10079 try { 10080 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10081 allCodePaths = pkg.getAllCodePaths(); 10082 } catch (PackageParserException e) { 10083 // Ignored; we tried our best 10084 } 10085 } 10086 10087 cleanUp(); 10088 removeDexFiles(allCodePaths, instructionSets); 10089 } 10090 10091 boolean doPostDeleteLI(boolean delete) { 10092 // XXX err, shouldn't we respect the delete flag? 10093 cleanUpResourcesLI(); 10094 return true; 10095 } 10096 } 10097 10098 private boolean isAsecExternal(String cid) { 10099 final String asecPath = PackageHelper.getSdFilesystem(cid); 10100 return !asecPath.startsWith(mAsecInternalPath); 10101 } 10102 10103 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10104 PackageManagerException { 10105 if (copyRet < 0) { 10106 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10107 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10108 throw new PackageManagerException(copyRet, message); 10109 } 10110 } 10111 } 10112 10113 /** 10114 * Extract the MountService "container ID" from the full code path of an 10115 * .apk. 10116 */ 10117 static String cidFromCodePath(String fullCodePath) { 10118 int eidx = fullCodePath.lastIndexOf("/"); 10119 String subStr1 = fullCodePath.substring(0, eidx); 10120 int sidx = subStr1.lastIndexOf("/"); 10121 return subStr1.substring(sidx+1, eidx); 10122 } 10123 10124 /** 10125 * Logic to handle installation of ASEC applications, including copying and 10126 * renaming logic. 10127 */ 10128 class AsecInstallArgs extends InstallArgs { 10129 static final String RES_FILE_NAME = "pkg.apk"; 10130 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10131 10132 String cid; 10133 String packagePath; 10134 String resourcePath; 10135 String legacyNativeLibraryDir; 10136 10137 /** New install */ 10138 AsecInstallArgs(InstallParams params) { 10139 super(params.origin, params.observer, params.installFlags, 10140 params.installerPackageName, params.getManifestDigest(), 10141 params.getUser(), null /* instruction sets */, 10142 params.packageAbiOverride); 10143 } 10144 10145 /** Existing install */ 10146 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10147 boolean isExternal, boolean isForwardLocked) { 10148 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10149 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10150 instructionSets, null); 10151 // Hackily pretend we're still looking at a full code path 10152 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10153 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10154 } 10155 10156 // Extract cid from fullCodePath 10157 int eidx = fullCodePath.lastIndexOf("/"); 10158 String subStr1 = fullCodePath.substring(0, eidx); 10159 int sidx = subStr1.lastIndexOf("/"); 10160 cid = subStr1.substring(sidx+1, eidx); 10161 setMountPath(subStr1); 10162 } 10163 10164 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10165 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10166 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10167 instructionSets, null); 10168 this.cid = cid; 10169 setMountPath(PackageHelper.getSdDir(cid)); 10170 } 10171 10172 void createCopyFile() { 10173 cid = mInstallerService.allocateExternalStageCidLegacy(); 10174 } 10175 10176 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10177 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10178 abiOverride); 10179 10180 final File target; 10181 if (isExternal()) { 10182 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10183 } else { 10184 target = Environment.getDataDirectory(); 10185 } 10186 10187 final StorageManager storage = StorageManager.from(mContext); 10188 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10189 } 10190 10191 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10192 if (origin.staged) { 10193 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10194 cid = origin.cid; 10195 setMountPath(PackageHelper.getSdDir(cid)); 10196 return PackageManager.INSTALL_SUCCEEDED; 10197 } 10198 10199 if (temp) { 10200 createCopyFile(); 10201 } else { 10202 /* 10203 * Pre-emptively destroy the container since it's destroyed if 10204 * copying fails due to it existing anyway. 10205 */ 10206 PackageHelper.destroySdDir(cid); 10207 } 10208 10209 final String newMountPath = imcs.copyPackageToContainer( 10210 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 10211 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10212 10213 if (newMountPath != null) { 10214 setMountPath(newMountPath); 10215 return PackageManager.INSTALL_SUCCEEDED; 10216 } else { 10217 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10218 } 10219 } 10220 10221 @Override 10222 String getCodePath() { 10223 return packagePath; 10224 } 10225 10226 @Override 10227 String getResourcePath() { 10228 return resourcePath; 10229 } 10230 10231 @Override 10232 String getLegacyNativeLibraryPath() { 10233 return legacyNativeLibraryDir; 10234 } 10235 10236 int doPreInstall(int status) { 10237 if (status != PackageManager.INSTALL_SUCCEEDED) { 10238 // Destroy container 10239 PackageHelper.destroySdDir(cid); 10240 } else { 10241 boolean mounted = PackageHelper.isContainerMounted(cid); 10242 if (!mounted) { 10243 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10244 Process.SYSTEM_UID); 10245 if (newMountPath != null) { 10246 setMountPath(newMountPath); 10247 } else { 10248 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10249 } 10250 } 10251 } 10252 return status; 10253 } 10254 10255 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10256 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10257 String newMountPath = null; 10258 if (PackageHelper.isContainerMounted(cid)) { 10259 // Unmount the container 10260 if (!PackageHelper.unMountSdDir(cid)) { 10261 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10262 return false; 10263 } 10264 } 10265 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10266 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10267 " which might be stale. Will try to clean up."); 10268 // Clean up the stale container and proceed to recreate. 10269 if (!PackageHelper.destroySdDir(newCacheId)) { 10270 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10271 return false; 10272 } 10273 // Successfully cleaned up stale container. Try to rename again. 10274 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10275 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10276 + " inspite of cleaning it up."); 10277 return false; 10278 } 10279 } 10280 if (!PackageHelper.isContainerMounted(newCacheId)) { 10281 Slog.w(TAG, "Mounting container " + newCacheId); 10282 newMountPath = PackageHelper.mountSdDir(newCacheId, 10283 getEncryptKey(), Process.SYSTEM_UID); 10284 } else { 10285 newMountPath = PackageHelper.getSdDir(newCacheId); 10286 } 10287 if (newMountPath == null) { 10288 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10289 return false; 10290 } 10291 Log.i(TAG, "Succesfully renamed " + cid + 10292 " to " + newCacheId + 10293 " at new path: " + newMountPath); 10294 cid = newCacheId; 10295 10296 final File beforeCodeFile = new File(packagePath); 10297 setMountPath(newMountPath); 10298 final File afterCodeFile = new File(packagePath); 10299 10300 // Reflect the rename in scanned details 10301 pkg.codePath = afterCodeFile.getAbsolutePath(); 10302 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10303 pkg.baseCodePath); 10304 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10305 pkg.splitCodePaths); 10306 10307 // Reflect the rename in app info 10308 pkg.applicationInfo.setCodePath(pkg.codePath); 10309 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10310 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10311 pkg.applicationInfo.setResourcePath(pkg.codePath); 10312 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10313 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10314 10315 return true; 10316 } 10317 10318 private void setMountPath(String mountPath) { 10319 final File mountFile = new File(mountPath); 10320 10321 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10322 if (monolithicFile.exists()) { 10323 packagePath = monolithicFile.getAbsolutePath(); 10324 if (isFwdLocked()) { 10325 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10326 } else { 10327 resourcePath = packagePath; 10328 } 10329 } else { 10330 packagePath = mountFile.getAbsolutePath(); 10331 resourcePath = packagePath; 10332 } 10333 10334 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10335 } 10336 10337 int doPostInstall(int status, int uid) { 10338 if (status != PackageManager.INSTALL_SUCCEEDED) { 10339 cleanUp(); 10340 } else { 10341 final int groupOwner; 10342 final String protectedFile; 10343 if (isFwdLocked()) { 10344 groupOwner = UserHandle.getSharedAppGid(uid); 10345 protectedFile = RES_FILE_NAME; 10346 } else { 10347 groupOwner = -1; 10348 protectedFile = null; 10349 } 10350 10351 if (uid < Process.FIRST_APPLICATION_UID 10352 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10353 Slog.e(TAG, "Failed to finalize " + cid); 10354 PackageHelper.destroySdDir(cid); 10355 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10356 } 10357 10358 boolean mounted = PackageHelper.isContainerMounted(cid); 10359 if (!mounted) { 10360 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10361 } 10362 } 10363 return status; 10364 } 10365 10366 private void cleanUp() { 10367 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10368 10369 // Destroy secure container 10370 PackageHelper.destroySdDir(cid); 10371 } 10372 10373 private List<String> getAllCodePaths() { 10374 final File codeFile = new File(getCodePath()); 10375 if (codeFile != null && codeFile.exists()) { 10376 try { 10377 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10378 return pkg.getAllCodePaths(); 10379 } catch (PackageParserException e) { 10380 // Ignored; we tried our best 10381 } 10382 } 10383 return Collections.EMPTY_LIST; 10384 } 10385 10386 void cleanUpResourcesLI() { 10387 // Enumerate all code paths before deleting 10388 cleanUpResourcesLI(getAllCodePaths()); 10389 } 10390 10391 private void cleanUpResourcesLI(List<String> allCodePaths) { 10392 cleanUp(); 10393 removeDexFiles(allCodePaths, instructionSets); 10394 } 10395 10396 10397 10398 String getPackageName() { 10399 return getAsecPackageName(cid); 10400 } 10401 10402 boolean doPostDeleteLI(boolean delete) { 10403 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10404 final List<String> allCodePaths = getAllCodePaths(); 10405 boolean mounted = PackageHelper.isContainerMounted(cid); 10406 if (mounted) { 10407 // Unmount first 10408 if (PackageHelper.unMountSdDir(cid)) { 10409 mounted = false; 10410 } 10411 } 10412 if (!mounted && delete) { 10413 cleanUpResourcesLI(allCodePaths); 10414 } 10415 return !mounted; 10416 } 10417 10418 @Override 10419 int doPreCopy() { 10420 if (isFwdLocked()) { 10421 if (!PackageHelper.fixSdPermissions(cid, 10422 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10423 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10424 } 10425 } 10426 10427 return PackageManager.INSTALL_SUCCEEDED; 10428 } 10429 10430 @Override 10431 int doPostCopy(int uid) { 10432 if (isFwdLocked()) { 10433 if (uid < Process.FIRST_APPLICATION_UID 10434 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10435 RES_FILE_NAME)) { 10436 Slog.e(TAG, "Failed to finalize " + cid); 10437 PackageHelper.destroySdDir(cid); 10438 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10439 } 10440 } 10441 10442 return PackageManager.INSTALL_SUCCEEDED; 10443 } 10444 } 10445 10446 static String getAsecPackageName(String packageCid) { 10447 int idx = packageCid.lastIndexOf("-"); 10448 if (idx == -1) { 10449 return packageCid; 10450 } 10451 return packageCid.substring(0, idx); 10452 } 10453 10454 // Utility method used to create code paths based on package name and available index. 10455 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10456 String idxStr = ""; 10457 int idx = 1; 10458 // Fall back to default value of idx=1 if prefix is not 10459 // part of oldCodePath 10460 if (oldCodePath != null) { 10461 String subStr = oldCodePath; 10462 // Drop the suffix right away 10463 if (suffix != null && subStr.endsWith(suffix)) { 10464 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10465 } 10466 // If oldCodePath already contains prefix find out the 10467 // ending index to either increment or decrement. 10468 int sidx = subStr.lastIndexOf(prefix); 10469 if (sidx != -1) { 10470 subStr = subStr.substring(sidx + prefix.length()); 10471 if (subStr != null) { 10472 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10473 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10474 } 10475 try { 10476 idx = Integer.parseInt(subStr); 10477 if (idx <= 1) { 10478 idx++; 10479 } else { 10480 idx--; 10481 } 10482 } catch(NumberFormatException e) { 10483 } 10484 } 10485 } 10486 } 10487 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10488 return prefix + idxStr; 10489 } 10490 10491 private File getNextCodePath(String packageName) { 10492 int suffix = 1; 10493 File result; 10494 do { 10495 result = new File(mAppInstallDir, packageName + "-" + suffix); 10496 suffix++; 10497 } while (result.exists()); 10498 return result; 10499 } 10500 10501 // Utility method that returns the relative package path with respect 10502 // to the installation directory. Like say for /data/data/com.test-1.apk 10503 // string com.test-1 is returned. 10504 static String deriveCodePathName(String codePath) { 10505 if (codePath == null) { 10506 return null; 10507 } 10508 final File codeFile = new File(codePath); 10509 final String name = codeFile.getName(); 10510 if (codeFile.isDirectory()) { 10511 return name; 10512 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10513 final int lastDot = name.lastIndexOf('.'); 10514 return name.substring(0, lastDot); 10515 } else { 10516 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10517 return null; 10518 } 10519 } 10520 10521 class PackageInstalledInfo { 10522 String name; 10523 int uid; 10524 // The set of users that originally had this package installed. 10525 int[] origUsers; 10526 // The set of users that now have this package installed. 10527 int[] newUsers; 10528 PackageParser.Package pkg; 10529 int returnCode; 10530 String returnMsg; 10531 PackageRemovedInfo removedInfo; 10532 10533 public void setError(int code, String msg) { 10534 returnCode = code; 10535 returnMsg = msg; 10536 Slog.w(TAG, msg); 10537 } 10538 10539 public void setError(String msg, PackageParserException e) { 10540 returnCode = e.error; 10541 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10542 Slog.w(TAG, msg, e); 10543 } 10544 10545 public void setError(String msg, PackageManagerException e) { 10546 returnCode = e.error; 10547 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10548 Slog.w(TAG, msg, e); 10549 } 10550 10551 // In some error cases we want to convey more info back to the observer 10552 String origPackage; 10553 String origPermission; 10554 } 10555 10556 /* 10557 * Install a non-existing package. 10558 */ 10559 private void installNewPackageLI(PackageParser.Package pkg, 10560 int parseFlags, int scanFlags, UserHandle user, 10561 String installerPackageName, PackageInstalledInfo res) { 10562 // Remember this for later, in case we need to rollback this install 10563 String pkgName = pkg.packageName; 10564 10565 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10566 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10567 synchronized(mPackages) { 10568 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10569 // A package with the same name is already installed, though 10570 // it has been renamed to an older name. The package we 10571 // are trying to install should be installed as an update to 10572 // the existing one, but that has not been requested, so bail. 10573 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10574 + " without first uninstalling package running as " 10575 + mSettings.mRenamedPackages.get(pkgName)); 10576 return; 10577 } 10578 if (mPackages.containsKey(pkgName)) { 10579 // Don't allow installation over an existing package with the same name. 10580 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10581 + " without first uninstalling."); 10582 return; 10583 } 10584 } 10585 10586 try { 10587 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10588 System.currentTimeMillis(), user); 10589 10590 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10591 // delete the partially installed application. the data directory will have to be 10592 // restored if it was already existing 10593 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10594 // remove package from internal structures. Note that we want deletePackageX to 10595 // delete the package data and cache directories that it created in 10596 // scanPackageLocked, unless those directories existed before we even tried to 10597 // install. 10598 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10599 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10600 res.removedInfo, true); 10601 } 10602 10603 } catch (PackageManagerException e) { 10604 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10605 } 10606 } 10607 10608 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10609 // Upgrade keysets are being used. Determine if new package has a superset of the 10610 // required keys. 10611 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10613 for (int i = 0; i < upgradeKeySets.length; i++) { 10614 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10615 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10616 return true; 10617 } 10618 } 10619 return false; 10620 } 10621 10622 private void replacePackageLI(PackageParser.Package pkg, 10623 int parseFlags, int scanFlags, UserHandle user, 10624 String installerPackageName, PackageInstalledInfo res) { 10625 PackageParser.Package oldPackage; 10626 String pkgName = pkg.packageName; 10627 int[] allUsers; 10628 boolean[] perUserInstalled; 10629 10630 // First find the old package info and check signatures 10631 synchronized(mPackages) { 10632 oldPackage = mPackages.get(pkgName); 10633 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10634 PackageSetting ps = mSettings.mPackages.get(pkgName); 10635 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10636 // default to original signature matching 10637 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10638 != PackageManager.SIGNATURE_MATCH) { 10639 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10640 "New package has a different signature: " + pkgName); 10641 return; 10642 } 10643 } else { 10644 if(!checkUpgradeKeySetLP(ps, pkg)) { 10645 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10646 "New package not signed by keys specified by upgrade-keysets: " 10647 + pkgName); 10648 return; 10649 } 10650 } 10651 10652 // In case of rollback, remember per-user/profile install state 10653 allUsers = sUserManager.getUserIds(); 10654 perUserInstalled = new boolean[allUsers.length]; 10655 for (int i = 0; i < allUsers.length; i++) { 10656 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10657 } 10658 } 10659 10660 boolean sysPkg = (isSystemApp(oldPackage)); 10661 if (sysPkg) { 10662 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10663 user, allUsers, perUserInstalled, installerPackageName, res); 10664 } else { 10665 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10666 user, allUsers, perUserInstalled, installerPackageName, res); 10667 } 10668 } 10669 10670 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10671 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10672 int[] allUsers, boolean[] perUserInstalled, 10673 String installerPackageName, PackageInstalledInfo res) { 10674 String pkgName = deletedPackage.packageName; 10675 boolean deletedPkg = true; 10676 boolean updatedSettings = false; 10677 10678 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10679 + deletedPackage); 10680 long origUpdateTime; 10681 if (pkg.mExtras != null) { 10682 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10683 } else { 10684 origUpdateTime = 0; 10685 } 10686 10687 // First delete the existing package while retaining the data directory 10688 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10689 res.removedInfo, true)) { 10690 // If the existing package wasn't successfully deleted 10691 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10692 deletedPkg = false; 10693 } else { 10694 // Successfully deleted the old package; proceed with replace. 10695 10696 // If deleted package lived in a container, give users a chance to 10697 // relinquish resources before killing. 10698 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10699 if (DEBUG_INSTALL) { 10700 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10701 } 10702 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10703 final ArrayList<String> pkgList = new ArrayList<String>(1); 10704 pkgList.add(deletedPackage.applicationInfo.packageName); 10705 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10706 } 10707 10708 deleteCodeCacheDirsLI(pkgName); 10709 try { 10710 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10711 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10712 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10713 user); 10714 updatedSettings = true; 10715 } catch (PackageManagerException e) { 10716 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10717 } 10718 } 10719 10720 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10721 // remove package from internal structures. Note that we want deletePackageX to 10722 // delete the package data and cache directories that it created in 10723 // scanPackageLocked, unless those directories existed before we even tried to 10724 // install. 10725 if(updatedSettings) { 10726 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10727 deletePackageLI( 10728 pkgName, null, true, allUsers, perUserInstalled, 10729 PackageManager.DELETE_KEEP_DATA, 10730 res.removedInfo, true); 10731 } 10732 // Since we failed to install the new package we need to restore the old 10733 // package that we deleted. 10734 if (deletedPkg) { 10735 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10736 File restoreFile = new File(deletedPackage.codePath); 10737 // Parse old package 10738 boolean oldOnSd = isExternal(deletedPackage); 10739 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10740 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10741 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10742 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10743 try { 10744 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10745 } catch (PackageManagerException e) { 10746 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10747 + e.getMessage()); 10748 return; 10749 } 10750 // Restore of old package succeeded. Update permissions. 10751 // writer 10752 synchronized (mPackages) { 10753 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10754 UPDATE_PERMISSIONS_ALL); 10755 // can downgrade to reader 10756 mSettings.writeLPr(); 10757 } 10758 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10759 } 10760 } 10761 } 10762 10763 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10764 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10765 int[] allUsers, boolean[] perUserInstalled, 10766 String installerPackageName, PackageInstalledInfo res) { 10767 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10768 + ", old=" + deletedPackage); 10769 boolean disabledSystem = false; 10770 boolean updatedSettings = false; 10771 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10772 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10773 != 0) { 10774 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10775 } 10776 String packageName = deletedPackage.packageName; 10777 if (packageName == null) { 10778 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10779 "Attempt to delete null packageName."); 10780 return; 10781 } 10782 PackageParser.Package oldPkg; 10783 PackageSetting oldPkgSetting; 10784 // reader 10785 synchronized (mPackages) { 10786 oldPkg = mPackages.get(packageName); 10787 oldPkgSetting = mSettings.mPackages.get(packageName); 10788 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10789 (oldPkgSetting == null)) { 10790 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10791 "Couldn't find package:" + packageName + " information"); 10792 return; 10793 } 10794 } 10795 10796 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10797 10798 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10799 res.removedInfo.removedPackage = packageName; 10800 // Remove existing system package 10801 removePackageLI(oldPkgSetting, true); 10802 // writer 10803 synchronized (mPackages) { 10804 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10805 if (!disabledSystem && deletedPackage != null) { 10806 // We didn't need to disable the .apk as a current system package, 10807 // which means we are replacing another update that is already 10808 // installed. We need to make sure to delete the older one's .apk. 10809 res.removedInfo.args = createInstallArgsForExisting(0, 10810 deletedPackage.applicationInfo.getCodePath(), 10811 deletedPackage.applicationInfo.getResourcePath(), 10812 deletedPackage.applicationInfo.nativeLibraryRootDir, 10813 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10814 } else { 10815 res.removedInfo.args = null; 10816 } 10817 } 10818 10819 // Successfully disabled the old package. Now proceed with re-installation 10820 deleteCodeCacheDirsLI(packageName); 10821 10822 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10823 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10824 10825 PackageParser.Package newPackage = null; 10826 try { 10827 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10828 if (newPackage.mExtras != null) { 10829 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10830 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10831 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10832 10833 // is the update attempting to change shared user? that isn't going to work... 10834 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10835 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10836 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10837 + " to " + newPkgSetting.sharedUser); 10838 updatedSettings = true; 10839 } 10840 } 10841 10842 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10843 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10844 user); 10845 updatedSettings = true; 10846 } 10847 10848 } catch (PackageManagerException e) { 10849 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10850 } 10851 10852 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10853 // Re installation failed. Restore old information 10854 // Remove new pkg information 10855 if (newPackage != null) { 10856 removeInstalledPackageLI(newPackage, true); 10857 } 10858 // Add back the old system package 10859 try { 10860 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10861 } catch (PackageManagerException e) { 10862 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10863 } 10864 // Restore the old system information in Settings 10865 synchronized (mPackages) { 10866 if (disabledSystem) { 10867 mSettings.enableSystemPackageLPw(packageName); 10868 } 10869 if (updatedSettings) { 10870 mSettings.setInstallerPackageName(packageName, 10871 oldPkgSetting.installerPackageName); 10872 } 10873 mSettings.writeLPr(); 10874 } 10875 } 10876 } 10877 10878 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10879 int[] allUsers, boolean[] perUserInstalled, 10880 PackageInstalledInfo res, UserHandle user) { 10881 String pkgName = newPackage.packageName; 10882 synchronized (mPackages) { 10883 //write settings. the installStatus will be incomplete at this stage. 10884 //note that the new package setting would have already been 10885 //added to mPackages. It hasn't been persisted yet. 10886 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10887 mSettings.writeLPr(); 10888 } 10889 10890 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10891 10892 synchronized (mPackages) { 10893 updatePermissionsLPw(newPackage.packageName, newPackage, 10894 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10895 ? UPDATE_PERMISSIONS_ALL : 0)); 10896 // For system-bundled packages, we assume that installing an upgraded version 10897 // of the package implies that the user actually wants to run that new code, 10898 // so we enable the package. 10899 PackageSetting ps = mSettings.mPackages.get(pkgName); 10900 if (ps != null) { 10901 if (isSystemApp(newPackage)) { 10902 // NB: implicit assumption that system package upgrades apply to all users 10903 if (DEBUG_INSTALL) { 10904 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10905 } 10906 if (res.origUsers != null) { 10907 for (int userHandle : res.origUsers) { 10908 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10909 userHandle, installerPackageName); 10910 } 10911 } 10912 // Also convey the prior install/uninstall state 10913 if (allUsers != null && perUserInstalled != null) { 10914 for (int i = 0; i < allUsers.length; i++) { 10915 if (DEBUG_INSTALL) { 10916 Slog.d(TAG, " user " + allUsers[i] 10917 + " => " + perUserInstalled[i]); 10918 } 10919 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10920 } 10921 // these install state changes will be persisted in the 10922 // upcoming call to mSettings.writeLPr(). 10923 } 10924 } 10925 // It's implied that when a user requests installation, they want the app to be 10926 // installed and enabled. 10927 int userId = user.getIdentifier(); 10928 if (userId != UserHandle.USER_ALL) { 10929 ps.setInstalled(true, userId); 10930 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10931 } 10932 } 10933 res.name = pkgName; 10934 res.uid = newPackage.applicationInfo.uid; 10935 res.pkg = newPackage; 10936 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10937 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10938 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10939 //to update install status 10940 mSettings.writeLPr(); 10941 } 10942 } 10943 10944 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10945 final int installFlags = args.installFlags; 10946 String installerPackageName = args.installerPackageName; 10947 File tmpPackageFile = new File(args.getCodePath()); 10948 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10949 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10950 boolean replace = false; 10951 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10952 // Result object to be returned 10953 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10954 10955 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10956 // Retrieve PackageSettings and parse package 10957 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10958 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10959 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10960 PackageParser pp = new PackageParser(); 10961 pp.setSeparateProcesses(mSeparateProcesses); 10962 pp.setDisplayMetrics(mMetrics); 10963 10964 final PackageParser.Package pkg; 10965 try { 10966 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10967 } catch (PackageParserException e) { 10968 res.setError("Failed parse during installPackageLI", e); 10969 return; 10970 } 10971 10972 // Mark that we have an install time CPU ABI override. 10973 pkg.cpuAbiOverride = args.abiOverride; 10974 10975 String pkgName = res.name = pkg.packageName; 10976 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10977 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10978 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10979 return; 10980 } 10981 } 10982 10983 try { 10984 pp.collectCertificates(pkg, parseFlags); 10985 pp.collectManifestDigest(pkg); 10986 } catch (PackageParserException e) { 10987 res.setError("Failed collect during installPackageLI", e); 10988 return; 10989 } 10990 10991 /* If the installer passed in a manifest digest, compare it now. */ 10992 if (args.manifestDigest != null) { 10993 if (DEBUG_INSTALL) { 10994 final String parsedManifest = pkg.manifestDigest == null ? "null" 10995 : pkg.manifestDigest.toString(); 10996 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10997 + parsedManifest); 10998 } 10999 11000 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11001 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11002 return; 11003 } 11004 } else if (DEBUG_INSTALL) { 11005 final String parsedManifest = pkg.manifestDigest == null 11006 ? "null" : pkg.manifestDigest.toString(); 11007 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11008 } 11009 11010 // Get rid of all references to package scan path via parser. 11011 pp = null; 11012 String oldCodePath = null; 11013 boolean systemApp = false; 11014 synchronized (mPackages) { 11015 // Check if installing already existing package 11016 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11017 String oldName = mSettings.mRenamedPackages.get(pkgName); 11018 if (pkg.mOriginalPackages != null 11019 && pkg.mOriginalPackages.contains(oldName) 11020 && mPackages.containsKey(oldName)) { 11021 // This package is derived from an original package, 11022 // and this device has been updating from that original 11023 // name. We must continue using the original name, so 11024 // rename the new package here. 11025 pkg.setPackageName(oldName); 11026 pkgName = pkg.packageName; 11027 replace = true; 11028 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11029 + oldName + " pkgName=" + pkgName); 11030 } else if (mPackages.containsKey(pkgName)) { 11031 // This package, under its official name, already exists 11032 // on the device; we should replace it. 11033 replace = true; 11034 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11035 } 11036 } 11037 11038 PackageSetting ps = mSettings.mPackages.get(pkgName); 11039 if (ps != null) { 11040 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11041 11042 // Quick sanity check that we're signed correctly if updating; 11043 // we'll check this again later when scanning, but we want to 11044 // bail early here before tripping over redefined permissions. 11045 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11046 try { 11047 verifySignaturesLP(ps, pkg); 11048 } catch (PackageManagerException e) { 11049 res.setError(e.error, e.getMessage()); 11050 return; 11051 } 11052 } else { 11053 if (!checkUpgradeKeySetLP(ps, pkg)) { 11054 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11055 + pkg.packageName + " upgrade keys do not match the " 11056 + "previously installed version"); 11057 return; 11058 } 11059 } 11060 11061 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11062 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11063 systemApp = (ps.pkg.applicationInfo.flags & 11064 ApplicationInfo.FLAG_SYSTEM) != 0; 11065 } 11066 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11067 } 11068 11069 // Check whether the newly-scanned package wants to define an already-defined perm 11070 int N = pkg.permissions.size(); 11071 for (int i = N-1; i >= 0; i--) { 11072 PackageParser.Permission perm = pkg.permissions.get(i); 11073 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11074 if (bp != null) { 11075 // If the defining package is signed with our cert, it's okay. This 11076 // also includes the "updating the same package" case, of course. 11077 // "updating same package" could also involve key-rotation. 11078 final boolean sigsOk; 11079 if (!bp.sourcePackage.equals(pkg.packageName) 11080 || !(bp.packageSetting instanceof PackageSetting) 11081 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11082 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11083 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11084 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11085 } else { 11086 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11087 } 11088 if (!sigsOk) { 11089 // If the owning package is the system itself, we log but allow 11090 // install to proceed; we fail the install on all other permission 11091 // redefinitions. 11092 if (!bp.sourcePackage.equals("android")) { 11093 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11094 + pkg.packageName + " attempting to redeclare permission " 11095 + perm.info.name + " already owned by " + bp.sourcePackage); 11096 res.origPermission = perm.info.name; 11097 res.origPackage = bp.sourcePackage; 11098 return; 11099 } else { 11100 Slog.w(TAG, "Package " + pkg.packageName 11101 + " attempting to redeclare system permission " 11102 + perm.info.name + "; ignoring new declaration"); 11103 pkg.permissions.remove(i); 11104 } 11105 } 11106 } 11107 } 11108 11109 } 11110 11111 if (systemApp && onSd) { 11112 // Disable updates to system apps on sdcard 11113 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11114 "Cannot install updates to system apps on sdcard"); 11115 return; 11116 } 11117 11118 // Run dexopt before old package gets removed, to minimize time when app is not available 11119 int result = mPackageDexOptimizer 11120 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11121 false /* defer */, false /* inclDependencies */); 11122 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11123 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11124 return; 11125 } 11126 11127 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11128 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11129 return; 11130 } 11131 11132 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11133 11134 if (replace) { 11135 // Call replacePackageLI with SCAN_NO_DEX, since we already made dexopt 11136 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11137 installerPackageName, res); 11138 } else { 11139 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11140 args.user, installerPackageName, res); 11141 } 11142 synchronized (mPackages) { 11143 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11144 if (ps != null) { 11145 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11146 } 11147 } 11148 } 11149 11150 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11151 if (mIntentFilterVerifierComponent == null) { 11152 Slog.d(TAG, "No IntentFilter verification will not be done as " 11153 + "there is no IntentFilterVerifier available!"); 11154 return; 11155 } 11156 11157 final int verifierUid = getPackageUid( 11158 mIntentFilterVerifierComponent.getPackageName(), 11159 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11160 11161 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11162 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11163 msg.obj = pkg; 11164 msg.arg1 = userId; 11165 msg.arg2 = verifierUid; 11166 11167 mHandler.sendMessage(msg); 11168 } 11169 11170 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11171 PackageParser.Package pkg) { 11172 int size = pkg.activities.size(); 11173 if (size == 0) { 11174 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11175 return; 11176 } 11177 11178 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11179 + " Activities needs verification ..."); 11180 11181 final int verificationId = mIntentFilterVerificationToken++; 11182 int count = 0; 11183 synchronized (mPackages) { 11184 for (PackageParser.Activity a : pkg.activities) { 11185 for (ActivityIntentInfo filter : a.intents) { 11186 boolean needFilterVerification = filter.needsVerification() && 11187 !filter.isVerified(); 11188 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11189 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11190 mIntentFilterVerifier.addOneIntentFilterVerification( 11191 verifierUid, userId, verificationId, filter, pkg.packageName); 11192 count++; 11193 } else { 11194 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11195 } 11196 } 11197 } 11198 } 11199 11200 if (count > 0) { 11201 mIntentFilterVerifier.startVerifications(userId); 11202 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11203 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11204 } else { 11205 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11206 } 11207 } 11208 11209 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11210 final ComponentName cn = filter.activity.getComponentName(); 11211 final String packageName = cn.getPackageName(); 11212 11213 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11214 packageName); 11215 if (ivi == null) { 11216 return true; 11217 } 11218 int status = ivi.getStatus(); 11219 switch (status) { 11220 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11221 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11222 return true; 11223 11224 default: 11225 // Nothing to do 11226 return false; 11227 } 11228 } 11229 11230 private static boolean isMultiArch(PackageSetting ps) { 11231 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11232 } 11233 11234 private static boolean isMultiArch(ApplicationInfo info) { 11235 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11236 } 11237 11238 private static boolean isExternal(PackageParser.Package pkg) { 11239 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11240 } 11241 11242 private static boolean isExternal(PackageSetting ps) { 11243 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11244 } 11245 11246 private static boolean isExternal(ApplicationInfo info) { 11247 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11248 } 11249 11250 private static boolean isSystemApp(PackageParser.Package pkg) { 11251 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11252 } 11253 11254 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11255 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11256 } 11257 11258 private static boolean isSystemApp(PackageSetting ps) { 11259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11260 } 11261 11262 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11263 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11264 } 11265 11266 private int packageFlagsToInstallFlags(PackageSetting ps) { 11267 int installFlags = 0; 11268 if (isExternal(ps)) { 11269 installFlags |= PackageManager.INSTALL_EXTERNAL; 11270 } 11271 if (ps.isForwardLocked()) { 11272 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11273 } 11274 return installFlags; 11275 } 11276 11277 private void deleteTempPackageFiles() { 11278 final FilenameFilter filter = new FilenameFilter() { 11279 public boolean accept(File dir, String name) { 11280 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11281 } 11282 }; 11283 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11284 file.delete(); 11285 } 11286 } 11287 11288 @Override 11289 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11290 int flags) { 11291 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11292 flags); 11293 } 11294 11295 @Override 11296 public void deletePackage(final String packageName, 11297 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11298 mContext.enforceCallingOrSelfPermission( 11299 android.Manifest.permission.DELETE_PACKAGES, null); 11300 final int uid = Binder.getCallingUid(); 11301 if (UserHandle.getUserId(uid) != userId) { 11302 mContext.enforceCallingPermission( 11303 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11304 "deletePackage for user " + userId); 11305 } 11306 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11307 try { 11308 observer.onPackageDeleted(packageName, 11309 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11310 } catch (RemoteException re) { 11311 } 11312 return; 11313 } 11314 11315 boolean uninstallBlocked = false; 11316 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11317 int[] users = sUserManager.getUserIds(); 11318 for (int i = 0; i < users.length; ++i) { 11319 if (getBlockUninstallForUser(packageName, users[i])) { 11320 uninstallBlocked = true; 11321 break; 11322 } 11323 } 11324 } else { 11325 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11326 } 11327 if (uninstallBlocked) { 11328 try { 11329 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11330 null); 11331 } catch (RemoteException re) { 11332 } 11333 return; 11334 } 11335 11336 if (DEBUG_REMOVE) { 11337 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11338 } 11339 // Queue up an async operation since the package deletion may take a little while. 11340 mHandler.post(new Runnable() { 11341 public void run() { 11342 mHandler.removeCallbacks(this); 11343 final int returnCode = deletePackageX(packageName, userId, flags); 11344 if (observer != null) { 11345 try { 11346 observer.onPackageDeleted(packageName, returnCode, null); 11347 } catch (RemoteException e) { 11348 Log.i(TAG, "Observer no longer exists."); 11349 } //end catch 11350 } //end if 11351 } //end run 11352 }); 11353 } 11354 11355 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11356 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11357 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11358 try { 11359 if (dpm != null) { 11360 if (dpm.isDeviceOwner(packageName)) { 11361 return true; 11362 } 11363 int[] users; 11364 if (userId == UserHandle.USER_ALL) { 11365 users = sUserManager.getUserIds(); 11366 } else { 11367 users = new int[]{userId}; 11368 } 11369 for (int i = 0; i < users.length; ++i) { 11370 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11371 return true; 11372 } 11373 } 11374 } 11375 } catch (RemoteException e) { 11376 } 11377 return false; 11378 } 11379 11380 /** 11381 * This method is an internal method that could be get invoked either 11382 * to delete an installed package or to clean up a failed installation. 11383 * After deleting an installed package, a broadcast is sent to notify any 11384 * listeners that the package has been installed. For cleaning up a failed 11385 * installation, the broadcast is not necessary since the package's 11386 * installation wouldn't have sent the initial broadcast either 11387 * The key steps in deleting a package are 11388 * deleting the package information in internal structures like mPackages, 11389 * deleting the packages base directories through installd 11390 * updating mSettings to reflect current status 11391 * persisting settings for later use 11392 * sending a broadcast if necessary 11393 */ 11394 private int deletePackageX(String packageName, int userId, int flags) { 11395 final PackageRemovedInfo info = new PackageRemovedInfo(); 11396 final boolean res; 11397 11398 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11399 ? UserHandle.ALL : new UserHandle(userId); 11400 11401 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11402 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11403 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11404 } 11405 11406 boolean removedForAllUsers = false; 11407 boolean systemUpdate = false; 11408 11409 // for the uninstall-updates case and restricted profiles, remember the per- 11410 // userhandle installed state 11411 int[] allUsers; 11412 boolean[] perUserInstalled; 11413 synchronized (mPackages) { 11414 PackageSetting ps = mSettings.mPackages.get(packageName); 11415 allUsers = sUserManager.getUserIds(); 11416 perUserInstalled = new boolean[allUsers.length]; 11417 for (int i = 0; i < allUsers.length; i++) { 11418 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11419 } 11420 } 11421 11422 synchronized (mInstallLock) { 11423 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11424 res = deletePackageLI(packageName, removeForUser, 11425 true, allUsers, perUserInstalled, 11426 flags | REMOVE_CHATTY, info, true); 11427 systemUpdate = info.isRemovedPackageSystemUpdate; 11428 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11429 removedForAllUsers = true; 11430 } 11431 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11432 + " removedForAllUsers=" + removedForAllUsers); 11433 } 11434 11435 if (res) { 11436 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11437 11438 // If the removed package was a system update, the old system package 11439 // was re-enabled; we need to broadcast this information 11440 if (systemUpdate) { 11441 Bundle extras = new Bundle(1); 11442 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11443 ? info.removedAppId : info.uid); 11444 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11445 11446 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11447 extras, null, null, null); 11448 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11449 extras, null, null, null); 11450 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11451 null, packageName, null, null); 11452 } 11453 } 11454 // Force a gc here. 11455 Runtime.getRuntime().gc(); 11456 // Delete the resources here after sending the broadcast to let 11457 // other processes clean up before deleting resources. 11458 if (info.args != null) { 11459 synchronized (mInstallLock) { 11460 info.args.doPostDeleteLI(true); 11461 } 11462 } 11463 11464 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11465 } 11466 11467 static class PackageRemovedInfo { 11468 String removedPackage; 11469 int uid = -1; 11470 int removedAppId = -1; 11471 int[] removedUsers = null; 11472 boolean isRemovedPackageSystemUpdate = false; 11473 // Clean up resources deleted packages. 11474 InstallArgs args = null; 11475 11476 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11477 Bundle extras = new Bundle(1); 11478 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11479 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11480 if (replacing) { 11481 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11482 } 11483 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11484 if (removedPackage != null) { 11485 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11486 extras, null, null, removedUsers); 11487 if (fullRemove && !replacing) { 11488 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11489 extras, null, null, removedUsers); 11490 } 11491 } 11492 if (removedAppId >= 0) { 11493 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11494 removedUsers); 11495 } 11496 } 11497 } 11498 11499 /* 11500 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11501 * flag is not set, the data directory is removed as well. 11502 * make sure this flag is set for partially installed apps. If not its meaningless to 11503 * delete a partially installed application. 11504 */ 11505 private void removePackageDataLI(PackageSetting ps, 11506 int[] allUserHandles, boolean[] perUserInstalled, 11507 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11508 String packageName = ps.name; 11509 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11510 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11511 // Retrieve object to delete permissions for shared user later on 11512 final PackageSetting deletedPs; 11513 // reader 11514 synchronized (mPackages) { 11515 deletedPs = mSettings.mPackages.get(packageName); 11516 if (outInfo != null) { 11517 outInfo.removedPackage = packageName; 11518 outInfo.removedUsers = deletedPs != null 11519 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11520 : null; 11521 } 11522 } 11523 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11524 removeDataDirsLI(packageName); 11525 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11526 } 11527 // writer 11528 synchronized (mPackages) { 11529 if (deletedPs != null) { 11530 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11531 if (outInfo != null) { 11532 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11533 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11534 } 11535 updatePermissionsLPw(deletedPs.name, null, 0); 11536 if (deletedPs.sharedUser != null) { 11537 // Remove permissions associated with package. Since runtime 11538 // permissions are per user we have to kill the removed package 11539 // or packages running under the shared user of the removed 11540 // package if revoking the permissions requested only by the removed 11541 // package is successful and this causes a change in gids. 11542 for (int userId : UserManagerService.getInstance().getUserIds()) { 11543 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11544 userId); 11545 if (userIdToKill == UserHandle.USER_ALL 11546 || userIdToKill >= UserHandle.USER_OWNER) { 11547 // If gids changed for this user, kill all affected packages. 11548 mHandler.post(new Runnable() { 11549 @Override 11550 public void run() { 11551 // This has to happen with no lock held. 11552 killSettingPackagesForUser(deletedPs, userIdToKill, 11553 KILL_APP_REASON_GIDS_CHANGED); 11554 } 11555 }); 11556 break; 11557 } 11558 } 11559 } 11560 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11561 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11562 } 11563 // make sure to preserve per-user disabled state if this removal was just 11564 // a downgrade of a system app to the factory package 11565 if (allUserHandles != null && perUserInstalled != null) { 11566 if (DEBUG_REMOVE) { 11567 Slog.d(TAG, "Propagating install state across downgrade"); 11568 } 11569 for (int i = 0; i < allUserHandles.length; i++) { 11570 if (DEBUG_REMOVE) { 11571 Slog.d(TAG, " user " + allUserHandles[i] 11572 + " => " + perUserInstalled[i]); 11573 } 11574 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11575 } 11576 } 11577 } 11578 // can downgrade to reader 11579 if (writeSettings) { 11580 // Save settings now 11581 mSettings.writeLPr(); 11582 } 11583 } 11584 if (outInfo != null) { 11585 // A user ID was deleted here. Go through all users and remove it 11586 // from KeyStore. 11587 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11588 } 11589 } 11590 11591 static boolean locationIsPrivileged(File path) { 11592 try { 11593 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11594 .getCanonicalPath(); 11595 return path.getCanonicalPath().startsWith(privilegedAppDir); 11596 } catch (IOException e) { 11597 Slog.e(TAG, "Unable to access code path " + path); 11598 } 11599 return false; 11600 } 11601 11602 /* 11603 * Tries to delete system package. 11604 */ 11605 private boolean deleteSystemPackageLI(PackageSetting newPs, 11606 int[] allUserHandles, boolean[] perUserInstalled, 11607 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11608 final boolean applyUserRestrictions 11609 = (allUserHandles != null) && (perUserInstalled != null); 11610 PackageSetting disabledPs = null; 11611 // Confirm if the system package has been updated 11612 // An updated system app can be deleted. This will also have to restore 11613 // the system pkg from system partition 11614 // reader 11615 synchronized (mPackages) { 11616 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11617 } 11618 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11619 + " disabledPs=" + disabledPs); 11620 if (disabledPs == null) { 11621 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11622 return false; 11623 } else if (DEBUG_REMOVE) { 11624 Slog.d(TAG, "Deleting system pkg from data partition"); 11625 } 11626 if (DEBUG_REMOVE) { 11627 if (applyUserRestrictions) { 11628 Slog.d(TAG, "Remembering install states:"); 11629 for (int i = 0; i < allUserHandles.length; i++) { 11630 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11631 } 11632 } 11633 } 11634 // Delete the updated package 11635 outInfo.isRemovedPackageSystemUpdate = true; 11636 if (disabledPs.versionCode < newPs.versionCode) { 11637 // Delete data for downgrades 11638 flags &= ~PackageManager.DELETE_KEEP_DATA; 11639 } else { 11640 // Preserve data by setting flag 11641 flags |= PackageManager.DELETE_KEEP_DATA; 11642 } 11643 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11644 allUserHandles, perUserInstalled, outInfo, writeSettings); 11645 if (!ret) { 11646 return false; 11647 } 11648 // writer 11649 synchronized (mPackages) { 11650 // Reinstate the old system package 11651 mSettings.enableSystemPackageLPw(newPs.name); 11652 // Remove any native libraries from the upgraded package. 11653 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11654 } 11655 // Install the system package 11656 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11657 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11658 if (locationIsPrivileged(disabledPs.codePath)) { 11659 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11660 } 11661 11662 final PackageParser.Package newPkg; 11663 try { 11664 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11665 } catch (PackageManagerException e) { 11666 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11667 return false; 11668 } 11669 11670 // writer 11671 synchronized (mPackages) { 11672 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11673 updatePermissionsLPw(newPkg.packageName, newPkg, 11674 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11675 if (applyUserRestrictions) { 11676 if (DEBUG_REMOVE) { 11677 Slog.d(TAG, "Propagating install state across reinstall"); 11678 } 11679 for (int i = 0; i < allUserHandles.length; i++) { 11680 if (DEBUG_REMOVE) { 11681 Slog.d(TAG, " user " + allUserHandles[i] 11682 + " => " + perUserInstalled[i]); 11683 } 11684 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11685 } 11686 // Regardless of writeSettings we need to ensure that this restriction 11687 // state propagation is persisted 11688 mSettings.writeAllUsersPackageRestrictionsLPr(); 11689 } 11690 // can downgrade to reader here 11691 if (writeSettings) { 11692 mSettings.writeLPr(); 11693 } 11694 } 11695 return true; 11696 } 11697 11698 private boolean deleteInstalledPackageLI(PackageSetting ps, 11699 boolean deleteCodeAndResources, int flags, 11700 int[] allUserHandles, boolean[] perUserInstalled, 11701 PackageRemovedInfo outInfo, boolean writeSettings) { 11702 if (outInfo != null) { 11703 outInfo.uid = ps.appId; 11704 } 11705 11706 // Delete package data from internal structures and also remove data if flag is set 11707 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11708 11709 // Delete application code and resources 11710 if (deleteCodeAndResources && (outInfo != null)) { 11711 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11712 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11713 getAppDexInstructionSets(ps)); 11714 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11715 } 11716 return true; 11717 } 11718 11719 @Override 11720 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11721 int userId) { 11722 mContext.enforceCallingOrSelfPermission( 11723 android.Manifest.permission.DELETE_PACKAGES, null); 11724 synchronized (mPackages) { 11725 PackageSetting ps = mSettings.mPackages.get(packageName); 11726 if (ps == null) { 11727 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11728 return false; 11729 } 11730 if (!ps.getInstalled(userId)) { 11731 // Can't block uninstall for an app that is not installed or enabled. 11732 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11733 return false; 11734 } 11735 ps.setBlockUninstall(blockUninstall, userId); 11736 mSettings.writePackageRestrictionsLPr(userId); 11737 } 11738 return true; 11739 } 11740 11741 @Override 11742 public boolean getBlockUninstallForUser(String packageName, int userId) { 11743 synchronized (mPackages) { 11744 PackageSetting ps = mSettings.mPackages.get(packageName); 11745 if (ps == null) { 11746 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11747 return false; 11748 } 11749 return ps.getBlockUninstall(userId); 11750 } 11751 } 11752 11753 /* 11754 * This method handles package deletion in general 11755 */ 11756 private boolean deletePackageLI(String packageName, UserHandle user, 11757 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11758 int flags, PackageRemovedInfo outInfo, 11759 boolean writeSettings) { 11760 if (packageName == null) { 11761 Slog.w(TAG, "Attempt to delete null packageName."); 11762 return false; 11763 } 11764 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11765 PackageSetting ps; 11766 boolean dataOnly = false; 11767 int removeUser = -1; 11768 int appId = -1; 11769 synchronized (mPackages) { 11770 ps = mSettings.mPackages.get(packageName); 11771 if (ps == null) { 11772 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11773 return false; 11774 } 11775 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11776 && user.getIdentifier() != UserHandle.USER_ALL) { 11777 // The caller is asking that the package only be deleted for a single 11778 // user. To do this, we just mark its uninstalled state and delete 11779 // its data. If this is a system app, we only allow this to happen if 11780 // they have set the special DELETE_SYSTEM_APP which requests different 11781 // semantics than normal for uninstalling system apps. 11782 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11783 ps.setUserState(user.getIdentifier(), 11784 COMPONENT_ENABLED_STATE_DEFAULT, 11785 false, //installed 11786 true, //stopped 11787 true, //notLaunched 11788 false, //hidden 11789 null, null, null, 11790 false, // blockUninstall 11791 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11792 if (!isSystemApp(ps)) { 11793 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11794 // Other user still have this package installed, so all 11795 // we need to do is clear this user's data and save that 11796 // it is uninstalled. 11797 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11798 removeUser = user.getIdentifier(); 11799 appId = ps.appId; 11800 mSettings.writePackageRestrictionsLPr(removeUser); 11801 } else { 11802 // We need to set it back to 'installed' so the uninstall 11803 // broadcasts will be sent correctly. 11804 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11805 ps.setInstalled(true, user.getIdentifier()); 11806 } 11807 } else { 11808 // This is a system app, so we assume that the 11809 // other users still have this package installed, so all 11810 // we need to do is clear this user's data and save that 11811 // it is uninstalled. 11812 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11813 removeUser = user.getIdentifier(); 11814 appId = ps.appId; 11815 mSettings.writePackageRestrictionsLPr(removeUser); 11816 } 11817 } 11818 } 11819 11820 if (removeUser >= 0) { 11821 // From above, we determined that we are deleting this only 11822 // for a single user. Continue the work here. 11823 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11824 if (outInfo != null) { 11825 outInfo.removedPackage = packageName; 11826 outInfo.removedAppId = appId; 11827 outInfo.removedUsers = new int[] {removeUser}; 11828 } 11829 mInstaller.clearUserData(packageName, removeUser); 11830 removeKeystoreDataIfNeeded(removeUser, appId); 11831 schedulePackageCleaning(packageName, removeUser, false); 11832 return true; 11833 } 11834 11835 if (dataOnly) { 11836 // Delete application data first 11837 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11838 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11839 return true; 11840 } 11841 11842 boolean ret = false; 11843 if (isSystemApp(ps)) { 11844 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11845 // When an updated system application is deleted we delete the existing resources as well and 11846 // fall back to existing code in system partition 11847 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11848 flags, outInfo, writeSettings); 11849 } else { 11850 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11851 // Kill application pre-emptively especially for apps on sd. 11852 killApplication(packageName, ps.appId, "uninstall pkg"); 11853 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11854 allUserHandles, perUserInstalled, 11855 outInfo, writeSettings); 11856 } 11857 11858 return ret; 11859 } 11860 11861 private final class ClearStorageConnection implements ServiceConnection { 11862 IMediaContainerService mContainerService; 11863 11864 @Override 11865 public void onServiceConnected(ComponentName name, IBinder service) { 11866 synchronized (this) { 11867 mContainerService = IMediaContainerService.Stub.asInterface(service); 11868 notifyAll(); 11869 } 11870 } 11871 11872 @Override 11873 public void onServiceDisconnected(ComponentName name) { 11874 } 11875 } 11876 11877 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11878 final boolean mounted; 11879 if (Environment.isExternalStorageEmulated()) { 11880 mounted = true; 11881 } else { 11882 final String status = Environment.getExternalStorageState(); 11883 11884 mounted = status.equals(Environment.MEDIA_MOUNTED) 11885 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11886 } 11887 11888 if (!mounted) { 11889 return; 11890 } 11891 11892 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11893 int[] users; 11894 if (userId == UserHandle.USER_ALL) { 11895 users = sUserManager.getUserIds(); 11896 } else { 11897 users = new int[] { userId }; 11898 } 11899 final ClearStorageConnection conn = new ClearStorageConnection(); 11900 if (mContext.bindServiceAsUser( 11901 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11902 try { 11903 for (int curUser : users) { 11904 long timeout = SystemClock.uptimeMillis() + 5000; 11905 synchronized (conn) { 11906 long now = SystemClock.uptimeMillis(); 11907 while (conn.mContainerService == null && now < timeout) { 11908 try { 11909 conn.wait(timeout - now); 11910 } catch (InterruptedException e) { 11911 } 11912 } 11913 } 11914 if (conn.mContainerService == null) { 11915 return; 11916 } 11917 11918 final UserEnvironment userEnv = new UserEnvironment(curUser); 11919 clearDirectory(conn.mContainerService, 11920 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11921 if (allData) { 11922 clearDirectory(conn.mContainerService, 11923 userEnv.buildExternalStorageAppDataDirs(packageName)); 11924 clearDirectory(conn.mContainerService, 11925 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11926 } 11927 } 11928 } finally { 11929 mContext.unbindService(conn); 11930 } 11931 } 11932 } 11933 11934 @Override 11935 public void clearApplicationUserData(final String packageName, 11936 final IPackageDataObserver observer, final int userId) { 11937 mContext.enforceCallingOrSelfPermission( 11938 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11939 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11940 // Queue up an async operation since the package deletion may take a little while. 11941 mHandler.post(new Runnable() { 11942 public void run() { 11943 mHandler.removeCallbacks(this); 11944 final boolean succeeded; 11945 synchronized (mInstallLock) { 11946 succeeded = clearApplicationUserDataLI(packageName, userId); 11947 } 11948 clearExternalStorageDataSync(packageName, userId, true); 11949 if (succeeded) { 11950 // invoke DeviceStorageMonitor's update method to clear any notifications 11951 DeviceStorageMonitorInternal 11952 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11953 if (dsm != null) { 11954 dsm.checkMemory(); 11955 } 11956 } 11957 if(observer != null) { 11958 try { 11959 observer.onRemoveCompleted(packageName, succeeded); 11960 } catch (RemoteException e) { 11961 Log.i(TAG, "Observer no longer exists."); 11962 } 11963 } //end if observer 11964 } //end run 11965 }); 11966 } 11967 11968 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11969 if (packageName == null) { 11970 Slog.w(TAG, "Attempt to delete null packageName."); 11971 return false; 11972 } 11973 11974 // Try finding details about the requested package 11975 PackageParser.Package pkg; 11976 synchronized (mPackages) { 11977 pkg = mPackages.get(packageName); 11978 if (pkg == null) { 11979 final PackageSetting ps = mSettings.mPackages.get(packageName); 11980 if (ps != null) { 11981 pkg = ps.pkg; 11982 } 11983 } 11984 } 11985 11986 if (pkg == null) { 11987 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11988 } 11989 11990 // Always delete data directories for package, even if we found no other 11991 // record of app. This helps users recover from UID mismatches without 11992 // resorting to a full data wipe. 11993 int retCode = mInstaller.clearUserData(packageName, userId); 11994 if (retCode < 0) { 11995 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11996 return false; 11997 } 11998 11999 if (pkg == null) { 12000 return false; 12001 } 12002 12003 if (pkg != null && pkg.applicationInfo != null) { 12004 final int appId = pkg.applicationInfo.uid; 12005 removeKeystoreDataIfNeeded(userId, appId); 12006 } 12007 12008 // Create a native library symlink only if we have native libraries 12009 // and if the native libraries are 32 bit libraries. We do not provide 12010 // this symlink for 64 bit libraries. 12011 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12012 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12013 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12014 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12015 Slog.w(TAG, "Failed linking native library dir"); 12016 return false; 12017 } 12018 } 12019 12020 return true; 12021 } 12022 12023 /** 12024 * Remove entries from the keystore daemon. Will only remove it if the 12025 * {@code appId} is valid. 12026 */ 12027 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12028 if (appId < 0) { 12029 return; 12030 } 12031 12032 final KeyStore keyStore = KeyStore.getInstance(); 12033 if (keyStore != null) { 12034 if (userId == UserHandle.USER_ALL) { 12035 for (final int individual : sUserManager.getUserIds()) { 12036 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12037 } 12038 } else { 12039 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12040 } 12041 } else { 12042 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12043 } 12044 } 12045 12046 @Override 12047 public void deleteApplicationCacheFiles(final String packageName, 12048 final IPackageDataObserver observer) { 12049 mContext.enforceCallingOrSelfPermission( 12050 android.Manifest.permission.DELETE_CACHE_FILES, null); 12051 // Queue up an async operation since the package deletion may take a little while. 12052 final int userId = UserHandle.getCallingUserId(); 12053 mHandler.post(new Runnable() { 12054 public void run() { 12055 mHandler.removeCallbacks(this); 12056 final boolean succeded; 12057 synchronized (mInstallLock) { 12058 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12059 } 12060 clearExternalStorageDataSync(packageName, userId, false); 12061 if(observer != null) { 12062 try { 12063 observer.onRemoveCompleted(packageName, succeded); 12064 } catch (RemoteException e) { 12065 Log.i(TAG, "Observer no longer exists."); 12066 } 12067 } //end if observer 12068 } //end run 12069 }); 12070 } 12071 12072 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12073 if (packageName == null) { 12074 Slog.w(TAG, "Attempt to delete null packageName."); 12075 return false; 12076 } 12077 PackageParser.Package p; 12078 synchronized (mPackages) { 12079 p = mPackages.get(packageName); 12080 } 12081 if (p == null) { 12082 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12083 return false; 12084 } 12085 final ApplicationInfo applicationInfo = p.applicationInfo; 12086 if (applicationInfo == null) { 12087 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12088 return false; 12089 } 12090 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12091 if (retCode < 0) { 12092 Slog.w(TAG, "Couldn't remove cache files for package: " 12093 + packageName + " u" + userId); 12094 return false; 12095 } 12096 return true; 12097 } 12098 12099 @Override 12100 public void getPackageSizeInfo(final String packageName, int userHandle, 12101 final IPackageStatsObserver observer) { 12102 mContext.enforceCallingOrSelfPermission( 12103 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12104 if (packageName == null) { 12105 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12106 } 12107 12108 PackageStats stats = new PackageStats(packageName, userHandle); 12109 12110 /* 12111 * Queue up an async operation since the package measurement may take a 12112 * little while. 12113 */ 12114 Message msg = mHandler.obtainMessage(INIT_COPY); 12115 msg.obj = new MeasureParams(stats, observer); 12116 mHandler.sendMessage(msg); 12117 } 12118 12119 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12120 PackageStats pStats) { 12121 if (packageName == null) { 12122 Slog.w(TAG, "Attempt to get size of null packageName."); 12123 return false; 12124 } 12125 PackageParser.Package p; 12126 boolean dataOnly = false; 12127 String libDirRoot = null; 12128 String asecPath = null; 12129 PackageSetting ps = null; 12130 synchronized (mPackages) { 12131 p = mPackages.get(packageName); 12132 ps = mSettings.mPackages.get(packageName); 12133 if(p == null) { 12134 dataOnly = true; 12135 if((ps == null) || (ps.pkg == null)) { 12136 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12137 return false; 12138 } 12139 p = ps.pkg; 12140 } 12141 if (ps != null) { 12142 libDirRoot = ps.legacyNativeLibraryPathString; 12143 } 12144 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12145 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12146 if (secureContainerId != null) { 12147 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12148 } 12149 } 12150 } 12151 String publicSrcDir = null; 12152 if(!dataOnly) { 12153 final ApplicationInfo applicationInfo = p.applicationInfo; 12154 if (applicationInfo == null) { 12155 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12156 return false; 12157 } 12158 if (p.isForwardLocked()) { 12159 publicSrcDir = applicationInfo.getBaseResourcePath(); 12160 } 12161 } 12162 // TODO: extend to measure size of split APKs 12163 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12164 // not just the first level. 12165 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12166 // just the primary. 12167 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12168 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12169 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12170 if (res < 0) { 12171 return false; 12172 } 12173 12174 // Fix-up for forward-locked applications in ASEC containers. 12175 if (!isExternal(p)) { 12176 pStats.codeSize += pStats.externalCodeSize; 12177 pStats.externalCodeSize = 0L; 12178 } 12179 12180 return true; 12181 } 12182 12183 12184 @Override 12185 public void addPackageToPreferred(String packageName) { 12186 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12187 } 12188 12189 @Override 12190 public void removePackageFromPreferred(String packageName) { 12191 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12192 } 12193 12194 @Override 12195 public List<PackageInfo> getPreferredPackages(int flags) { 12196 return new ArrayList<PackageInfo>(); 12197 } 12198 12199 private int getUidTargetSdkVersionLockedLPr(int uid) { 12200 Object obj = mSettings.getUserIdLPr(uid); 12201 if (obj instanceof SharedUserSetting) { 12202 final SharedUserSetting sus = (SharedUserSetting) obj; 12203 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12204 final Iterator<PackageSetting> it = sus.packages.iterator(); 12205 while (it.hasNext()) { 12206 final PackageSetting ps = it.next(); 12207 if (ps.pkg != null) { 12208 int v = ps.pkg.applicationInfo.targetSdkVersion; 12209 if (v < vers) vers = v; 12210 } 12211 } 12212 return vers; 12213 } else if (obj instanceof PackageSetting) { 12214 final PackageSetting ps = (PackageSetting) obj; 12215 if (ps.pkg != null) { 12216 return ps.pkg.applicationInfo.targetSdkVersion; 12217 } 12218 } 12219 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12220 } 12221 12222 @Override 12223 public void addPreferredActivity(IntentFilter filter, int match, 12224 ComponentName[] set, ComponentName activity, int userId) { 12225 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12226 "Adding preferred"); 12227 } 12228 12229 private void addPreferredActivityInternal(IntentFilter filter, int match, 12230 ComponentName[] set, ComponentName activity, boolean always, int userId, 12231 String opname) { 12232 // writer 12233 int callingUid = Binder.getCallingUid(); 12234 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12235 if (filter.countActions() == 0) { 12236 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12237 return; 12238 } 12239 synchronized (mPackages) { 12240 if (mContext.checkCallingOrSelfPermission( 12241 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12242 != PackageManager.PERMISSION_GRANTED) { 12243 if (getUidTargetSdkVersionLockedLPr(callingUid) 12244 < Build.VERSION_CODES.FROYO) { 12245 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12246 + callingUid); 12247 return; 12248 } 12249 mContext.enforceCallingOrSelfPermission( 12250 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12251 } 12252 12253 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12254 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12255 + userId + ":"); 12256 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12257 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12258 scheduleWritePackageRestrictionsLocked(userId); 12259 } 12260 } 12261 12262 @Override 12263 public void replacePreferredActivity(IntentFilter filter, int match, 12264 ComponentName[] set, ComponentName activity, int userId) { 12265 if (filter.countActions() != 1) { 12266 throw new IllegalArgumentException( 12267 "replacePreferredActivity expects filter to have only 1 action."); 12268 } 12269 if (filter.countDataAuthorities() != 0 12270 || filter.countDataPaths() != 0 12271 || filter.countDataSchemes() > 1 12272 || filter.countDataTypes() != 0) { 12273 throw new IllegalArgumentException( 12274 "replacePreferredActivity expects filter to have no data authorities, " + 12275 "paths, or types; and at most one scheme."); 12276 } 12277 12278 final int callingUid = Binder.getCallingUid(); 12279 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12280 synchronized (mPackages) { 12281 if (mContext.checkCallingOrSelfPermission( 12282 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12283 != PackageManager.PERMISSION_GRANTED) { 12284 if (getUidTargetSdkVersionLockedLPr(callingUid) 12285 < Build.VERSION_CODES.FROYO) { 12286 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12287 + Binder.getCallingUid()); 12288 return; 12289 } 12290 mContext.enforceCallingOrSelfPermission( 12291 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12292 } 12293 12294 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12295 if (pir != null) { 12296 // Get all of the existing entries that exactly match this filter. 12297 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12298 if (existing != null && existing.size() == 1) { 12299 PreferredActivity cur = existing.get(0); 12300 if (DEBUG_PREFERRED) { 12301 Slog.i(TAG, "Checking replace of preferred:"); 12302 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12303 if (!cur.mPref.mAlways) { 12304 Slog.i(TAG, " -- CUR; not mAlways!"); 12305 } else { 12306 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12307 Slog.i(TAG, " -- CUR: mSet=" 12308 + Arrays.toString(cur.mPref.mSetComponents)); 12309 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12310 Slog.i(TAG, " -- NEW: mMatch=" 12311 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12312 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12313 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12314 } 12315 } 12316 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12317 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12318 && cur.mPref.sameSet(set)) { 12319 // Setting the preferred activity to what it happens to be already 12320 if (DEBUG_PREFERRED) { 12321 Slog.i(TAG, "Replacing with same preferred activity " 12322 + cur.mPref.mShortComponent + " for user " 12323 + userId + ":"); 12324 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12325 } 12326 return; 12327 } 12328 } 12329 12330 if (existing != null) { 12331 if (DEBUG_PREFERRED) { 12332 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12333 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12334 } 12335 for (int i = 0; i < existing.size(); i++) { 12336 PreferredActivity pa = existing.get(i); 12337 if (DEBUG_PREFERRED) { 12338 Slog.i(TAG, "Removing existing preferred activity " 12339 + pa.mPref.mComponent + ":"); 12340 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12341 } 12342 pir.removeFilter(pa); 12343 } 12344 } 12345 } 12346 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12347 "Replacing preferred"); 12348 } 12349 } 12350 12351 @Override 12352 public void clearPackagePreferredActivities(String packageName) { 12353 final int uid = Binder.getCallingUid(); 12354 // writer 12355 synchronized (mPackages) { 12356 PackageParser.Package pkg = mPackages.get(packageName); 12357 if (pkg == null || pkg.applicationInfo.uid != uid) { 12358 if (mContext.checkCallingOrSelfPermission( 12359 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12360 != PackageManager.PERMISSION_GRANTED) { 12361 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12362 < Build.VERSION_CODES.FROYO) { 12363 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12364 + Binder.getCallingUid()); 12365 return; 12366 } 12367 mContext.enforceCallingOrSelfPermission( 12368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12369 } 12370 } 12371 12372 int user = UserHandle.getCallingUserId(); 12373 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12374 scheduleWritePackageRestrictionsLocked(user); 12375 } 12376 } 12377 } 12378 12379 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12380 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12381 ArrayList<PreferredActivity> removed = null; 12382 boolean changed = false; 12383 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12384 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12385 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12386 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12387 continue; 12388 } 12389 Iterator<PreferredActivity> it = pir.filterIterator(); 12390 while (it.hasNext()) { 12391 PreferredActivity pa = it.next(); 12392 // Mark entry for removal only if it matches the package name 12393 // and the entry is of type "always". 12394 if (packageName == null || 12395 (pa.mPref.mComponent.getPackageName().equals(packageName) 12396 && pa.mPref.mAlways)) { 12397 if (removed == null) { 12398 removed = new ArrayList<PreferredActivity>(); 12399 } 12400 removed.add(pa); 12401 } 12402 } 12403 if (removed != null) { 12404 for (int j=0; j<removed.size(); j++) { 12405 PreferredActivity pa = removed.get(j); 12406 pir.removeFilter(pa); 12407 } 12408 changed = true; 12409 } 12410 } 12411 return changed; 12412 } 12413 12414 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12415 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12416 if (userId == UserHandle.USER_ALL) { 12417 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12418 for (int oneUserId : sUserManager.getUserIds()) { 12419 scheduleWritePackageRestrictionsLocked(oneUserId); 12420 } 12421 } else { 12422 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12423 scheduleWritePackageRestrictionsLocked(userId); 12424 } 12425 } 12426 12427 @Override 12428 public void resetPreferredActivities(int userId) { 12429 /* TODO: Actually use userId. Why is it being passed in? */ 12430 mContext.enforceCallingOrSelfPermission( 12431 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12432 // writer 12433 synchronized (mPackages) { 12434 int user = UserHandle.getCallingUserId(); 12435 clearPackagePreferredActivitiesLPw(null, user); 12436 mSettings.readDefaultPreferredAppsLPw(this, user); 12437 scheduleWritePackageRestrictionsLocked(user); 12438 } 12439 } 12440 12441 @Override 12442 public int getPreferredActivities(List<IntentFilter> outFilters, 12443 List<ComponentName> outActivities, String packageName) { 12444 12445 int num = 0; 12446 final int userId = UserHandle.getCallingUserId(); 12447 // reader 12448 synchronized (mPackages) { 12449 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12450 if (pir != null) { 12451 final Iterator<PreferredActivity> it = pir.filterIterator(); 12452 while (it.hasNext()) { 12453 final PreferredActivity pa = it.next(); 12454 if (packageName == null 12455 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12456 && pa.mPref.mAlways)) { 12457 if (outFilters != null) { 12458 outFilters.add(new IntentFilter(pa)); 12459 } 12460 if (outActivities != null) { 12461 outActivities.add(pa.mPref.mComponent); 12462 } 12463 } 12464 } 12465 } 12466 } 12467 12468 return num; 12469 } 12470 12471 @Override 12472 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12473 int userId) { 12474 int callingUid = Binder.getCallingUid(); 12475 if (callingUid != Process.SYSTEM_UID) { 12476 throw new SecurityException( 12477 "addPersistentPreferredActivity can only be run by the system"); 12478 } 12479 if (filter.countActions() == 0) { 12480 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12481 return; 12482 } 12483 synchronized (mPackages) { 12484 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12485 " :"); 12486 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12487 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12488 new PersistentPreferredActivity(filter, activity)); 12489 scheduleWritePackageRestrictionsLocked(userId); 12490 } 12491 } 12492 12493 @Override 12494 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12495 int callingUid = Binder.getCallingUid(); 12496 if (callingUid != Process.SYSTEM_UID) { 12497 throw new SecurityException( 12498 "clearPackagePersistentPreferredActivities can only be run by the system"); 12499 } 12500 ArrayList<PersistentPreferredActivity> removed = null; 12501 boolean changed = false; 12502 synchronized (mPackages) { 12503 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12504 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12505 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12506 .valueAt(i); 12507 if (userId != thisUserId) { 12508 continue; 12509 } 12510 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12511 while (it.hasNext()) { 12512 PersistentPreferredActivity ppa = it.next(); 12513 // Mark entry for removal only if it matches the package name. 12514 if (ppa.mComponent.getPackageName().equals(packageName)) { 12515 if (removed == null) { 12516 removed = new ArrayList<PersistentPreferredActivity>(); 12517 } 12518 removed.add(ppa); 12519 } 12520 } 12521 if (removed != null) { 12522 for (int j=0; j<removed.size(); j++) { 12523 PersistentPreferredActivity ppa = removed.get(j); 12524 ppir.removeFilter(ppa); 12525 } 12526 changed = true; 12527 } 12528 } 12529 12530 if (changed) { 12531 scheduleWritePackageRestrictionsLocked(userId); 12532 } 12533 } 12534 } 12535 12536 /** 12537 * Non-Binder method, support for the backup/restore mechanism: write the 12538 * full set of preferred activities in its canonical XML format. Returns true 12539 * on success; false otherwise. 12540 */ 12541 @Override 12542 public byte[] getPreferredActivityBackup(int userId) { 12543 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12544 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12545 } 12546 12547 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12548 try { 12549 final XmlSerializer serializer = new FastXmlSerializer(); 12550 serializer.setOutput(dataStream, "utf-8"); 12551 serializer.startDocument(null, true); 12552 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12553 12554 synchronized (mPackages) { 12555 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12556 } 12557 12558 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12559 serializer.endDocument(); 12560 serializer.flush(); 12561 } catch (Exception e) { 12562 if (DEBUG_BACKUP) { 12563 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12564 } 12565 return null; 12566 } 12567 12568 return dataStream.toByteArray(); 12569 } 12570 12571 @Override 12572 public void restorePreferredActivities(byte[] backup, int userId) { 12573 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12574 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12575 } 12576 12577 try { 12578 final XmlPullParser parser = Xml.newPullParser(); 12579 parser.setInput(new ByteArrayInputStream(backup), null); 12580 12581 int type; 12582 while ((type = parser.next()) != XmlPullParser.START_TAG 12583 && type != XmlPullParser.END_DOCUMENT) { 12584 } 12585 if (type != XmlPullParser.START_TAG) { 12586 // oops didn't find a start tag?! 12587 if (DEBUG_BACKUP) { 12588 Slog.e(TAG, "Didn't find start tag during restore"); 12589 } 12590 return; 12591 } 12592 12593 // this is supposed to be TAG_PREFERRED_BACKUP 12594 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12595 if (DEBUG_BACKUP) { 12596 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12597 } 12598 return; 12599 } 12600 12601 // skip interfering stuff, then we're aligned with the backing implementation 12602 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12603 synchronized (mPackages) { 12604 mSettings.readPreferredActivitiesLPw(parser, userId); 12605 } 12606 } catch (Exception e) { 12607 if (DEBUG_BACKUP) { 12608 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12609 } 12610 } 12611 } 12612 12613 @Override 12614 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12615 int sourceUserId, int targetUserId, int flags) { 12616 mContext.enforceCallingOrSelfPermission( 12617 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12618 int callingUid = Binder.getCallingUid(); 12619 enforceOwnerRights(ownerPackage, callingUid); 12620 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12621 if (intentFilter.countActions() == 0) { 12622 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12623 return; 12624 } 12625 synchronized (mPackages) { 12626 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12627 ownerPackage, targetUserId, flags); 12628 CrossProfileIntentResolver resolver = 12629 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12630 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12631 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12632 if (existing != null) { 12633 int size = existing.size(); 12634 for (int i = 0; i < size; i++) { 12635 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12636 return; 12637 } 12638 } 12639 } 12640 resolver.addFilter(newFilter); 12641 scheduleWritePackageRestrictionsLocked(sourceUserId); 12642 } 12643 } 12644 12645 @Override 12646 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12647 mContext.enforceCallingOrSelfPermission( 12648 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12649 int callingUid = Binder.getCallingUid(); 12650 enforceOwnerRights(ownerPackage, callingUid); 12651 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12652 synchronized (mPackages) { 12653 CrossProfileIntentResolver resolver = 12654 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12655 ArraySet<CrossProfileIntentFilter> set = 12656 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12657 for (CrossProfileIntentFilter filter : set) { 12658 if (filter.getOwnerPackage().equals(ownerPackage)) { 12659 resolver.removeFilter(filter); 12660 } 12661 } 12662 scheduleWritePackageRestrictionsLocked(sourceUserId); 12663 } 12664 } 12665 12666 // Enforcing that callingUid is owning pkg on userId 12667 private void enforceOwnerRights(String pkg, int callingUid) { 12668 // The system owns everything. 12669 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12670 return; 12671 } 12672 int callingUserId = UserHandle.getUserId(callingUid); 12673 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12674 if (pi == null) { 12675 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12676 + callingUserId); 12677 } 12678 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12679 throw new SecurityException("Calling uid " + callingUid 12680 + " does not own package " + pkg); 12681 } 12682 } 12683 12684 @Override 12685 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12686 Intent intent = new Intent(Intent.ACTION_MAIN); 12687 intent.addCategory(Intent.CATEGORY_HOME); 12688 12689 final int callingUserId = UserHandle.getCallingUserId(); 12690 List<ResolveInfo> list = queryIntentActivities(intent, null, 12691 PackageManager.GET_META_DATA, callingUserId); 12692 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12693 true, false, false, callingUserId); 12694 12695 allHomeCandidates.clear(); 12696 if (list != null) { 12697 for (ResolveInfo ri : list) { 12698 allHomeCandidates.add(ri); 12699 } 12700 } 12701 return (preferred == null || preferred.activityInfo == null) 12702 ? null 12703 : new ComponentName(preferred.activityInfo.packageName, 12704 preferred.activityInfo.name); 12705 } 12706 12707 @Override 12708 public void setApplicationEnabledSetting(String appPackageName, 12709 int newState, int flags, int userId, String callingPackage) { 12710 if (!sUserManager.exists(userId)) return; 12711 if (callingPackage == null) { 12712 callingPackage = Integer.toString(Binder.getCallingUid()); 12713 } 12714 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12715 } 12716 12717 @Override 12718 public void setComponentEnabledSetting(ComponentName componentName, 12719 int newState, int flags, int userId) { 12720 if (!sUserManager.exists(userId)) return; 12721 setEnabledSetting(componentName.getPackageName(), 12722 componentName.getClassName(), newState, flags, userId, null); 12723 } 12724 12725 private void setEnabledSetting(final String packageName, String className, int newState, 12726 final int flags, int userId, String callingPackage) { 12727 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12728 || newState == COMPONENT_ENABLED_STATE_ENABLED 12729 || newState == COMPONENT_ENABLED_STATE_DISABLED 12730 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12731 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12732 throw new IllegalArgumentException("Invalid new component state: " 12733 + newState); 12734 } 12735 PackageSetting pkgSetting; 12736 final int uid = Binder.getCallingUid(); 12737 final int permission = mContext.checkCallingOrSelfPermission( 12738 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12739 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12740 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12741 boolean sendNow = false; 12742 boolean isApp = (className == null); 12743 String componentName = isApp ? packageName : className; 12744 int packageUid = -1; 12745 ArrayList<String> components; 12746 12747 // writer 12748 synchronized (mPackages) { 12749 pkgSetting = mSettings.mPackages.get(packageName); 12750 if (pkgSetting == null) { 12751 if (className == null) { 12752 throw new IllegalArgumentException( 12753 "Unknown package: " + packageName); 12754 } 12755 throw new IllegalArgumentException( 12756 "Unknown component: " + packageName 12757 + "/" + className); 12758 } 12759 // Allow root and verify that userId is not being specified by a different user 12760 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12761 throw new SecurityException( 12762 "Permission Denial: attempt to change component state from pid=" 12763 + Binder.getCallingPid() 12764 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12765 } 12766 if (className == null) { 12767 // We're dealing with an application/package level state change 12768 if (pkgSetting.getEnabled(userId) == newState) { 12769 // Nothing to do 12770 return; 12771 } 12772 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12773 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12774 // Don't care about who enables an app. 12775 callingPackage = null; 12776 } 12777 pkgSetting.setEnabled(newState, userId, callingPackage); 12778 // pkgSetting.pkg.mSetEnabled = newState; 12779 } else { 12780 // We're dealing with a component level state change 12781 // First, verify that this is a valid class name. 12782 PackageParser.Package pkg = pkgSetting.pkg; 12783 if (pkg == null || !pkg.hasComponentClassName(className)) { 12784 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12785 throw new IllegalArgumentException("Component class " + className 12786 + " does not exist in " + packageName); 12787 } else { 12788 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12789 + className + " does not exist in " + packageName); 12790 } 12791 } 12792 switch (newState) { 12793 case COMPONENT_ENABLED_STATE_ENABLED: 12794 if (!pkgSetting.enableComponentLPw(className, userId)) { 12795 return; 12796 } 12797 break; 12798 case COMPONENT_ENABLED_STATE_DISABLED: 12799 if (!pkgSetting.disableComponentLPw(className, userId)) { 12800 return; 12801 } 12802 break; 12803 case COMPONENT_ENABLED_STATE_DEFAULT: 12804 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12805 return; 12806 } 12807 break; 12808 default: 12809 Slog.e(TAG, "Invalid new component state: " + newState); 12810 return; 12811 } 12812 } 12813 scheduleWritePackageRestrictionsLocked(userId); 12814 components = mPendingBroadcasts.get(userId, packageName); 12815 final boolean newPackage = components == null; 12816 if (newPackage) { 12817 components = new ArrayList<String>(); 12818 } 12819 if (!components.contains(componentName)) { 12820 components.add(componentName); 12821 } 12822 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12823 sendNow = true; 12824 // Purge entry from pending broadcast list if another one exists already 12825 // since we are sending one right away. 12826 mPendingBroadcasts.remove(userId, packageName); 12827 } else { 12828 if (newPackage) { 12829 mPendingBroadcasts.put(userId, packageName, components); 12830 } 12831 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12832 // Schedule a message 12833 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12834 } 12835 } 12836 } 12837 12838 long callingId = Binder.clearCallingIdentity(); 12839 try { 12840 if (sendNow) { 12841 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12842 sendPackageChangedBroadcast(packageName, 12843 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12844 } 12845 } finally { 12846 Binder.restoreCallingIdentity(callingId); 12847 } 12848 } 12849 12850 private void sendPackageChangedBroadcast(String packageName, 12851 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12852 if (DEBUG_INSTALL) 12853 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12854 + componentNames); 12855 Bundle extras = new Bundle(4); 12856 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12857 String nameList[] = new String[componentNames.size()]; 12858 componentNames.toArray(nameList); 12859 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12860 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12861 extras.putInt(Intent.EXTRA_UID, packageUid); 12862 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12863 new int[] {UserHandle.getUserId(packageUid)}); 12864 } 12865 12866 @Override 12867 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12868 if (!sUserManager.exists(userId)) return; 12869 final int uid = Binder.getCallingUid(); 12870 final int permission = mContext.checkCallingOrSelfPermission( 12871 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12872 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12873 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12874 // writer 12875 synchronized (mPackages) { 12876 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12877 uid, userId)) { 12878 scheduleWritePackageRestrictionsLocked(userId); 12879 } 12880 } 12881 } 12882 12883 @Override 12884 public String getInstallerPackageName(String packageName) { 12885 // reader 12886 synchronized (mPackages) { 12887 return mSettings.getInstallerPackageNameLPr(packageName); 12888 } 12889 } 12890 12891 @Override 12892 public int getApplicationEnabledSetting(String packageName, int userId) { 12893 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12894 int uid = Binder.getCallingUid(); 12895 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12896 // reader 12897 synchronized (mPackages) { 12898 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12899 } 12900 } 12901 12902 @Override 12903 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12904 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12905 int uid = Binder.getCallingUid(); 12906 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12907 // reader 12908 synchronized (mPackages) { 12909 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12910 } 12911 } 12912 12913 @Override 12914 public void enterSafeMode() { 12915 enforceSystemOrRoot("Only the system can request entering safe mode"); 12916 12917 if (!mSystemReady) { 12918 mSafeMode = true; 12919 } 12920 } 12921 12922 @Override 12923 public void systemReady() { 12924 mSystemReady = true; 12925 12926 // Read the compatibilty setting when the system is ready. 12927 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12928 mContext.getContentResolver(), 12929 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12930 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12931 if (DEBUG_SETTINGS) { 12932 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12933 } 12934 12935 synchronized (mPackages) { 12936 // Verify that all of the preferred activity components actually 12937 // exist. It is possible for applications to be updated and at 12938 // that point remove a previously declared activity component that 12939 // had been set as a preferred activity. We try to clean this up 12940 // the next time we encounter that preferred activity, but it is 12941 // possible for the user flow to never be able to return to that 12942 // situation so here we do a sanity check to make sure we haven't 12943 // left any junk around. 12944 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12945 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12946 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12947 removed.clear(); 12948 for (PreferredActivity pa : pir.filterSet()) { 12949 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12950 removed.add(pa); 12951 } 12952 } 12953 if (removed.size() > 0) { 12954 for (int r=0; r<removed.size(); r++) { 12955 PreferredActivity pa = removed.get(r); 12956 Slog.w(TAG, "Removing dangling preferred activity: " 12957 + pa.mPref.mComponent); 12958 pir.removeFilter(pa); 12959 } 12960 mSettings.writePackageRestrictionsLPr( 12961 mSettings.mPreferredActivities.keyAt(i)); 12962 } 12963 } 12964 } 12965 sUserManager.systemReady(); 12966 12967 // Kick off any messages waiting for system ready 12968 if (mPostSystemReadyMessages != null) { 12969 for (Message msg : mPostSystemReadyMessages) { 12970 msg.sendToTarget(); 12971 } 12972 mPostSystemReadyMessages = null; 12973 } 12974 12975 // Watch for external volumes that come and go over time 12976 final StorageManager storage = mContext.getSystemService(StorageManager.class); 12977 storage.registerListener(mStorageListener); 12978 } 12979 12980 @Override 12981 public boolean isSafeMode() { 12982 return mSafeMode; 12983 } 12984 12985 @Override 12986 public boolean hasSystemUidErrors() { 12987 return mHasSystemUidErrors; 12988 } 12989 12990 static String arrayToString(int[] array) { 12991 StringBuffer buf = new StringBuffer(128); 12992 buf.append('['); 12993 if (array != null) { 12994 for (int i=0; i<array.length; i++) { 12995 if (i > 0) buf.append(", "); 12996 buf.append(array[i]); 12997 } 12998 } 12999 buf.append(']'); 13000 return buf.toString(); 13001 } 13002 13003 static class DumpState { 13004 public static final int DUMP_LIBS = 1 << 0; 13005 public static final int DUMP_FEATURES = 1 << 1; 13006 public static final int DUMP_RESOLVERS = 1 << 2; 13007 public static final int DUMP_PERMISSIONS = 1 << 3; 13008 public static final int DUMP_PACKAGES = 1 << 4; 13009 public static final int DUMP_SHARED_USERS = 1 << 5; 13010 public static final int DUMP_MESSAGES = 1 << 6; 13011 public static final int DUMP_PROVIDERS = 1 << 7; 13012 public static final int DUMP_VERIFIERS = 1 << 8; 13013 public static final int DUMP_PREFERRED = 1 << 9; 13014 public static final int DUMP_PREFERRED_XML = 1 << 10; 13015 public static final int DUMP_KEYSETS = 1 << 11; 13016 public static final int DUMP_VERSION = 1 << 12; 13017 public static final int DUMP_INSTALLS = 1 << 13; 13018 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13019 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13020 13021 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13022 13023 private int mTypes; 13024 13025 private int mOptions; 13026 13027 private boolean mTitlePrinted; 13028 13029 private SharedUserSetting mSharedUser; 13030 13031 public boolean isDumping(int type) { 13032 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13033 return true; 13034 } 13035 13036 return (mTypes & type) != 0; 13037 } 13038 13039 public void setDump(int type) { 13040 mTypes |= type; 13041 } 13042 13043 public boolean isOptionEnabled(int option) { 13044 return (mOptions & option) != 0; 13045 } 13046 13047 public void setOptionEnabled(int option) { 13048 mOptions |= option; 13049 } 13050 13051 public boolean onTitlePrinted() { 13052 final boolean printed = mTitlePrinted; 13053 mTitlePrinted = true; 13054 return printed; 13055 } 13056 13057 public boolean getTitlePrinted() { 13058 return mTitlePrinted; 13059 } 13060 13061 public void setTitlePrinted(boolean enabled) { 13062 mTitlePrinted = enabled; 13063 } 13064 13065 public SharedUserSetting getSharedUser() { 13066 return mSharedUser; 13067 } 13068 13069 public void setSharedUser(SharedUserSetting user) { 13070 mSharedUser = user; 13071 } 13072 } 13073 13074 @Override 13075 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13076 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13077 != PackageManager.PERMISSION_GRANTED) { 13078 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13079 + Binder.getCallingPid() 13080 + ", uid=" + Binder.getCallingUid() 13081 + " without permission " 13082 + android.Manifest.permission.DUMP); 13083 return; 13084 } 13085 13086 DumpState dumpState = new DumpState(); 13087 boolean fullPreferred = false; 13088 boolean checkin = false; 13089 13090 String packageName = null; 13091 13092 int opti = 0; 13093 while (opti < args.length) { 13094 String opt = args[opti]; 13095 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13096 break; 13097 } 13098 opti++; 13099 13100 if ("-a".equals(opt)) { 13101 // Right now we only know how to print all. 13102 } else if ("-h".equals(opt)) { 13103 pw.println("Package manager dump options:"); 13104 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13105 pw.println(" --checkin: dump for a checkin"); 13106 pw.println(" -f: print details of intent filters"); 13107 pw.println(" -h: print this help"); 13108 pw.println(" cmd may be one of:"); 13109 pw.println(" l[ibraries]: list known shared libraries"); 13110 pw.println(" f[ibraries]: list device features"); 13111 pw.println(" k[eysets]: print known keysets"); 13112 pw.println(" r[esolvers]: dump intent resolvers"); 13113 pw.println(" perm[issions]: dump permissions"); 13114 pw.println(" pref[erred]: print preferred package settings"); 13115 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13116 pw.println(" prov[iders]: dump content providers"); 13117 pw.println(" p[ackages]: dump installed packages"); 13118 pw.println(" s[hared-users]: dump shared user IDs"); 13119 pw.println(" m[essages]: print collected runtime messages"); 13120 pw.println(" v[erifiers]: print package verifier info"); 13121 pw.println(" version: print database version info"); 13122 pw.println(" write: write current settings now"); 13123 pw.println(" <package.name>: info about given package"); 13124 pw.println(" installs: details about install sessions"); 13125 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13126 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13127 return; 13128 } else if ("--checkin".equals(opt)) { 13129 checkin = true; 13130 } else if ("-f".equals(opt)) { 13131 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13132 } else { 13133 pw.println("Unknown argument: " + opt + "; use -h for help"); 13134 } 13135 } 13136 13137 // Is the caller requesting to dump a particular piece of data? 13138 if (opti < args.length) { 13139 String cmd = args[opti]; 13140 opti++; 13141 // Is this a package name? 13142 if ("android".equals(cmd) || cmd.contains(".")) { 13143 packageName = cmd; 13144 // When dumping a single package, we always dump all of its 13145 // filter information since the amount of data will be reasonable. 13146 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13147 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13148 dumpState.setDump(DumpState.DUMP_LIBS); 13149 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13150 dumpState.setDump(DumpState.DUMP_FEATURES); 13151 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13152 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13153 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13154 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13155 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13156 dumpState.setDump(DumpState.DUMP_PREFERRED); 13157 } else if ("preferred-xml".equals(cmd)) { 13158 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13159 if (opti < args.length && "--full".equals(args[opti])) { 13160 fullPreferred = true; 13161 opti++; 13162 } 13163 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13164 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13165 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13166 dumpState.setDump(DumpState.DUMP_PACKAGES); 13167 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13168 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13169 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13170 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13171 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13172 dumpState.setDump(DumpState.DUMP_MESSAGES); 13173 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13174 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13175 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13176 || "intent-filter-verifiers".equals(cmd)) { 13177 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13178 } else if ("version".equals(cmd)) { 13179 dumpState.setDump(DumpState.DUMP_VERSION); 13180 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13181 dumpState.setDump(DumpState.DUMP_KEYSETS); 13182 } else if ("installs".equals(cmd)) { 13183 dumpState.setDump(DumpState.DUMP_INSTALLS); 13184 } else if ("write".equals(cmd)) { 13185 synchronized (mPackages) { 13186 mSettings.writeLPr(); 13187 pw.println("Settings written."); 13188 return; 13189 } 13190 } 13191 } 13192 13193 if (checkin) { 13194 pw.println("vers,1"); 13195 } 13196 13197 // reader 13198 synchronized (mPackages) { 13199 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13200 if (!checkin) { 13201 if (dumpState.onTitlePrinted()) 13202 pw.println(); 13203 pw.println("Database versions:"); 13204 pw.print(" SDK Version:"); 13205 pw.print(" internal="); 13206 pw.print(mSettings.mInternalSdkPlatform); 13207 pw.print(" external="); 13208 pw.println(mSettings.mExternalSdkPlatform); 13209 pw.print(" DB Version:"); 13210 pw.print(" internal="); 13211 pw.print(mSettings.mInternalDatabaseVersion); 13212 pw.print(" external="); 13213 pw.println(mSettings.mExternalDatabaseVersion); 13214 } 13215 } 13216 13217 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13218 if (!checkin) { 13219 if (dumpState.onTitlePrinted()) 13220 pw.println(); 13221 pw.println("Verifiers:"); 13222 pw.print(" Required: "); 13223 pw.print(mRequiredVerifierPackage); 13224 pw.print(" (uid="); 13225 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13226 pw.println(")"); 13227 } else if (mRequiredVerifierPackage != null) { 13228 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13229 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13230 } 13231 } 13232 13233 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13234 packageName == null) { 13235 if (mIntentFilterVerifierComponent != null) { 13236 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13237 if (!checkin) { 13238 if (dumpState.onTitlePrinted()) 13239 pw.println(); 13240 pw.println("Intent Filter Verifier:"); 13241 pw.print(" Using: "); 13242 pw.print(verifierPackageName); 13243 pw.print(" (uid="); 13244 pw.print(getPackageUid(verifierPackageName, 0)); 13245 pw.println(")"); 13246 } else if (verifierPackageName != null) { 13247 pw.print("ifv,"); pw.print(verifierPackageName); 13248 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13249 } 13250 } else { 13251 pw.println(); 13252 pw.println("No Intent Filter Verifier available!"); 13253 } 13254 } 13255 13256 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13257 boolean printedHeader = false; 13258 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13259 while (it.hasNext()) { 13260 String name = it.next(); 13261 SharedLibraryEntry ent = mSharedLibraries.get(name); 13262 if (!checkin) { 13263 if (!printedHeader) { 13264 if (dumpState.onTitlePrinted()) 13265 pw.println(); 13266 pw.println("Libraries:"); 13267 printedHeader = true; 13268 } 13269 pw.print(" "); 13270 } else { 13271 pw.print("lib,"); 13272 } 13273 pw.print(name); 13274 if (!checkin) { 13275 pw.print(" -> "); 13276 } 13277 if (ent.path != null) { 13278 if (!checkin) { 13279 pw.print("(jar) "); 13280 pw.print(ent.path); 13281 } else { 13282 pw.print(",jar,"); 13283 pw.print(ent.path); 13284 } 13285 } else { 13286 if (!checkin) { 13287 pw.print("(apk) "); 13288 pw.print(ent.apk); 13289 } else { 13290 pw.print(",apk,"); 13291 pw.print(ent.apk); 13292 } 13293 } 13294 pw.println(); 13295 } 13296 } 13297 13298 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13299 if (dumpState.onTitlePrinted()) 13300 pw.println(); 13301 if (!checkin) { 13302 pw.println("Features:"); 13303 } 13304 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13305 while (it.hasNext()) { 13306 String name = it.next(); 13307 if (!checkin) { 13308 pw.print(" "); 13309 } else { 13310 pw.print("feat,"); 13311 } 13312 pw.println(name); 13313 } 13314 } 13315 13316 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13317 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13318 : "Activity Resolver Table:", " ", packageName, 13319 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13320 dumpState.setTitlePrinted(true); 13321 } 13322 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13323 : "Receiver Resolver Table:", " ", packageName, 13324 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13325 dumpState.setTitlePrinted(true); 13326 } 13327 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13328 : "Service Resolver Table:", " ", packageName, 13329 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13330 dumpState.setTitlePrinted(true); 13331 } 13332 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13333 : "Provider Resolver Table:", " ", packageName, 13334 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13335 dumpState.setTitlePrinted(true); 13336 } 13337 } 13338 13339 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13340 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13341 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13342 int user = mSettings.mPreferredActivities.keyAt(i); 13343 if (pir.dump(pw, 13344 dumpState.getTitlePrinted() 13345 ? "\nPreferred Activities User " + user + ":" 13346 : "Preferred Activities User " + user + ":", " ", 13347 packageName, true, false)) { 13348 dumpState.setTitlePrinted(true); 13349 } 13350 } 13351 } 13352 13353 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13354 pw.flush(); 13355 FileOutputStream fout = new FileOutputStream(fd); 13356 BufferedOutputStream str = new BufferedOutputStream(fout); 13357 XmlSerializer serializer = new FastXmlSerializer(); 13358 try { 13359 serializer.setOutput(str, "utf-8"); 13360 serializer.startDocument(null, true); 13361 serializer.setFeature( 13362 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13363 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13364 serializer.endDocument(); 13365 serializer.flush(); 13366 } catch (IllegalArgumentException e) { 13367 pw.println("Failed writing: " + e); 13368 } catch (IllegalStateException e) { 13369 pw.println("Failed writing: " + e); 13370 } catch (IOException e) { 13371 pw.println("Failed writing: " + e); 13372 } 13373 } 13374 13375 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13376 pw.println(); 13377 int count = mSettings.mPackages.size(); 13378 if (count == 0) { 13379 pw.println("No domain preferred apps!"); 13380 pw.println(); 13381 } else { 13382 final String prefix = " "; 13383 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13384 if (allPackageSettings.size() == 0) { 13385 pw.println("No domain preferred apps!"); 13386 pw.println(); 13387 } else { 13388 pw.println("Domain preferred apps status:"); 13389 pw.println(); 13390 count = 0; 13391 for (PackageSetting ps : allPackageSettings) { 13392 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13393 if (ivi == null || ivi.getPackageName() == null) continue; 13394 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13395 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13396 pw.println(prefix + "Status: " + ivi.getStatusString()); 13397 pw.println(); 13398 count++; 13399 } 13400 if (count == 0) { 13401 pw.println(prefix + "No domain preferred app status!"); 13402 pw.println(); 13403 } 13404 for (int userId : sUserManager.getUserIds()) { 13405 pw.println("Domain preferred apps for User " + userId + ":"); 13406 pw.println(); 13407 count = 0; 13408 for (PackageSetting ps : allPackageSettings) { 13409 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13410 if (ivi == null || ivi.getPackageName() == null) { 13411 continue; 13412 } 13413 final int status = ps.getDomainVerificationStatusForUser(userId); 13414 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13415 continue; 13416 } 13417 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13418 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13419 String statusStr = IntentFilterVerificationInfo. 13420 getStatusStringFromValue(status); 13421 pw.println(prefix + "Status: " + statusStr); 13422 pw.println(); 13423 count++; 13424 } 13425 if (count == 0) { 13426 pw.println(prefix + "No domain preferred apps!"); 13427 pw.println(); 13428 } 13429 } 13430 } 13431 } 13432 } 13433 13434 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13435 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13436 if (packageName == null) { 13437 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13438 if (iperm == 0) { 13439 if (dumpState.onTitlePrinted()) 13440 pw.println(); 13441 pw.println("AppOp Permissions:"); 13442 } 13443 pw.print(" AppOp Permission "); 13444 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13445 pw.println(":"); 13446 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13447 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13448 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13449 } 13450 } 13451 } 13452 } 13453 13454 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13455 boolean printedSomething = false; 13456 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13457 if (packageName != null && !packageName.equals(p.info.packageName)) { 13458 continue; 13459 } 13460 if (!printedSomething) { 13461 if (dumpState.onTitlePrinted()) 13462 pw.println(); 13463 pw.println("Registered ContentProviders:"); 13464 printedSomething = true; 13465 } 13466 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13467 pw.print(" "); pw.println(p.toString()); 13468 } 13469 printedSomething = false; 13470 for (Map.Entry<String, PackageParser.Provider> entry : 13471 mProvidersByAuthority.entrySet()) { 13472 PackageParser.Provider p = entry.getValue(); 13473 if (packageName != null && !packageName.equals(p.info.packageName)) { 13474 continue; 13475 } 13476 if (!printedSomething) { 13477 if (dumpState.onTitlePrinted()) 13478 pw.println(); 13479 pw.println("ContentProvider Authorities:"); 13480 printedSomething = true; 13481 } 13482 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13483 pw.print(" "); pw.println(p.toString()); 13484 if (p.info != null && p.info.applicationInfo != null) { 13485 final String appInfo = p.info.applicationInfo.toString(); 13486 pw.print(" applicationInfo="); pw.println(appInfo); 13487 } 13488 } 13489 } 13490 13491 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13492 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13493 } 13494 13495 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13496 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13497 } 13498 13499 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13500 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13501 } 13502 13503 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13504 // XXX should handle packageName != null by dumping only install data that 13505 // the given package is involved with. 13506 if (dumpState.onTitlePrinted()) pw.println(); 13507 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13508 } 13509 13510 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13511 if (dumpState.onTitlePrinted()) pw.println(); 13512 mSettings.dumpReadMessagesLPr(pw, dumpState); 13513 13514 pw.println(); 13515 pw.println("Package warning messages:"); 13516 BufferedReader in = null; 13517 String line = null; 13518 try { 13519 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13520 while ((line = in.readLine()) != null) { 13521 if (line.contains("ignored: updated version")) continue; 13522 pw.println(line); 13523 } 13524 } catch (IOException ignored) { 13525 } finally { 13526 IoUtils.closeQuietly(in); 13527 } 13528 } 13529 13530 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13531 BufferedReader in = null; 13532 String line = null; 13533 try { 13534 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13535 while ((line = in.readLine()) != null) { 13536 if (line.contains("ignored: updated version")) continue; 13537 pw.print("msg,"); 13538 pw.println(line); 13539 } 13540 } catch (IOException ignored) { 13541 } finally { 13542 IoUtils.closeQuietly(in); 13543 } 13544 } 13545 } 13546 } 13547 13548 // ------- apps on sdcard specific code ------- 13549 static final boolean DEBUG_SD_INSTALL = false; 13550 13551 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13552 13553 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13554 13555 private boolean mMediaMounted = false; 13556 13557 static String getEncryptKey() { 13558 try { 13559 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13560 SD_ENCRYPTION_KEYSTORE_NAME); 13561 if (sdEncKey == null) { 13562 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13563 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13564 if (sdEncKey == null) { 13565 Slog.e(TAG, "Failed to create encryption keys"); 13566 return null; 13567 } 13568 } 13569 return sdEncKey; 13570 } catch (NoSuchAlgorithmException nsae) { 13571 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13572 return null; 13573 } catch (IOException ioe) { 13574 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13575 return null; 13576 } 13577 } 13578 13579 /* 13580 * Update media status on PackageManager. 13581 */ 13582 @Override 13583 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13584 int callingUid = Binder.getCallingUid(); 13585 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13586 throw new SecurityException("Media status can only be updated by the system"); 13587 } 13588 // reader; this apparently protects mMediaMounted, but should probably 13589 // be a different lock in that case. 13590 synchronized (mPackages) { 13591 Log.i(TAG, "Updating external media status from " 13592 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13593 + (mediaStatus ? "mounted" : "unmounted")); 13594 if (DEBUG_SD_INSTALL) 13595 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13596 + ", mMediaMounted=" + mMediaMounted); 13597 if (mediaStatus == mMediaMounted) { 13598 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13599 : 0, -1); 13600 mHandler.sendMessage(msg); 13601 return; 13602 } 13603 mMediaMounted = mediaStatus; 13604 } 13605 // Queue up an async operation since the package installation may take a 13606 // little while. 13607 mHandler.post(new Runnable() { 13608 public void run() { 13609 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13610 } 13611 }); 13612 } 13613 13614 /** 13615 * Called by MountService when the initial ASECs to scan are available. 13616 * Should block until all the ASEC containers are finished being scanned. 13617 */ 13618 public void scanAvailableAsecs() { 13619 updateExternalMediaStatusInner(true, false, false); 13620 if (mShouldRestoreconData) { 13621 SELinuxMMAC.setRestoreconDone(); 13622 mShouldRestoreconData = false; 13623 } 13624 } 13625 13626 /* 13627 * Collect information of applications on external media, map them against 13628 * existing containers and update information based on current mount status. 13629 * Please note that we always have to report status if reportStatus has been 13630 * set to true especially when unloading packages. 13631 */ 13632 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13633 boolean externalStorage) { 13634 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13635 int[] uidArr = EmptyArray.INT; 13636 13637 final String[] list = PackageHelper.getSecureContainerList(); 13638 if (ArrayUtils.isEmpty(list)) { 13639 Log.i(TAG, "No secure containers found"); 13640 } else { 13641 // Process list of secure containers and categorize them 13642 // as active or stale based on their package internal state. 13643 13644 // reader 13645 synchronized (mPackages) { 13646 for (String cid : list) { 13647 // Leave stages untouched for now; installer service owns them 13648 if (PackageInstallerService.isStageName(cid)) continue; 13649 13650 if (DEBUG_SD_INSTALL) 13651 Log.i(TAG, "Processing container " + cid); 13652 String pkgName = getAsecPackageName(cid); 13653 if (pkgName == null) { 13654 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13655 continue; 13656 } 13657 if (DEBUG_SD_INSTALL) 13658 Log.i(TAG, "Looking for pkg : " + pkgName); 13659 13660 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13661 if (ps == null) { 13662 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13663 continue; 13664 } 13665 13666 /* 13667 * Skip packages that are not external if we're unmounting 13668 * external storage. 13669 */ 13670 if (externalStorage && !isMounted && !isExternal(ps)) { 13671 continue; 13672 } 13673 13674 final AsecInstallArgs args = new AsecInstallArgs(cid, 13675 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13676 // The package status is changed only if the code path 13677 // matches between settings and the container id. 13678 if (ps.codePathString != null 13679 && ps.codePathString.startsWith(args.getCodePath())) { 13680 if (DEBUG_SD_INSTALL) { 13681 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13682 + " at code path: " + ps.codePathString); 13683 } 13684 13685 // We do have a valid package installed on sdcard 13686 processCids.put(args, ps.codePathString); 13687 final int uid = ps.appId; 13688 if (uid != -1) { 13689 uidArr = ArrayUtils.appendInt(uidArr, uid); 13690 } 13691 } else { 13692 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13693 + ps.codePathString); 13694 } 13695 } 13696 } 13697 13698 Arrays.sort(uidArr); 13699 } 13700 13701 // Process packages with valid entries. 13702 if (isMounted) { 13703 if (DEBUG_SD_INSTALL) 13704 Log.i(TAG, "Loading packages"); 13705 loadMediaPackages(processCids, uidArr); 13706 startCleaningPackages(); 13707 mInstallerService.onSecureContainersAvailable(); 13708 } else { 13709 if (DEBUG_SD_INSTALL) 13710 Log.i(TAG, "Unloading packages"); 13711 unloadMediaPackages(processCids, uidArr, reportStatus); 13712 } 13713 } 13714 13715 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13716 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13717 int size = pkgList.size(); 13718 if (size > 0) { 13719 // Send broadcasts here 13720 Bundle extras = new Bundle(); 13721 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13722 .toArray(new String[size])); 13723 if (uidArr != null) { 13724 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13725 } 13726 if (replacing) { 13727 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13728 } 13729 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13730 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13731 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13732 } 13733 } 13734 13735 /* 13736 * Look at potentially valid container ids from processCids If package 13737 * information doesn't match the one on record or package scanning fails, 13738 * the cid is added to list of removeCids. We currently don't delete stale 13739 * containers. 13740 */ 13741 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13742 ArrayList<String> pkgList = new ArrayList<String>(); 13743 Set<AsecInstallArgs> keys = processCids.keySet(); 13744 13745 for (AsecInstallArgs args : keys) { 13746 String codePath = processCids.get(args); 13747 if (DEBUG_SD_INSTALL) 13748 Log.i(TAG, "Loading container : " + args.cid); 13749 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13750 try { 13751 // Make sure there are no container errors first. 13752 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13753 Slog.e(TAG, "Failed to mount cid : " + args.cid 13754 + " when installing from sdcard"); 13755 continue; 13756 } 13757 // Check code path here. 13758 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13759 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13760 + " does not match one in settings " + codePath); 13761 continue; 13762 } 13763 // Parse package 13764 int parseFlags = mDefParseFlags; 13765 if (args.isExternal()) { 13766 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13767 } 13768 if (args.isFwdLocked()) { 13769 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13770 } 13771 13772 synchronized (mInstallLock) { 13773 PackageParser.Package pkg = null; 13774 try { 13775 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13776 } catch (PackageManagerException e) { 13777 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13778 } 13779 // Scan the package 13780 if (pkg != null) { 13781 /* 13782 * TODO why is the lock being held? doPostInstall is 13783 * called in other places without the lock. This needs 13784 * to be straightened out. 13785 */ 13786 // writer 13787 synchronized (mPackages) { 13788 retCode = PackageManager.INSTALL_SUCCEEDED; 13789 pkgList.add(pkg.packageName); 13790 // Post process args 13791 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13792 pkg.applicationInfo.uid); 13793 } 13794 } else { 13795 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13796 } 13797 } 13798 13799 } finally { 13800 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13801 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13802 } 13803 } 13804 } 13805 // writer 13806 synchronized (mPackages) { 13807 // If the platform SDK has changed since the last time we booted, 13808 // we need to re-grant app permission to catch any new ones that 13809 // appear. This is really a hack, and means that apps can in some 13810 // cases get permissions that the user didn't initially explicitly 13811 // allow... it would be nice to have some better way to handle 13812 // this situation. 13813 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13814 if (regrantPermissions) 13815 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13816 + mSdkVersion + "; regranting permissions for external storage"); 13817 mSettings.mExternalSdkPlatform = mSdkVersion; 13818 13819 // Make sure group IDs have been assigned, and any permission 13820 // changes in other apps are accounted for 13821 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13822 | (regrantPermissions 13823 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13824 : 0)); 13825 13826 mSettings.updateExternalDatabaseVersion(); 13827 13828 // can downgrade to reader 13829 // Persist settings 13830 mSettings.writeLPr(); 13831 } 13832 // Send a broadcast to let everyone know we are done processing 13833 if (pkgList.size() > 0) { 13834 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13835 } 13836 } 13837 13838 /* 13839 * Utility method to unload a list of specified containers 13840 */ 13841 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13842 // Just unmount all valid containers. 13843 for (AsecInstallArgs arg : cidArgs) { 13844 synchronized (mInstallLock) { 13845 arg.doPostDeleteLI(false); 13846 } 13847 } 13848 } 13849 13850 /* 13851 * Unload packages mounted on external media. This involves deleting package 13852 * data from internal structures, sending broadcasts about diabled packages, 13853 * gc'ing to free up references, unmounting all secure containers 13854 * corresponding to packages on external media, and posting a 13855 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13856 * that we always have to post this message if status has been requested no 13857 * matter what. 13858 */ 13859 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13860 final boolean reportStatus) { 13861 if (DEBUG_SD_INSTALL) 13862 Log.i(TAG, "unloading media packages"); 13863 ArrayList<String> pkgList = new ArrayList<String>(); 13864 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13865 final Set<AsecInstallArgs> keys = processCids.keySet(); 13866 for (AsecInstallArgs args : keys) { 13867 String pkgName = args.getPackageName(); 13868 if (DEBUG_SD_INSTALL) 13869 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13870 // Delete package internally 13871 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13872 synchronized (mInstallLock) { 13873 boolean res = deletePackageLI(pkgName, null, false, null, null, 13874 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13875 if (res) { 13876 pkgList.add(pkgName); 13877 } else { 13878 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13879 failedList.add(args); 13880 } 13881 } 13882 } 13883 13884 // reader 13885 synchronized (mPackages) { 13886 // We didn't update the settings after removing each package; 13887 // write them now for all packages. 13888 mSettings.writeLPr(); 13889 } 13890 13891 // We have to absolutely send UPDATED_MEDIA_STATUS only 13892 // after confirming that all the receivers processed the ordered 13893 // broadcast when packages get disabled, force a gc to clean things up. 13894 // and unload all the containers. 13895 if (pkgList.size() > 0) { 13896 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13897 new IIntentReceiver.Stub() { 13898 public void performReceive(Intent intent, int resultCode, String data, 13899 Bundle extras, boolean ordered, boolean sticky, 13900 int sendingUser) throws RemoteException { 13901 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13902 reportStatus ? 1 : 0, 1, keys); 13903 mHandler.sendMessage(msg); 13904 } 13905 }); 13906 } else { 13907 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13908 keys); 13909 mHandler.sendMessage(msg); 13910 } 13911 } 13912 13913 /** Binder call */ 13914 @Override 13915 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13916 final int flags) { 13917 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13918 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13919 int returnCode = PackageManager.MOVE_SUCCEEDED; 13920 int currInstallFlags = 0; 13921 int newInstallFlags = 0; 13922 13923 File codeFile = null; 13924 String installerPackageName = null; 13925 String packageAbiOverride = null; 13926 13927 // reader 13928 synchronized (mPackages) { 13929 final PackageParser.Package pkg = mPackages.get(packageName); 13930 final PackageSetting ps = mSettings.mPackages.get(packageName); 13931 if (pkg == null || ps == null) { 13932 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13933 } else { 13934 // Disable moving fwd locked apps and system packages 13935 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13936 Slog.w(TAG, "Cannot move system application"); 13937 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13938 } else if (pkg.mOperationPending) { 13939 Slog.w(TAG, "Attempt to move package which has pending operations"); 13940 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13941 } else { 13942 // Find install location first 13943 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13944 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13945 Slog.w(TAG, "Ambigous flags specified for move location."); 13946 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13947 } else { 13948 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13949 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13950 currInstallFlags = isExternal(pkg) 13951 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13952 13953 if (newInstallFlags == currInstallFlags) { 13954 Slog.w(TAG, "No move required. Trying to move to same location"); 13955 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13956 } else { 13957 if (pkg.isForwardLocked()) { 13958 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13959 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13960 } 13961 } 13962 } 13963 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13964 pkg.mOperationPending = true; 13965 } 13966 } 13967 13968 codeFile = new File(pkg.codePath); 13969 installerPackageName = ps.installerPackageName; 13970 packageAbiOverride = ps.cpuAbiOverrideString; 13971 } 13972 } 13973 13974 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13975 try { 13976 observer.packageMoved(packageName, returnCode); 13977 } catch (RemoteException ignored) { 13978 } 13979 return; 13980 } 13981 13982 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13983 @Override 13984 public void onUserActionRequired(Intent intent) throws RemoteException { 13985 throw new IllegalStateException(); 13986 } 13987 13988 @Override 13989 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13990 Bundle extras) throws RemoteException { 13991 Slog.d(TAG, "Install result for move: " 13992 + PackageManager.installStatusToString(returnCode, msg)); 13993 13994 // We usually have a new package now after the install, but if 13995 // we failed we need to clear the pending flag on the original 13996 // package object. 13997 synchronized (mPackages) { 13998 final PackageParser.Package pkg = mPackages.get(packageName); 13999 if (pkg != null) { 14000 pkg.mOperationPending = false; 14001 } 14002 } 14003 14004 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14005 switch (status) { 14006 case PackageInstaller.STATUS_SUCCESS: 14007 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14008 break; 14009 case PackageInstaller.STATUS_FAILURE_STORAGE: 14010 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14011 break; 14012 default: 14013 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14014 break; 14015 } 14016 } 14017 }; 14018 14019 // Treat a move like reinstalling an existing app, which ensures that we 14020 // process everythign uniformly, like unpacking native libraries. 14021 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14022 14023 final Message msg = mHandler.obtainMessage(INIT_COPY); 14024 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14025 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 14026 installerPackageName, null, user, packageAbiOverride); 14027 mHandler.sendMessage(msg); 14028 } 14029 14030 @Override 14031 public boolean setInstallLocation(int loc) { 14032 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14033 null); 14034 if (getInstallLocation() == loc) { 14035 return true; 14036 } 14037 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14038 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14039 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14040 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14041 return true; 14042 } 14043 return false; 14044 } 14045 14046 @Override 14047 public int getInstallLocation() { 14048 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14049 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14050 PackageHelper.APP_INSTALL_AUTO); 14051 } 14052 14053 /** Called by UserManagerService */ 14054 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14055 mDirtyUsers.remove(userHandle); 14056 mSettings.removeUserLPw(userHandle); 14057 mPendingBroadcasts.remove(userHandle); 14058 if (mInstaller != null) { 14059 // Technically, we shouldn't be doing this with the package lock 14060 // held. However, this is very rare, and there is already so much 14061 // other disk I/O going on, that we'll let it slide for now. 14062 mInstaller.removeUserDataDirs(userHandle); 14063 } 14064 mUserNeedsBadging.delete(userHandle); 14065 removeUnusedPackagesLILPw(userManager, userHandle); 14066 } 14067 14068 /** 14069 * We're removing userHandle and would like to remove any downloaded packages 14070 * that are no longer in use by any other user. 14071 * @param userHandle the user being removed 14072 */ 14073 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14074 final boolean DEBUG_CLEAN_APKS = false; 14075 int [] users = userManager.getUserIdsLPr(); 14076 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14077 while (psit.hasNext()) { 14078 PackageSetting ps = psit.next(); 14079 if (ps.pkg == null) { 14080 continue; 14081 } 14082 final String packageName = ps.pkg.packageName; 14083 // Skip over if system app 14084 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14085 continue; 14086 } 14087 if (DEBUG_CLEAN_APKS) { 14088 Slog.i(TAG, "Checking package " + packageName); 14089 } 14090 boolean keep = false; 14091 for (int i = 0; i < users.length; i++) { 14092 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14093 keep = true; 14094 if (DEBUG_CLEAN_APKS) { 14095 Slog.i(TAG, " Keeping package " + packageName + " for user " 14096 + users[i]); 14097 } 14098 break; 14099 } 14100 } 14101 if (!keep) { 14102 if (DEBUG_CLEAN_APKS) { 14103 Slog.i(TAG, " Removing package " + packageName); 14104 } 14105 mHandler.post(new Runnable() { 14106 public void run() { 14107 deletePackageX(packageName, userHandle, 0); 14108 } //end run 14109 }); 14110 } 14111 } 14112 } 14113 14114 /** Called by UserManagerService */ 14115 void createNewUserLILPw(int userHandle, File path) { 14116 if (mInstaller != null) { 14117 mInstaller.createUserConfig(userHandle); 14118 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14119 } 14120 } 14121 14122 void newUserCreatedLILPw(int userHandle) { 14123 // Adding a user requires updating runtime permissions for system apps. 14124 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14125 } 14126 14127 @Override 14128 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14129 mContext.enforceCallingOrSelfPermission( 14130 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14131 "Only package verification agents can read the verifier device identity"); 14132 14133 synchronized (mPackages) { 14134 return mSettings.getVerifierDeviceIdentityLPw(); 14135 } 14136 } 14137 14138 @Override 14139 public void setPermissionEnforced(String permission, boolean enforced) { 14140 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14141 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14142 synchronized (mPackages) { 14143 if (mSettings.mReadExternalStorageEnforced == null 14144 || mSettings.mReadExternalStorageEnforced != enforced) { 14145 mSettings.mReadExternalStorageEnforced = enforced; 14146 mSettings.writeLPr(); 14147 } 14148 } 14149 // kill any non-foreground processes so we restart them and 14150 // grant/revoke the GID. 14151 final IActivityManager am = ActivityManagerNative.getDefault(); 14152 if (am != null) { 14153 final long token = Binder.clearCallingIdentity(); 14154 try { 14155 am.killProcessesBelowForeground("setPermissionEnforcement"); 14156 } catch (RemoteException e) { 14157 } finally { 14158 Binder.restoreCallingIdentity(token); 14159 } 14160 } 14161 } else { 14162 throw new IllegalArgumentException("No selective enforcement for " + permission); 14163 } 14164 } 14165 14166 @Override 14167 @Deprecated 14168 public boolean isPermissionEnforced(String permission) { 14169 return true; 14170 } 14171 14172 @Override 14173 public boolean isStorageLow() { 14174 final long token = Binder.clearCallingIdentity(); 14175 try { 14176 final DeviceStorageMonitorInternal 14177 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14178 if (dsm != null) { 14179 return dsm.isMemoryLow(); 14180 } else { 14181 return false; 14182 } 14183 } finally { 14184 Binder.restoreCallingIdentity(token); 14185 } 14186 } 14187 14188 @Override 14189 public IPackageInstaller getPackageInstaller() { 14190 return mInstallerService; 14191 } 14192 14193 private boolean userNeedsBadging(int userId) { 14194 int index = mUserNeedsBadging.indexOfKey(userId); 14195 if (index < 0) { 14196 final UserInfo userInfo; 14197 final long token = Binder.clearCallingIdentity(); 14198 try { 14199 userInfo = sUserManager.getUserInfo(userId); 14200 } finally { 14201 Binder.restoreCallingIdentity(token); 14202 } 14203 final boolean b; 14204 if (userInfo != null && userInfo.isManagedProfile()) { 14205 b = true; 14206 } else { 14207 b = false; 14208 } 14209 mUserNeedsBadging.put(userId, b); 14210 return b; 14211 } 14212 return mUserNeedsBadging.valueAt(index); 14213 } 14214 14215 @Override 14216 public KeySet getKeySetByAlias(String packageName, String alias) { 14217 if (packageName == null || alias == null) { 14218 return null; 14219 } 14220 synchronized(mPackages) { 14221 final PackageParser.Package pkg = mPackages.get(packageName); 14222 if (pkg == null) { 14223 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14224 throw new IllegalArgumentException("Unknown package: " + packageName); 14225 } 14226 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14227 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14228 } 14229 } 14230 14231 @Override 14232 public KeySet getSigningKeySet(String packageName) { 14233 if (packageName == null) { 14234 return null; 14235 } 14236 synchronized(mPackages) { 14237 final PackageParser.Package pkg = mPackages.get(packageName); 14238 if (pkg == null) { 14239 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14240 throw new IllegalArgumentException("Unknown package: " + packageName); 14241 } 14242 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14243 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14244 throw new SecurityException("May not access signing KeySet of other apps."); 14245 } 14246 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14247 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14248 } 14249 } 14250 14251 @Override 14252 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14253 if (packageName == null || ks == null) { 14254 return false; 14255 } 14256 synchronized(mPackages) { 14257 final PackageParser.Package pkg = mPackages.get(packageName); 14258 if (pkg == null) { 14259 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14260 throw new IllegalArgumentException("Unknown package: " + packageName); 14261 } 14262 IBinder ksh = ks.getToken(); 14263 if (ksh instanceof KeySetHandle) { 14264 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14265 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14266 } 14267 return false; 14268 } 14269 } 14270 14271 @Override 14272 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14273 if (packageName == null || ks == null) { 14274 return false; 14275 } 14276 synchronized(mPackages) { 14277 final PackageParser.Package pkg = mPackages.get(packageName); 14278 if (pkg == null) { 14279 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14280 throw new IllegalArgumentException("Unknown package: " + packageName); 14281 } 14282 IBinder ksh = ks.getToken(); 14283 if (ksh instanceof KeySetHandle) { 14284 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14285 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14286 } 14287 return false; 14288 } 14289 } 14290 14291 public void getUsageStatsIfNoPackageUsageInfo() { 14292 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14293 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14294 if (usm == null) { 14295 throw new IllegalStateException("UsageStatsManager must be initialized"); 14296 } 14297 long now = System.currentTimeMillis(); 14298 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14299 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14300 String packageName = entry.getKey(); 14301 PackageParser.Package pkg = mPackages.get(packageName); 14302 if (pkg == null) { 14303 continue; 14304 } 14305 UsageStats usage = entry.getValue(); 14306 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14307 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14308 } 14309 } 14310 } 14311 14312 /** 14313 * Check and throw if the given before/after packages would be considered a 14314 * downgrade. 14315 */ 14316 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14317 throws PackageManagerException { 14318 if (after.versionCode < before.mVersionCode) { 14319 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14320 "Update version code " + after.versionCode + " is older than current " 14321 + before.mVersionCode); 14322 } else if (after.versionCode == before.mVersionCode) { 14323 if (after.baseRevisionCode < before.baseRevisionCode) { 14324 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14325 "Update base revision code " + after.baseRevisionCode 14326 + " is older than current " + before.baseRevisionCode); 14327 } 14328 14329 if (!ArrayUtils.isEmpty(after.splitNames)) { 14330 for (int i = 0; i < after.splitNames.length; i++) { 14331 final String splitName = after.splitNames[i]; 14332 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14333 if (j != -1) { 14334 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14335 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14336 "Update split " + splitName + " revision code " 14337 + after.splitRevisionCodes[i] + " is older than current " 14338 + before.splitRevisionCodes[j]); 14339 } 14340 } 14341 } 14342 } 14343 } 14344 } 14345} 14346