PackageManagerService.java revision 1c1b47125da018b44240739db75f8898e064a948
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; 65 66import android.Manifest; 67import android.content.pm.IntentFilterVerificationInfo; 68import android.util.ArrayMap; 69 70import com.android.internal.R; 71import com.android.internal.app.IMediaContainerService; 72import com.android.internal.app.ResolverActivity; 73import com.android.internal.content.NativeLibraryHelper; 74import com.android.internal.content.PackageHelper; 75import com.android.internal.os.IParcelFileDescriptorFactory; 76import com.android.internal.util.ArrayUtils; 77import com.android.internal.util.FastPrintWriter; 78import com.android.internal.util.FastXmlSerializer; 79import com.android.internal.util.IndentingPrintWriter; 80import com.android.server.EventLogTags; 81import com.android.server.IntentResolver; 82import com.android.server.LocalServices; 83import com.android.server.ServiceThread; 84import com.android.server.SystemConfig; 85import com.android.server.Watchdog; 86import com.android.server.pm.Settings.DatabaseVersion; 87import com.android.server.storage.DeviceStorageMonitorInternal; 88 89import org.xmlpull.v1.XmlSerializer; 90 91import android.app.ActivityManager; 92import android.app.ActivityManagerNative; 93import android.app.AppGlobals; 94import android.app.IActivityManager; 95import android.app.admin.IDevicePolicyManager; 96import android.app.backup.IBackupManager; 97import android.app.usage.UsageStats; 98import android.app.usage.UsageStatsManager; 99import android.content.BroadcastReceiver; 100import android.content.ComponentName; 101import android.content.Context; 102import android.content.IIntentReceiver; 103import android.content.Intent; 104import android.content.IntentFilter; 105import android.content.IntentSender; 106import android.content.IntentSender.SendIntentException; 107import android.content.ServiceConnection; 108import android.content.pm.ActivityInfo; 109import android.content.pm.ApplicationInfo; 110import android.content.pm.FeatureInfo; 111import android.content.pm.IPackageDataObserver; 112import android.content.pm.IPackageDeleteObserver; 113import android.content.pm.IPackageDeleteObserver2; 114import android.content.pm.IPackageInstallObserver2; 115import android.content.pm.IPackageInstaller; 116import android.content.pm.IPackageManager; 117import android.content.pm.IPackageMoveObserver; 118import android.content.pm.IPackageStatsObserver; 119import android.content.pm.InstrumentationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageParser; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.storage.IMountService; 154import android.os.storage.StorageManager; 155import android.os.Debug; 156import android.os.FileUtils; 157import android.os.Handler; 158import android.os.IBinder; 159import android.os.Looper; 160import android.os.Message; 161import android.os.Parcel; 162import android.os.ParcelFileDescriptor; 163import android.os.Process; 164import android.os.RemoteException; 165import android.os.SELinux; 166import android.os.ServiceManager; 167import android.os.SystemClock; 168import android.os.SystemProperties; 169import android.os.UserHandle; 170import android.os.UserManager; 171import android.security.KeyStore; 172import android.security.SystemKeyStore; 173import android.system.ErrnoException; 174import android.system.Os; 175import android.system.StructStat; 176import android.text.TextUtils; 177import android.text.format.DateUtils; 178import android.util.ArraySet; 179import android.util.AtomicFile; 180import android.util.DisplayMetrics; 181import android.util.EventLog; 182import android.util.ExceptionUtils; 183import android.util.Log; 184import android.util.LogPrinter; 185import android.util.PrintStreamPrinter; 186import android.util.Slog; 187import android.util.SparseArray; 188import android.util.SparseBooleanArray; 189import android.view.Display; 190 191import java.io.BufferedInputStream; 192import java.io.BufferedOutputStream; 193import java.io.BufferedReader; 194import java.io.File; 195import java.io.FileDescriptor; 196import java.io.FileNotFoundException; 197import java.io.FileOutputStream; 198import java.io.FileReader; 199import java.io.FilenameFilter; 200import java.io.IOException; 201import java.io.InputStream; 202import java.io.PrintWriter; 203import java.nio.charset.StandardCharsets; 204import java.security.NoSuchAlgorithmException; 205import java.security.PublicKey; 206import java.security.cert.CertificateEncodingException; 207import java.security.cert.CertificateException; 208import java.text.SimpleDateFormat; 209import java.util.ArrayList; 210import java.util.Arrays; 211import java.util.Collection; 212import java.util.Collections; 213import java.util.Comparator; 214import java.util.Date; 215import java.util.Iterator; 216import java.util.List; 217import java.util.Map; 218import java.util.Objects; 219import java.util.Set; 220import java.util.concurrent.atomic.AtomicBoolean; 221import java.util.concurrent.atomic.AtomicLong; 222 223import dalvik.system.DexFile; 224import dalvik.system.VMRuntime; 225 226import libcore.io.IoUtils; 227import libcore.util.EmptyArray; 228 229/** 230 * Keep track of all those .apks everywhere. 231 * 232 * This is very central to the platform's security; please run the unit 233 * tests whenever making modifications here: 234 * 235mmm frameworks/base/tests/AndroidTests 236adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 237adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 238 * 239 * {@hide} 240 */ 241public class PackageManagerService extends IPackageManager.Stub { 242 static final String TAG = "PackageManager"; 243 static final boolean DEBUG_SETTINGS = false; 244 static final boolean DEBUG_PREFERRED = false; 245 static final boolean DEBUG_UPGRADE = false; 246 private static final boolean DEBUG_INSTALL = false; 247 private static final boolean DEBUG_REMOVE = false; 248 private static final boolean DEBUG_BROADCASTS = false; 249 private static final boolean DEBUG_SHOW_INFO = false; 250 private static final boolean DEBUG_PACKAGE_INFO = false; 251 private static final boolean DEBUG_INTENT_MATCHING = false; 252 private static final boolean DEBUG_PACKAGE_SCANNING = false; 253 private static final boolean DEBUG_VERIFY = false; 254 private static final boolean DEBUG_DEXOPT = false; 255 private static final boolean DEBUG_ABI_SELECTION = false; 256 257 static final boolean RUNTIME_PERMISSIONS_ENABLED = 258 SystemProperties.getInt("ro.runtime.permissions.enabled", 0) == 1; 259 260 private static final int RADIO_UID = Process.PHONE_UID; 261 private static final int LOG_UID = Process.LOG_UID; 262 private static final int NFC_UID = Process.NFC_UID; 263 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 264 private static final int SHELL_UID = Process.SHELL_UID; 265 266 // Cap the size of permission trees that 3rd party apps can define 267 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 268 269 // Suffix used during package installation when copying/moving 270 // package apks to install directory. 271 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 272 273 static final int SCAN_NO_DEX = 1<<1; 274 static final int SCAN_FORCE_DEX = 1<<2; 275 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 276 static final int SCAN_NEW_INSTALL = 1<<4; 277 static final int SCAN_NO_PATHS = 1<<5; 278 static final int SCAN_UPDATE_TIME = 1<<6; 279 static final int SCAN_DEFER_DEX = 1<<7; 280 static final int SCAN_BOOTING = 1<<8; 281 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 282 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 283 static final int SCAN_REPLACING = 1<<11; 284 static final int SCAN_REQUIRE_KNOWN = 1<<12; 285 286 static final int REMOVE_CHATTY = 1<<16; 287 288 /** 289 * Timeout (in milliseconds) after which the watchdog should declare that 290 * our handler thread is wedged. The usual default for such things is one 291 * minute but we sometimes do very lengthy I/O operations on this thread, 292 * such as installing multi-gigabyte applications, so ours needs to be longer. 293 */ 294 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 295 296 /** 297 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 298 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 299 * settings entry if available, otherwise we use the hardcoded default. If it's been 300 * more than this long since the last fstrim, we force one during the boot sequence. 301 * 302 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 303 * one gets run at the next available charging+idle time. This final mandatory 304 * no-fstrim check kicks in only of the other scheduling criteria is never met. 305 */ 306 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 307 308 /** 309 * Whether verification is enabled by default. 310 */ 311 private static final boolean DEFAULT_VERIFY_ENABLE = true; 312 313 /** 314 * The default maximum time to wait for the verification agent to return in 315 * milliseconds. 316 */ 317 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 318 319 /** 320 * The default response for package verification timeout. 321 * 322 * This can be either PackageManager.VERIFICATION_ALLOW or 323 * PackageManager.VERIFICATION_REJECT. 324 */ 325 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 326 327 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 328 329 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 330 DEFAULT_CONTAINER_PACKAGE, 331 "com.android.defcontainer.DefaultContainerService"); 332 333 private static final String KILL_APP_REASON_GIDS_CHANGED = 334 "permission grant or revoke changed gids"; 335 336 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 337 "permissions revoked"; 338 339 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 340 341 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 342 343 /** Permission grant: not grant the permission. */ 344 private static final int GRANT_DENIED = 1; 345 346 /** Permission grant: grant the permission as an install permission. */ 347 private static final int GRANT_INSTALL = 2; 348 349 /** Permission grant: grant the permission as a runtime one. */ 350 private static final int GRANT_RUNTIME = 3; 351 352 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 353 private static final int GRANT_UPGRADE = 4; 354 355 final ServiceThread mHandlerThread; 356 357 final PackageHandler mHandler; 358 359 /** 360 * Messages for {@link #mHandler} that need to wait for system ready before 361 * being dispatched. 362 */ 363 private ArrayList<Message> mPostSystemReadyMessages; 364 365 final int mSdkVersion = Build.VERSION.SDK_INT; 366 367 final Context mContext; 368 final boolean mFactoryTest; 369 final boolean mOnlyCore; 370 final boolean mLazyDexOpt; 371 final long mDexOptLRUThresholdInMills; 372 final DisplayMetrics mMetrics; 373 final int mDefParseFlags; 374 final String[] mSeparateProcesses; 375 final boolean mIsUpgrade; 376 377 // This is where all application persistent data goes. 378 final File mAppDataDir; 379 380 // This is where all application persistent data goes for secondary users. 381 final File mUserAppDataDir; 382 383 /** The location for ASEC container files on internal storage. */ 384 final String mAsecInternalPath; 385 386 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 387 // LOCK HELD. Can be called with mInstallLock held. 388 final Installer mInstaller; 389 390 /** Directory where installed third-party apps stored */ 391 final File mAppInstallDir; 392 393 /** 394 * Directory to which applications installed internally have their 395 * 32 bit native libraries copied. 396 */ 397 private File mAppLib32InstallDir; 398 399 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 400 // apps. 401 final File mDrmAppPrivateInstallDir; 402 403 // ---------------------------------------------------------------- 404 405 // Lock for state used when installing and doing other long running 406 // operations. Methods that must be called with this lock held have 407 // the suffix "LI". 408 final Object mInstallLock = new Object(); 409 410 // ---------------------------------------------------------------- 411 412 // Keys are String (package name), values are Package. This also serves 413 // as the lock for the global state. Methods that must be called with 414 // this lock held have the prefix "LP". 415 final ArrayMap<String, PackageParser.Package> mPackages = 416 new ArrayMap<String, PackageParser.Package>(); 417 418 // Tracks available target package names -> overlay package paths. 419 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 420 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 421 422 final Settings mSettings; 423 boolean mRestoredSettings; 424 425 // System configuration read by SystemConfig. 426 final int[] mGlobalGids; 427 final SparseArray<ArraySet<String>> mSystemPermissions; 428 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 429 430 // If mac_permissions.xml was found for seinfo labeling. 431 boolean mFoundPolicyFile; 432 433 // If a recursive restorecon of /data/data/<pkg> is needed. 434 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 435 436 public static final class SharedLibraryEntry { 437 public final String path; 438 public final String apk; 439 440 SharedLibraryEntry(String _path, String _apk) { 441 path = _path; 442 apk = _apk; 443 } 444 } 445 446 // Currently known shared libraries. 447 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 448 new ArrayMap<String, SharedLibraryEntry>(); 449 450 // All available activities, for your resolving pleasure. 451 final ActivityIntentResolver mActivities = 452 new ActivityIntentResolver(); 453 454 // All available receivers, for your resolving pleasure. 455 final ActivityIntentResolver mReceivers = 456 new ActivityIntentResolver(); 457 458 // All available services, for your resolving pleasure. 459 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 460 461 // All available providers, for your resolving pleasure. 462 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 463 464 // Mapping from provider base names (first directory in content URI codePath) 465 // to the provider information. 466 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 467 new ArrayMap<String, PackageParser.Provider>(); 468 469 // Mapping from instrumentation class names to info about them. 470 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 471 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 472 473 // Mapping from permission names to info about them. 474 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 475 new ArrayMap<String, PackageParser.PermissionGroup>(); 476 477 // Packages whose data we have transfered into another package, thus 478 // should no longer exist. 479 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 480 481 // Broadcast actions that are only available to the system. 482 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 483 484 /** List of packages waiting for verification. */ 485 final SparseArray<PackageVerificationState> mPendingVerification 486 = new SparseArray<PackageVerificationState>(); 487 488 /** Set of packages associated with each app op permission. */ 489 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 490 491 final PackageInstallerService mInstallerService; 492 493 private final PackageDexOptimizer mPackageDexOptimizer; 494 // Cache of users who need badging. 495 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 496 497 /** Token for keys in mPendingVerification. */ 498 private int mPendingVerificationToken = 0; 499 500 volatile boolean mSystemReady; 501 volatile boolean mSafeMode; 502 volatile boolean mHasSystemUidErrors; 503 504 ApplicationInfo mAndroidApplication; 505 final ActivityInfo mResolveActivity = new ActivityInfo(); 506 final ResolveInfo mResolveInfo = new ResolveInfo(); 507 ComponentName mResolveComponentName; 508 PackageParser.Package mPlatformPackage; 509 ComponentName mCustomResolverComponentName; 510 511 boolean mResolverReplaced = false; 512 513 private final ComponentName mIntentFilterVerifierComponent; 514 private int mIntentFilterVerificationToken = 0; 515 516 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 517 = new SparseArray<IntentFilterVerificationState>(); 518 519 private interface IntentFilterVerifier<T extends IntentFilter> { 520 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 521 T filter, String packageName); 522 void startVerifications(int userId); 523 void receiveVerificationResponse(int verificationId); 524 } 525 526 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 527 private Context mContext; 528 private ComponentName mIntentFilterVerifierComponent; 529 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 530 531 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 532 mContext = context; 533 mIntentFilterVerifierComponent = verifierComponent; 534 } 535 536 private String getDefaultScheme() { 537 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 538 return IntentFilter.SCHEME_HTTP; 539 } 540 541 @Override 542 public void startVerifications(int userId) { 543 // Launch verifications requests 544 int count = mCurrentIntentFilterVerifications.size(); 545 for (int n=0; n<count; n++) { 546 int verificationId = mCurrentIntentFilterVerifications.get(n); 547 final IntentFilterVerificationState ivs = 548 mIntentFilterVerificationStates.get(verificationId); 549 550 String packageName = ivs.getPackageName(); 551 boolean modified = false; 552 553 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 554 final int filterCount = filters.size(); 555 for (int m=0; m<filterCount; m++) { 556 PackageParser.ActivityIntentInfo filter = filters.get(m); 557 synchronized (mPackages) { 558 modified = mSettings.createIntentFilterVerificationIfNeededLPw( 559 packageName, filter.getHosts()); 560 } 561 } 562 synchronized (mPackages) { 563 if (modified) { 564 scheduleWriteSettingsLocked(); 565 } 566 } 567 sendVerificationRequest(userId, verificationId, ivs); 568 } 569 mCurrentIntentFilterVerifications.clear(); 570 } 571 572 private void sendVerificationRequest(int userId, int verificationId, 573 IntentFilterVerificationState ivs) { 574 575 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 576 verificationIntent.putExtra( 577 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 578 verificationId); 579 verificationIntent.putExtra( 580 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 581 getDefaultScheme()); 582 verificationIntent.putExtra( 583 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 584 ivs.getHostsString()); 585 verificationIntent.putExtra( 586 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 587 ivs.getPackageName()); 588 verificationIntent.setComponent(mIntentFilterVerifierComponent); 589 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 590 591 UserHandle user = new UserHandle(userId); 592 mContext.sendBroadcastAsUser(verificationIntent, user); 593 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 594 } 595 596 public void receiveVerificationResponse(int verificationId) { 597 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 598 599 final boolean verified = ivs.isVerified(); 600 601 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 602 final int count = filters.size(); 603 for (int n=0; n<count; n++) { 604 PackageParser.ActivityIntentInfo filter = filters.get(n); 605 filter.setVerified(verified); 606 607 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 608 + verified + " and hosts:" + ivs.getHostsString()); 609 } 610 611 mIntentFilterVerificationStates.remove(verificationId); 612 613 final String packageName = ivs.getPackageName(); 614 IntentFilterVerificationInfo ivi = null; 615 616 synchronized (mPackages) { 617 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 618 } 619 if (ivi == null) { 620 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 621 + verificationId + " packageName:" + packageName); 622 return; 623 } 624 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 625 + verificationId); 626 627 synchronized (mPackages) { 628 if (verified) { 629 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 630 } else { 631 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 632 } 633 scheduleWriteSettingsLocked(); 634 635 final int userId = ivs.getUserId(); 636 if (userId != UserHandle.USER_ALL) { 637 final int userStatus = 638 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 639 640 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 641 boolean needUpdate = false; 642 643 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 644 // already been set by the User thru the Disambiguation dialog 645 switch (userStatus) { 646 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 647 if (verified) { 648 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 649 } else { 650 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 651 } 652 needUpdate = true; 653 break; 654 655 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 656 if (verified) { 657 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 658 needUpdate = true; 659 } 660 break; 661 662 default: 663 // Nothing to do 664 } 665 666 if (needUpdate) { 667 mSettings.updateIntentFilterVerificationStatusLPw( 668 packageName, updatedStatus, userId); 669 scheduleWritePackageRestrictionsLocked(userId); 670 } 671 } 672 } 673 } 674 675 @Override 676 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 677 ActivityIntentInfo filter, String packageName) { 678 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 679 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 680 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 681 return false; 682 } 683 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 684 if (ivs == null) { 685 ivs = createDomainVerificationState(verifierId, userId, verificationId, 686 packageName); 687 } 688 ArrayList<String> hosts = filter.getHostsList(); 689 if (!hasValidHosts(hosts)) { 690 return false; 691 } 692 ivs.addFilter(filter); 693 return true; 694 } 695 696 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 697 int userId, int verificationId, String packageName) { 698 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 699 verifierId, userId, packageName); 700 ivs.setPendingState(); 701 synchronized (mPackages) { 702 mIntentFilterVerificationStates.append(verificationId, ivs); 703 mCurrentIntentFilterVerifications.add(verificationId); 704 } 705 return ivs; 706 } 707 708 private boolean hasValidHosts(ArrayList<String> hosts) { 709 if (hosts.size() == 0) { 710 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 711 return false; 712 } 713 String hostEndBase = null; 714 for (String host : hosts) { 715 String[] hostParts = host.split("\\."); 716 // Should be at minimum a host like "example.com" 717 if (hostParts.length < 2) { 718 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 719 return false; 720 } 721 // Verify that we have the same ending domain 722 int length = hostParts.length; 723 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 724 if (hostEndBase == null) { 725 hostEndBase = hostEnd; 726 } 727 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 728 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 729 return false; 730 } 731 } 732 return true; 733 } 734 } 735 736 private IntentFilterVerifier mIntentFilterVerifier; 737 738 // Set of pending broadcasts for aggregating enable/disable of components. 739 static class PendingPackageBroadcasts { 740 // for each user id, a map of <package name -> components within that package> 741 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 742 743 public PendingPackageBroadcasts() { 744 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 745 } 746 747 public ArrayList<String> get(int userId, String packageName) { 748 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 749 return packages.get(packageName); 750 } 751 752 public void put(int userId, String packageName, ArrayList<String> components) { 753 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 754 packages.put(packageName, components); 755 } 756 757 public void remove(int userId, String packageName) { 758 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 759 if (packages != null) { 760 packages.remove(packageName); 761 } 762 } 763 764 public void remove(int userId) { 765 mUidMap.remove(userId); 766 } 767 768 public int userIdCount() { 769 return mUidMap.size(); 770 } 771 772 public int userIdAt(int n) { 773 return mUidMap.keyAt(n); 774 } 775 776 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 777 return mUidMap.get(userId); 778 } 779 780 public int size() { 781 // total number of pending broadcast entries across all userIds 782 int num = 0; 783 for (int i = 0; i< mUidMap.size(); i++) { 784 num += mUidMap.valueAt(i).size(); 785 } 786 return num; 787 } 788 789 public void clear() { 790 mUidMap.clear(); 791 } 792 793 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 794 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 795 if (map == null) { 796 map = new ArrayMap<String, ArrayList<String>>(); 797 mUidMap.put(userId, map); 798 } 799 return map; 800 } 801 } 802 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 803 804 // Service Connection to remote media container service to copy 805 // package uri's from external media onto secure containers 806 // or internal storage. 807 private IMediaContainerService mContainerService = null; 808 809 static final int SEND_PENDING_BROADCAST = 1; 810 static final int MCS_BOUND = 3; 811 static final int END_COPY = 4; 812 static final int INIT_COPY = 5; 813 static final int MCS_UNBIND = 6; 814 static final int START_CLEANING_PACKAGE = 7; 815 static final int FIND_INSTALL_LOC = 8; 816 static final int POST_INSTALL = 9; 817 static final int MCS_RECONNECT = 10; 818 static final int MCS_GIVE_UP = 11; 819 static final int UPDATED_MEDIA_STATUS = 12; 820 static final int WRITE_SETTINGS = 13; 821 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 822 static final int PACKAGE_VERIFIED = 15; 823 static final int CHECK_PENDING_VERIFICATION = 16; 824 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 825 static final int INTENT_FILTER_VERIFIED = 18; 826 827 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 828 829 // Delay time in millisecs 830 static final int BROADCAST_DELAY = 10 * 1000; 831 832 static UserManagerService sUserManager; 833 834 // Stores a list of users whose package restrictions file needs to be updated 835 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 836 837 final private DefaultContainerConnection mDefContainerConn = 838 new DefaultContainerConnection(); 839 class DefaultContainerConnection implements ServiceConnection { 840 public void onServiceConnected(ComponentName name, IBinder service) { 841 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 842 IMediaContainerService imcs = 843 IMediaContainerService.Stub.asInterface(service); 844 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 845 } 846 847 public void onServiceDisconnected(ComponentName name) { 848 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 849 } 850 }; 851 852 // Recordkeeping of restore-after-install operations that are currently in flight 853 // between the Package Manager and the Backup Manager 854 class PostInstallData { 855 public InstallArgs args; 856 public PackageInstalledInfo res; 857 858 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 859 args = _a; 860 res = _r; 861 } 862 }; 863 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 864 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 865 866 private final String mRequiredVerifierPackage; 867 868 private final PackageUsage mPackageUsage = new PackageUsage(); 869 870 private class PackageUsage { 871 private static final int WRITE_INTERVAL 872 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 873 874 private final Object mFileLock = new Object(); 875 private final AtomicLong mLastWritten = new AtomicLong(0); 876 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 877 878 private boolean mIsHistoricalPackageUsageAvailable = true; 879 880 boolean isHistoricalPackageUsageAvailable() { 881 return mIsHistoricalPackageUsageAvailable; 882 } 883 884 void write(boolean force) { 885 if (force) { 886 writeInternal(); 887 return; 888 } 889 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 890 && !DEBUG_DEXOPT) { 891 return; 892 } 893 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 894 new Thread("PackageUsage_DiskWriter") { 895 @Override 896 public void run() { 897 try { 898 writeInternal(); 899 } finally { 900 mBackgroundWriteRunning.set(false); 901 } 902 } 903 }.start(); 904 } 905 } 906 907 private void writeInternal() { 908 synchronized (mPackages) { 909 synchronized (mFileLock) { 910 AtomicFile file = getFile(); 911 FileOutputStream f = null; 912 try { 913 f = file.startWrite(); 914 BufferedOutputStream out = new BufferedOutputStream(f); 915 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 916 StringBuilder sb = new StringBuilder(); 917 for (PackageParser.Package pkg : mPackages.values()) { 918 if (pkg.mLastPackageUsageTimeInMills == 0) { 919 continue; 920 } 921 sb.setLength(0); 922 sb.append(pkg.packageName); 923 sb.append(' '); 924 sb.append((long)pkg.mLastPackageUsageTimeInMills); 925 sb.append('\n'); 926 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 927 } 928 out.flush(); 929 file.finishWrite(f); 930 } catch (IOException e) { 931 if (f != null) { 932 file.failWrite(f); 933 } 934 Log.e(TAG, "Failed to write package usage times", e); 935 } 936 } 937 } 938 mLastWritten.set(SystemClock.elapsedRealtime()); 939 } 940 941 void readLP() { 942 synchronized (mFileLock) { 943 AtomicFile file = getFile(); 944 BufferedInputStream in = null; 945 try { 946 in = new BufferedInputStream(file.openRead()); 947 StringBuffer sb = new StringBuffer(); 948 while (true) { 949 String packageName = readToken(in, sb, ' '); 950 if (packageName == null) { 951 break; 952 } 953 String timeInMillisString = readToken(in, sb, '\n'); 954 if (timeInMillisString == null) { 955 throw new IOException("Failed to find last usage time for package " 956 + packageName); 957 } 958 PackageParser.Package pkg = mPackages.get(packageName); 959 if (pkg == null) { 960 continue; 961 } 962 long timeInMillis; 963 try { 964 timeInMillis = Long.parseLong(timeInMillisString.toString()); 965 } catch (NumberFormatException e) { 966 throw new IOException("Failed to parse " + timeInMillisString 967 + " as a long.", e); 968 } 969 pkg.mLastPackageUsageTimeInMills = timeInMillis; 970 } 971 } catch (FileNotFoundException expected) { 972 mIsHistoricalPackageUsageAvailable = false; 973 } catch (IOException e) { 974 Log.w(TAG, "Failed to read package usage times", e); 975 } finally { 976 IoUtils.closeQuietly(in); 977 } 978 } 979 mLastWritten.set(SystemClock.elapsedRealtime()); 980 } 981 982 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 983 throws IOException { 984 sb.setLength(0); 985 while (true) { 986 int ch = in.read(); 987 if (ch == -1) { 988 if (sb.length() == 0) { 989 return null; 990 } 991 throw new IOException("Unexpected EOF"); 992 } 993 if (ch == endOfToken) { 994 return sb.toString(); 995 } 996 sb.append((char)ch); 997 } 998 } 999 1000 private AtomicFile getFile() { 1001 File dataDir = Environment.getDataDirectory(); 1002 File systemDir = new File(dataDir, "system"); 1003 File fname = new File(systemDir, "package-usage.list"); 1004 return new AtomicFile(fname); 1005 } 1006 } 1007 1008 class PackageHandler extends Handler { 1009 private boolean mBound = false; 1010 final ArrayList<HandlerParams> mPendingInstalls = 1011 new ArrayList<HandlerParams>(); 1012 1013 private boolean connectToService() { 1014 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1015 " DefaultContainerService"); 1016 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1017 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1018 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1019 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1020 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1021 mBound = true; 1022 return true; 1023 } 1024 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1025 return false; 1026 } 1027 1028 private void disconnectService() { 1029 mContainerService = null; 1030 mBound = false; 1031 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1032 mContext.unbindService(mDefContainerConn); 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1034 } 1035 1036 PackageHandler(Looper looper) { 1037 super(looper); 1038 } 1039 1040 public void handleMessage(Message msg) { 1041 try { 1042 doHandleMessage(msg); 1043 } finally { 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 } 1046 } 1047 1048 void doHandleMessage(Message msg) { 1049 switch (msg.what) { 1050 case INIT_COPY: { 1051 HandlerParams params = (HandlerParams) msg.obj; 1052 int idx = mPendingInstalls.size(); 1053 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1054 // If a bind was already initiated we dont really 1055 // need to do anything. The pending install 1056 // will be processed later on. 1057 if (!mBound) { 1058 // If this is the only one pending we might 1059 // have to bind to the service again. 1060 if (!connectToService()) { 1061 Slog.e(TAG, "Failed to bind to media container service"); 1062 params.serviceError(); 1063 return; 1064 } else { 1065 // Once we bind to the service, the first 1066 // pending request will be processed. 1067 mPendingInstalls.add(idx, params); 1068 } 1069 } else { 1070 mPendingInstalls.add(idx, params); 1071 // Already bound to the service. Just make 1072 // sure we trigger off processing the first request. 1073 if (idx == 0) { 1074 mHandler.sendEmptyMessage(MCS_BOUND); 1075 } 1076 } 1077 break; 1078 } 1079 case MCS_BOUND: { 1080 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1081 if (msg.obj != null) { 1082 mContainerService = (IMediaContainerService) msg.obj; 1083 } 1084 if (mContainerService == null) { 1085 // Something seriously wrong. Bail out 1086 Slog.e(TAG, "Cannot bind to media container service"); 1087 for (HandlerParams params : mPendingInstalls) { 1088 // Indicate service bind error 1089 params.serviceError(); 1090 } 1091 mPendingInstalls.clear(); 1092 } else if (mPendingInstalls.size() > 0) { 1093 HandlerParams params = mPendingInstalls.get(0); 1094 if (params != null) { 1095 if (params.startCopy()) { 1096 // We are done... look for more work or to 1097 // go idle. 1098 if (DEBUG_SD_INSTALL) Log.i(TAG, 1099 "Checking for more work or unbind..."); 1100 // Delete pending install 1101 if (mPendingInstalls.size() > 0) { 1102 mPendingInstalls.remove(0); 1103 } 1104 if (mPendingInstalls.size() == 0) { 1105 if (mBound) { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, 1107 "Posting delayed MCS_UNBIND"); 1108 removeMessages(MCS_UNBIND); 1109 Message ubmsg = obtainMessage(MCS_UNBIND); 1110 // Unbind after a little delay, to avoid 1111 // continual thrashing. 1112 sendMessageDelayed(ubmsg, 10000); 1113 } 1114 } else { 1115 // There are more pending requests in queue. 1116 // Just post MCS_BOUND message to trigger processing 1117 // of next pending install. 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Posting MCS_BOUND for next work"); 1120 mHandler.sendEmptyMessage(MCS_BOUND); 1121 } 1122 } 1123 } 1124 } else { 1125 // Should never happen ideally. 1126 Slog.w(TAG, "Empty queue"); 1127 } 1128 break; 1129 } 1130 case MCS_RECONNECT: { 1131 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1132 if (mPendingInstalls.size() > 0) { 1133 if (mBound) { 1134 disconnectService(); 1135 } 1136 if (!connectToService()) { 1137 Slog.e(TAG, "Failed to bind to media container service"); 1138 for (HandlerParams params : mPendingInstalls) { 1139 // Indicate service bind error 1140 params.serviceError(); 1141 } 1142 mPendingInstalls.clear(); 1143 } 1144 } 1145 break; 1146 } 1147 case MCS_UNBIND: { 1148 // If there is no actual work left, then time to unbind. 1149 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1150 1151 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1152 if (mBound) { 1153 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1154 1155 disconnectService(); 1156 } 1157 } else if (mPendingInstalls.size() > 0) { 1158 // There are more pending requests in queue. 1159 // Just post MCS_BOUND message to trigger processing 1160 // of next pending install. 1161 mHandler.sendEmptyMessage(MCS_BOUND); 1162 } 1163 1164 break; 1165 } 1166 case MCS_GIVE_UP: { 1167 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1168 mPendingInstalls.remove(0); 1169 break; 1170 } 1171 case SEND_PENDING_BROADCAST: { 1172 String packages[]; 1173 ArrayList<String> components[]; 1174 int size = 0; 1175 int uids[]; 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1177 synchronized (mPackages) { 1178 if (mPendingBroadcasts == null) { 1179 return; 1180 } 1181 size = mPendingBroadcasts.size(); 1182 if (size <= 0) { 1183 // Nothing to be done. Just return 1184 return; 1185 } 1186 packages = new String[size]; 1187 components = new ArrayList[size]; 1188 uids = new int[size]; 1189 int i = 0; // filling out the above arrays 1190 1191 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1192 int packageUserId = mPendingBroadcasts.userIdAt(n); 1193 Iterator<Map.Entry<String, ArrayList<String>>> it 1194 = mPendingBroadcasts.packagesForUserId(packageUserId) 1195 .entrySet().iterator(); 1196 while (it.hasNext() && i < size) { 1197 Map.Entry<String, ArrayList<String>> ent = it.next(); 1198 packages[i] = ent.getKey(); 1199 components[i] = ent.getValue(); 1200 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1201 uids[i] = (ps != null) 1202 ? UserHandle.getUid(packageUserId, ps.appId) 1203 : -1; 1204 i++; 1205 } 1206 } 1207 size = i; 1208 mPendingBroadcasts.clear(); 1209 } 1210 // Send broadcasts 1211 for (int i = 0; i < size; i++) { 1212 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1213 } 1214 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1215 break; 1216 } 1217 case START_CLEANING_PACKAGE: { 1218 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1219 final String packageName = (String)msg.obj; 1220 final int userId = msg.arg1; 1221 final boolean andCode = msg.arg2 != 0; 1222 synchronized (mPackages) { 1223 if (userId == UserHandle.USER_ALL) { 1224 int[] users = sUserManager.getUserIds(); 1225 for (int user : users) { 1226 mSettings.addPackageToCleanLPw( 1227 new PackageCleanItem(user, packageName, andCode)); 1228 } 1229 } else { 1230 mSettings.addPackageToCleanLPw( 1231 new PackageCleanItem(userId, packageName, andCode)); 1232 } 1233 } 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1235 startCleaningPackages(); 1236 } break; 1237 case POST_INSTALL: { 1238 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1239 PostInstallData data = mRunningInstalls.get(msg.arg1); 1240 mRunningInstalls.delete(msg.arg1); 1241 boolean deleteOld = false; 1242 1243 if (data != null) { 1244 InstallArgs args = data.args; 1245 PackageInstalledInfo res = data.res; 1246 1247 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1248 res.removedInfo.sendBroadcast(false, true, false); 1249 Bundle extras = new Bundle(1); 1250 extras.putInt(Intent.EXTRA_UID, res.uid); 1251 1252 // Now that we successfully installed the package, grant runtime 1253 // permissions if requested before broadcasting the install. 1254 if ((args.installFlags 1255 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1256 grantRequestedRuntimePermissions(res.pkg, 1257 args.user.getIdentifier()); 1258 } 1259 1260 // Determine the set of users who are adding this 1261 // package for the first time vs. those who are seeing 1262 // an update. 1263 int[] firstUsers; 1264 int[] updateUsers = new int[0]; 1265 if (res.origUsers == null || res.origUsers.length == 0) { 1266 firstUsers = res.newUsers; 1267 } else { 1268 firstUsers = new int[0]; 1269 for (int i=0; i<res.newUsers.length; i++) { 1270 int user = res.newUsers[i]; 1271 boolean isNew = true; 1272 for (int j=0; j<res.origUsers.length; j++) { 1273 if (res.origUsers[j] == user) { 1274 isNew = false; 1275 break; 1276 } 1277 } 1278 if (isNew) { 1279 int[] newFirst = new int[firstUsers.length+1]; 1280 System.arraycopy(firstUsers, 0, newFirst, 0, 1281 firstUsers.length); 1282 newFirst[firstUsers.length] = user; 1283 firstUsers = newFirst; 1284 } else { 1285 int[] newUpdate = new int[updateUsers.length+1]; 1286 System.arraycopy(updateUsers, 0, newUpdate, 0, 1287 updateUsers.length); 1288 newUpdate[updateUsers.length] = user; 1289 updateUsers = newUpdate; 1290 } 1291 } 1292 } 1293 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1294 res.pkg.applicationInfo.packageName, 1295 extras, null, null, firstUsers); 1296 final boolean update = res.removedInfo.removedPackage != null; 1297 if (update) { 1298 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1299 } 1300 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1301 res.pkg.applicationInfo.packageName, 1302 extras, null, null, updateUsers); 1303 if (update) { 1304 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1305 res.pkg.applicationInfo.packageName, 1306 extras, null, null, updateUsers); 1307 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1308 null, null, 1309 res.pkg.applicationInfo.packageName, null, updateUsers); 1310 1311 // treat asec-hosted packages like removable media on upgrade 1312 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1313 if (DEBUG_INSTALL) { 1314 Slog.i(TAG, "upgrading pkg " + res.pkg 1315 + " is ASEC-hosted -> AVAILABLE"); 1316 } 1317 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1318 ArrayList<String> pkgList = new ArrayList<String>(1); 1319 pkgList.add(res.pkg.applicationInfo.packageName); 1320 sendResourcesChangedBroadcast(true, true, 1321 pkgList,uidArray, null); 1322 } 1323 } 1324 if (res.removedInfo.args != null) { 1325 // Remove the replaced package's older resources safely now 1326 deleteOld = true; 1327 } 1328 1329 // Log current value of "unknown sources" setting 1330 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1331 getUnknownSourcesSettings()); 1332 } 1333 // Force a gc to clear up things 1334 Runtime.getRuntime().gc(); 1335 // We delete after a gc for applications on sdcard. 1336 if (deleteOld) { 1337 synchronized (mInstallLock) { 1338 res.removedInfo.args.doPostDeleteLI(true); 1339 } 1340 } 1341 if (args.observer != null) { 1342 try { 1343 Bundle extras = extrasForInstallResult(res); 1344 args.observer.onPackageInstalled(res.name, res.returnCode, 1345 res.returnMsg, extras); 1346 } catch (RemoteException e) { 1347 Slog.i(TAG, "Observer no longer exists."); 1348 } 1349 } 1350 } else { 1351 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1352 } 1353 } break; 1354 case UPDATED_MEDIA_STATUS: { 1355 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1356 boolean reportStatus = msg.arg1 == 1; 1357 boolean doGc = msg.arg2 == 1; 1358 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1359 if (doGc) { 1360 // Force a gc to clear up stale containers. 1361 Runtime.getRuntime().gc(); 1362 } 1363 if (msg.obj != null) { 1364 @SuppressWarnings("unchecked") 1365 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1367 // Unload containers 1368 unloadAllContainers(args); 1369 } 1370 if (reportStatus) { 1371 try { 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1373 PackageHelper.getMountService().finishMediaUpdate(); 1374 } catch (RemoteException e) { 1375 Log.e(TAG, "MountService not running?"); 1376 } 1377 } 1378 } break; 1379 case WRITE_SETTINGS: { 1380 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1381 synchronized (mPackages) { 1382 removeMessages(WRITE_SETTINGS); 1383 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1384 mSettings.writeLPr(); 1385 mDirtyUsers.clear(); 1386 } 1387 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1388 } break; 1389 case WRITE_PACKAGE_RESTRICTIONS: { 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1391 synchronized (mPackages) { 1392 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1393 for (int userId : mDirtyUsers) { 1394 mSettings.writePackageRestrictionsLPr(userId); 1395 } 1396 mDirtyUsers.clear(); 1397 } 1398 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1399 } break; 1400 case CHECK_PENDING_VERIFICATION: { 1401 final int verificationId = msg.arg1; 1402 final PackageVerificationState state = mPendingVerification.get(verificationId); 1403 1404 if ((state != null) && !state.timeoutExtended()) { 1405 final InstallArgs args = state.getInstallArgs(); 1406 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1407 1408 Slog.i(TAG, "Verification timed out for " + originUri); 1409 mPendingVerification.remove(verificationId); 1410 1411 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1412 1413 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1414 Slog.i(TAG, "Continuing with installation of " + originUri); 1415 state.setVerifierResponse(Binder.getCallingUid(), 1416 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1417 broadcastPackageVerified(verificationId, originUri, 1418 PackageManager.VERIFICATION_ALLOW, 1419 state.getInstallArgs().getUser()); 1420 try { 1421 ret = args.copyApk(mContainerService, true); 1422 } catch (RemoteException e) { 1423 Slog.e(TAG, "Could not contact the ContainerService"); 1424 } 1425 } else { 1426 broadcastPackageVerified(verificationId, originUri, 1427 PackageManager.VERIFICATION_REJECT, 1428 state.getInstallArgs().getUser()); 1429 } 1430 1431 processPendingInstall(args, ret); 1432 mHandler.sendEmptyMessage(MCS_UNBIND); 1433 } 1434 break; 1435 } 1436 case PACKAGE_VERIFIED: { 1437 final int verificationId = msg.arg1; 1438 1439 final PackageVerificationState state = mPendingVerification.get(verificationId); 1440 if (state == null) { 1441 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1442 break; 1443 } 1444 1445 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1446 1447 state.setVerifierResponse(response.callerUid, response.code); 1448 1449 if (state.isVerificationComplete()) { 1450 mPendingVerification.remove(verificationId); 1451 1452 final InstallArgs args = state.getInstallArgs(); 1453 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1454 1455 int ret; 1456 if (state.isInstallAllowed()) { 1457 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1458 broadcastPackageVerified(verificationId, originUri, 1459 response.code, state.getInstallArgs().getUser()); 1460 try { 1461 ret = args.copyApk(mContainerService, true); 1462 } catch (RemoteException e) { 1463 Slog.e(TAG, "Could not contact the ContainerService"); 1464 } 1465 } else { 1466 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1467 } 1468 1469 processPendingInstall(args, ret); 1470 1471 mHandler.sendEmptyMessage(MCS_UNBIND); 1472 } 1473 1474 break; 1475 } 1476 case START_INTENT_FILTER_VERIFICATIONS: { 1477 int userId = msg.arg1; 1478 int verifierUid = msg.arg2; 1479 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1480 1481 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1482 break; 1483 } 1484 case INTENT_FILTER_VERIFIED: { 1485 final int verificationId = msg.arg1; 1486 1487 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1488 verificationId); 1489 if (state == null) { 1490 Slog.w(TAG, "Invalid IntentFilter verification token " 1491 + verificationId + " received"); 1492 break; 1493 } 1494 1495 final int userId = state.getUserId(); 1496 1497 Slog.d(TAG, "Processing IntentFilter verification with token:" 1498 + verificationId + " and userId:" + userId); 1499 1500 final IntentFilterVerificationResponse response = 1501 (IntentFilterVerificationResponse) msg.obj; 1502 1503 state.setVerifierResponse(response.callerUid, response.code); 1504 1505 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1506 + " and userId:" + userId 1507 + " is settings verifier response with response code:" 1508 + response.code); 1509 1510 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1511 Slog.d(TAG, "Domains failing verification: " 1512 + response.getFailedDomainsString()); 1513 } 1514 1515 if (state.isVerificationComplete()) { 1516 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1517 } else { 1518 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1519 + " was not said to be complete"); 1520 } 1521 1522 break; 1523 } 1524 } 1525 } 1526 } 1527 1528 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1529 if (userId >= UserHandle.USER_OWNER) { 1530 grantRequestedRuntimePermissionsForUser(pkg, userId); 1531 } else if (userId == UserHandle.USER_ALL) { 1532 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1533 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1534 } 1535 } 1536 } 1537 1538 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1539 SettingBase sb = (SettingBase) pkg.mExtras; 1540 if (sb == null) { 1541 return; 1542 } 1543 1544 PermissionsState permissionsState = sb.getPermissionsState(); 1545 1546 for (String permission : pkg.requestedPermissions) { 1547 BasePermission bp = mSettings.mPermissions.get(permission); 1548 if (bp != null && bp.isRuntime()) { 1549 permissionsState.grantRuntimePermission(bp, userId); 1550 } 1551 } 1552 } 1553 1554 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1555 Bundle extras = null; 1556 switch (res.returnCode) { 1557 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1558 extras = new Bundle(); 1559 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1560 res.origPermission); 1561 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1562 res.origPackage); 1563 break; 1564 } 1565 } 1566 return extras; 1567 } 1568 1569 void scheduleWriteSettingsLocked() { 1570 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1571 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1572 } 1573 } 1574 1575 void scheduleWritePackageRestrictionsLocked(int userId) { 1576 if (!sUserManager.exists(userId)) return; 1577 mDirtyUsers.add(userId); 1578 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1579 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1580 } 1581 } 1582 1583 public static PackageManagerService main(Context context, Installer installer, 1584 boolean factoryTest, boolean onlyCore) { 1585 PackageManagerService m = new PackageManagerService(context, installer, 1586 factoryTest, onlyCore); 1587 ServiceManager.addService("package", m); 1588 return m; 1589 } 1590 1591 static String[] splitString(String str, char sep) { 1592 int count = 1; 1593 int i = 0; 1594 while ((i=str.indexOf(sep, i)) >= 0) { 1595 count++; 1596 i++; 1597 } 1598 1599 String[] res = new String[count]; 1600 i=0; 1601 count = 0; 1602 int lastI=0; 1603 while ((i=str.indexOf(sep, i)) >= 0) { 1604 res[count] = str.substring(lastI, i); 1605 count++; 1606 i++; 1607 lastI = i; 1608 } 1609 res[count] = str.substring(lastI, str.length()); 1610 return res; 1611 } 1612 1613 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1614 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1615 Context.DISPLAY_SERVICE); 1616 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1617 } 1618 1619 public PackageManagerService(Context context, Installer installer, 1620 boolean factoryTest, boolean onlyCore) { 1621 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1622 SystemClock.uptimeMillis()); 1623 1624 if (mSdkVersion <= 0) { 1625 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1626 } 1627 1628 mContext = context; 1629 mFactoryTest = factoryTest; 1630 mOnlyCore = onlyCore; 1631 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1632 mMetrics = new DisplayMetrics(); 1633 mSettings = new Settings(mPackages); 1634 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1635 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1636 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1637 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1638 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1639 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1640 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1641 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1642 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1643 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1644 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1645 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1646 1647 // TODO: add a property to control this? 1648 long dexOptLRUThresholdInMinutes; 1649 if (mLazyDexOpt) { 1650 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1651 } else { 1652 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1653 } 1654 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1655 1656 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1657 if (separateProcesses != null && separateProcesses.length() > 0) { 1658 if ("*".equals(separateProcesses)) { 1659 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1660 mSeparateProcesses = null; 1661 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1662 } else { 1663 mDefParseFlags = 0; 1664 mSeparateProcesses = separateProcesses.split(","); 1665 Slog.w(TAG, "Running with debug.separate_processes: " 1666 + separateProcesses); 1667 } 1668 } else { 1669 mDefParseFlags = 0; 1670 mSeparateProcesses = null; 1671 } 1672 1673 mInstaller = installer; 1674 mPackageDexOptimizer = new PackageDexOptimizer(this); 1675 1676 getDefaultDisplayMetrics(context, mMetrics); 1677 1678 SystemConfig systemConfig = SystemConfig.getInstance(); 1679 mGlobalGids = systemConfig.getGlobalGids(); 1680 mSystemPermissions = systemConfig.getSystemPermissions(); 1681 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1682 1683 synchronized (mInstallLock) { 1684 // writer 1685 synchronized (mPackages) { 1686 mHandlerThread = new ServiceThread(TAG, 1687 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1688 mHandlerThread.start(); 1689 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1690 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1691 1692 File dataDir = Environment.getDataDirectory(); 1693 mAppDataDir = new File(dataDir, "data"); 1694 mAppInstallDir = new File(dataDir, "app"); 1695 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1696 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1697 mUserAppDataDir = new File(dataDir, "user"); 1698 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1699 1700 sUserManager = new UserManagerService(context, this, 1701 mInstallLock, mPackages); 1702 1703 // Propagate permission configuration in to package manager. 1704 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1705 = systemConfig.getPermissions(); 1706 for (int i=0; i<permConfig.size(); i++) { 1707 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1708 BasePermission bp = mSettings.mPermissions.get(perm.name); 1709 if (bp == null) { 1710 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1711 mSettings.mPermissions.put(perm.name, bp); 1712 } 1713 if (perm.gids != null) { 1714 bp.setGids(perm.gids, perm.perUser); 1715 } 1716 } 1717 1718 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1719 for (int i=0; i<libConfig.size(); i++) { 1720 mSharedLibraries.put(libConfig.keyAt(i), 1721 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1722 } 1723 1724 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1725 1726 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1727 mSdkVersion, mOnlyCore); 1728 1729 String customResolverActivity = Resources.getSystem().getString( 1730 R.string.config_customResolverActivity); 1731 if (TextUtils.isEmpty(customResolverActivity)) { 1732 customResolverActivity = null; 1733 } else { 1734 mCustomResolverComponentName = ComponentName.unflattenFromString( 1735 customResolverActivity); 1736 } 1737 1738 long startTime = SystemClock.uptimeMillis(); 1739 1740 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1741 startTime); 1742 1743 // Set flag to monitor and not change apk file paths when 1744 // scanning install directories. 1745 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1746 1747 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1748 1749 /** 1750 * Add everything in the in the boot class path to the 1751 * list of process files because dexopt will have been run 1752 * if necessary during zygote startup. 1753 */ 1754 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1755 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1756 1757 if (bootClassPath != null) { 1758 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1759 for (String element : bootClassPathElements) { 1760 alreadyDexOpted.add(element); 1761 } 1762 } else { 1763 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1764 } 1765 1766 if (systemServerClassPath != null) { 1767 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1768 for (String element : systemServerClassPathElements) { 1769 alreadyDexOpted.add(element); 1770 } 1771 } else { 1772 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1773 } 1774 1775 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1776 final String[] dexCodeInstructionSets = 1777 getDexCodeInstructionSets( 1778 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1779 1780 /** 1781 * Ensure all external libraries have had dexopt run on them. 1782 */ 1783 if (mSharedLibraries.size() > 0) { 1784 // NOTE: For now, we're compiling these system "shared libraries" 1785 // (and framework jars) into all available architectures. It's possible 1786 // to compile them only when we come across an app that uses them (there's 1787 // already logic for that in scanPackageLI) but that adds some complexity. 1788 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1789 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1790 final String lib = libEntry.path; 1791 if (lib == null) { 1792 continue; 1793 } 1794 1795 try { 1796 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1797 dexCodeInstructionSet, 1798 false); 1799 if (dexoptRequired != DexFile.UP_TO_DATE) { 1800 alreadyDexOpted.add(lib); 1801 1802 // The list of "shared libraries" we have at this point is 1803 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1804 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1805 } else { 1806 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1807 } 1808 } 1809 } catch (FileNotFoundException e) { 1810 Slog.w(TAG, "Library not found: " + lib); 1811 } catch (IOException e) { 1812 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1813 + e.getMessage()); 1814 } 1815 } 1816 } 1817 } 1818 1819 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1820 1821 // Gross hack for now: we know this file doesn't contain any 1822 // code, so don't dexopt it to avoid the resulting log spew. 1823 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1824 1825 // Gross hack for now: we know this file is only part of 1826 // the boot class path for art, so don't dexopt it to 1827 // avoid the resulting log spew. 1828 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1829 1830 /** 1831 * And there are a number of commands implemented in Java, which 1832 * we currently need to do the dexopt on so that they can be 1833 * run from a non-root shell. 1834 */ 1835 String[] frameworkFiles = frameworkDir.list(); 1836 if (frameworkFiles != null) { 1837 // TODO: We could compile these only for the most preferred ABI. We should 1838 // first double check that the dex files for these commands are not referenced 1839 // by other system apps. 1840 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1841 for (int i=0; i<frameworkFiles.length; i++) { 1842 File libPath = new File(frameworkDir, frameworkFiles[i]); 1843 String path = libPath.getPath(); 1844 // Skip the file if we already did it. 1845 if (alreadyDexOpted.contains(path)) { 1846 continue; 1847 } 1848 // Skip the file if it is not a type we want to dexopt. 1849 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1850 continue; 1851 } 1852 try { 1853 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1854 dexCodeInstructionSet, 1855 false); 1856 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1857 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1858 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1859 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1860 } 1861 } catch (FileNotFoundException e) { 1862 Slog.w(TAG, "Jar not found: " + path); 1863 } catch (IOException e) { 1864 Slog.w(TAG, "Exception reading jar: " + path, e); 1865 } 1866 } 1867 } 1868 } 1869 1870 // Collect vendor overlay packages. 1871 // (Do this before scanning any apps.) 1872 // For security and version matching reason, only consider 1873 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1874 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1875 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1876 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1877 1878 // Find base frameworks (resource packages without code). 1879 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1880 | PackageParser.PARSE_IS_SYSTEM_DIR 1881 | PackageParser.PARSE_IS_PRIVILEGED, 1882 scanFlags | SCAN_NO_DEX, 0); 1883 1884 // Collected privileged system packages. 1885 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1886 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1887 | PackageParser.PARSE_IS_SYSTEM_DIR 1888 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1889 1890 // Collect ordinary system packages. 1891 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1892 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1893 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1894 1895 // Collect all vendor packages. 1896 File vendorAppDir = new File("/vendor/app"); 1897 try { 1898 vendorAppDir = vendorAppDir.getCanonicalFile(); 1899 } catch (IOException e) { 1900 // failed to look up canonical path, continue with original one 1901 } 1902 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1903 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1904 1905 // Collect all OEM packages. 1906 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1907 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1908 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1909 1910 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1911 mInstaller.moveFiles(); 1912 1913 // Prune any system packages that no longer exist. 1914 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1915 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1916 if (!mOnlyCore) { 1917 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1918 while (psit.hasNext()) { 1919 PackageSetting ps = psit.next(); 1920 1921 /* 1922 * If this is not a system app, it can't be a 1923 * disable system app. 1924 */ 1925 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1926 continue; 1927 } 1928 1929 /* 1930 * If the package is scanned, it's not erased. 1931 */ 1932 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1933 if (scannedPkg != null) { 1934 /* 1935 * If the system app is both scanned and in the 1936 * disabled packages list, then it must have been 1937 * added via OTA. Remove it from the currently 1938 * scanned package so the previously user-installed 1939 * application can be scanned. 1940 */ 1941 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1942 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1943 + ps.name + "; removing system app. Last known codePath=" 1944 + ps.codePathString + ", installStatus=" + ps.installStatus 1945 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1946 + scannedPkg.mVersionCode); 1947 removePackageLI(ps, true); 1948 expectingBetter.put(ps.name, ps.codePath); 1949 } 1950 1951 continue; 1952 } 1953 1954 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1955 psit.remove(); 1956 logCriticalInfo(Log.WARN, "System package " + ps.name 1957 + " no longer exists; wiping its data"); 1958 removeDataDirsLI(ps.name); 1959 } else { 1960 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1961 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1962 possiblyDeletedUpdatedSystemApps.add(ps.name); 1963 } 1964 } 1965 } 1966 } 1967 1968 //look for any incomplete package installations 1969 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1970 //clean up list 1971 for(int i = 0; i < deletePkgsList.size(); i++) { 1972 //clean up here 1973 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1974 } 1975 //delete tmp files 1976 deleteTempPackageFiles(); 1977 1978 // Remove any shared userIDs that have no associated packages 1979 mSettings.pruneSharedUsersLPw(); 1980 1981 if (!mOnlyCore) { 1982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1983 SystemClock.uptimeMillis()); 1984 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 1985 1986 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1987 scanFlags | SCAN_REQUIRE_KNOWN, 0); 1988 1989 /** 1990 * Remove disable package settings for any updated system 1991 * apps that were removed via an OTA. If they're not a 1992 * previously-updated app, remove them completely. 1993 * Otherwise, just revoke their system-level permissions. 1994 */ 1995 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1996 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1997 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1998 1999 String msg; 2000 if (deletedPkg == null) { 2001 msg = "Updated system package " + deletedAppName 2002 + " no longer exists; wiping its data"; 2003 removeDataDirsLI(deletedAppName); 2004 } else { 2005 msg = "Updated system app + " + deletedAppName 2006 + " no longer present; removing system privileges for " 2007 + deletedAppName; 2008 2009 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2010 2011 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2012 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2013 } 2014 logCriticalInfo(Log.WARN, msg); 2015 } 2016 2017 /** 2018 * Make sure all system apps that we expected to appear on 2019 * the userdata partition actually showed up. If they never 2020 * appeared, crawl back and revive the system version. 2021 */ 2022 for (int i = 0; i < expectingBetter.size(); i++) { 2023 final String packageName = expectingBetter.keyAt(i); 2024 if (!mPackages.containsKey(packageName)) { 2025 final File scanFile = expectingBetter.valueAt(i); 2026 2027 logCriticalInfo(Log.WARN, "Expected better " + packageName 2028 + " but never showed up; reverting to system"); 2029 2030 final int reparseFlags; 2031 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2032 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2033 | PackageParser.PARSE_IS_SYSTEM_DIR 2034 | PackageParser.PARSE_IS_PRIVILEGED; 2035 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2036 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR; 2038 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2039 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR; 2041 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2042 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2043 | PackageParser.PARSE_IS_SYSTEM_DIR; 2044 } else { 2045 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2046 continue; 2047 } 2048 2049 mSettings.enableSystemPackageLPw(packageName); 2050 2051 try { 2052 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2053 } catch (PackageManagerException e) { 2054 Slog.e(TAG, "Failed to parse original system package: " 2055 + e.getMessage()); 2056 } 2057 } 2058 } 2059 } 2060 2061 // Now that we know all of the shared libraries, update all clients to have 2062 // the correct library paths. 2063 updateAllSharedLibrariesLPw(); 2064 2065 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2066 // NOTE: We ignore potential failures here during a system scan (like 2067 // the rest of the commands above) because there's precious little we 2068 // can do about it. A settings error is reported, though. 2069 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2070 false /* force dexopt */, false /* defer dexopt */); 2071 } 2072 2073 // Now that we know all the packages we are keeping, 2074 // read and update their last usage times. 2075 mPackageUsage.readLP(); 2076 2077 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2078 SystemClock.uptimeMillis()); 2079 Slog.i(TAG, "Time to scan packages: " 2080 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2081 + " seconds"); 2082 2083 // If the platform SDK has changed since the last time we booted, 2084 // we need to re-grant app permission to catch any new ones that 2085 // appear. This is really a hack, and means that apps can in some 2086 // cases get permissions that the user didn't initially explicitly 2087 // allow... it would be nice to have some better way to handle 2088 // this situation. 2089 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2090 != mSdkVersion; 2091 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2092 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2093 + "; regranting permissions for internal storage"); 2094 mSettings.mInternalSdkPlatform = mSdkVersion; 2095 2096 // For now runtime permissions are toggled via a system property. 2097 if (!RUNTIME_PERMISSIONS_ENABLED) { 2098 // Remove the runtime permissions state if the feature 2099 // was disabled by flipping the system property. 2100 mSettings.deleteRuntimePermissionsFiles(); 2101 } 2102 2103 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2104 | (regrantPermissions 2105 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2106 : 0)); 2107 2108 // If this is the first boot, and it is a normal boot, then 2109 // we need to initialize the default preferred apps. 2110 if (!mRestoredSettings && !onlyCore) { 2111 mSettings.readDefaultPreferredAppsLPw(this, 0); 2112 } 2113 2114 // If this is first boot after an OTA, and a normal boot, then 2115 // we need to clear code cache directories. 2116 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2117 if (mIsUpgrade && !onlyCore) { 2118 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2119 for (String pkgName : mSettings.mPackages.keySet()) { 2120 deleteCodeCacheDirsLI(pkgName); 2121 } 2122 mSettings.mFingerprint = Build.FINGERPRINT; 2123 } 2124 2125 // All the changes are done during package scanning. 2126 mSettings.updateInternalDatabaseVersion(); 2127 2128 // can downgrade to reader 2129 mSettings.writeLPr(); 2130 2131 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2132 SystemClock.uptimeMillis()); 2133 2134 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2135 2136 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 2137 2138 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2139 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2140 mIntentFilterVerifierComponent); 2141 2142 } // synchronized (mPackages) 2143 } // synchronized (mInstallLock) 2144 2145 // Now after opening every single application zip, make sure they 2146 // are all flushed. Not really needed, but keeps things nice and 2147 // tidy. 2148 Runtime.getRuntime().gc(); 2149 } 2150 2151 @Override 2152 public boolean isFirstBoot() { 2153 return !mRestoredSettings; 2154 } 2155 2156 @Override 2157 public boolean isOnlyCoreApps() { 2158 return mOnlyCore; 2159 } 2160 2161 @Override 2162 public boolean isUpgrade() { 2163 return mIsUpgrade; 2164 } 2165 2166 private String getRequiredVerifierLPr() { 2167 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2168 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2169 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2170 2171 String requiredVerifier = null; 2172 2173 final int N = receivers.size(); 2174 for (int i = 0; i < N; i++) { 2175 final ResolveInfo info = receivers.get(i); 2176 2177 if (info.activityInfo == null) { 2178 continue; 2179 } 2180 2181 final String packageName = info.activityInfo.packageName; 2182 2183 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2184 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2185 continue; 2186 } 2187 2188 if (requiredVerifier != null) { 2189 throw new RuntimeException("There can be only one required verifier"); 2190 } 2191 2192 requiredVerifier = packageName; 2193 } 2194 2195 return requiredVerifier; 2196 } 2197 2198 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2199 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2200 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2201 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2202 2203 ComponentName verifierComponentName = null; 2204 2205 int priority = -1000; 2206 final int N = receivers.size(); 2207 for (int i = 0; i < N; i++) { 2208 final ResolveInfo info = receivers.get(i); 2209 2210 if (info.activityInfo == null) { 2211 continue; 2212 } 2213 2214 final String packageName = info.activityInfo.packageName; 2215 2216 final PackageSetting ps = mSettings.mPackages.get(packageName); 2217 if (ps == null) { 2218 continue; 2219 } 2220 2221 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2222 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2223 continue; 2224 } 2225 2226 // Select the IntentFilterVerifier with the highest priority 2227 if (priority < info.priority) { 2228 priority = info.priority; 2229 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2230 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2231 " with priority: " + info.priority); 2232 } 2233 } 2234 2235 return verifierComponentName; 2236 } 2237 2238 @Override 2239 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2240 throws RemoteException { 2241 try { 2242 return super.onTransact(code, data, reply, flags); 2243 } catch (RuntimeException e) { 2244 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2245 Slog.wtf(TAG, "Package Manager Crash", e); 2246 } 2247 throw e; 2248 } 2249 } 2250 2251 void cleanupInstallFailedPackage(PackageSetting ps) { 2252 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2253 2254 removeDataDirsLI(ps.name); 2255 if (ps.codePath != null) { 2256 if (ps.codePath.isDirectory()) { 2257 FileUtils.deleteContents(ps.codePath); 2258 } 2259 ps.codePath.delete(); 2260 } 2261 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2262 if (ps.resourcePath.isDirectory()) { 2263 FileUtils.deleteContents(ps.resourcePath); 2264 } 2265 ps.resourcePath.delete(); 2266 } 2267 mSettings.removePackageLPw(ps.name); 2268 } 2269 2270 static int[] appendInts(int[] cur, int[] add) { 2271 if (add == null) return cur; 2272 if (cur == null) return add; 2273 final int N = add.length; 2274 for (int i=0; i<N; i++) { 2275 cur = appendInt(cur, add[i]); 2276 } 2277 return cur; 2278 } 2279 2280 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2281 if (!sUserManager.exists(userId)) return null; 2282 final PackageSetting ps = (PackageSetting) p.mExtras; 2283 if (ps == null) { 2284 return null; 2285 } 2286 2287 final PermissionsState permissionsState = ps.getPermissionsState(); 2288 2289 final int[] gids = permissionsState.computeGids(userId); 2290 final Set<String> permissions = permissionsState.getPermissions(userId); 2291 final PackageUserState state = ps.readUserState(userId); 2292 2293 return PackageParser.generatePackageInfo(p, gids, flags, 2294 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2295 } 2296 2297 @Override 2298 public boolean isPackageAvailable(String packageName, int userId) { 2299 if (!sUserManager.exists(userId)) return false; 2300 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2301 synchronized (mPackages) { 2302 PackageParser.Package p = mPackages.get(packageName); 2303 if (p != null) { 2304 final PackageSetting ps = (PackageSetting) p.mExtras; 2305 if (ps != null) { 2306 final PackageUserState state = ps.readUserState(userId); 2307 if (state != null) { 2308 return PackageParser.isAvailable(state); 2309 } 2310 } 2311 } 2312 } 2313 return false; 2314 } 2315 2316 @Override 2317 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2318 if (!sUserManager.exists(userId)) return null; 2319 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2320 // reader 2321 synchronized (mPackages) { 2322 PackageParser.Package p = mPackages.get(packageName); 2323 if (DEBUG_PACKAGE_INFO) 2324 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2325 if (p != null) { 2326 return generatePackageInfo(p, flags, userId); 2327 } 2328 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2329 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2330 } 2331 } 2332 return null; 2333 } 2334 2335 @Override 2336 public String[] currentToCanonicalPackageNames(String[] names) { 2337 String[] out = new String[names.length]; 2338 // reader 2339 synchronized (mPackages) { 2340 for (int i=names.length-1; i>=0; i--) { 2341 PackageSetting ps = mSettings.mPackages.get(names[i]); 2342 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2343 } 2344 } 2345 return out; 2346 } 2347 2348 @Override 2349 public String[] canonicalToCurrentPackageNames(String[] names) { 2350 String[] out = new String[names.length]; 2351 // reader 2352 synchronized (mPackages) { 2353 for (int i=names.length-1; i>=0; i--) { 2354 String cur = mSettings.mRenamedPackages.get(names[i]); 2355 out[i] = cur != null ? cur : names[i]; 2356 } 2357 } 2358 return out; 2359 } 2360 2361 @Override 2362 public int getPackageUid(String packageName, int userId) { 2363 if (!sUserManager.exists(userId)) return -1; 2364 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2365 2366 // reader 2367 synchronized (mPackages) { 2368 PackageParser.Package p = mPackages.get(packageName); 2369 if(p != null) { 2370 return UserHandle.getUid(userId, p.applicationInfo.uid); 2371 } 2372 PackageSetting ps = mSettings.mPackages.get(packageName); 2373 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2374 return -1; 2375 } 2376 p = ps.pkg; 2377 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2378 } 2379 } 2380 2381 @Override 2382 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2383 if (!sUserManager.exists(userId)) { 2384 return null; 2385 } 2386 2387 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2388 "getPackageGids"); 2389 2390 // reader 2391 synchronized (mPackages) { 2392 PackageParser.Package p = mPackages.get(packageName); 2393 if (DEBUG_PACKAGE_INFO) { 2394 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2395 } 2396 if (p != null) { 2397 PackageSetting ps = (PackageSetting) p.mExtras; 2398 return ps.getPermissionsState().computeGids(userId); 2399 } 2400 } 2401 2402 return null; 2403 } 2404 2405 static PermissionInfo generatePermissionInfo( 2406 BasePermission bp, int flags) { 2407 if (bp.perm != null) { 2408 return PackageParser.generatePermissionInfo(bp.perm, flags); 2409 } 2410 PermissionInfo pi = new PermissionInfo(); 2411 pi.name = bp.name; 2412 pi.packageName = bp.sourcePackage; 2413 pi.nonLocalizedLabel = bp.name; 2414 pi.protectionLevel = bp.protectionLevel; 2415 return pi; 2416 } 2417 2418 @Override 2419 public PermissionInfo getPermissionInfo(String name, int flags) { 2420 // reader 2421 synchronized (mPackages) { 2422 final BasePermission p = mSettings.mPermissions.get(name); 2423 if (p != null) { 2424 return generatePermissionInfo(p, flags); 2425 } 2426 return null; 2427 } 2428 } 2429 2430 @Override 2431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2432 // reader 2433 synchronized (mPackages) { 2434 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2435 for (BasePermission p : mSettings.mPermissions.values()) { 2436 if (group == null) { 2437 if (p.perm == null || p.perm.info.group == null) { 2438 out.add(generatePermissionInfo(p, flags)); 2439 } 2440 } else { 2441 if (p.perm != null && group.equals(p.perm.info.group)) { 2442 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2443 } 2444 } 2445 } 2446 2447 if (out.size() > 0) { 2448 return out; 2449 } 2450 return mPermissionGroups.containsKey(group) ? out : null; 2451 } 2452 } 2453 2454 @Override 2455 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2456 // reader 2457 synchronized (mPackages) { 2458 return PackageParser.generatePermissionGroupInfo( 2459 mPermissionGroups.get(name), flags); 2460 } 2461 } 2462 2463 @Override 2464 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2465 // reader 2466 synchronized (mPackages) { 2467 final int N = mPermissionGroups.size(); 2468 ArrayList<PermissionGroupInfo> out 2469 = new ArrayList<PermissionGroupInfo>(N); 2470 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2471 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2472 } 2473 return out; 2474 } 2475 } 2476 2477 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2478 int userId) { 2479 if (!sUserManager.exists(userId)) return null; 2480 PackageSetting ps = mSettings.mPackages.get(packageName); 2481 if (ps != null) { 2482 if (ps.pkg == null) { 2483 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2484 flags, userId); 2485 if (pInfo != null) { 2486 return pInfo.applicationInfo; 2487 } 2488 return null; 2489 } 2490 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2491 ps.readUserState(userId), userId); 2492 } 2493 return null; 2494 } 2495 2496 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2497 int userId) { 2498 if (!sUserManager.exists(userId)) return null; 2499 PackageSetting ps = mSettings.mPackages.get(packageName); 2500 if (ps != null) { 2501 PackageParser.Package pkg = ps.pkg; 2502 if (pkg == null) { 2503 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2504 return null; 2505 } 2506 // Only data remains, so we aren't worried about code paths 2507 pkg = new PackageParser.Package(packageName); 2508 pkg.applicationInfo.packageName = packageName; 2509 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2510 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2511 pkg.applicationInfo.dataDir = 2512 getDataPathForPackage(packageName, 0).getPath(); 2513 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2514 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2515 } 2516 return generatePackageInfo(pkg, flags, userId); 2517 } 2518 return null; 2519 } 2520 2521 @Override 2522 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2523 if (!sUserManager.exists(userId)) return null; 2524 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2525 // writer 2526 synchronized (mPackages) { 2527 PackageParser.Package p = mPackages.get(packageName); 2528 if (DEBUG_PACKAGE_INFO) Log.v( 2529 TAG, "getApplicationInfo " + packageName 2530 + ": " + p); 2531 if (p != null) { 2532 PackageSetting ps = mSettings.mPackages.get(packageName); 2533 if (ps == null) return null; 2534 // Note: isEnabledLP() does not apply here - always return info 2535 return PackageParser.generateApplicationInfo( 2536 p, flags, ps.readUserState(userId), userId); 2537 } 2538 if ("android".equals(packageName)||"system".equals(packageName)) { 2539 return mAndroidApplication; 2540 } 2541 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2542 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2543 } 2544 } 2545 return null; 2546 } 2547 2548 2549 @Override 2550 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2551 mContext.enforceCallingOrSelfPermission( 2552 android.Manifest.permission.CLEAR_APP_CACHE, null); 2553 // Queue up an async operation since clearing cache may take a little while. 2554 mHandler.post(new Runnable() { 2555 public void run() { 2556 mHandler.removeCallbacks(this); 2557 int retCode = -1; 2558 synchronized (mInstallLock) { 2559 retCode = mInstaller.freeCache(freeStorageSize); 2560 if (retCode < 0) { 2561 Slog.w(TAG, "Couldn't clear application caches"); 2562 } 2563 } 2564 if (observer != null) { 2565 try { 2566 observer.onRemoveCompleted(null, (retCode >= 0)); 2567 } catch (RemoteException e) { 2568 Slog.w(TAG, "RemoveException when invoking call back"); 2569 } 2570 } 2571 } 2572 }); 2573 } 2574 2575 @Override 2576 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2577 mContext.enforceCallingOrSelfPermission( 2578 android.Manifest.permission.CLEAR_APP_CACHE, null); 2579 // Queue up an async operation since clearing cache may take a little while. 2580 mHandler.post(new Runnable() { 2581 public void run() { 2582 mHandler.removeCallbacks(this); 2583 int retCode = -1; 2584 synchronized (mInstallLock) { 2585 retCode = mInstaller.freeCache(freeStorageSize); 2586 if (retCode < 0) { 2587 Slog.w(TAG, "Couldn't clear application caches"); 2588 } 2589 } 2590 if(pi != null) { 2591 try { 2592 // Callback via pending intent 2593 int code = (retCode >= 0) ? 1 : 0; 2594 pi.sendIntent(null, code, null, 2595 null, null); 2596 } catch (SendIntentException e1) { 2597 Slog.i(TAG, "Failed to send pending intent"); 2598 } 2599 } 2600 } 2601 }); 2602 } 2603 2604 void freeStorage(long freeStorageSize) throws IOException { 2605 synchronized (mInstallLock) { 2606 if (mInstaller.freeCache(freeStorageSize) < 0) { 2607 throw new IOException("Failed to free enough space"); 2608 } 2609 } 2610 } 2611 2612 @Override 2613 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2614 if (!sUserManager.exists(userId)) return null; 2615 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2616 synchronized (mPackages) { 2617 PackageParser.Activity a = mActivities.mActivities.get(component); 2618 2619 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2620 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2622 if (ps == null) return null; 2623 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2624 userId); 2625 } 2626 if (mResolveComponentName.equals(component)) { 2627 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2628 new PackageUserState(), userId); 2629 } 2630 } 2631 return null; 2632 } 2633 2634 @Override 2635 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2636 String resolvedType) { 2637 synchronized (mPackages) { 2638 PackageParser.Activity a = mActivities.mActivities.get(component); 2639 if (a == null) { 2640 return false; 2641 } 2642 for (int i=0; i<a.intents.size(); i++) { 2643 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2644 intent.getData(), intent.getCategories(), TAG) >= 0) { 2645 return true; 2646 } 2647 } 2648 return false; 2649 } 2650 } 2651 2652 @Override 2653 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2654 if (!sUserManager.exists(userId)) return null; 2655 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2656 synchronized (mPackages) { 2657 PackageParser.Activity a = mReceivers.mActivities.get(component); 2658 if (DEBUG_PACKAGE_INFO) Log.v( 2659 TAG, "getReceiverInfo " + component + ": " + a); 2660 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2661 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2662 if (ps == null) return null; 2663 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2664 userId); 2665 } 2666 } 2667 return null; 2668 } 2669 2670 @Override 2671 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2672 if (!sUserManager.exists(userId)) return null; 2673 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2674 synchronized (mPackages) { 2675 PackageParser.Service s = mServices.mServices.get(component); 2676 if (DEBUG_PACKAGE_INFO) Log.v( 2677 TAG, "getServiceInfo " + component + ": " + s); 2678 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2679 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2680 if (ps == null) return null; 2681 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2682 userId); 2683 } 2684 } 2685 return null; 2686 } 2687 2688 @Override 2689 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2690 if (!sUserManager.exists(userId)) return null; 2691 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2692 synchronized (mPackages) { 2693 PackageParser.Provider p = mProviders.mProviders.get(component); 2694 if (DEBUG_PACKAGE_INFO) Log.v( 2695 TAG, "getProviderInfo " + component + ": " + p); 2696 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2697 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2698 if (ps == null) return null; 2699 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2700 userId); 2701 } 2702 } 2703 return null; 2704 } 2705 2706 @Override 2707 public String[] getSystemSharedLibraryNames() { 2708 Set<String> libSet; 2709 synchronized (mPackages) { 2710 libSet = mSharedLibraries.keySet(); 2711 int size = libSet.size(); 2712 if (size > 0) { 2713 String[] libs = new String[size]; 2714 libSet.toArray(libs); 2715 return libs; 2716 } 2717 } 2718 return null; 2719 } 2720 2721 /** 2722 * @hide 2723 */ 2724 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2725 synchronized (mPackages) { 2726 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2727 if (lib != null && lib.apk != null) { 2728 return mPackages.get(lib.apk); 2729 } 2730 } 2731 return null; 2732 } 2733 2734 @Override 2735 public FeatureInfo[] getSystemAvailableFeatures() { 2736 Collection<FeatureInfo> featSet; 2737 synchronized (mPackages) { 2738 featSet = mAvailableFeatures.values(); 2739 int size = featSet.size(); 2740 if (size > 0) { 2741 FeatureInfo[] features = new FeatureInfo[size+1]; 2742 featSet.toArray(features); 2743 FeatureInfo fi = new FeatureInfo(); 2744 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2745 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2746 features[size] = fi; 2747 return features; 2748 } 2749 } 2750 return null; 2751 } 2752 2753 @Override 2754 public boolean hasSystemFeature(String name) { 2755 synchronized (mPackages) { 2756 return mAvailableFeatures.containsKey(name); 2757 } 2758 } 2759 2760 private void checkValidCaller(int uid, int userId) { 2761 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2762 return; 2763 2764 throw new SecurityException("Caller uid=" + uid 2765 + " is not privileged to communicate with user=" + userId); 2766 } 2767 2768 @Override 2769 public int checkPermission(String permName, String pkgName, int userId) { 2770 if (!sUserManager.exists(userId)) { 2771 return PackageManager.PERMISSION_DENIED; 2772 } 2773 2774 synchronized (mPackages) { 2775 final PackageParser.Package p = mPackages.get(pkgName); 2776 if (p != null && p.mExtras != null) { 2777 final PackageSetting ps = (PackageSetting) p.mExtras; 2778 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2779 return PackageManager.PERMISSION_GRANTED; 2780 } 2781 } 2782 } 2783 2784 return PackageManager.PERMISSION_DENIED; 2785 } 2786 2787 @Override 2788 public int checkUidPermission(String permName, int uid) { 2789 final int userId = UserHandle.getUserId(uid); 2790 2791 if (!sUserManager.exists(userId)) { 2792 return PackageManager.PERMISSION_DENIED; 2793 } 2794 2795 synchronized (mPackages) { 2796 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2797 if (obj != null) { 2798 final SettingBase ps = (SettingBase) obj; 2799 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2800 return PackageManager.PERMISSION_GRANTED; 2801 } 2802 } else { 2803 ArraySet<String> perms = mSystemPermissions.get(uid); 2804 if (perms != null && perms.contains(permName)) { 2805 return PackageManager.PERMISSION_GRANTED; 2806 } 2807 } 2808 } 2809 2810 return PackageManager.PERMISSION_DENIED; 2811 } 2812 2813 /** 2814 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2815 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2816 * @param checkShell TODO(yamasani): 2817 * @param message the message to log on security exception 2818 */ 2819 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2820 boolean checkShell, String message) { 2821 if (userId < 0) { 2822 throw new IllegalArgumentException("Invalid userId " + userId); 2823 } 2824 if (checkShell) { 2825 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2826 } 2827 if (userId == UserHandle.getUserId(callingUid)) return; 2828 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2829 if (requireFullPermission) { 2830 mContext.enforceCallingOrSelfPermission( 2831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2832 } else { 2833 try { 2834 mContext.enforceCallingOrSelfPermission( 2835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2836 } catch (SecurityException se) { 2837 mContext.enforceCallingOrSelfPermission( 2838 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2839 } 2840 } 2841 } 2842 } 2843 2844 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2845 if (callingUid == Process.SHELL_UID) { 2846 if (userHandle >= 0 2847 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2848 throw new SecurityException("Shell does not have permission to access user " 2849 + userHandle); 2850 } else if (userHandle < 0) { 2851 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2852 + Debug.getCallers(3)); 2853 } 2854 } 2855 } 2856 2857 private BasePermission findPermissionTreeLP(String permName) { 2858 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2859 if (permName.startsWith(bp.name) && 2860 permName.length() > bp.name.length() && 2861 permName.charAt(bp.name.length()) == '.') { 2862 return bp; 2863 } 2864 } 2865 return null; 2866 } 2867 2868 private BasePermission checkPermissionTreeLP(String permName) { 2869 if (permName != null) { 2870 BasePermission bp = findPermissionTreeLP(permName); 2871 if (bp != null) { 2872 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2873 return bp; 2874 } 2875 throw new SecurityException("Calling uid " 2876 + Binder.getCallingUid() 2877 + " is not allowed to add to permission tree " 2878 + bp.name + " owned by uid " + bp.uid); 2879 } 2880 } 2881 throw new SecurityException("No permission tree found for " + permName); 2882 } 2883 2884 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2885 if (s1 == null) { 2886 return s2 == null; 2887 } 2888 if (s2 == null) { 2889 return false; 2890 } 2891 if (s1.getClass() != s2.getClass()) { 2892 return false; 2893 } 2894 return s1.equals(s2); 2895 } 2896 2897 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2898 if (pi1.icon != pi2.icon) return false; 2899 if (pi1.logo != pi2.logo) return false; 2900 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2901 if (!compareStrings(pi1.name, pi2.name)) return false; 2902 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2903 // We'll take care of setting this one. 2904 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2905 // These are not currently stored in settings. 2906 //if (!compareStrings(pi1.group, pi2.group)) return false; 2907 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2908 //if (pi1.labelRes != pi2.labelRes) return false; 2909 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2910 return true; 2911 } 2912 2913 int permissionInfoFootprint(PermissionInfo info) { 2914 int size = info.name.length(); 2915 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2916 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2917 return size; 2918 } 2919 2920 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2921 int size = 0; 2922 for (BasePermission perm : mSettings.mPermissions.values()) { 2923 if (perm.uid == tree.uid) { 2924 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2925 } 2926 } 2927 return size; 2928 } 2929 2930 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2931 // We calculate the max size of permissions defined by this uid and throw 2932 // if that plus the size of 'info' would exceed our stated maximum. 2933 if (tree.uid != Process.SYSTEM_UID) { 2934 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2935 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2936 throw new SecurityException("Permission tree size cap exceeded"); 2937 } 2938 } 2939 } 2940 2941 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2942 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2943 throw new SecurityException("Label must be specified in permission"); 2944 } 2945 BasePermission tree = checkPermissionTreeLP(info.name); 2946 BasePermission bp = mSettings.mPermissions.get(info.name); 2947 boolean added = bp == null; 2948 boolean changed = true; 2949 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2950 if (added) { 2951 enforcePermissionCapLocked(info, tree); 2952 bp = new BasePermission(info.name, tree.sourcePackage, 2953 BasePermission.TYPE_DYNAMIC); 2954 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2955 throw new SecurityException( 2956 "Not allowed to modify non-dynamic permission " 2957 + info.name); 2958 } else { 2959 if (bp.protectionLevel == fixedLevel 2960 && bp.perm.owner.equals(tree.perm.owner) 2961 && bp.uid == tree.uid 2962 && comparePermissionInfos(bp.perm.info, info)) { 2963 changed = false; 2964 } 2965 } 2966 bp.protectionLevel = fixedLevel; 2967 info = new PermissionInfo(info); 2968 info.protectionLevel = fixedLevel; 2969 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2970 bp.perm.info.packageName = tree.perm.info.packageName; 2971 bp.uid = tree.uid; 2972 if (added) { 2973 mSettings.mPermissions.put(info.name, bp); 2974 } 2975 if (changed) { 2976 if (!async) { 2977 mSettings.writeLPr(); 2978 } else { 2979 scheduleWriteSettingsLocked(); 2980 } 2981 } 2982 return added; 2983 } 2984 2985 @Override 2986 public boolean addPermission(PermissionInfo info) { 2987 synchronized (mPackages) { 2988 return addPermissionLocked(info, false); 2989 } 2990 } 2991 2992 @Override 2993 public boolean addPermissionAsync(PermissionInfo info) { 2994 synchronized (mPackages) { 2995 return addPermissionLocked(info, true); 2996 } 2997 } 2998 2999 @Override 3000 public void removePermission(String name) { 3001 synchronized (mPackages) { 3002 checkPermissionTreeLP(name); 3003 BasePermission bp = mSettings.mPermissions.get(name); 3004 if (bp != null) { 3005 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3006 throw new SecurityException( 3007 "Not allowed to modify non-dynamic permission " 3008 + name); 3009 } 3010 mSettings.mPermissions.remove(name); 3011 mSettings.writeLPr(); 3012 } 3013 } 3014 } 3015 3016 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3017 BasePermission bp) { 3018 int index = pkg.requestedPermissions.indexOf(bp.name); 3019 if (index == -1) { 3020 throw new SecurityException("Package " + pkg.packageName 3021 + " has not requested permission " + bp.name); 3022 } 3023 if (!bp.isRuntime()) { 3024 throw new SecurityException("Permission " + bp.name 3025 + " is not a changeable permission type"); 3026 } 3027 } 3028 3029 @Override 3030 public boolean grantPermission(String packageName, String name, int userId) { 3031 if (!RUNTIME_PERMISSIONS_ENABLED) { 3032 return false; 3033 } 3034 3035 if (!sUserManager.exists(userId)) { 3036 return false; 3037 } 3038 3039 mContext.enforceCallingOrSelfPermission( 3040 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3041 "grantPermission"); 3042 3043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3044 "grantPermission"); 3045 3046 boolean gidsChanged = false; 3047 final SettingBase sb; 3048 3049 synchronized (mPackages) { 3050 final PackageParser.Package pkg = mPackages.get(packageName); 3051 if (pkg == null) { 3052 throw new IllegalArgumentException("Unknown package: " + packageName); 3053 } 3054 3055 final BasePermission bp = mSettings.mPermissions.get(name); 3056 if (bp == null) { 3057 throw new IllegalArgumentException("Unknown permission: " + name); 3058 } 3059 3060 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3061 3062 sb = (SettingBase) pkg.mExtras; 3063 if (sb == null) { 3064 throw new IllegalArgumentException("Unknown package: " + packageName); 3065 } 3066 3067 final PermissionsState permissionsState = sb.getPermissionsState(); 3068 3069 final int result = permissionsState.grantRuntimePermission(bp, userId); 3070 switch (result) { 3071 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3072 return false; 3073 } 3074 3075 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3076 gidsChanged = true; 3077 } break; 3078 } 3079 3080 // Not critical if that is lost - app has to request again. 3081 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3082 } 3083 3084 if (gidsChanged) { 3085 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3086 } 3087 3088 return true; 3089 } 3090 3091 @Override 3092 public boolean revokePermission(String packageName, String name, int userId) { 3093 if (!RUNTIME_PERMISSIONS_ENABLED) { 3094 return false; 3095 } 3096 3097 if (!sUserManager.exists(userId)) { 3098 return false; 3099 } 3100 3101 mContext.enforceCallingOrSelfPermission( 3102 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3103 "revokePermission"); 3104 3105 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3106 "revokePermission"); 3107 3108 final SettingBase sb; 3109 3110 synchronized (mPackages) { 3111 final PackageParser.Package pkg = mPackages.get(packageName); 3112 if (pkg == null) { 3113 throw new IllegalArgumentException("Unknown package: " + packageName); 3114 } 3115 3116 final BasePermission bp = mSettings.mPermissions.get(name); 3117 if (bp == null) { 3118 throw new IllegalArgumentException("Unknown permission: " + name); 3119 } 3120 3121 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3122 3123 sb = (SettingBase) pkg.mExtras; 3124 if (sb == null) { 3125 throw new IllegalArgumentException("Unknown package: " + packageName); 3126 } 3127 3128 final PermissionsState permissionsState = sb.getPermissionsState(); 3129 3130 if (permissionsState.revokeRuntimePermission(bp, userId) == 3131 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3132 return false; 3133 } 3134 3135 // Critical, after this call all should never have the permission. 3136 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3137 } 3138 3139 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3140 3141 return true; 3142 } 3143 3144 @Override 3145 public boolean isProtectedBroadcast(String actionName) { 3146 synchronized (mPackages) { 3147 return mProtectedBroadcasts.contains(actionName); 3148 } 3149 } 3150 3151 @Override 3152 public int checkSignatures(String pkg1, String pkg2) { 3153 synchronized (mPackages) { 3154 final PackageParser.Package p1 = mPackages.get(pkg1); 3155 final PackageParser.Package p2 = mPackages.get(pkg2); 3156 if (p1 == null || p1.mExtras == null 3157 || p2 == null || p2.mExtras == null) { 3158 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3159 } 3160 return compareSignatures(p1.mSignatures, p2.mSignatures); 3161 } 3162 } 3163 3164 @Override 3165 public int checkUidSignatures(int uid1, int uid2) { 3166 // Map to base uids. 3167 uid1 = UserHandle.getAppId(uid1); 3168 uid2 = UserHandle.getAppId(uid2); 3169 // reader 3170 synchronized (mPackages) { 3171 Signature[] s1; 3172 Signature[] s2; 3173 Object obj = mSettings.getUserIdLPr(uid1); 3174 if (obj != null) { 3175 if (obj instanceof SharedUserSetting) { 3176 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3177 } else if (obj instanceof PackageSetting) { 3178 s1 = ((PackageSetting)obj).signatures.mSignatures; 3179 } else { 3180 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3181 } 3182 } else { 3183 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3184 } 3185 obj = mSettings.getUserIdLPr(uid2); 3186 if (obj != null) { 3187 if (obj instanceof SharedUserSetting) { 3188 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3189 } else if (obj instanceof PackageSetting) { 3190 s2 = ((PackageSetting)obj).signatures.mSignatures; 3191 } else { 3192 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3193 } 3194 } else { 3195 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3196 } 3197 return compareSignatures(s1, s2); 3198 } 3199 } 3200 3201 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3202 final long identity = Binder.clearCallingIdentity(); 3203 try { 3204 if (sb instanceof SharedUserSetting) { 3205 SharedUserSetting sus = (SharedUserSetting) sb; 3206 final int packageCount = sus.packages.size(); 3207 for (int i = 0; i < packageCount; i++) { 3208 PackageSetting susPs = sus.packages.valueAt(i); 3209 if (userId == UserHandle.USER_ALL) { 3210 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3211 } else { 3212 final int uid = UserHandle.getUid(userId, susPs.appId); 3213 killUid(uid, reason); 3214 } 3215 } 3216 } else if (sb instanceof PackageSetting) { 3217 PackageSetting ps = (PackageSetting) sb; 3218 if (userId == UserHandle.USER_ALL) { 3219 killApplication(ps.pkg.packageName, ps.appId, reason); 3220 } else { 3221 final int uid = UserHandle.getUid(userId, ps.appId); 3222 killUid(uid, reason); 3223 } 3224 } 3225 } finally { 3226 Binder.restoreCallingIdentity(identity); 3227 } 3228 } 3229 3230 private static void killUid(int uid, String reason) { 3231 IActivityManager am = ActivityManagerNative.getDefault(); 3232 if (am != null) { 3233 try { 3234 am.killUid(uid, reason); 3235 } catch (RemoteException e) { 3236 /* ignore - same process */ 3237 } 3238 } 3239 } 3240 3241 /** 3242 * Compares two sets of signatures. Returns: 3243 * <br /> 3244 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3245 * <br /> 3246 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3247 * <br /> 3248 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3249 * <br /> 3250 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3251 * <br /> 3252 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3253 */ 3254 static int compareSignatures(Signature[] s1, Signature[] s2) { 3255 if (s1 == null) { 3256 return s2 == null 3257 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3258 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3259 } 3260 3261 if (s2 == null) { 3262 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3263 } 3264 3265 if (s1.length != s2.length) { 3266 return PackageManager.SIGNATURE_NO_MATCH; 3267 } 3268 3269 // Since both signature sets are of size 1, we can compare without HashSets. 3270 if (s1.length == 1) { 3271 return s1[0].equals(s2[0]) ? 3272 PackageManager.SIGNATURE_MATCH : 3273 PackageManager.SIGNATURE_NO_MATCH; 3274 } 3275 3276 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3277 for (Signature sig : s1) { 3278 set1.add(sig); 3279 } 3280 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3281 for (Signature sig : s2) { 3282 set2.add(sig); 3283 } 3284 // Make sure s2 contains all signatures in s1. 3285 if (set1.equals(set2)) { 3286 return PackageManager.SIGNATURE_MATCH; 3287 } 3288 return PackageManager.SIGNATURE_NO_MATCH; 3289 } 3290 3291 /** 3292 * If the database version for this type of package (internal storage or 3293 * external storage) is less than the version where package signatures 3294 * were updated, return true. 3295 */ 3296 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3297 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3298 DatabaseVersion.SIGNATURE_END_ENTITY)) 3299 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3300 DatabaseVersion.SIGNATURE_END_ENTITY)); 3301 } 3302 3303 /** 3304 * Used for backward compatibility to make sure any packages with 3305 * certificate chains get upgraded to the new style. {@code existingSigs} 3306 * will be in the old format (since they were stored on disk from before the 3307 * system upgrade) and {@code scannedSigs} will be in the newer format. 3308 */ 3309 private int compareSignaturesCompat(PackageSignatures existingSigs, 3310 PackageParser.Package scannedPkg) { 3311 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3312 return PackageManager.SIGNATURE_NO_MATCH; 3313 } 3314 3315 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3316 for (Signature sig : existingSigs.mSignatures) { 3317 existingSet.add(sig); 3318 } 3319 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3320 for (Signature sig : scannedPkg.mSignatures) { 3321 try { 3322 Signature[] chainSignatures = sig.getChainSignatures(); 3323 for (Signature chainSig : chainSignatures) { 3324 scannedCompatSet.add(chainSig); 3325 } 3326 } catch (CertificateEncodingException e) { 3327 scannedCompatSet.add(sig); 3328 } 3329 } 3330 /* 3331 * Make sure the expanded scanned set contains all signatures in the 3332 * existing one. 3333 */ 3334 if (scannedCompatSet.equals(existingSet)) { 3335 // Migrate the old signatures to the new scheme. 3336 existingSigs.assignSignatures(scannedPkg.mSignatures); 3337 // The new KeySets will be re-added later in the scanning process. 3338 synchronized (mPackages) { 3339 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3340 } 3341 return PackageManager.SIGNATURE_MATCH; 3342 } 3343 return PackageManager.SIGNATURE_NO_MATCH; 3344 } 3345 3346 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3347 if (isExternal(scannedPkg)) { 3348 return mSettings.isExternalDatabaseVersionOlderThan( 3349 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3350 } else { 3351 return mSettings.isInternalDatabaseVersionOlderThan( 3352 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3353 } 3354 } 3355 3356 private int compareSignaturesRecover(PackageSignatures existingSigs, 3357 PackageParser.Package scannedPkg) { 3358 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3359 return PackageManager.SIGNATURE_NO_MATCH; 3360 } 3361 3362 String msg = null; 3363 try { 3364 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3365 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3366 + scannedPkg.packageName); 3367 return PackageManager.SIGNATURE_MATCH; 3368 } 3369 } catch (CertificateException e) { 3370 msg = e.getMessage(); 3371 } 3372 3373 logCriticalInfo(Log.INFO, 3374 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3375 return PackageManager.SIGNATURE_NO_MATCH; 3376 } 3377 3378 @Override 3379 public String[] getPackagesForUid(int uid) { 3380 uid = UserHandle.getAppId(uid); 3381 // reader 3382 synchronized (mPackages) { 3383 Object obj = mSettings.getUserIdLPr(uid); 3384 if (obj instanceof SharedUserSetting) { 3385 final SharedUserSetting sus = (SharedUserSetting) obj; 3386 final int N = sus.packages.size(); 3387 final String[] res = new String[N]; 3388 final Iterator<PackageSetting> it = sus.packages.iterator(); 3389 int i = 0; 3390 while (it.hasNext()) { 3391 res[i++] = it.next().name; 3392 } 3393 return res; 3394 } else if (obj instanceof PackageSetting) { 3395 final PackageSetting ps = (PackageSetting) obj; 3396 return new String[] { ps.name }; 3397 } 3398 } 3399 return null; 3400 } 3401 3402 @Override 3403 public String getNameForUid(int uid) { 3404 // reader 3405 synchronized (mPackages) { 3406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3407 if (obj instanceof SharedUserSetting) { 3408 final SharedUserSetting sus = (SharedUserSetting) obj; 3409 return sus.name + ":" + sus.userId; 3410 } else if (obj instanceof PackageSetting) { 3411 final PackageSetting ps = (PackageSetting) obj; 3412 return ps.name; 3413 } 3414 } 3415 return null; 3416 } 3417 3418 @Override 3419 public int getUidForSharedUser(String sharedUserName) { 3420 if(sharedUserName == null) { 3421 return -1; 3422 } 3423 // reader 3424 synchronized (mPackages) { 3425 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3426 if (suid == null) { 3427 return -1; 3428 } 3429 return suid.userId; 3430 } 3431 } 3432 3433 @Override 3434 public int getFlagsForUid(int uid) { 3435 synchronized (mPackages) { 3436 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3437 if (obj instanceof SharedUserSetting) { 3438 final SharedUserSetting sus = (SharedUserSetting) obj; 3439 return sus.pkgFlags; 3440 } else if (obj instanceof PackageSetting) { 3441 final PackageSetting ps = (PackageSetting) obj; 3442 return ps.pkgFlags; 3443 } 3444 } 3445 return 0; 3446 } 3447 3448 @Override 3449 public int getPrivateFlagsForUid(int uid) { 3450 synchronized (mPackages) { 3451 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3452 if (obj instanceof SharedUserSetting) { 3453 final SharedUserSetting sus = (SharedUserSetting) obj; 3454 return sus.pkgPrivateFlags; 3455 } else if (obj instanceof PackageSetting) { 3456 final PackageSetting ps = (PackageSetting) obj; 3457 return ps.pkgPrivateFlags; 3458 } 3459 } 3460 return 0; 3461 } 3462 3463 @Override 3464 public boolean isUidPrivileged(int uid) { 3465 uid = UserHandle.getAppId(uid); 3466 // reader 3467 synchronized (mPackages) { 3468 Object obj = mSettings.getUserIdLPr(uid); 3469 if (obj instanceof SharedUserSetting) { 3470 final SharedUserSetting sus = (SharedUserSetting) obj; 3471 final Iterator<PackageSetting> it = sus.packages.iterator(); 3472 while (it.hasNext()) { 3473 if (it.next().isPrivileged()) { 3474 return true; 3475 } 3476 } 3477 } else if (obj instanceof PackageSetting) { 3478 final PackageSetting ps = (PackageSetting) obj; 3479 return ps.isPrivileged(); 3480 } 3481 } 3482 return false; 3483 } 3484 3485 @Override 3486 public String[] getAppOpPermissionPackages(String permissionName) { 3487 synchronized (mPackages) { 3488 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3489 if (pkgs == null) { 3490 return null; 3491 } 3492 return pkgs.toArray(new String[pkgs.size()]); 3493 } 3494 } 3495 3496 @Override 3497 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3498 int flags, int userId) { 3499 if (!sUserManager.exists(userId)) return null; 3500 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3501 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3502 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3503 } 3504 3505 @Override 3506 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3507 IntentFilter filter, int match, ComponentName activity) { 3508 final int userId = UserHandle.getCallingUserId(); 3509 if (DEBUG_PREFERRED) { 3510 Log.v(TAG, "setLastChosenActivity intent=" + intent 3511 + " resolvedType=" + resolvedType 3512 + " flags=" + flags 3513 + " filter=" + filter 3514 + " match=" + match 3515 + " activity=" + activity); 3516 filter.dump(new PrintStreamPrinter(System.out), " "); 3517 } 3518 intent.setComponent(null); 3519 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3520 // Find any earlier preferred or last chosen entries and nuke them 3521 findPreferredActivity(intent, resolvedType, 3522 flags, query, 0, false, true, false, userId); 3523 // Add the new activity as the last chosen for this filter 3524 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3525 "Setting last chosen"); 3526 } 3527 3528 @Override 3529 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3530 final int userId = UserHandle.getCallingUserId(); 3531 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3532 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3533 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3534 false, false, false, userId); 3535 } 3536 3537 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3538 int flags, List<ResolveInfo> query, int userId) { 3539 if (query != null) { 3540 final int N = query.size(); 3541 if (N == 1) { 3542 return query.get(0); 3543 } else if (N > 1) { 3544 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3545 // If there is more than one activity with the same priority, 3546 // then let the user decide between them. 3547 ResolveInfo r0 = query.get(0); 3548 ResolveInfo r1 = query.get(1); 3549 if (DEBUG_INTENT_MATCHING || debug) { 3550 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3551 + r1.activityInfo.name + "=" + r1.priority); 3552 } 3553 // If the first activity has a higher priority, or a different 3554 // default, then it is always desireable to pick it. 3555 if (r0.priority != r1.priority 3556 || r0.preferredOrder != r1.preferredOrder 3557 || r0.isDefault != r1.isDefault) { 3558 return query.get(0); 3559 } 3560 // If we have saved a preference for a preferred activity for 3561 // this Intent, use that. 3562 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3563 flags, query, r0.priority, true, false, debug, userId); 3564 if (ri != null) { 3565 return ri; 3566 } 3567 if (userId != 0) { 3568 ri = new ResolveInfo(mResolveInfo); 3569 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3570 ri.activityInfo.applicationInfo = new ApplicationInfo( 3571 ri.activityInfo.applicationInfo); 3572 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3573 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3574 return ri; 3575 } 3576 return mResolveInfo; 3577 } 3578 } 3579 return null; 3580 } 3581 3582 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3583 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3584 final int N = query.size(); 3585 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3586 .get(userId); 3587 // Get the list of persistent preferred activities that handle the intent 3588 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3589 List<PersistentPreferredActivity> pprefs = ppir != null 3590 ? ppir.queryIntent(intent, resolvedType, 3591 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3592 : null; 3593 if (pprefs != null && pprefs.size() > 0) { 3594 final int M = pprefs.size(); 3595 for (int i=0; i<M; i++) { 3596 final PersistentPreferredActivity ppa = pprefs.get(i); 3597 if (DEBUG_PREFERRED || debug) { 3598 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3599 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3600 + "\n component=" + ppa.mComponent); 3601 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3602 } 3603 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3604 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3605 if (DEBUG_PREFERRED || debug) { 3606 Slog.v(TAG, "Found persistent preferred activity:"); 3607 if (ai != null) { 3608 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3609 } else { 3610 Slog.v(TAG, " null"); 3611 } 3612 } 3613 if (ai == null) { 3614 // This previously registered persistent preferred activity 3615 // component is no longer known. Ignore it and do NOT remove it. 3616 continue; 3617 } 3618 for (int j=0; j<N; j++) { 3619 final ResolveInfo ri = query.get(j); 3620 if (!ri.activityInfo.applicationInfo.packageName 3621 .equals(ai.applicationInfo.packageName)) { 3622 continue; 3623 } 3624 if (!ri.activityInfo.name.equals(ai.name)) { 3625 continue; 3626 } 3627 // Found a persistent preference that can handle the intent. 3628 if (DEBUG_PREFERRED || debug) { 3629 Slog.v(TAG, "Returning persistent preferred activity: " + 3630 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3631 } 3632 return ri; 3633 } 3634 } 3635 } 3636 return null; 3637 } 3638 3639 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3640 List<ResolveInfo> query, int priority, boolean always, 3641 boolean removeMatches, boolean debug, int userId) { 3642 if (!sUserManager.exists(userId)) return null; 3643 // writer 3644 synchronized (mPackages) { 3645 if (intent.getSelector() != null) { 3646 intent = intent.getSelector(); 3647 } 3648 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3649 3650 // Try to find a matching persistent preferred activity. 3651 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3652 debug, userId); 3653 3654 // If a persistent preferred activity matched, use it. 3655 if (pri != null) { 3656 return pri; 3657 } 3658 3659 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3660 // Get the list of preferred activities that handle the intent 3661 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3662 List<PreferredActivity> prefs = pir != null 3663 ? pir.queryIntent(intent, resolvedType, 3664 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3665 : null; 3666 if (prefs != null && prefs.size() > 0) { 3667 boolean changed = false; 3668 try { 3669 // First figure out how good the original match set is. 3670 // We will only allow preferred activities that came 3671 // from the same match quality. 3672 int match = 0; 3673 3674 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3675 3676 final int N = query.size(); 3677 for (int j=0; j<N; j++) { 3678 final ResolveInfo ri = query.get(j); 3679 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3680 + ": 0x" + Integer.toHexString(match)); 3681 if (ri.match > match) { 3682 match = ri.match; 3683 } 3684 } 3685 3686 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3687 + Integer.toHexString(match)); 3688 3689 match &= IntentFilter.MATCH_CATEGORY_MASK; 3690 final int M = prefs.size(); 3691 for (int i=0; i<M; i++) { 3692 final PreferredActivity pa = prefs.get(i); 3693 if (DEBUG_PREFERRED || debug) { 3694 Slog.v(TAG, "Checking PreferredActivity ds=" 3695 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3696 + "\n component=" + pa.mPref.mComponent); 3697 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3698 } 3699 if (pa.mPref.mMatch != match) { 3700 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3701 + Integer.toHexString(pa.mPref.mMatch)); 3702 continue; 3703 } 3704 // If it's not an "always" type preferred activity and that's what we're 3705 // looking for, skip it. 3706 if (always && !pa.mPref.mAlways) { 3707 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3708 continue; 3709 } 3710 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3711 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3712 if (DEBUG_PREFERRED || debug) { 3713 Slog.v(TAG, "Found preferred activity:"); 3714 if (ai != null) { 3715 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3716 } else { 3717 Slog.v(TAG, " null"); 3718 } 3719 } 3720 if (ai == null) { 3721 // This previously registered preferred activity 3722 // component is no longer known. Most likely an update 3723 // to the app was installed and in the new version this 3724 // component no longer exists. Clean it up by removing 3725 // it from the preferred activities list, and skip it. 3726 Slog.w(TAG, "Removing dangling preferred activity: " 3727 + pa.mPref.mComponent); 3728 pir.removeFilter(pa); 3729 changed = true; 3730 continue; 3731 } 3732 for (int j=0; j<N; j++) { 3733 final ResolveInfo ri = query.get(j); 3734 if (!ri.activityInfo.applicationInfo.packageName 3735 .equals(ai.applicationInfo.packageName)) { 3736 continue; 3737 } 3738 if (!ri.activityInfo.name.equals(ai.name)) { 3739 continue; 3740 } 3741 3742 if (removeMatches) { 3743 pir.removeFilter(pa); 3744 changed = true; 3745 if (DEBUG_PREFERRED) { 3746 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3747 } 3748 break; 3749 } 3750 3751 // Okay we found a previously set preferred or last chosen app. 3752 // If the result set is different from when this 3753 // was created, we need to clear it and re-ask the 3754 // user their preference, if we're looking for an "always" type entry. 3755 if (always && !pa.mPref.sameSet(query)) { 3756 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3757 + intent + " type " + resolvedType); 3758 if (DEBUG_PREFERRED) { 3759 Slog.v(TAG, "Removing preferred activity since set changed " 3760 + pa.mPref.mComponent); 3761 } 3762 pir.removeFilter(pa); 3763 // Re-add the filter as a "last chosen" entry (!always) 3764 PreferredActivity lastChosen = new PreferredActivity( 3765 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3766 pir.addFilter(lastChosen); 3767 changed = true; 3768 return null; 3769 } 3770 3771 // Yay! Either the set matched or we're looking for the last chosen 3772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3773 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3774 return ri; 3775 } 3776 } 3777 } finally { 3778 if (changed) { 3779 if (DEBUG_PREFERRED) { 3780 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3781 } 3782 scheduleWritePackageRestrictionsLocked(userId); 3783 } 3784 } 3785 } 3786 } 3787 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3788 return null; 3789 } 3790 3791 /* 3792 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3793 */ 3794 @Override 3795 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3796 int targetUserId) { 3797 mContext.enforceCallingOrSelfPermission( 3798 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3799 List<CrossProfileIntentFilter> matches = 3800 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3801 if (matches != null) { 3802 int size = matches.size(); 3803 for (int i = 0; i < size; i++) { 3804 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3805 } 3806 } 3807 return false; 3808 } 3809 3810 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3811 String resolvedType, int userId) { 3812 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3813 if (resolver != null) { 3814 return resolver.queryIntent(intent, resolvedType, false, userId); 3815 } 3816 return null; 3817 } 3818 3819 @Override 3820 public List<ResolveInfo> queryIntentActivities(Intent intent, 3821 String resolvedType, int flags, int userId) { 3822 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3823 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3824 ComponentName comp = intent.getComponent(); 3825 if (comp == null) { 3826 if (intent.getSelector() != null) { 3827 intent = intent.getSelector(); 3828 comp = intent.getComponent(); 3829 } 3830 } 3831 3832 if (comp != null) { 3833 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3834 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3835 if (ai != null) { 3836 final ResolveInfo ri = new ResolveInfo(); 3837 ri.activityInfo = ai; 3838 list.add(ri); 3839 } 3840 return list; 3841 } 3842 3843 // reader 3844 synchronized (mPackages) { 3845 final String pkgName = intent.getPackage(); 3846 if (pkgName == null) { 3847 List<CrossProfileIntentFilter> matchingFilters = 3848 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3849 // Check for results that need to skip the current profile. 3850 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3851 resolvedType, flags, userId); 3852 if (resolveInfo != null) { 3853 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3854 result.add(resolveInfo); 3855 return filterIfNotPrimaryUser(result, userId); 3856 } 3857 // Check for cross profile results. 3858 resolveInfo = queryCrossProfileIntents( 3859 matchingFilters, intent, resolvedType, flags, userId); 3860 3861 // Check for results in the current profile. Adding GET_RESOLVED_FILTER flags 3862 // as we need it later 3863 List<ResolveInfo> result = mActivities.queryIntent( 3864 intent, resolvedType, flags, userId); 3865 if (resolveInfo != null) { 3866 result.add(resolveInfo); 3867 Collections.sort(result, mResolvePrioritySorter); 3868 } 3869 result = filterIfNotPrimaryUser(result, userId); 3870 if (result.size() > 1) { 3871 return filterCandidatesWithDomainPreferedActivitiesLPw(result); 3872 } 3873 3874 return result; 3875 } 3876 final PackageParser.Package pkg = mPackages.get(pkgName); 3877 if (pkg != null) { 3878 return filterIfNotPrimaryUser( 3879 mActivities.queryIntentForPackage( 3880 intent, resolvedType, flags, pkg.activities, userId), 3881 userId); 3882 } 3883 return new ArrayList<ResolveInfo>(); 3884 } 3885 } 3886 3887 /** 3888 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3889 * 3890 * @return filtered list 3891 */ 3892 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3893 if (userId == UserHandle.USER_OWNER) { 3894 return resolveInfos; 3895 } 3896 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3897 ResolveInfo info = resolveInfos.get(i); 3898 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3899 resolveInfos.remove(i); 3900 } 3901 } 3902 return resolveInfos; 3903 } 3904 3905 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPw( 3906 List<ResolveInfo> candidates) { 3907 if (DEBUG_PREFERRED) { 3908 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3909 candidates.size()); 3910 } 3911 final int userId = UserHandle.getCallingUserId(); 3912 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(candidates); 3913 synchronized (mPackages) { 3914 final int count = result.size(); 3915 for (int n = count-1; n >= 0; n--) { 3916 ResolveInfo info = result.get(n); 3917 if (!info.filterNeedsVerification) { 3918 continue; 3919 } 3920 String packageName = info.activityInfo.packageName; 3921 PackageSetting ps = mSettings.mPackages.get(packageName); 3922 if (ps != null) { 3923 // Try to get the status from User settings first 3924 int status = ps.getDomainVerificationStatusForUser(userId); 3925 // if none available, get the master status 3926 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 3927 if (ps.getIntentFilterVerificationInfo() != null) { 3928 status = ps.getIntentFilterVerificationInfo().getStatus(); 3929 } 3930 } 3931 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 3932 result.clear(); 3933 result.add(info); 3934 // We break the for loop as we are good to go 3935 break; 3936 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 3937 result.remove(n); 3938 } 3939 } 3940 } 3941 } 3942 if (DEBUG_PREFERRED) { 3943 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 3944 result.size()); 3945 } 3946 return result; 3947 } 3948 3949 private ResolveInfo querySkipCurrentProfileIntents( 3950 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3951 int flags, int sourceUserId) { 3952 if (matchingFilters != null) { 3953 int size = matchingFilters.size(); 3954 for (int i = 0; i < size; i ++) { 3955 CrossProfileIntentFilter filter = matchingFilters.get(i); 3956 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3957 // Checking if there are activities in the target user that can handle the 3958 // intent. 3959 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3960 flags, sourceUserId); 3961 if (resolveInfo != null) { 3962 return resolveInfo; 3963 } 3964 } 3965 } 3966 } 3967 return null; 3968 } 3969 3970 // Return matching ResolveInfo if any for skip current profile intent filters. 3971 private ResolveInfo queryCrossProfileIntents( 3972 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3973 int flags, int sourceUserId) { 3974 if (matchingFilters != null) { 3975 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3976 // match the same intent. For performance reasons, it is better not to 3977 // run queryIntent twice for the same userId 3978 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3979 int size = matchingFilters.size(); 3980 for (int i = 0; i < size; i++) { 3981 CrossProfileIntentFilter filter = matchingFilters.get(i); 3982 int targetUserId = filter.getTargetUserId(); 3983 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3984 && !alreadyTriedUserIds.get(targetUserId)) { 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) return resolveInfo; 3990 alreadyTriedUserIds.put(targetUserId, true); 3991 } 3992 } 3993 } 3994 return null; 3995 } 3996 3997 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3998 String resolvedType, int flags, int sourceUserId) { 3999 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4000 resolvedType, flags, filter.getTargetUserId()); 4001 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4002 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4003 } 4004 return null; 4005 } 4006 4007 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4008 int sourceUserId, int targetUserId) { 4009 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4010 String className; 4011 if (targetUserId == UserHandle.USER_OWNER) { 4012 className = FORWARD_INTENT_TO_USER_OWNER; 4013 } else { 4014 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4015 } 4016 ComponentName forwardingActivityComponentName = new ComponentName( 4017 mAndroidApplication.packageName, className); 4018 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4019 sourceUserId); 4020 if (targetUserId == UserHandle.USER_OWNER) { 4021 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4022 forwardingResolveInfo.noResourceId = true; 4023 } 4024 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4025 forwardingResolveInfo.priority = 0; 4026 forwardingResolveInfo.preferredOrder = 0; 4027 forwardingResolveInfo.match = 0; 4028 forwardingResolveInfo.isDefault = true; 4029 forwardingResolveInfo.filter = filter; 4030 forwardingResolveInfo.targetUserId = targetUserId; 4031 return forwardingResolveInfo; 4032 } 4033 4034 @Override 4035 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4036 Intent[] specifics, String[] specificTypes, Intent intent, 4037 String resolvedType, int flags, int userId) { 4038 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4039 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4040 false, "query intent activity options"); 4041 final String resultsAction = intent.getAction(); 4042 4043 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4044 | PackageManager.GET_RESOLVED_FILTER, userId); 4045 4046 if (DEBUG_INTENT_MATCHING) { 4047 Log.v(TAG, "Query " + intent + ": " + results); 4048 } 4049 4050 int specificsPos = 0; 4051 int N; 4052 4053 // todo: note that the algorithm used here is O(N^2). This 4054 // isn't a problem in our current environment, but if we start running 4055 // into situations where we have more than 5 or 10 matches then this 4056 // should probably be changed to something smarter... 4057 4058 // First we go through and resolve each of the specific items 4059 // that were supplied, taking care of removing any corresponding 4060 // duplicate items in the generic resolve list. 4061 if (specifics != null) { 4062 for (int i=0; i<specifics.length; i++) { 4063 final Intent sintent = specifics[i]; 4064 if (sintent == null) { 4065 continue; 4066 } 4067 4068 if (DEBUG_INTENT_MATCHING) { 4069 Log.v(TAG, "Specific #" + i + ": " + sintent); 4070 } 4071 4072 String action = sintent.getAction(); 4073 if (resultsAction != null && resultsAction.equals(action)) { 4074 // If this action was explicitly requested, then don't 4075 // remove things that have it. 4076 action = null; 4077 } 4078 4079 ResolveInfo ri = null; 4080 ActivityInfo ai = null; 4081 4082 ComponentName comp = sintent.getComponent(); 4083 if (comp == null) { 4084 ri = resolveIntent( 4085 sintent, 4086 specificTypes != null ? specificTypes[i] : null, 4087 flags, userId); 4088 if (ri == null) { 4089 continue; 4090 } 4091 if (ri == mResolveInfo) { 4092 // ACK! Must do something better with this. 4093 } 4094 ai = ri.activityInfo; 4095 comp = new ComponentName(ai.applicationInfo.packageName, 4096 ai.name); 4097 } else { 4098 ai = getActivityInfo(comp, flags, userId); 4099 if (ai == null) { 4100 continue; 4101 } 4102 } 4103 4104 // Look for any generic query activities that are duplicates 4105 // of this specific one, and remove them from the results. 4106 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4107 N = results.size(); 4108 int j; 4109 for (j=specificsPos; j<N; j++) { 4110 ResolveInfo sri = results.get(j); 4111 if ((sri.activityInfo.name.equals(comp.getClassName()) 4112 && sri.activityInfo.applicationInfo.packageName.equals( 4113 comp.getPackageName())) 4114 || (action != null && sri.filter.matchAction(action))) { 4115 results.remove(j); 4116 if (DEBUG_INTENT_MATCHING) Log.v( 4117 TAG, "Removing duplicate item from " + j 4118 + " due to specific " + specificsPos); 4119 if (ri == null) { 4120 ri = sri; 4121 } 4122 j--; 4123 N--; 4124 } 4125 } 4126 4127 // Add this specific item to its proper place. 4128 if (ri == null) { 4129 ri = new ResolveInfo(); 4130 ri.activityInfo = ai; 4131 } 4132 results.add(specificsPos, ri); 4133 ri.specificIndex = i; 4134 specificsPos++; 4135 } 4136 } 4137 4138 // Now we go through the remaining generic results and remove any 4139 // duplicate actions that are found here. 4140 N = results.size(); 4141 for (int i=specificsPos; i<N-1; i++) { 4142 final ResolveInfo rii = results.get(i); 4143 if (rii.filter == null) { 4144 continue; 4145 } 4146 4147 // Iterate over all of the actions of this result's intent 4148 // filter... typically this should be just one. 4149 final Iterator<String> it = rii.filter.actionsIterator(); 4150 if (it == null) { 4151 continue; 4152 } 4153 while (it.hasNext()) { 4154 final String action = it.next(); 4155 if (resultsAction != null && resultsAction.equals(action)) { 4156 // If this action was explicitly requested, then don't 4157 // remove things that have it. 4158 continue; 4159 } 4160 for (int j=i+1; j<N; j++) { 4161 final ResolveInfo rij = results.get(j); 4162 if (rij.filter != null && rij.filter.hasAction(action)) { 4163 results.remove(j); 4164 if (DEBUG_INTENT_MATCHING) Log.v( 4165 TAG, "Removing duplicate item from " + j 4166 + " due to action " + action + " at " + i); 4167 j--; 4168 N--; 4169 } 4170 } 4171 } 4172 4173 // If the caller didn't request filter information, drop it now 4174 // so we don't have to marshall/unmarshall it. 4175 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4176 rii.filter = null; 4177 } 4178 } 4179 4180 // Filter out the caller activity if so requested. 4181 if (caller != null) { 4182 N = results.size(); 4183 for (int i=0; i<N; i++) { 4184 ActivityInfo ainfo = results.get(i).activityInfo; 4185 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4186 && caller.getClassName().equals(ainfo.name)) { 4187 results.remove(i); 4188 break; 4189 } 4190 } 4191 } 4192 4193 // If the caller didn't request filter information, 4194 // drop them now so we don't have to 4195 // marshall/unmarshall it. 4196 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4197 N = results.size(); 4198 for (int i=0; i<N; i++) { 4199 results.get(i).filter = null; 4200 } 4201 } 4202 4203 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4204 return results; 4205 } 4206 4207 @Override 4208 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4209 int userId) { 4210 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4211 ComponentName comp = intent.getComponent(); 4212 if (comp == null) { 4213 if (intent.getSelector() != null) { 4214 intent = intent.getSelector(); 4215 comp = intent.getComponent(); 4216 } 4217 } 4218 if (comp != null) { 4219 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4220 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4221 if (ai != null) { 4222 ResolveInfo ri = new ResolveInfo(); 4223 ri.activityInfo = ai; 4224 list.add(ri); 4225 } 4226 return list; 4227 } 4228 4229 // reader 4230 synchronized (mPackages) { 4231 String pkgName = intent.getPackage(); 4232 if (pkgName == null) { 4233 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4234 } 4235 final PackageParser.Package pkg = mPackages.get(pkgName); 4236 if (pkg != null) { 4237 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4238 userId); 4239 } 4240 return null; 4241 } 4242 } 4243 4244 @Override 4245 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4246 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4247 if (!sUserManager.exists(userId)) return null; 4248 if (query != null) { 4249 if (query.size() >= 1) { 4250 // If there is more than one service with the same priority, 4251 // just arbitrarily pick the first one. 4252 return query.get(0); 4253 } 4254 } 4255 return null; 4256 } 4257 4258 @Override 4259 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4260 int userId) { 4261 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4262 ComponentName comp = intent.getComponent(); 4263 if (comp == null) { 4264 if (intent.getSelector() != null) { 4265 intent = intent.getSelector(); 4266 comp = intent.getComponent(); 4267 } 4268 } 4269 if (comp != null) { 4270 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4271 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4272 if (si != null) { 4273 final ResolveInfo ri = new ResolveInfo(); 4274 ri.serviceInfo = si; 4275 list.add(ri); 4276 } 4277 return list; 4278 } 4279 4280 // reader 4281 synchronized (mPackages) { 4282 String pkgName = intent.getPackage(); 4283 if (pkgName == null) { 4284 return mServices.queryIntent(intent, resolvedType, flags, userId); 4285 } 4286 final PackageParser.Package pkg = mPackages.get(pkgName); 4287 if (pkg != null) { 4288 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4289 userId); 4290 } 4291 return null; 4292 } 4293 } 4294 4295 @Override 4296 public List<ResolveInfo> queryIntentContentProviders( 4297 Intent intent, String resolvedType, int flags, int userId) { 4298 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4299 ComponentName comp = intent.getComponent(); 4300 if (comp == null) { 4301 if (intent.getSelector() != null) { 4302 intent = intent.getSelector(); 4303 comp = intent.getComponent(); 4304 } 4305 } 4306 if (comp != null) { 4307 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4308 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4309 if (pi != null) { 4310 final ResolveInfo ri = new ResolveInfo(); 4311 ri.providerInfo = pi; 4312 list.add(ri); 4313 } 4314 return list; 4315 } 4316 4317 // reader 4318 synchronized (mPackages) { 4319 String pkgName = intent.getPackage(); 4320 if (pkgName == null) { 4321 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4322 } 4323 final PackageParser.Package pkg = mPackages.get(pkgName); 4324 if (pkg != null) { 4325 return mProviders.queryIntentForPackage( 4326 intent, resolvedType, flags, pkg.providers, userId); 4327 } 4328 return null; 4329 } 4330 } 4331 4332 @Override 4333 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4334 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4335 4336 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4337 4338 // writer 4339 synchronized (mPackages) { 4340 ArrayList<PackageInfo> list; 4341 if (listUninstalled) { 4342 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4343 for (PackageSetting ps : mSettings.mPackages.values()) { 4344 PackageInfo pi; 4345 if (ps.pkg != null) { 4346 pi = generatePackageInfo(ps.pkg, flags, userId); 4347 } else { 4348 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4349 } 4350 if (pi != null) { 4351 list.add(pi); 4352 } 4353 } 4354 } else { 4355 list = new ArrayList<PackageInfo>(mPackages.size()); 4356 for (PackageParser.Package p : mPackages.values()) { 4357 PackageInfo pi = generatePackageInfo(p, flags, userId); 4358 if (pi != null) { 4359 list.add(pi); 4360 } 4361 } 4362 } 4363 4364 return new ParceledListSlice<PackageInfo>(list); 4365 } 4366 } 4367 4368 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4369 String[] permissions, boolean[] tmp, int flags, int userId) { 4370 int numMatch = 0; 4371 final PermissionsState permissionsState = ps.getPermissionsState(); 4372 for (int i=0; i<permissions.length; i++) { 4373 final String permission = permissions[i]; 4374 if (permissionsState.hasPermission(permission, userId)) { 4375 tmp[i] = true; 4376 numMatch++; 4377 } else { 4378 tmp[i] = false; 4379 } 4380 } 4381 if (numMatch == 0) { 4382 return; 4383 } 4384 PackageInfo pi; 4385 if (ps.pkg != null) { 4386 pi = generatePackageInfo(ps.pkg, flags, userId); 4387 } else { 4388 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4389 } 4390 // The above might return null in cases of uninstalled apps or install-state 4391 // skew across users/profiles. 4392 if (pi != null) { 4393 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4394 if (numMatch == permissions.length) { 4395 pi.requestedPermissions = permissions; 4396 } else { 4397 pi.requestedPermissions = new String[numMatch]; 4398 numMatch = 0; 4399 for (int i=0; i<permissions.length; i++) { 4400 if (tmp[i]) { 4401 pi.requestedPermissions[numMatch] = permissions[i]; 4402 numMatch++; 4403 } 4404 } 4405 } 4406 } 4407 list.add(pi); 4408 } 4409 } 4410 4411 @Override 4412 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4413 String[] permissions, int flags, int userId) { 4414 if (!sUserManager.exists(userId)) return null; 4415 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4416 4417 // writer 4418 synchronized (mPackages) { 4419 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4420 boolean[] tmpBools = new boolean[permissions.length]; 4421 if (listUninstalled) { 4422 for (PackageSetting ps : mSettings.mPackages.values()) { 4423 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4424 } 4425 } else { 4426 for (PackageParser.Package pkg : mPackages.values()) { 4427 PackageSetting ps = (PackageSetting)pkg.mExtras; 4428 if (ps != null) { 4429 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4430 userId); 4431 } 4432 } 4433 } 4434 4435 return new ParceledListSlice<PackageInfo>(list); 4436 } 4437 } 4438 4439 @Override 4440 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4441 if (!sUserManager.exists(userId)) return null; 4442 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4443 4444 // writer 4445 synchronized (mPackages) { 4446 ArrayList<ApplicationInfo> list; 4447 if (listUninstalled) { 4448 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4449 for (PackageSetting ps : mSettings.mPackages.values()) { 4450 ApplicationInfo ai; 4451 if (ps.pkg != null) { 4452 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4453 ps.readUserState(userId), userId); 4454 } else { 4455 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4456 } 4457 if (ai != null) { 4458 list.add(ai); 4459 } 4460 } 4461 } else { 4462 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4463 for (PackageParser.Package p : mPackages.values()) { 4464 if (p.mExtras != null) { 4465 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4466 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4467 if (ai != null) { 4468 list.add(ai); 4469 } 4470 } 4471 } 4472 } 4473 4474 return new ParceledListSlice<ApplicationInfo>(list); 4475 } 4476 } 4477 4478 public List<ApplicationInfo> getPersistentApplications(int flags) { 4479 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4480 4481 // reader 4482 synchronized (mPackages) { 4483 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4484 final int userId = UserHandle.getCallingUserId(); 4485 while (i.hasNext()) { 4486 final PackageParser.Package p = i.next(); 4487 if (p.applicationInfo != null 4488 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4489 && (!mSafeMode || isSystemApp(p))) { 4490 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4491 if (ps != null) { 4492 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4493 ps.readUserState(userId), userId); 4494 if (ai != null) { 4495 finalList.add(ai); 4496 } 4497 } 4498 } 4499 } 4500 } 4501 4502 return finalList; 4503 } 4504 4505 @Override 4506 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4507 if (!sUserManager.exists(userId)) return null; 4508 // reader 4509 synchronized (mPackages) { 4510 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4511 PackageSetting ps = provider != null 4512 ? mSettings.mPackages.get(provider.owner.packageName) 4513 : null; 4514 return ps != null 4515 && mSettings.isEnabledLPr(provider.info, flags, userId) 4516 && (!mSafeMode || (provider.info.applicationInfo.flags 4517 &ApplicationInfo.FLAG_SYSTEM) != 0) 4518 ? PackageParser.generateProviderInfo(provider, flags, 4519 ps.readUserState(userId), userId) 4520 : null; 4521 } 4522 } 4523 4524 /** 4525 * @deprecated 4526 */ 4527 @Deprecated 4528 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4529 // reader 4530 synchronized (mPackages) { 4531 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4532 .entrySet().iterator(); 4533 final int userId = UserHandle.getCallingUserId(); 4534 while (i.hasNext()) { 4535 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4536 PackageParser.Provider p = entry.getValue(); 4537 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4538 4539 if (ps != null && p.syncable 4540 && (!mSafeMode || (p.info.applicationInfo.flags 4541 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4542 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4543 ps.readUserState(userId), userId); 4544 if (info != null) { 4545 outNames.add(entry.getKey()); 4546 outInfo.add(info); 4547 } 4548 } 4549 } 4550 } 4551 } 4552 4553 @Override 4554 public List<ProviderInfo> queryContentProviders(String processName, 4555 int uid, int flags) { 4556 ArrayList<ProviderInfo> finalList = null; 4557 // reader 4558 synchronized (mPackages) { 4559 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4560 final int userId = processName != null ? 4561 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4562 while (i.hasNext()) { 4563 final PackageParser.Provider p = i.next(); 4564 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4565 if (ps != null && p.info.authority != null 4566 && (processName == null 4567 || (p.info.processName.equals(processName) 4568 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4569 && mSettings.isEnabledLPr(p.info, flags, userId) 4570 && (!mSafeMode 4571 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4572 if (finalList == null) { 4573 finalList = new ArrayList<ProviderInfo>(3); 4574 } 4575 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4576 ps.readUserState(userId), userId); 4577 if (info != null) { 4578 finalList.add(info); 4579 } 4580 } 4581 } 4582 } 4583 4584 if (finalList != null) { 4585 Collections.sort(finalList, mProviderInitOrderSorter); 4586 } 4587 4588 return finalList; 4589 } 4590 4591 @Override 4592 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4593 int flags) { 4594 // reader 4595 synchronized (mPackages) { 4596 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4597 return PackageParser.generateInstrumentationInfo(i, flags); 4598 } 4599 } 4600 4601 @Override 4602 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4603 int flags) { 4604 ArrayList<InstrumentationInfo> finalList = 4605 new ArrayList<InstrumentationInfo>(); 4606 4607 // reader 4608 synchronized (mPackages) { 4609 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4610 while (i.hasNext()) { 4611 final PackageParser.Instrumentation p = i.next(); 4612 if (targetPackage == null 4613 || targetPackage.equals(p.info.targetPackage)) { 4614 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4615 flags); 4616 if (ii != null) { 4617 finalList.add(ii); 4618 } 4619 } 4620 } 4621 } 4622 4623 return finalList; 4624 } 4625 4626 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4627 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4628 if (overlays == null) { 4629 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4630 return; 4631 } 4632 for (PackageParser.Package opkg : overlays.values()) { 4633 // Not much to do if idmap fails: we already logged the error 4634 // and we certainly don't want to abort installation of pkg simply 4635 // because an overlay didn't fit properly. For these reasons, 4636 // ignore the return value of createIdmapForPackagePairLI. 4637 createIdmapForPackagePairLI(pkg, opkg); 4638 } 4639 } 4640 4641 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4642 PackageParser.Package opkg) { 4643 if (!opkg.mTrustedOverlay) { 4644 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4645 opkg.baseCodePath + ": overlay not trusted"); 4646 return false; 4647 } 4648 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4649 if (overlaySet == null) { 4650 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4651 opkg.baseCodePath + " but target package has no known overlays"); 4652 return false; 4653 } 4654 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4655 // TODO: generate idmap for split APKs 4656 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4657 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4658 + opkg.baseCodePath); 4659 return false; 4660 } 4661 PackageParser.Package[] overlayArray = 4662 overlaySet.values().toArray(new PackageParser.Package[0]); 4663 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4664 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4665 return p1.mOverlayPriority - p2.mOverlayPriority; 4666 } 4667 }; 4668 Arrays.sort(overlayArray, cmp); 4669 4670 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4671 int i = 0; 4672 for (PackageParser.Package p : overlayArray) { 4673 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4674 } 4675 return true; 4676 } 4677 4678 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4679 final File[] files = dir.listFiles(); 4680 if (ArrayUtils.isEmpty(files)) { 4681 Log.d(TAG, "No files in app dir " + dir); 4682 return; 4683 } 4684 4685 if (DEBUG_PACKAGE_SCANNING) { 4686 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4687 + " flags=0x" + Integer.toHexString(parseFlags)); 4688 } 4689 4690 for (File file : files) { 4691 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4692 && !PackageInstallerService.isStageName(file.getName()); 4693 if (!isPackage) { 4694 // Ignore entries which are not packages 4695 continue; 4696 } 4697 try { 4698 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4699 scanFlags, currentTime, null); 4700 } catch (PackageManagerException e) { 4701 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4702 4703 // Delete invalid userdata apps 4704 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4705 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4706 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4707 if (file.isDirectory()) { 4708 FileUtils.deleteContents(file); 4709 } 4710 file.delete(); 4711 } 4712 } 4713 } 4714 } 4715 4716 private static File getSettingsProblemFile() { 4717 File dataDir = Environment.getDataDirectory(); 4718 File systemDir = new File(dataDir, "system"); 4719 File fname = new File(systemDir, "uiderrors.txt"); 4720 return fname; 4721 } 4722 4723 static void reportSettingsProblem(int priority, String msg) { 4724 logCriticalInfo(priority, msg); 4725 } 4726 4727 static void logCriticalInfo(int priority, String msg) { 4728 Slog.println(priority, TAG, msg); 4729 EventLogTags.writePmCriticalInfo(msg); 4730 try { 4731 File fname = getSettingsProblemFile(); 4732 FileOutputStream out = new FileOutputStream(fname, true); 4733 PrintWriter pw = new FastPrintWriter(out); 4734 SimpleDateFormat formatter = new SimpleDateFormat(); 4735 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4736 pw.println(dateString + ": " + msg); 4737 pw.close(); 4738 FileUtils.setPermissions( 4739 fname.toString(), 4740 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4741 -1, -1); 4742 } catch (java.io.IOException e) { 4743 } 4744 } 4745 4746 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4747 PackageParser.Package pkg, File srcFile, int parseFlags) 4748 throws PackageManagerException { 4749 if (ps != null 4750 && ps.codePath.equals(srcFile) 4751 && ps.timeStamp == srcFile.lastModified() 4752 && !isCompatSignatureUpdateNeeded(pkg) 4753 && !isRecoverSignatureUpdateNeeded(pkg)) { 4754 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4755 if (ps.signatures.mSignatures != null 4756 && ps.signatures.mSignatures.length != 0 4757 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4758 // Optimization: reuse the existing cached certificates 4759 // if the package appears to be unchanged. 4760 pkg.mSignatures = ps.signatures.mSignatures; 4761 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4762 synchronized (mPackages) { 4763 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4764 } 4765 return; 4766 } 4767 4768 Slog.w(TAG, "PackageSetting for " + ps.name 4769 + " is missing signatures. Collecting certs again to recover them."); 4770 } else { 4771 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4772 } 4773 4774 try { 4775 pp.collectCertificates(pkg, parseFlags); 4776 pp.collectManifestDigest(pkg); 4777 } catch (PackageParserException e) { 4778 throw PackageManagerException.from(e); 4779 } 4780 } 4781 4782 /* 4783 * Scan a package and return the newly parsed package. 4784 * Returns null in case of errors and the error code is stored in mLastScanError 4785 */ 4786 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4787 long currentTime, UserHandle user) throws PackageManagerException { 4788 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4789 parseFlags |= mDefParseFlags; 4790 PackageParser pp = new PackageParser(); 4791 pp.setSeparateProcesses(mSeparateProcesses); 4792 pp.setOnlyCoreApps(mOnlyCore); 4793 pp.setDisplayMetrics(mMetrics); 4794 4795 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4796 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4797 } 4798 4799 final PackageParser.Package pkg; 4800 try { 4801 pkg = pp.parsePackage(scanFile, parseFlags); 4802 } catch (PackageParserException e) { 4803 throw PackageManagerException.from(e); 4804 } 4805 4806 PackageSetting ps = null; 4807 PackageSetting updatedPkg; 4808 // reader 4809 synchronized (mPackages) { 4810 // Look to see if we already know about this package. 4811 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4812 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4813 // This package has been renamed to its original name. Let's 4814 // use that. 4815 ps = mSettings.peekPackageLPr(oldName); 4816 } 4817 // If there was no original package, see one for the real package name. 4818 if (ps == null) { 4819 ps = mSettings.peekPackageLPr(pkg.packageName); 4820 } 4821 // Check to see if this package could be hiding/updating a system 4822 // package. Must look for it either under the original or real 4823 // package name depending on our state. 4824 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4825 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4826 } 4827 boolean updatedPkgBetter = false; 4828 // First check if this is a system package that may involve an update 4829 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4830 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4831 // it needs to drop FLAG_PRIVILEGED. 4832 if (locationIsPrivileged(scanFile)) { 4833 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4834 } else { 4835 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4836 } 4837 4838 if (ps != null && !ps.codePath.equals(scanFile)) { 4839 // The path has changed from what was last scanned... check the 4840 // version of the new path against what we have stored to determine 4841 // what to do. 4842 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4843 if (pkg.mVersionCode <= ps.versionCode) { 4844 // The system package has been updated and the code path does not match 4845 // Ignore entry. Skip it. 4846 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4847 + " ignored: updated version " + ps.versionCode 4848 + " better than this " + pkg.mVersionCode); 4849 if (!updatedPkg.codePath.equals(scanFile)) { 4850 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4851 + ps.name + " changing from " + updatedPkg.codePathString 4852 + " to " + scanFile); 4853 updatedPkg.codePath = scanFile; 4854 updatedPkg.codePathString = scanFile.toString(); 4855 updatedPkg.resourcePath = scanFile; 4856 updatedPkg.resourcePathString = scanFile.toString(); 4857 } 4858 updatedPkg.pkg = pkg; 4859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4860 } else { 4861 // The current app on the system partition is better than 4862 // what we have updated to on the data partition; switch 4863 // back to the system partition version. 4864 // At this point, its safely assumed that package installation for 4865 // apps in system partition will go through. If not there won't be a working 4866 // version of the app 4867 // writer 4868 synchronized (mPackages) { 4869 // Just remove the loaded entries from package lists. 4870 mPackages.remove(ps.name); 4871 } 4872 4873 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4874 + " reverting from " + ps.codePathString 4875 + ": new version " + pkg.mVersionCode 4876 + " better than installed " + ps.versionCode); 4877 4878 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4879 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4880 getAppDexInstructionSets(ps)); 4881 synchronized (mInstallLock) { 4882 args.cleanUpResourcesLI(); 4883 } 4884 synchronized (mPackages) { 4885 mSettings.enableSystemPackageLPw(ps.name); 4886 } 4887 updatedPkgBetter = true; 4888 } 4889 } 4890 } 4891 4892 if (updatedPkg != null) { 4893 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4894 // initially 4895 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4896 4897 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4898 // flag set initially 4899 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4900 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4901 } 4902 } 4903 4904 // Verify certificates against what was last scanned 4905 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4906 4907 /* 4908 * A new system app appeared, but we already had a non-system one of the 4909 * same name installed earlier. 4910 */ 4911 boolean shouldHideSystemApp = false; 4912 if (updatedPkg == null && ps != null 4913 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4914 /* 4915 * Check to make sure the signatures match first. If they don't, 4916 * wipe the installed application and its data. 4917 */ 4918 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4919 != PackageManager.SIGNATURE_MATCH) { 4920 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4921 + " signatures don't match existing userdata copy; removing"); 4922 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4923 ps = null; 4924 } else { 4925 /* 4926 * If the newly-added system app is an older version than the 4927 * already installed version, hide it. It will be scanned later 4928 * and re-added like an update. 4929 */ 4930 if (pkg.mVersionCode <= ps.versionCode) { 4931 shouldHideSystemApp = true; 4932 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4933 + " but new version " + pkg.mVersionCode + " better than installed " 4934 + ps.versionCode + "; hiding system"); 4935 } else { 4936 /* 4937 * The newly found system app is a newer version that the 4938 * one previously installed. Simply remove the 4939 * already-installed application and replace it with our own 4940 * while keeping the application data. 4941 */ 4942 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4943 + " reverting from " + ps.codePathString + ": new version " 4944 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4945 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4946 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4947 getAppDexInstructionSets(ps)); 4948 synchronized (mInstallLock) { 4949 args.cleanUpResourcesLI(); 4950 } 4951 } 4952 } 4953 } 4954 4955 // The apk is forward locked (not public) if its code and resources 4956 // are kept in different files. (except for app in either system or 4957 // vendor path). 4958 // TODO grab this value from PackageSettings 4959 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4960 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4961 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4962 } 4963 } 4964 4965 // TODO: extend to support forward-locked splits 4966 String resourcePath = null; 4967 String baseResourcePath = null; 4968 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4969 if (ps != null && ps.resourcePathString != null) { 4970 resourcePath = ps.resourcePathString; 4971 baseResourcePath = ps.resourcePathString; 4972 } else { 4973 // Should not happen at all. Just log an error. 4974 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4975 } 4976 } else { 4977 resourcePath = pkg.codePath; 4978 baseResourcePath = pkg.baseCodePath; 4979 } 4980 4981 // Set application objects path explicitly. 4982 pkg.applicationInfo.setCodePath(pkg.codePath); 4983 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4984 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4985 pkg.applicationInfo.setResourcePath(resourcePath); 4986 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4987 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4988 4989 // Note that we invoke the following method only if we are about to unpack an application 4990 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4991 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4992 4993 /* 4994 * If the system app should be overridden by a previously installed 4995 * data, hide the system app now and let the /data/app scan pick it up 4996 * again. 4997 */ 4998 if (shouldHideSystemApp) { 4999 synchronized (mPackages) { 5000 /* 5001 * We have to grant systems permissions before we hide, because 5002 * grantPermissions will assume the package update is trying to 5003 * expand its permissions. 5004 */ 5005 grantPermissionsLPw(pkg, true, pkg.packageName); 5006 mSettings.disableSystemPackageLPw(pkg.packageName); 5007 } 5008 } 5009 5010 return scannedPkg; 5011 } 5012 5013 private static String fixProcessName(String defProcessName, 5014 String processName, int uid) { 5015 if (processName == null) { 5016 return defProcessName; 5017 } 5018 return processName; 5019 } 5020 5021 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5022 throws PackageManagerException { 5023 if (pkgSetting.signatures.mSignatures != null) { 5024 // Already existing package. Make sure signatures match 5025 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5026 == PackageManager.SIGNATURE_MATCH; 5027 if (!match) { 5028 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5029 == PackageManager.SIGNATURE_MATCH; 5030 } 5031 if (!match) { 5032 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5033 == PackageManager.SIGNATURE_MATCH; 5034 } 5035 if (!match) { 5036 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5037 + pkg.packageName + " signatures do not match the " 5038 + "previously installed version; ignoring!"); 5039 } 5040 } 5041 5042 // Check for shared user signatures 5043 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5044 // Already existing package. Make sure signatures match 5045 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5046 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5047 if (!match) { 5048 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5049 == PackageManager.SIGNATURE_MATCH; 5050 } 5051 if (!match) { 5052 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5053 == PackageManager.SIGNATURE_MATCH; 5054 } 5055 if (!match) { 5056 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5057 "Package " + pkg.packageName 5058 + " has no signatures that match those in shared user " 5059 + pkgSetting.sharedUser.name + "; ignoring!"); 5060 } 5061 } 5062 } 5063 5064 /** 5065 * Enforces that only the system UID or root's UID can call a method exposed 5066 * via Binder. 5067 * 5068 * @param message used as message if SecurityException is thrown 5069 * @throws SecurityException if the caller is not system or root 5070 */ 5071 private static final void enforceSystemOrRoot(String message) { 5072 final int uid = Binder.getCallingUid(); 5073 if (uid != Process.SYSTEM_UID && uid != 0) { 5074 throw new SecurityException(message); 5075 } 5076 } 5077 5078 @Override 5079 public void performBootDexOpt() { 5080 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5081 5082 // Before everything else, see whether we need to fstrim. 5083 try { 5084 IMountService ms = PackageHelper.getMountService(); 5085 if (ms != null) { 5086 final boolean isUpgrade = isUpgrade(); 5087 boolean doTrim = isUpgrade; 5088 if (doTrim) { 5089 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5090 } else { 5091 final long interval = android.provider.Settings.Global.getLong( 5092 mContext.getContentResolver(), 5093 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5094 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5095 if (interval > 0) { 5096 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5097 if (timeSinceLast > interval) { 5098 doTrim = true; 5099 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5100 + "; running immediately"); 5101 } 5102 } 5103 } 5104 if (doTrim) { 5105 if (!isFirstBoot()) { 5106 try { 5107 ActivityManagerNative.getDefault().showBootMessage( 5108 mContext.getResources().getString( 5109 R.string.android_upgrading_fstrim), true); 5110 } catch (RemoteException e) { 5111 } 5112 } 5113 ms.runMaintenance(); 5114 } 5115 } else { 5116 Slog.e(TAG, "Mount service unavailable!"); 5117 } 5118 } catch (RemoteException e) { 5119 // Can't happen; MountService is local 5120 } 5121 5122 final ArraySet<PackageParser.Package> pkgs; 5123 synchronized (mPackages) { 5124 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5125 } 5126 5127 if (pkgs != null) { 5128 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5129 // in case the device runs out of space. 5130 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5131 // Give priority to core apps. 5132 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5133 PackageParser.Package pkg = it.next(); 5134 if (pkg.coreApp) { 5135 if (DEBUG_DEXOPT) { 5136 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5137 } 5138 sortedPkgs.add(pkg); 5139 it.remove(); 5140 } 5141 } 5142 // Give priority to system apps that listen for pre boot complete. 5143 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5144 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5145 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5146 PackageParser.Package pkg = it.next(); 5147 if (pkgNames.contains(pkg.packageName)) { 5148 if (DEBUG_DEXOPT) { 5149 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5150 } 5151 sortedPkgs.add(pkg); 5152 it.remove(); 5153 } 5154 } 5155 // Give priority to system apps. 5156 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5157 PackageParser.Package pkg = it.next(); 5158 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5159 if (DEBUG_DEXOPT) { 5160 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5161 } 5162 sortedPkgs.add(pkg); 5163 it.remove(); 5164 } 5165 } 5166 // Give priority to updated system apps. 5167 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5168 PackageParser.Package pkg = it.next(); 5169 if (isUpdatedSystemApp(pkg)) { 5170 if (DEBUG_DEXOPT) { 5171 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5172 } 5173 sortedPkgs.add(pkg); 5174 it.remove(); 5175 } 5176 } 5177 // Give priority to apps that listen for boot complete. 5178 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5179 pkgNames = getPackageNamesForIntent(intent); 5180 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5181 PackageParser.Package pkg = it.next(); 5182 if (pkgNames.contains(pkg.packageName)) { 5183 if (DEBUG_DEXOPT) { 5184 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5185 } 5186 sortedPkgs.add(pkg); 5187 it.remove(); 5188 } 5189 } 5190 // Filter out packages that aren't recently used. 5191 filterRecentlyUsedApps(pkgs); 5192 // Add all remaining apps. 5193 for (PackageParser.Package pkg : pkgs) { 5194 if (DEBUG_DEXOPT) { 5195 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5196 } 5197 sortedPkgs.add(pkg); 5198 } 5199 5200 // If we want to be lazy, filter everything that wasn't recently used. 5201 if (mLazyDexOpt) { 5202 filterRecentlyUsedApps(sortedPkgs); 5203 } 5204 5205 int i = 0; 5206 int total = sortedPkgs.size(); 5207 File dataDir = Environment.getDataDirectory(); 5208 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5209 if (lowThreshold == 0) { 5210 throw new IllegalStateException("Invalid low memory threshold"); 5211 } 5212 for (PackageParser.Package pkg : sortedPkgs) { 5213 long usableSpace = dataDir.getUsableSpace(); 5214 if (usableSpace < lowThreshold) { 5215 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5216 break; 5217 } 5218 performBootDexOpt(pkg, ++i, total); 5219 } 5220 } 5221 } 5222 5223 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5224 // Filter out packages that aren't recently used. 5225 // 5226 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5227 // should do a full dexopt. 5228 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5229 int total = pkgs.size(); 5230 int skipped = 0; 5231 long now = System.currentTimeMillis(); 5232 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5233 PackageParser.Package pkg = i.next(); 5234 long then = pkg.mLastPackageUsageTimeInMills; 5235 if (then + mDexOptLRUThresholdInMills < now) { 5236 if (DEBUG_DEXOPT) { 5237 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5238 ((then == 0) ? "never" : new Date(then))); 5239 } 5240 i.remove(); 5241 skipped++; 5242 } 5243 } 5244 if (DEBUG_DEXOPT) { 5245 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5246 } 5247 } 5248 } 5249 5250 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5251 List<ResolveInfo> ris = null; 5252 try { 5253 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5254 intent, null, 0, UserHandle.USER_OWNER); 5255 } catch (RemoteException e) { 5256 } 5257 ArraySet<String> pkgNames = new ArraySet<String>(); 5258 if (ris != null) { 5259 for (ResolveInfo ri : ris) { 5260 pkgNames.add(ri.activityInfo.packageName); 5261 } 5262 } 5263 return pkgNames; 5264 } 5265 5266 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5267 if (DEBUG_DEXOPT) { 5268 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5269 } 5270 if (!isFirstBoot()) { 5271 try { 5272 ActivityManagerNative.getDefault().showBootMessage( 5273 mContext.getResources().getString(R.string.android_upgrading_apk, 5274 curr, total), true); 5275 } catch (RemoteException e) { 5276 } 5277 } 5278 PackageParser.Package p = pkg; 5279 synchronized (mInstallLock) { 5280 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5281 false /* force dex */, false /* defer */, true /* include dependencies */); 5282 } 5283 } 5284 5285 @Override 5286 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5287 return performDexOpt(packageName, instructionSet, false); 5288 } 5289 5290 private static String getPrimaryInstructionSet(ApplicationInfo info) { 5291 if (info.primaryCpuAbi == null) { 5292 return getPreferredInstructionSet(); 5293 } 5294 5295 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 5296 } 5297 5298 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5299 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5300 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5301 if (!dexopt && !updateUsage) { 5302 // We aren't going to dexopt or update usage, so bail early. 5303 return false; 5304 } 5305 PackageParser.Package p; 5306 final String targetInstructionSet; 5307 synchronized (mPackages) { 5308 p = mPackages.get(packageName); 5309 if (p == null) { 5310 return false; 5311 } 5312 if (updateUsage) { 5313 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5314 } 5315 mPackageUsage.write(false); 5316 if (!dexopt) { 5317 // We aren't going to dexopt, so bail early. 5318 return false; 5319 } 5320 5321 targetInstructionSet = instructionSet != null ? instructionSet : 5322 getPrimaryInstructionSet(p.applicationInfo); 5323 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5324 return false; 5325 } 5326 } 5327 5328 synchronized (mInstallLock) { 5329 final String[] instructionSets = new String[] { targetInstructionSet }; 5330 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5331 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5332 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5333 } 5334 } 5335 5336 public ArraySet<String> getPackagesThatNeedDexOpt() { 5337 ArraySet<String> pkgs = null; 5338 synchronized (mPackages) { 5339 for (PackageParser.Package p : mPackages.values()) { 5340 if (DEBUG_DEXOPT) { 5341 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5342 } 5343 if (!p.mDexOptPerformed.isEmpty()) { 5344 continue; 5345 } 5346 if (pkgs == null) { 5347 pkgs = new ArraySet<String>(); 5348 } 5349 pkgs.add(p.packageName); 5350 } 5351 } 5352 return pkgs; 5353 } 5354 5355 public void shutdown() { 5356 mPackageUsage.write(true); 5357 } 5358 5359 @Override 5360 public void forceDexOpt(String packageName) { 5361 enforceSystemOrRoot("forceDexOpt"); 5362 5363 PackageParser.Package pkg; 5364 synchronized (mPackages) { 5365 pkg = mPackages.get(packageName); 5366 if (pkg == null) { 5367 throw new IllegalArgumentException("Missing package: " + packageName); 5368 } 5369 } 5370 5371 synchronized (mInstallLock) { 5372 final String[] instructionSets = new String[] { 5373 getPrimaryInstructionSet(pkg.applicationInfo) }; 5374 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5375 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5376 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5377 throw new IllegalStateException("Failed to dexopt: " + res); 5378 } 5379 } 5380 } 5381 5382 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5383 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5384 Slog.w(TAG, "Unable to update from " + oldPkg.name 5385 + " to " + newPkg.packageName 5386 + ": old package not in system partition"); 5387 return false; 5388 } else if (mPackages.get(oldPkg.name) != null) { 5389 Slog.w(TAG, "Unable to update from " + oldPkg.name 5390 + " to " + newPkg.packageName 5391 + ": old package still exists"); 5392 return false; 5393 } 5394 return true; 5395 } 5396 5397 private File getDataPathForPackage(String packageName, int userId) { 5398 /* 5399 * Until we fully support multiple users, return the directory we 5400 * previously would have. The PackageManagerTests will need to be 5401 * revised when this is changed back.. 5402 */ 5403 if (userId == 0) { 5404 return new File(mAppDataDir, packageName); 5405 } else { 5406 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5407 + File.separator + packageName); 5408 } 5409 } 5410 5411 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5412 int[] users = sUserManager.getUserIds(); 5413 int res = mInstaller.install(packageName, uid, uid, seinfo); 5414 if (res < 0) { 5415 return res; 5416 } 5417 for (int user : users) { 5418 if (user != 0) { 5419 res = mInstaller.createUserData(packageName, 5420 UserHandle.getUid(user, uid), user, seinfo); 5421 if (res < 0) { 5422 return res; 5423 } 5424 } 5425 } 5426 return res; 5427 } 5428 5429 private int removeDataDirsLI(String packageName) { 5430 int[] users = sUserManager.getUserIds(); 5431 int res = 0; 5432 for (int user : users) { 5433 int resInner = mInstaller.remove(packageName, user); 5434 if (resInner < 0) { 5435 res = resInner; 5436 } 5437 } 5438 5439 return res; 5440 } 5441 5442 private int deleteCodeCacheDirsLI(String packageName) { 5443 int[] users = sUserManager.getUserIds(); 5444 int res = 0; 5445 for (int user : users) { 5446 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5447 if (resInner < 0) { 5448 res = resInner; 5449 } 5450 } 5451 return res; 5452 } 5453 5454 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5455 PackageParser.Package changingLib) { 5456 if (file.path != null) { 5457 usesLibraryFiles.add(file.path); 5458 return; 5459 } 5460 PackageParser.Package p = mPackages.get(file.apk); 5461 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5462 // If we are doing this while in the middle of updating a library apk, 5463 // then we need to make sure to use that new apk for determining the 5464 // dependencies here. (We haven't yet finished committing the new apk 5465 // to the package manager state.) 5466 if (p == null || p.packageName.equals(changingLib.packageName)) { 5467 p = changingLib; 5468 } 5469 } 5470 if (p != null) { 5471 usesLibraryFiles.addAll(p.getAllCodePaths()); 5472 } 5473 } 5474 5475 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5476 PackageParser.Package changingLib) throws PackageManagerException { 5477 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5478 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5479 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5480 for (int i=0; i<N; i++) { 5481 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5482 if (file == null) { 5483 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5484 "Package " + pkg.packageName + " requires unavailable shared library " 5485 + pkg.usesLibraries.get(i) + "; failing!"); 5486 } 5487 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5488 } 5489 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5490 for (int i=0; i<N; i++) { 5491 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5492 if (file == null) { 5493 Slog.w(TAG, "Package " + pkg.packageName 5494 + " desires unavailable shared library " 5495 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5496 } else { 5497 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5498 } 5499 } 5500 N = usesLibraryFiles.size(); 5501 if (N > 0) { 5502 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5503 } else { 5504 pkg.usesLibraryFiles = null; 5505 } 5506 } 5507 } 5508 5509 private static boolean hasString(List<String> list, List<String> which) { 5510 if (list == null) { 5511 return false; 5512 } 5513 for (int i=list.size()-1; i>=0; i--) { 5514 for (int j=which.size()-1; j>=0; j--) { 5515 if (which.get(j).equals(list.get(i))) { 5516 return true; 5517 } 5518 } 5519 } 5520 return false; 5521 } 5522 5523 private void updateAllSharedLibrariesLPw() { 5524 for (PackageParser.Package pkg : mPackages.values()) { 5525 try { 5526 updateSharedLibrariesLPw(pkg, null); 5527 } catch (PackageManagerException e) { 5528 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5529 } 5530 } 5531 } 5532 5533 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5534 PackageParser.Package changingPkg) { 5535 ArrayList<PackageParser.Package> res = null; 5536 for (PackageParser.Package pkg : mPackages.values()) { 5537 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5538 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5539 if (res == null) { 5540 res = new ArrayList<PackageParser.Package>(); 5541 } 5542 res.add(pkg); 5543 try { 5544 updateSharedLibrariesLPw(pkg, changingPkg); 5545 } catch (PackageManagerException e) { 5546 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5547 } 5548 } 5549 } 5550 return res; 5551 } 5552 5553 /** 5554 * Derive the value of the {@code cpuAbiOverride} based on the provided 5555 * value and an optional stored value from the package settings. 5556 */ 5557 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5558 String cpuAbiOverride = null; 5559 5560 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5561 cpuAbiOverride = null; 5562 } else if (abiOverride != null) { 5563 cpuAbiOverride = abiOverride; 5564 } else if (settings != null) { 5565 cpuAbiOverride = settings.cpuAbiOverrideString; 5566 } 5567 5568 return cpuAbiOverride; 5569 } 5570 5571 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5572 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5573 boolean success = false; 5574 try { 5575 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5576 currentTime, user); 5577 success = true; 5578 return res; 5579 } finally { 5580 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5581 removeDataDirsLI(pkg.packageName); 5582 } 5583 } 5584 } 5585 5586 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5587 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5588 final File scanFile = new File(pkg.codePath); 5589 if (pkg.applicationInfo.getCodePath() == null || 5590 pkg.applicationInfo.getResourcePath() == null) { 5591 // Bail out. The resource and code paths haven't been set. 5592 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5593 "Code and resource paths haven't been set correctly"); 5594 } 5595 5596 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5597 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5598 } else { 5599 // Only allow system apps to be flagged as core apps. 5600 pkg.coreApp = false; 5601 } 5602 5603 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5604 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5605 } 5606 5607 if (mCustomResolverComponentName != null && 5608 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5609 setUpCustomResolverActivity(pkg); 5610 } 5611 5612 if (pkg.packageName.equals("android")) { 5613 synchronized (mPackages) { 5614 if (mAndroidApplication != null) { 5615 Slog.w(TAG, "*************************************************"); 5616 Slog.w(TAG, "Core android package being redefined. Skipping."); 5617 Slog.w(TAG, " file=" + scanFile); 5618 Slog.w(TAG, "*************************************************"); 5619 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5620 "Core android package being redefined. Skipping."); 5621 } 5622 5623 // Set up information for our fall-back user intent resolution activity. 5624 mPlatformPackage = pkg; 5625 pkg.mVersionCode = mSdkVersion; 5626 mAndroidApplication = pkg.applicationInfo; 5627 5628 if (!mResolverReplaced) { 5629 mResolveActivity.applicationInfo = mAndroidApplication; 5630 mResolveActivity.name = ResolverActivity.class.getName(); 5631 mResolveActivity.packageName = mAndroidApplication.packageName; 5632 mResolveActivity.processName = "system:ui"; 5633 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5634 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5635 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5636 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5637 mResolveActivity.exported = true; 5638 mResolveActivity.enabled = true; 5639 mResolveInfo.activityInfo = mResolveActivity; 5640 mResolveInfo.priority = 0; 5641 mResolveInfo.preferredOrder = 0; 5642 mResolveInfo.match = 0; 5643 mResolveComponentName = new ComponentName( 5644 mAndroidApplication.packageName, mResolveActivity.name); 5645 } 5646 } 5647 } 5648 5649 if (DEBUG_PACKAGE_SCANNING) { 5650 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5651 Log.d(TAG, "Scanning package " + pkg.packageName); 5652 } 5653 5654 if (mPackages.containsKey(pkg.packageName) 5655 || mSharedLibraries.containsKey(pkg.packageName)) { 5656 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5657 "Application package " + pkg.packageName 5658 + " already installed. Skipping duplicate."); 5659 } 5660 5661 // If we're only installing presumed-existing packages, require that the 5662 // scanned APK is both already known and at the path previously established 5663 // for it. Previously unknown packages we pick up normally, but if we have an 5664 // a priori expectation about this package's install presence, enforce it. 5665 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5666 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5667 if (known != null) { 5668 if (DEBUG_PACKAGE_SCANNING) { 5669 Log.d(TAG, "Examining " + pkg.codePath 5670 + " and requiring known paths " + known.codePathString 5671 + " & " + known.resourcePathString); 5672 } 5673 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5674 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5675 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5676 "Application package " + pkg.packageName 5677 + " found at " + pkg.applicationInfo.getCodePath() 5678 + " but expected at " + known.codePathString + "; ignoring."); 5679 } 5680 } 5681 } 5682 5683 // Initialize package source and resource directories 5684 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5685 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5686 5687 SharedUserSetting suid = null; 5688 PackageSetting pkgSetting = null; 5689 5690 if (!isSystemApp(pkg)) { 5691 // Only system apps can use these features. 5692 pkg.mOriginalPackages = null; 5693 pkg.mRealPackage = null; 5694 pkg.mAdoptPermissions = null; 5695 } 5696 5697 // writer 5698 synchronized (mPackages) { 5699 if (pkg.mSharedUserId != null) { 5700 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5701 if (suid == null) { 5702 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5703 "Creating application package " + pkg.packageName 5704 + " for shared user failed"); 5705 } 5706 if (DEBUG_PACKAGE_SCANNING) { 5707 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5708 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5709 + "): packages=" + suid.packages); 5710 } 5711 } 5712 5713 // Check if we are renaming from an original package name. 5714 PackageSetting origPackage = null; 5715 String realName = null; 5716 if (pkg.mOriginalPackages != null) { 5717 // This package may need to be renamed to a previously 5718 // installed name. Let's check on that... 5719 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5720 if (pkg.mOriginalPackages.contains(renamed)) { 5721 // This package had originally been installed as the 5722 // original name, and we have already taken care of 5723 // transitioning to the new one. Just update the new 5724 // one to continue using the old name. 5725 realName = pkg.mRealPackage; 5726 if (!pkg.packageName.equals(renamed)) { 5727 // Callers into this function may have already taken 5728 // care of renaming the package; only do it here if 5729 // it is not already done. 5730 pkg.setPackageName(renamed); 5731 } 5732 5733 } else { 5734 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5735 if ((origPackage = mSettings.peekPackageLPr( 5736 pkg.mOriginalPackages.get(i))) != null) { 5737 // We do have the package already installed under its 5738 // original name... should we use it? 5739 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5740 // New package is not compatible with original. 5741 origPackage = null; 5742 continue; 5743 } else if (origPackage.sharedUser != null) { 5744 // Make sure uid is compatible between packages. 5745 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5746 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5747 + " to " + pkg.packageName + ": old uid " 5748 + origPackage.sharedUser.name 5749 + " differs from " + pkg.mSharedUserId); 5750 origPackage = null; 5751 continue; 5752 } 5753 } else { 5754 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5755 + pkg.packageName + " to old name " + origPackage.name); 5756 } 5757 break; 5758 } 5759 } 5760 } 5761 } 5762 5763 if (mTransferedPackages.contains(pkg.packageName)) { 5764 Slog.w(TAG, "Package " + pkg.packageName 5765 + " was transferred to another, but its .apk remains"); 5766 } 5767 5768 // Just create the setting, don't add it yet. For already existing packages 5769 // the PkgSetting exists already and doesn't have to be created. 5770 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5771 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5772 pkg.applicationInfo.primaryCpuAbi, 5773 pkg.applicationInfo.secondaryCpuAbi, 5774 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5775 user, false); 5776 if (pkgSetting == null) { 5777 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5778 "Creating application package " + pkg.packageName + " failed"); 5779 } 5780 5781 if (pkgSetting.origPackage != null) { 5782 // If we are first transitioning from an original package, 5783 // fix up the new package's name now. We need to do this after 5784 // looking up the package under its new name, so getPackageLP 5785 // can take care of fiddling things correctly. 5786 pkg.setPackageName(origPackage.name); 5787 5788 // File a report about this. 5789 String msg = "New package " + pkgSetting.realName 5790 + " renamed to replace old package " + pkgSetting.name; 5791 reportSettingsProblem(Log.WARN, msg); 5792 5793 // Make a note of it. 5794 mTransferedPackages.add(origPackage.name); 5795 5796 // No longer need to retain this. 5797 pkgSetting.origPackage = null; 5798 } 5799 5800 if (realName != null) { 5801 // Make a note of it. 5802 mTransferedPackages.add(pkg.packageName); 5803 } 5804 5805 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5806 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5807 } 5808 5809 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5810 // Check all shared libraries and map to their actual file path. 5811 // We only do this here for apps not on a system dir, because those 5812 // are the only ones that can fail an install due to this. We 5813 // will take care of the system apps by updating all of their 5814 // library paths after the scan is done. 5815 updateSharedLibrariesLPw(pkg, null); 5816 } 5817 5818 if (mFoundPolicyFile) { 5819 SELinuxMMAC.assignSeinfoValue(pkg); 5820 } 5821 5822 pkg.applicationInfo.uid = pkgSetting.appId; 5823 pkg.mExtras = pkgSetting; 5824 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5825 try { 5826 verifySignaturesLP(pkgSetting, pkg); 5827 // We just determined the app is signed correctly, so bring 5828 // over the latest parsed certs. 5829 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5830 } catch (PackageManagerException e) { 5831 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5832 throw e; 5833 } 5834 // The signature has changed, but this package is in the system 5835 // image... let's recover! 5836 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5837 // However... if this package is part of a shared user, but it 5838 // doesn't match the signature of the shared user, let's fail. 5839 // What this means is that you can't change the signatures 5840 // associated with an overall shared user, which doesn't seem all 5841 // that unreasonable. 5842 if (pkgSetting.sharedUser != null) { 5843 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5844 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5845 throw new PackageManagerException( 5846 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5847 "Signature mismatch for shared user : " 5848 + pkgSetting.sharedUser); 5849 } 5850 } 5851 // File a report about this. 5852 String msg = "System package " + pkg.packageName 5853 + " signature changed; retaining data."; 5854 reportSettingsProblem(Log.WARN, msg); 5855 } 5856 } else { 5857 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5858 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5859 + pkg.packageName + " upgrade keys do not match the " 5860 + "previously installed version"); 5861 } else { 5862 // We just determined the app is signed correctly, so bring 5863 // over the latest parsed certs. 5864 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5865 } 5866 } 5867 // Verify that this new package doesn't have any content providers 5868 // that conflict with existing packages. Only do this if the 5869 // package isn't already installed, since we don't want to break 5870 // things that are installed. 5871 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5872 final int N = pkg.providers.size(); 5873 int i; 5874 for (i=0; i<N; i++) { 5875 PackageParser.Provider p = pkg.providers.get(i); 5876 if (p.info.authority != null) { 5877 String names[] = p.info.authority.split(";"); 5878 for (int j = 0; j < names.length; j++) { 5879 if (mProvidersByAuthority.containsKey(names[j])) { 5880 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5881 final String otherPackageName = 5882 ((other != null && other.getComponentName() != null) ? 5883 other.getComponentName().getPackageName() : "?"); 5884 throw new PackageManagerException( 5885 INSTALL_FAILED_CONFLICTING_PROVIDER, 5886 "Can't install because provider name " + names[j] 5887 + " (in package " + pkg.applicationInfo.packageName 5888 + ") is already used by " + otherPackageName); 5889 } 5890 } 5891 } 5892 } 5893 } 5894 5895 if (pkg.mAdoptPermissions != null) { 5896 // This package wants to adopt ownership of permissions from 5897 // another package. 5898 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5899 final String origName = pkg.mAdoptPermissions.get(i); 5900 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5901 if (orig != null) { 5902 if (verifyPackageUpdateLPr(orig, pkg)) { 5903 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5904 + pkg.packageName); 5905 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5906 } 5907 } 5908 } 5909 } 5910 } 5911 5912 final String pkgName = pkg.packageName; 5913 5914 final long scanFileTime = scanFile.lastModified(); 5915 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5916 pkg.applicationInfo.processName = fixProcessName( 5917 pkg.applicationInfo.packageName, 5918 pkg.applicationInfo.processName, 5919 pkg.applicationInfo.uid); 5920 5921 File dataPath; 5922 if (mPlatformPackage == pkg) { 5923 // The system package is special. 5924 dataPath = new File(Environment.getDataDirectory(), "system"); 5925 5926 pkg.applicationInfo.dataDir = dataPath.getPath(); 5927 5928 } else { 5929 // This is a normal package, need to make its data directory. 5930 dataPath = getDataPathForPackage(pkg.packageName, 0); 5931 5932 boolean uidError = false; 5933 if (dataPath.exists()) { 5934 int currentUid = 0; 5935 try { 5936 StructStat stat = Os.stat(dataPath.getPath()); 5937 currentUid = stat.st_uid; 5938 } catch (ErrnoException e) { 5939 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5940 } 5941 5942 // If we have mismatched owners for the data path, we have a problem. 5943 if (currentUid != pkg.applicationInfo.uid) { 5944 boolean recovered = false; 5945 if (currentUid == 0) { 5946 // The directory somehow became owned by root. Wow. 5947 // This is probably because the system was stopped while 5948 // installd was in the middle of messing with its libs 5949 // directory. Ask installd to fix that. 5950 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5951 pkg.applicationInfo.uid); 5952 if (ret >= 0) { 5953 recovered = true; 5954 String msg = "Package " + pkg.packageName 5955 + " unexpectedly changed to uid 0; recovered to " + 5956 + pkg.applicationInfo.uid; 5957 reportSettingsProblem(Log.WARN, msg); 5958 } 5959 } 5960 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5961 || (scanFlags&SCAN_BOOTING) != 0)) { 5962 // If this is a system app, we can at least delete its 5963 // current data so the application will still work. 5964 int ret = removeDataDirsLI(pkgName); 5965 if (ret >= 0) { 5966 // TODO: Kill the processes first 5967 // Old data gone! 5968 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5969 ? "System package " : "Third party package "; 5970 String msg = prefix + pkg.packageName 5971 + " has changed from uid: " 5972 + currentUid + " to " 5973 + pkg.applicationInfo.uid + "; old data erased"; 5974 reportSettingsProblem(Log.WARN, msg); 5975 recovered = true; 5976 5977 // And now re-install the app. 5978 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5979 pkg.applicationInfo.seinfo); 5980 if (ret == -1) { 5981 // Ack should not happen! 5982 msg = prefix + pkg.packageName 5983 + " could not have data directory re-created after delete."; 5984 reportSettingsProblem(Log.WARN, msg); 5985 throw new PackageManagerException( 5986 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5987 } 5988 } 5989 if (!recovered) { 5990 mHasSystemUidErrors = true; 5991 } 5992 } else if (!recovered) { 5993 // If we allow this install to proceed, we will be broken. 5994 // Abort, abort! 5995 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5996 "scanPackageLI"); 5997 } 5998 if (!recovered) { 5999 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6000 + pkg.applicationInfo.uid + "/fs_" 6001 + currentUid; 6002 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6003 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6004 String msg = "Package " + pkg.packageName 6005 + " has mismatched uid: " 6006 + currentUid + " on disk, " 6007 + pkg.applicationInfo.uid + " in settings"; 6008 // writer 6009 synchronized (mPackages) { 6010 mSettings.mReadMessages.append(msg); 6011 mSettings.mReadMessages.append('\n'); 6012 uidError = true; 6013 if (!pkgSetting.uidError) { 6014 reportSettingsProblem(Log.ERROR, msg); 6015 } 6016 } 6017 } 6018 } 6019 pkg.applicationInfo.dataDir = dataPath.getPath(); 6020 if (mShouldRestoreconData) { 6021 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6022 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6023 pkg.applicationInfo.uid); 6024 } 6025 } else { 6026 if (DEBUG_PACKAGE_SCANNING) { 6027 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6028 Log.v(TAG, "Want this data dir: " + dataPath); 6029 } 6030 //invoke installer to do the actual installation 6031 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6032 pkg.applicationInfo.seinfo); 6033 if (ret < 0) { 6034 // Error from installer 6035 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6036 "Unable to create data dirs [errorCode=" + ret + "]"); 6037 } 6038 6039 if (dataPath.exists()) { 6040 pkg.applicationInfo.dataDir = dataPath.getPath(); 6041 } else { 6042 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6043 pkg.applicationInfo.dataDir = null; 6044 } 6045 } 6046 6047 pkgSetting.uidError = uidError; 6048 } 6049 6050 final String path = scanFile.getPath(); 6051 final String codePath = pkg.applicationInfo.getCodePath(); 6052 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6053 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 6054 setBundledAppAbisAndRoots(pkg, pkgSetting); 6055 6056 // If we haven't found any native libraries for the app, check if it has 6057 // renderscript code. We'll need to force the app to 32 bit if it has 6058 // renderscript bitcode. 6059 if (pkg.applicationInfo.primaryCpuAbi == null 6060 && pkg.applicationInfo.secondaryCpuAbi == null 6061 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6062 NativeLibraryHelper.Handle handle = null; 6063 try { 6064 handle = NativeLibraryHelper.Handle.create(scanFile); 6065 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6066 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6067 } 6068 } catch (IOException ioe) { 6069 Slog.w(TAG, "Error scanning system app : " + ioe); 6070 } finally { 6071 IoUtils.closeQuietly(handle); 6072 } 6073 } 6074 6075 setNativeLibraryPaths(pkg); 6076 } else { 6077 // TODO: We can probably be smarter about this stuff. For installed apps, 6078 // we can calculate this information at install time once and for all. For 6079 // system apps, we can probably assume that this information doesn't change 6080 // after the first boot scan. As things stand, we do lots of unnecessary work. 6081 6082 // Give ourselves some initial paths; we'll come back for another 6083 // pass once we've determined ABI below. 6084 setNativeLibraryPaths(pkg); 6085 6086 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6087 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6088 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6089 6090 NativeLibraryHelper.Handle handle = null; 6091 try { 6092 handle = NativeLibraryHelper.Handle.create(scanFile); 6093 // TODO(multiArch): This can be null for apps that didn't go through the 6094 // usual installation process. We can calculate it again, like we 6095 // do during install time. 6096 // 6097 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6098 // unnecessary. 6099 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6100 6101 // Null out the abis so that they can be recalculated. 6102 pkg.applicationInfo.primaryCpuAbi = null; 6103 pkg.applicationInfo.secondaryCpuAbi = null; 6104 if (isMultiArch(pkg.applicationInfo)) { 6105 // Warn if we've set an abiOverride for multi-lib packages.. 6106 // By definition, we need to copy both 32 and 64 bit libraries for 6107 // such packages. 6108 if (pkg.cpuAbiOverride != null 6109 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6110 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6111 } 6112 6113 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6114 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6115 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6116 if (isAsec) { 6117 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6118 } else { 6119 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6120 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6121 useIsaSpecificSubdirs); 6122 } 6123 } 6124 6125 maybeThrowExceptionForMultiArchCopy( 6126 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6127 6128 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6129 if (isAsec) { 6130 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6131 } else { 6132 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6133 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6134 useIsaSpecificSubdirs); 6135 } 6136 } 6137 6138 maybeThrowExceptionForMultiArchCopy( 6139 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6140 6141 if (abi64 >= 0) { 6142 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6143 } 6144 6145 if (abi32 >= 0) { 6146 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6147 if (abi64 >= 0) { 6148 pkg.applicationInfo.secondaryCpuAbi = abi; 6149 } else { 6150 pkg.applicationInfo.primaryCpuAbi = abi; 6151 } 6152 } 6153 } else { 6154 String[] abiList = (cpuAbiOverride != null) ? 6155 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6156 6157 // Enable gross and lame hacks for apps that are built with old 6158 // SDK tools. We must scan their APKs for renderscript bitcode and 6159 // not launch them if it's present. Don't bother checking on devices 6160 // that don't have 64 bit support. 6161 boolean needsRenderScriptOverride = false; 6162 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6163 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6164 abiList = Build.SUPPORTED_32_BIT_ABIS; 6165 needsRenderScriptOverride = true; 6166 } 6167 6168 final int copyRet; 6169 if (isAsec) { 6170 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6171 } else { 6172 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6173 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6174 } 6175 6176 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6177 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6178 "Error unpackaging native libs for app, errorCode=" + copyRet); 6179 } 6180 6181 if (copyRet >= 0) { 6182 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6183 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6184 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6185 } else if (needsRenderScriptOverride) { 6186 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6187 } 6188 } 6189 } catch (IOException ioe) { 6190 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6191 } finally { 6192 IoUtils.closeQuietly(handle); 6193 } 6194 6195 // Now that we've calculated the ABIs and determined if it's an internal app, 6196 // we will go ahead and populate the nativeLibraryPath. 6197 setNativeLibraryPaths(pkg); 6198 6199 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6200 final int[] userIds = sUserManager.getUserIds(); 6201 synchronized (mInstallLock) { 6202 // Create a native library symlink only if we have native libraries 6203 // and if the native libraries are 32 bit libraries. We do not provide 6204 // this symlink for 64 bit libraries. 6205 if (pkg.applicationInfo.primaryCpuAbi != null && 6206 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6207 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6208 for (int userId : userIds) { 6209 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6210 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6211 "Failed linking native library dir (user=" + userId + ")"); 6212 } 6213 } 6214 } 6215 } 6216 } 6217 6218 // This is a special case for the "system" package, where the ABI is 6219 // dictated by the zygote configuration (and init.rc). We should keep track 6220 // of this ABI so that we can deal with "normal" applications that run under 6221 // the same UID correctly. 6222 if (mPlatformPackage == pkg) { 6223 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6224 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6225 } 6226 6227 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6228 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6229 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6230 // Copy the derived override back to the parsed package, so that we can 6231 // update the package settings accordingly. 6232 pkg.cpuAbiOverride = cpuAbiOverride; 6233 6234 if (DEBUG_ABI_SELECTION) { 6235 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6236 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6237 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6238 } 6239 6240 // Push the derived path down into PackageSettings so we know what to 6241 // clean up at uninstall time. 6242 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6243 6244 if (DEBUG_ABI_SELECTION) { 6245 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6246 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6247 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6248 } 6249 6250 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6251 // We don't do this here during boot because we can do it all 6252 // at once after scanning all existing packages. 6253 // 6254 // We also do this *before* we perform dexopt on this package, so that 6255 // we can avoid redundant dexopts, and also to make sure we've got the 6256 // code and package path correct. 6257 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6258 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6259 } 6260 6261 if ((scanFlags & SCAN_NO_DEX) == 0) { 6262 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6263 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6264 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6265 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6266 } 6267 } 6268 6269 if (mFactoryTest && pkg.requestedPermissions.contains( 6270 android.Manifest.permission.FACTORY_TEST)) { 6271 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6272 } 6273 6274 ArrayList<PackageParser.Package> clientLibPkgs = null; 6275 6276 // writer 6277 synchronized (mPackages) { 6278 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6279 // Only system apps can add new shared libraries. 6280 if (pkg.libraryNames != null) { 6281 for (int i=0; i<pkg.libraryNames.size(); i++) { 6282 String name = pkg.libraryNames.get(i); 6283 boolean allowed = false; 6284 if (isUpdatedSystemApp(pkg)) { 6285 // New library entries can only be added through the 6286 // system image. This is important to get rid of a lot 6287 // of nasty edge cases: for example if we allowed a non- 6288 // system update of the app to add a library, then uninstalling 6289 // the update would make the library go away, and assumptions 6290 // we made such as through app install filtering would now 6291 // have allowed apps on the device which aren't compatible 6292 // with it. Better to just have the restriction here, be 6293 // conservative, and create many fewer cases that can negatively 6294 // impact the user experience. 6295 final PackageSetting sysPs = mSettings 6296 .getDisabledSystemPkgLPr(pkg.packageName); 6297 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6298 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6299 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6300 allowed = true; 6301 allowed = true; 6302 break; 6303 } 6304 } 6305 } 6306 } else { 6307 allowed = true; 6308 } 6309 if (allowed) { 6310 if (!mSharedLibraries.containsKey(name)) { 6311 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6312 } else if (!name.equals(pkg.packageName)) { 6313 Slog.w(TAG, "Package " + pkg.packageName + " library " 6314 + name + " already exists; skipping"); 6315 } 6316 } else { 6317 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6318 + name + " that is not declared on system image; skipping"); 6319 } 6320 } 6321 if ((scanFlags&SCAN_BOOTING) == 0) { 6322 // If we are not booting, we need to update any applications 6323 // that are clients of our shared library. If we are booting, 6324 // this will all be done once the scan is complete. 6325 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6326 } 6327 } 6328 } 6329 } 6330 6331 // We also need to dexopt any apps that are dependent on this library. Note that 6332 // if these fail, we should abort the install since installing the library will 6333 // result in some apps being broken. 6334 if (clientLibPkgs != null) { 6335 if ((scanFlags & SCAN_NO_DEX) == 0) { 6336 for (int i = 0; i < clientLibPkgs.size(); i++) { 6337 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6338 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6339 null /* instruction sets */, forceDex, 6340 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6341 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6342 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6343 "scanPackageLI failed to dexopt clientLibPkgs"); 6344 } 6345 } 6346 } 6347 } 6348 6349 // Request the ActivityManager to kill the process(only for existing packages) 6350 // so that we do not end up in a confused state while the user is still using the older 6351 // version of the application while the new one gets installed. 6352 if ((scanFlags & SCAN_REPLACING) != 0) { 6353 killApplication(pkg.applicationInfo.packageName, 6354 pkg.applicationInfo.uid, "update pkg"); 6355 } 6356 6357 // Also need to kill any apps that are dependent on the library. 6358 if (clientLibPkgs != null) { 6359 for (int i=0; i<clientLibPkgs.size(); i++) { 6360 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6361 killApplication(clientPkg.applicationInfo.packageName, 6362 clientPkg.applicationInfo.uid, "update lib"); 6363 } 6364 } 6365 6366 // writer 6367 synchronized (mPackages) { 6368 // We don't expect installation to fail beyond this point 6369 6370 // Add the new setting to mSettings 6371 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6372 // Add the new setting to mPackages 6373 mPackages.put(pkg.applicationInfo.packageName, pkg); 6374 // Make sure we don't accidentally delete its data. 6375 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6376 while (iter.hasNext()) { 6377 PackageCleanItem item = iter.next(); 6378 if (pkgName.equals(item.packageName)) { 6379 iter.remove(); 6380 } 6381 } 6382 6383 // Take care of first install / last update times. 6384 if (currentTime != 0) { 6385 if (pkgSetting.firstInstallTime == 0) { 6386 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6387 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6388 pkgSetting.lastUpdateTime = currentTime; 6389 } 6390 } else if (pkgSetting.firstInstallTime == 0) { 6391 // We need *something*. Take time time stamp of the file. 6392 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6393 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6394 if (scanFileTime != pkgSetting.timeStamp) { 6395 // A package on the system image has changed; consider this 6396 // to be an update. 6397 pkgSetting.lastUpdateTime = scanFileTime; 6398 } 6399 } 6400 6401 // Add the package's KeySets to the global KeySetManagerService 6402 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6403 try { 6404 // Old KeySetData no longer valid. 6405 ksms.removeAppKeySetDataLPw(pkg.packageName); 6406 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6407 if (pkg.mKeySetMapping != null) { 6408 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6409 pkg.mKeySetMapping.entrySet()) { 6410 if (entry.getValue() != null) { 6411 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6412 entry.getValue(), entry.getKey()); 6413 } 6414 } 6415 if (pkg.mUpgradeKeySets != null) { 6416 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6417 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6418 } 6419 } 6420 } 6421 } catch (NullPointerException e) { 6422 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6423 } catch (IllegalArgumentException e) { 6424 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6425 } 6426 6427 int N = pkg.providers.size(); 6428 StringBuilder r = null; 6429 int i; 6430 for (i=0; i<N; i++) { 6431 PackageParser.Provider p = pkg.providers.get(i); 6432 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6433 p.info.processName, pkg.applicationInfo.uid); 6434 mProviders.addProvider(p); 6435 p.syncable = p.info.isSyncable; 6436 if (p.info.authority != null) { 6437 String names[] = p.info.authority.split(";"); 6438 p.info.authority = null; 6439 for (int j = 0; j < names.length; j++) { 6440 if (j == 1 && p.syncable) { 6441 // We only want the first authority for a provider to possibly be 6442 // syncable, so if we already added this provider using a different 6443 // authority clear the syncable flag. We copy the provider before 6444 // changing it because the mProviders object contains a reference 6445 // to a provider that we don't want to change. 6446 // Only do this for the second authority since the resulting provider 6447 // object can be the same for all future authorities for this provider. 6448 p = new PackageParser.Provider(p); 6449 p.syncable = false; 6450 } 6451 if (!mProvidersByAuthority.containsKey(names[j])) { 6452 mProvidersByAuthority.put(names[j], p); 6453 if (p.info.authority == null) { 6454 p.info.authority = names[j]; 6455 } else { 6456 p.info.authority = p.info.authority + ";" + names[j]; 6457 } 6458 if (DEBUG_PACKAGE_SCANNING) { 6459 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6460 Log.d(TAG, "Registered content provider: " + names[j] 6461 + ", className = " + p.info.name + ", isSyncable = " 6462 + p.info.isSyncable); 6463 } 6464 } else { 6465 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6466 Slog.w(TAG, "Skipping provider name " + names[j] + 6467 " (in package " + pkg.applicationInfo.packageName + 6468 "): name already used by " 6469 + ((other != null && other.getComponentName() != null) 6470 ? other.getComponentName().getPackageName() : "?")); 6471 } 6472 } 6473 } 6474 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6475 if (r == null) { 6476 r = new StringBuilder(256); 6477 } else { 6478 r.append(' '); 6479 } 6480 r.append(p.info.name); 6481 } 6482 } 6483 if (r != null) { 6484 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6485 } 6486 6487 N = pkg.services.size(); 6488 r = null; 6489 for (i=0; i<N; i++) { 6490 PackageParser.Service s = pkg.services.get(i); 6491 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6492 s.info.processName, pkg.applicationInfo.uid); 6493 mServices.addService(s); 6494 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6495 if (r == null) { 6496 r = new StringBuilder(256); 6497 } else { 6498 r.append(' '); 6499 } 6500 r.append(s.info.name); 6501 } 6502 } 6503 if (r != null) { 6504 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6505 } 6506 6507 N = pkg.receivers.size(); 6508 r = null; 6509 for (i=0; i<N; i++) { 6510 PackageParser.Activity a = pkg.receivers.get(i); 6511 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6512 a.info.processName, pkg.applicationInfo.uid); 6513 mReceivers.addActivity(a, "receiver"); 6514 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6515 if (r == null) { 6516 r = new StringBuilder(256); 6517 } else { 6518 r.append(' '); 6519 } 6520 r.append(a.info.name); 6521 } 6522 } 6523 if (r != null) { 6524 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6525 } 6526 6527 N = pkg.activities.size(); 6528 r = null; 6529 for (i=0; i<N; i++) { 6530 PackageParser.Activity a = pkg.activities.get(i); 6531 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6532 a.info.processName, pkg.applicationInfo.uid); 6533 mActivities.addActivity(a, "activity"); 6534 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6535 if (r == null) { 6536 r = new StringBuilder(256); 6537 } else { 6538 r.append(' '); 6539 } 6540 r.append(a.info.name); 6541 } 6542 } 6543 if (r != null) { 6544 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6545 } 6546 6547 N = pkg.permissionGroups.size(); 6548 r = null; 6549 for (i=0; i<N; i++) { 6550 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6551 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6552 if (cur == null) { 6553 mPermissionGroups.put(pg.info.name, pg); 6554 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6555 if (r == null) { 6556 r = new StringBuilder(256); 6557 } else { 6558 r.append(' '); 6559 } 6560 r.append(pg.info.name); 6561 } 6562 } else { 6563 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6564 + pg.info.packageName + " ignored: original from " 6565 + cur.info.packageName); 6566 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6567 if (r == null) { 6568 r = new StringBuilder(256); 6569 } else { 6570 r.append(' '); 6571 } 6572 r.append("DUP:"); 6573 r.append(pg.info.name); 6574 } 6575 } 6576 } 6577 if (r != null) { 6578 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6579 } 6580 6581 N = pkg.permissions.size(); 6582 r = null; 6583 for (i=0; i<N; i++) { 6584 PackageParser.Permission p = pkg.permissions.get(i); 6585 ArrayMap<String, BasePermission> permissionMap = 6586 p.tree ? mSettings.mPermissionTrees 6587 : mSettings.mPermissions; 6588 p.group = mPermissionGroups.get(p.info.group); 6589 if (p.info.group == null || p.group != null) { 6590 BasePermission bp = permissionMap.get(p.info.name); 6591 6592 // Allow system apps to redefine non-system permissions 6593 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6594 final boolean currentOwnerIsSystem = (bp.perm != null 6595 && isSystemApp(bp.perm.owner)); 6596 if (isSystemApp(p.owner)) { 6597 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6598 // It's a built-in permission and no owner, take ownership now 6599 bp.packageSetting = pkgSetting; 6600 bp.perm = p; 6601 bp.uid = pkg.applicationInfo.uid; 6602 bp.sourcePackage = p.info.packageName; 6603 } else if (!currentOwnerIsSystem) { 6604 String msg = "New decl " + p.owner + " of permission " 6605 + p.info.name + " is system; overriding " + bp.sourcePackage; 6606 reportSettingsProblem(Log.WARN, msg); 6607 bp = null; 6608 } 6609 } 6610 } 6611 6612 if (bp == null) { 6613 bp = new BasePermission(p.info.name, p.info.packageName, 6614 BasePermission.TYPE_NORMAL); 6615 permissionMap.put(p.info.name, bp); 6616 } 6617 6618 if (bp.perm == null) { 6619 if (bp.sourcePackage == null 6620 || bp.sourcePackage.equals(p.info.packageName)) { 6621 BasePermission tree = findPermissionTreeLP(p.info.name); 6622 if (tree == null 6623 || tree.sourcePackage.equals(p.info.packageName)) { 6624 bp.packageSetting = pkgSetting; 6625 bp.perm = p; 6626 bp.uid = pkg.applicationInfo.uid; 6627 bp.sourcePackage = p.info.packageName; 6628 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6629 if (r == null) { 6630 r = new StringBuilder(256); 6631 } else { 6632 r.append(' '); 6633 } 6634 r.append(p.info.name); 6635 } 6636 } else { 6637 Slog.w(TAG, "Permission " + p.info.name + " from package " 6638 + p.info.packageName + " ignored: base tree " 6639 + tree.name + " is from package " 6640 + tree.sourcePackage); 6641 } 6642 } else { 6643 Slog.w(TAG, "Permission " + p.info.name + " from package " 6644 + p.info.packageName + " ignored: original from " 6645 + bp.sourcePackage); 6646 } 6647 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6648 if (r == null) { 6649 r = new StringBuilder(256); 6650 } else { 6651 r.append(' '); 6652 } 6653 r.append("DUP:"); 6654 r.append(p.info.name); 6655 } 6656 if (bp.perm == p) { 6657 bp.protectionLevel = p.info.protectionLevel; 6658 } 6659 } else { 6660 Slog.w(TAG, "Permission " + p.info.name + " from package " 6661 + p.info.packageName + " ignored: no group " 6662 + p.group); 6663 } 6664 } 6665 if (r != null) { 6666 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6667 } 6668 6669 N = pkg.instrumentation.size(); 6670 r = null; 6671 for (i=0; i<N; i++) { 6672 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6673 a.info.packageName = pkg.applicationInfo.packageName; 6674 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6675 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6676 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6677 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6678 a.info.dataDir = pkg.applicationInfo.dataDir; 6679 6680 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6681 // need other information about the application, like the ABI and what not ? 6682 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6683 mInstrumentation.put(a.getComponentName(), a); 6684 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6685 if (r == null) { 6686 r = new StringBuilder(256); 6687 } else { 6688 r.append(' '); 6689 } 6690 r.append(a.info.name); 6691 } 6692 } 6693 if (r != null) { 6694 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6695 } 6696 6697 if (pkg.protectedBroadcasts != null) { 6698 N = pkg.protectedBroadcasts.size(); 6699 for (i=0; i<N; i++) { 6700 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6701 } 6702 } 6703 6704 pkgSetting.setTimeStamp(scanFileTime); 6705 6706 // Create idmap files for pairs of (packages, overlay packages). 6707 // Note: "android", ie framework-res.apk, is handled by native layers. 6708 if (pkg.mOverlayTarget != null) { 6709 // This is an overlay package. 6710 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6711 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6712 mOverlays.put(pkg.mOverlayTarget, 6713 new ArrayMap<String, PackageParser.Package>()); 6714 } 6715 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6716 map.put(pkg.packageName, pkg); 6717 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6718 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6719 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6720 "scanPackageLI failed to createIdmap"); 6721 } 6722 } 6723 } else if (mOverlays.containsKey(pkg.packageName) && 6724 !pkg.packageName.equals("android")) { 6725 // This is a regular package, with one or more known overlay packages. 6726 createIdmapsForPackageLI(pkg); 6727 } 6728 } 6729 6730 return pkg; 6731 } 6732 6733 /** 6734 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6735 * i.e, so that all packages can be run inside a single process if required. 6736 * 6737 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6738 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6739 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6740 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6741 * updating a package that belongs to a shared user. 6742 * 6743 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6744 * adds unnecessary complexity. 6745 */ 6746 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6747 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6748 String requiredInstructionSet = null; 6749 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6750 requiredInstructionSet = VMRuntime.getInstructionSet( 6751 scannedPackage.applicationInfo.primaryCpuAbi); 6752 } 6753 6754 PackageSetting requirer = null; 6755 for (PackageSetting ps : packagesForUser) { 6756 // If packagesForUser contains scannedPackage, we skip it. This will happen 6757 // when scannedPackage is an update of an existing package. Without this check, 6758 // we will never be able to change the ABI of any package belonging to a shared 6759 // user, even if it's compatible with other packages. 6760 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6761 if (ps.primaryCpuAbiString == null) { 6762 continue; 6763 } 6764 6765 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6766 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6767 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6768 // this but there's not much we can do. 6769 String errorMessage = "Instruction set mismatch, " 6770 + ((requirer == null) ? "[caller]" : requirer) 6771 + " requires " + requiredInstructionSet + " whereas " + ps 6772 + " requires " + instructionSet; 6773 Slog.w(TAG, errorMessage); 6774 } 6775 6776 if (requiredInstructionSet == null) { 6777 requiredInstructionSet = instructionSet; 6778 requirer = ps; 6779 } 6780 } 6781 } 6782 6783 if (requiredInstructionSet != null) { 6784 String adjustedAbi; 6785 if (requirer != null) { 6786 // requirer != null implies that either scannedPackage was null or that scannedPackage 6787 // did not require an ABI, in which case we have to adjust scannedPackage to match 6788 // the ABI of the set (which is the same as requirer's ABI) 6789 adjustedAbi = requirer.primaryCpuAbiString; 6790 if (scannedPackage != null) { 6791 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6792 } 6793 } else { 6794 // requirer == null implies that we're updating all ABIs in the set to 6795 // match scannedPackage. 6796 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6797 } 6798 6799 for (PackageSetting ps : packagesForUser) { 6800 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6801 if (ps.primaryCpuAbiString != null) { 6802 continue; 6803 } 6804 6805 ps.primaryCpuAbiString = adjustedAbi; 6806 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6807 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6808 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6809 6810 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6811 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6812 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6813 ps.primaryCpuAbiString = null; 6814 ps.pkg.applicationInfo.primaryCpuAbi = null; 6815 return; 6816 } else { 6817 mInstaller.rmdex(ps.codePathString, 6818 getDexCodeInstructionSet(getPreferredInstructionSet())); 6819 } 6820 } 6821 } 6822 } 6823 } 6824 } 6825 6826 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6827 synchronized (mPackages) { 6828 mResolverReplaced = true; 6829 // Set up information for custom user intent resolution activity. 6830 mResolveActivity.applicationInfo = pkg.applicationInfo; 6831 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6832 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6833 mResolveActivity.processName = pkg.applicationInfo.packageName; 6834 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6835 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6836 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6837 mResolveActivity.theme = 0; 6838 mResolveActivity.exported = true; 6839 mResolveActivity.enabled = true; 6840 mResolveInfo.activityInfo = mResolveActivity; 6841 mResolveInfo.priority = 0; 6842 mResolveInfo.preferredOrder = 0; 6843 mResolveInfo.match = 0; 6844 mResolveComponentName = mCustomResolverComponentName; 6845 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6846 mResolveComponentName); 6847 } 6848 } 6849 6850 private static String calculateBundledApkRoot(final String codePathString) { 6851 final File codePath = new File(codePathString); 6852 final File codeRoot; 6853 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6854 codeRoot = Environment.getRootDirectory(); 6855 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6856 codeRoot = Environment.getOemDirectory(); 6857 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6858 codeRoot = Environment.getVendorDirectory(); 6859 } else { 6860 // Unrecognized code path; take its top real segment as the apk root: 6861 // e.g. /something/app/blah.apk => /something 6862 try { 6863 File f = codePath.getCanonicalFile(); 6864 File parent = f.getParentFile(); // non-null because codePath is a file 6865 File tmp; 6866 while ((tmp = parent.getParentFile()) != null) { 6867 f = parent; 6868 parent = tmp; 6869 } 6870 codeRoot = f; 6871 Slog.w(TAG, "Unrecognized code path " 6872 + codePath + " - using " + codeRoot); 6873 } catch (IOException e) { 6874 // Can't canonicalize the code path -- shenanigans? 6875 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6876 return Environment.getRootDirectory().getPath(); 6877 } 6878 } 6879 return codeRoot.getPath(); 6880 } 6881 6882 /** 6883 * Derive and set the location of native libraries for the given package, 6884 * which varies depending on where and how the package was installed. 6885 */ 6886 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6887 final ApplicationInfo info = pkg.applicationInfo; 6888 final String codePath = pkg.codePath; 6889 final File codeFile = new File(codePath); 6890 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6891 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6892 6893 info.nativeLibraryRootDir = null; 6894 info.nativeLibraryRootRequiresIsa = false; 6895 info.nativeLibraryDir = null; 6896 info.secondaryNativeLibraryDir = null; 6897 6898 if (isApkFile(codeFile)) { 6899 // Monolithic install 6900 if (bundledApp) { 6901 // If "/system/lib64/apkname" exists, assume that is the per-package 6902 // native library directory to use; otherwise use "/system/lib/apkname". 6903 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6904 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6905 getPrimaryInstructionSet(info)); 6906 6907 // This is a bundled system app so choose the path based on the ABI. 6908 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6909 // is just the default path. 6910 final String apkName = deriveCodePathName(codePath); 6911 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6912 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6913 apkName).getAbsolutePath(); 6914 6915 if (info.secondaryCpuAbi != null) { 6916 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6917 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6918 secondaryLibDir, apkName).getAbsolutePath(); 6919 } 6920 } else if (asecApp) { 6921 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6922 .getAbsolutePath(); 6923 } else { 6924 final String apkName = deriveCodePathName(codePath); 6925 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6926 .getAbsolutePath(); 6927 } 6928 6929 info.nativeLibraryRootRequiresIsa = false; 6930 info.nativeLibraryDir = info.nativeLibraryRootDir; 6931 } else { 6932 // Cluster install 6933 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6934 info.nativeLibraryRootRequiresIsa = true; 6935 6936 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6937 getPrimaryInstructionSet(info)).getAbsolutePath(); 6938 6939 if (info.secondaryCpuAbi != null) { 6940 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6941 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6942 } 6943 } 6944 } 6945 6946 /** 6947 * Calculate the abis and roots for a bundled app. These can uniquely 6948 * be determined from the contents of the system partition, i.e whether 6949 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6950 * of this information, and instead assume that the system was built 6951 * sensibly. 6952 */ 6953 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6954 PackageSetting pkgSetting) { 6955 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6956 6957 // If "/system/lib64/apkname" exists, assume that is the per-package 6958 // native library directory to use; otherwise use "/system/lib/apkname". 6959 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6960 setBundledAppAbi(pkg, apkRoot, apkName); 6961 // pkgSetting might be null during rescan following uninstall of updates 6962 // to a bundled app, so accommodate that possibility. The settings in 6963 // that case will be established later from the parsed package. 6964 // 6965 // If the settings aren't null, sync them up with what we've just derived. 6966 // note that apkRoot isn't stored in the package settings. 6967 if (pkgSetting != null) { 6968 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6969 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6970 } 6971 } 6972 6973 /** 6974 * Deduces the ABI of a bundled app and sets the relevant fields on the 6975 * parsed pkg object. 6976 * 6977 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6978 * under which system libraries are installed. 6979 * @param apkName the name of the installed package. 6980 */ 6981 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6982 final File codeFile = new File(pkg.codePath); 6983 6984 final boolean has64BitLibs; 6985 final boolean has32BitLibs; 6986 if (isApkFile(codeFile)) { 6987 // Monolithic install 6988 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6989 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6990 } else { 6991 // Cluster install 6992 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6993 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6994 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6995 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6996 has64BitLibs = (new File(rootDir, isa)).exists(); 6997 } else { 6998 has64BitLibs = false; 6999 } 7000 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7001 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7002 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7003 has32BitLibs = (new File(rootDir, isa)).exists(); 7004 } else { 7005 has32BitLibs = false; 7006 } 7007 } 7008 7009 if (has64BitLibs && !has32BitLibs) { 7010 // The package has 64 bit libs, but not 32 bit libs. Its primary 7011 // ABI should be 64 bit. We can safely assume here that the bundled 7012 // native libraries correspond to the most preferred ABI in the list. 7013 7014 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7015 pkg.applicationInfo.secondaryCpuAbi = null; 7016 } else if (has32BitLibs && !has64BitLibs) { 7017 // The package has 32 bit libs but not 64 bit libs. Its primary 7018 // ABI should be 32 bit. 7019 7020 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7021 pkg.applicationInfo.secondaryCpuAbi = null; 7022 } else if (has32BitLibs && has64BitLibs) { 7023 // The application has both 64 and 32 bit bundled libraries. We check 7024 // here that the app declares multiArch support, and warn if it doesn't. 7025 // 7026 // We will be lenient here and record both ABIs. The primary will be the 7027 // ABI that's higher on the list, i.e, a device that's configured to prefer 7028 // 64 bit apps will see a 64 bit primary ABI, 7029 7030 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7031 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7032 } 7033 7034 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7035 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7036 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7037 } else { 7038 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7039 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7040 } 7041 } else { 7042 pkg.applicationInfo.primaryCpuAbi = null; 7043 pkg.applicationInfo.secondaryCpuAbi = null; 7044 } 7045 } 7046 7047 private void killApplication(String pkgName, int appId, String reason) { 7048 // Request the ActivityManager to kill the process(only for existing packages) 7049 // so that we do not end up in a confused state while the user is still using the older 7050 // version of the application while the new one gets installed. 7051 IActivityManager am = ActivityManagerNative.getDefault(); 7052 if (am != null) { 7053 try { 7054 am.killApplicationWithAppId(pkgName, appId, reason); 7055 } catch (RemoteException e) { 7056 } 7057 } 7058 } 7059 7060 void removePackageLI(PackageSetting ps, boolean chatty) { 7061 if (DEBUG_INSTALL) { 7062 if (chatty) 7063 Log.d(TAG, "Removing package " + ps.name); 7064 } 7065 7066 // writer 7067 synchronized (mPackages) { 7068 mPackages.remove(ps.name); 7069 final PackageParser.Package pkg = ps.pkg; 7070 if (pkg != null) { 7071 cleanPackageDataStructuresLILPw(pkg, chatty); 7072 } 7073 } 7074 } 7075 7076 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7077 if (DEBUG_INSTALL) { 7078 if (chatty) 7079 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7080 } 7081 7082 // writer 7083 synchronized (mPackages) { 7084 mPackages.remove(pkg.applicationInfo.packageName); 7085 cleanPackageDataStructuresLILPw(pkg, chatty); 7086 } 7087 } 7088 7089 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7090 int N = pkg.providers.size(); 7091 StringBuilder r = null; 7092 int i; 7093 for (i=0; i<N; i++) { 7094 PackageParser.Provider p = pkg.providers.get(i); 7095 mProviders.removeProvider(p); 7096 if (p.info.authority == null) { 7097 7098 /* There was another ContentProvider with this authority when 7099 * this app was installed so this authority is null, 7100 * Ignore it as we don't have to unregister the provider. 7101 */ 7102 continue; 7103 } 7104 String names[] = p.info.authority.split(";"); 7105 for (int j = 0; j < names.length; j++) { 7106 if (mProvidersByAuthority.get(names[j]) == p) { 7107 mProvidersByAuthority.remove(names[j]); 7108 if (DEBUG_REMOVE) { 7109 if (chatty) 7110 Log.d(TAG, "Unregistered content provider: " + names[j] 7111 + ", className = " + p.info.name + ", isSyncable = " 7112 + p.info.isSyncable); 7113 } 7114 } 7115 } 7116 if (DEBUG_REMOVE && chatty) { 7117 if (r == null) { 7118 r = new StringBuilder(256); 7119 } else { 7120 r.append(' '); 7121 } 7122 r.append(p.info.name); 7123 } 7124 } 7125 if (r != null) { 7126 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7127 } 7128 7129 N = pkg.services.size(); 7130 r = null; 7131 for (i=0; i<N; i++) { 7132 PackageParser.Service s = pkg.services.get(i); 7133 mServices.removeService(s); 7134 if (chatty) { 7135 if (r == null) { 7136 r = new StringBuilder(256); 7137 } else { 7138 r.append(' '); 7139 } 7140 r.append(s.info.name); 7141 } 7142 } 7143 if (r != null) { 7144 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7145 } 7146 7147 N = pkg.receivers.size(); 7148 r = null; 7149 for (i=0; i<N; i++) { 7150 PackageParser.Activity a = pkg.receivers.get(i); 7151 mReceivers.removeActivity(a, "receiver"); 7152 if (DEBUG_REMOVE && chatty) { 7153 if (r == null) { 7154 r = new StringBuilder(256); 7155 } else { 7156 r.append(' '); 7157 } 7158 r.append(a.info.name); 7159 } 7160 } 7161 if (r != null) { 7162 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7163 } 7164 7165 N = pkg.activities.size(); 7166 r = null; 7167 for (i=0; i<N; i++) { 7168 PackageParser.Activity a = pkg.activities.get(i); 7169 mActivities.removeActivity(a, "activity"); 7170 if (DEBUG_REMOVE && chatty) { 7171 if (r == null) { 7172 r = new StringBuilder(256); 7173 } else { 7174 r.append(' '); 7175 } 7176 r.append(a.info.name); 7177 } 7178 } 7179 if (r != null) { 7180 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7181 } 7182 7183 N = pkg.permissions.size(); 7184 r = null; 7185 for (i=0; i<N; i++) { 7186 PackageParser.Permission p = pkg.permissions.get(i); 7187 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7188 if (bp == null) { 7189 bp = mSettings.mPermissionTrees.get(p.info.name); 7190 } 7191 if (bp != null && bp.perm == p) { 7192 bp.perm = null; 7193 if (DEBUG_REMOVE && chatty) { 7194 if (r == null) { 7195 r = new StringBuilder(256); 7196 } else { 7197 r.append(' '); 7198 } 7199 r.append(p.info.name); 7200 } 7201 } 7202 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7203 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7204 if (appOpPerms != null) { 7205 appOpPerms.remove(pkg.packageName); 7206 } 7207 } 7208 } 7209 if (r != null) { 7210 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7211 } 7212 7213 N = pkg.requestedPermissions.size(); 7214 r = null; 7215 for (i=0; i<N; i++) { 7216 String perm = pkg.requestedPermissions.get(i); 7217 BasePermission bp = mSettings.mPermissions.get(perm); 7218 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7219 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7220 if (appOpPerms != null) { 7221 appOpPerms.remove(pkg.packageName); 7222 if (appOpPerms.isEmpty()) { 7223 mAppOpPermissionPackages.remove(perm); 7224 } 7225 } 7226 } 7227 } 7228 if (r != null) { 7229 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7230 } 7231 7232 N = pkg.instrumentation.size(); 7233 r = null; 7234 for (i=0; i<N; i++) { 7235 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7236 mInstrumentation.remove(a.getComponentName()); 7237 if (DEBUG_REMOVE && chatty) { 7238 if (r == null) { 7239 r = new StringBuilder(256); 7240 } else { 7241 r.append(' '); 7242 } 7243 r.append(a.info.name); 7244 } 7245 } 7246 if (r != null) { 7247 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7248 } 7249 7250 r = null; 7251 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7252 // Only system apps can hold shared libraries. 7253 if (pkg.libraryNames != null) { 7254 for (i=0; i<pkg.libraryNames.size(); i++) { 7255 String name = pkg.libraryNames.get(i); 7256 SharedLibraryEntry cur = mSharedLibraries.get(name); 7257 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7258 mSharedLibraries.remove(name); 7259 if (DEBUG_REMOVE && chatty) { 7260 if (r == null) { 7261 r = new StringBuilder(256); 7262 } else { 7263 r.append(' '); 7264 } 7265 r.append(name); 7266 } 7267 } 7268 } 7269 } 7270 } 7271 if (r != null) { 7272 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7273 } 7274 } 7275 7276 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7277 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7278 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7279 return true; 7280 } 7281 } 7282 return false; 7283 } 7284 7285 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7286 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7287 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7288 7289 private void updatePermissionsLPw(String changingPkg, 7290 PackageParser.Package pkgInfo, int flags) { 7291 // Make sure there are no dangling permission trees. 7292 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7293 while (it.hasNext()) { 7294 final BasePermission bp = it.next(); 7295 if (bp.packageSetting == null) { 7296 // We may not yet have parsed the package, so just see if 7297 // we still know about its settings. 7298 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7299 } 7300 if (bp.packageSetting == null) { 7301 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7302 + " from package " + bp.sourcePackage); 7303 it.remove(); 7304 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7305 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7306 Slog.i(TAG, "Removing old permission tree: " + bp.name 7307 + " from package " + bp.sourcePackage); 7308 flags |= UPDATE_PERMISSIONS_ALL; 7309 it.remove(); 7310 } 7311 } 7312 } 7313 7314 // Make sure all dynamic permissions have been assigned to a package, 7315 // and make sure there are no dangling permissions. 7316 it = mSettings.mPermissions.values().iterator(); 7317 while (it.hasNext()) { 7318 final BasePermission bp = it.next(); 7319 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7320 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7321 + bp.name + " pkg=" + bp.sourcePackage 7322 + " info=" + bp.pendingInfo); 7323 if (bp.packageSetting == null && bp.pendingInfo != null) { 7324 final BasePermission tree = findPermissionTreeLP(bp.name); 7325 if (tree != null && tree.perm != null) { 7326 bp.packageSetting = tree.packageSetting; 7327 bp.perm = new PackageParser.Permission(tree.perm.owner, 7328 new PermissionInfo(bp.pendingInfo)); 7329 bp.perm.info.packageName = tree.perm.info.packageName; 7330 bp.perm.info.name = bp.name; 7331 bp.uid = tree.uid; 7332 } 7333 } 7334 } 7335 if (bp.packageSetting == null) { 7336 // We may not yet have parsed the package, so just see if 7337 // we still know about its settings. 7338 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7339 } 7340 if (bp.packageSetting == null) { 7341 Slog.w(TAG, "Removing dangling permission: " + bp.name 7342 + " from package " + bp.sourcePackage); 7343 it.remove(); 7344 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7345 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7346 Slog.i(TAG, "Removing old permission: " + bp.name 7347 + " from package " + bp.sourcePackage); 7348 flags |= UPDATE_PERMISSIONS_ALL; 7349 it.remove(); 7350 } 7351 } 7352 } 7353 7354 // Now update the permissions for all packages, in particular 7355 // replace the granted permissions of the system packages. 7356 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7357 for (PackageParser.Package pkg : mPackages.values()) { 7358 if (pkg != pkgInfo) { 7359 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7360 changingPkg); 7361 } 7362 } 7363 } 7364 7365 if (pkgInfo != null) { 7366 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7367 } 7368 } 7369 7370 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7371 String packageOfInterest) { 7372 // IMPORTANT: There are two types of permissions: install and runtime. 7373 // Install time permissions are granted when the app is installed to 7374 // all device users and users added in the future. Runtime permissions 7375 // are granted at runtime explicitly to specific users. Normal and signature 7376 // protected permissions are install time permissions. Dangerous permissions 7377 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7378 // otherwise they are runtime permissions. This function does not manage 7379 // runtime permissions except for the case an app targeting Lollipop MR1 7380 // being upgraded to target a newer SDK, in which case dangerous permissions 7381 // are transformed from install time to runtime ones. 7382 7383 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7384 if (ps == null) { 7385 return; 7386 } 7387 7388 PermissionsState permissionsState = ps.getPermissionsState(); 7389 PermissionsState origPermissions = permissionsState; 7390 7391 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7392 7393 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7394 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7395 7396 boolean changedInstallPermission = false; 7397 7398 if (replace) { 7399 ps.installPermissionsFixed = false; 7400 origPermissions = new PermissionsState(permissionsState); 7401 permissionsState.reset(); 7402 } 7403 7404 permissionsState.setGlobalGids(mGlobalGids); 7405 7406 final int N = pkg.requestedPermissions.size(); 7407 for (int i=0; i<N; i++) { 7408 final String name = pkg.requestedPermissions.get(i); 7409 final BasePermission bp = mSettings.mPermissions.get(name); 7410 7411 if (DEBUG_INSTALL) { 7412 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7413 } 7414 7415 if (bp == null || bp.packageSetting == null) { 7416 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7417 Slog.w(TAG, "Unknown permission " + name 7418 + " in package " + pkg.packageName); 7419 } 7420 continue; 7421 } 7422 7423 final String perm = bp.name; 7424 boolean allowedSig = false; 7425 int grant = GRANT_DENIED; 7426 7427 // Keep track of app op permissions. 7428 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7429 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7430 if (pkgs == null) { 7431 pkgs = new ArraySet<>(); 7432 mAppOpPermissionPackages.put(bp.name, pkgs); 7433 } 7434 pkgs.add(pkg.packageName); 7435 } 7436 7437 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7438 switch (level) { 7439 case PermissionInfo.PROTECTION_NORMAL: { 7440 // For all apps normal permissions are install time ones. 7441 grant = GRANT_INSTALL; 7442 } break; 7443 7444 case PermissionInfo.PROTECTION_DANGEROUS: { 7445 if (!RUNTIME_PERMISSIONS_ENABLED 7446 || pkg.applicationInfo.targetSdkVersion 7447 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7448 // For legacy apps dangerous permissions are install time ones. 7449 grant = GRANT_INSTALL; 7450 } else if (ps.isSystem()) { 7451 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7452 if (origPermissions.hasInstallPermission(bp.name)) { 7453 // If a system app had an install permission, then the app was 7454 // upgraded and we grant the permissions as runtime to all users. 7455 grant = GRANT_UPGRADE; 7456 upgradeUserIds = currentUserIds; 7457 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7458 // If users changed since the last permissions update for a 7459 // system app, we grant the permission as runtime to the new users. 7460 grant = GRANT_UPGRADE; 7461 upgradeUserIds = currentUserIds; 7462 for (int userId : updatedUserIds) { 7463 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7464 } 7465 } else { 7466 // Otherwise, we grant the permission as runtime if the app 7467 // already had it, i.e. we preserve runtime permissions. 7468 grant = GRANT_RUNTIME; 7469 } 7470 } else if (origPermissions.hasInstallPermission(bp.name)) { 7471 // For legacy apps that became modern, install becomes runtime. 7472 grant = GRANT_UPGRADE; 7473 upgradeUserIds = currentUserIds; 7474 } else if (replace) { 7475 // For upgraded modern apps keep runtime permissions unchanged. 7476 grant = GRANT_RUNTIME; 7477 } 7478 } break; 7479 7480 case PermissionInfo.PROTECTION_SIGNATURE: { 7481 // For all apps signature permissions are install time ones. 7482 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7483 if (allowedSig) { 7484 grant = GRANT_INSTALL; 7485 } 7486 } break; 7487 } 7488 7489 if (DEBUG_INSTALL) { 7490 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7491 } 7492 7493 if (grant != GRANT_DENIED) { 7494 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7495 // If this is an existing, non-system package, then 7496 // we can't add any new permissions to it. 7497 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7498 // Except... if this is a permission that was added 7499 // to the platform (note: need to only do this when 7500 // updating the platform). 7501 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7502 grant = GRANT_DENIED; 7503 } 7504 } 7505 } 7506 7507 switch (grant) { 7508 case GRANT_INSTALL: { 7509 // Grant an install permission. 7510 if (permissionsState.grantInstallPermission(bp) != 7511 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7512 changedInstallPermission = true; 7513 } 7514 } break; 7515 7516 case GRANT_RUNTIME: { 7517 // Grant previously granted runtime permissions. 7518 for (int userId : UserManagerService.getInstance().getUserIds()) { 7519 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7520 if (permissionsState.grantRuntimePermission(bp, userId) == 7521 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7522 // If we cannot put the permission as it was, we have to write. 7523 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7524 changedRuntimePermissionUserIds, userId); 7525 } 7526 } 7527 } 7528 } break; 7529 7530 case GRANT_UPGRADE: { 7531 // Grant runtime permissions for a previously held install permission. 7532 permissionsState.revokeInstallPermission(bp); 7533 for (int userId : upgradeUserIds) { 7534 if (permissionsState.grantRuntimePermission(bp, userId) != 7535 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7536 // If we granted the permission, we have to write. 7537 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7538 changedRuntimePermissionUserIds, userId); 7539 } 7540 } 7541 } break; 7542 7543 default: { 7544 if (packageOfInterest == null 7545 || packageOfInterest.equals(pkg.packageName)) { 7546 Slog.w(TAG, "Not granting permission " + perm 7547 + " to package " + pkg.packageName 7548 + " because it was previously installed without"); 7549 } 7550 } break; 7551 } 7552 } else { 7553 if (permissionsState.revokeInstallPermission(bp) != 7554 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7555 changedInstallPermission = true; 7556 Slog.i(TAG, "Un-granting permission " + perm 7557 + " from package " + pkg.packageName 7558 + " (protectionLevel=" + bp.protectionLevel 7559 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7560 + ")"); 7561 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7562 // Don't print warning for app op permissions, since it is fine for them 7563 // not to be granted, there is a UI for the user to decide. 7564 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7565 Slog.w(TAG, "Not granting permission " + perm 7566 + " to package " + pkg.packageName 7567 + " (protectionLevel=" + bp.protectionLevel 7568 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7569 + ")"); 7570 } 7571 } 7572 } 7573 } 7574 7575 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7576 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7577 // This is the first that we have heard about this package, so the 7578 // permissions we have now selected are fixed until explicitly 7579 // changed. 7580 ps.installPermissionsFixed = true; 7581 } 7582 7583 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7584 7585 // Persist the runtime permissions state for users with changes. 7586 if (RUNTIME_PERMISSIONS_ENABLED) { 7587 for (int userId : changedRuntimePermissionUserIds) { 7588 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7589 } 7590 } 7591 } 7592 7593 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7594 boolean allowed = false; 7595 final int NP = PackageParser.NEW_PERMISSIONS.length; 7596 for (int ip=0; ip<NP; ip++) { 7597 final PackageParser.NewPermissionInfo npi 7598 = PackageParser.NEW_PERMISSIONS[ip]; 7599 if (npi.name.equals(perm) 7600 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7601 allowed = true; 7602 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7603 + pkg.packageName); 7604 break; 7605 } 7606 } 7607 return allowed; 7608 } 7609 7610 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7611 BasePermission bp, PermissionsState origPermissions) { 7612 boolean allowed; 7613 allowed = (compareSignatures( 7614 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7615 == PackageManager.SIGNATURE_MATCH) 7616 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7617 == PackageManager.SIGNATURE_MATCH); 7618 if (!allowed && (bp.protectionLevel 7619 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7620 if (isSystemApp(pkg)) { 7621 // For updated system applications, a system permission 7622 // is granted only if it had been defined by the original application. 7623 if (isUpdatedSystemApp(pkg)) { 7624 final PackageSetting sysPs = mSettings 7625 .getDisabledSystemPkgLPr(pkg.packageName); 7626 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7627 // If the original was granted this permission, we take 7628 // that grant decision as read and propagate it to the 7629 // update. 7630 if (sysPs.isPrivileged()) { 7631 allowed = true; 7632 } 7633 } else { 7634 // The system apk may have been updated with an older 7635 // version of the one on the data partition, but which 7636 // granted a new system permission that it didn't have 7637 // before. In this case we do want to allow the app to 7638 // now get the new permission if the ancestral apk is 7639 // privileged to get it. 7640 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7641 for (int j=0; 7642 j<sysPs.pkg.requestedPermissions.size(); j++) { 7643 if (perm.equals( 7644 sysPs.pkg.requestedPermissions.get(j))) { 7645 allowed = true; 7646 break; 7647 } 7648 } 7649 } 7650 } 7651 } else { 7652 allowed = isPrivilegedApp(pkg); 7653 } 7654 } 7655 } 7656 if (!allowed && (bp.protectionLevel 7657 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7658 // For development permissions, a development permission 7659 // is granted only if it was already granted. 7660 allowed = origPermissions.hasInstallPermission(perm); 7661 } 7662 return allowed; 7663 } 7664 7665 final class ActivityIntentResolver 7666 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7667 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7668 boolean defaultOnly, int userId) { 7669 if (!sUserManager.exists(userId)) return null; 7670 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7671 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7672 } 7673 7674 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7675 int userId) { 7676 if (!sUserManager.exists(userId)) return null; 7677 mFlags = flags; 7678 return super.queryIntent(intent, resolvedType, 7679 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7680 } 7681 7682 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7683 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7684 if (!sUserManager.exists(userId)) return null; 7685 if (packageActivities == null) { 7686 return null; 7687 } 7688 mFlags = flags; 7689 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7690 final int N = packageActivities.size(); 7691 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7692 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7693 7694 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7695 for (int i = 0; i < N; ++i) { 7696 intentFilters = packageActivities.get(i).intents; 7697 if (intentFilters != null && intentFilters.size() > 0) { 7698 PackageParser.ActivityIntentInfo[] array = 7699 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7700 intentFilters.toArray(array); 7701 listCut.add(array); 7702 } 7703 } 7704 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7705 } 7706 7707 public final void addActivity(PackageParser.Activity a, String type) { 7708 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7709 mActivities.put(a.getComponentName(), a); 7710 if (DEBUG_SHOW_INFO) 7711 Log.v( 7712 TAG, " " + type + " " + 7713 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7714 if (DEBUG_SHOW_INFO) 7715 Log.v(TAG, " Class=" + a.info.name); 7716 final int NI = a.intents.size(); 7717 for (int j=0; j<NI; j++) { 7718 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7719 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7720 intent.setPriority(0); 7721 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7722 + a.className + " with priority > 0, forcing to 0"); 7723 } 7724 if (DEBUG_SHOW_INFO) { 7725 Log.v(TAG, " IntentFilter:"); 7726 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7727 } 7728 if (!intent.debugCheck()) { 7729 Log.w(TAG, "==> For Activity " + a.info.name); 7730 } 7731 addFilter(intent); 7732 } 7733 } 7734 7735 public final void removeActivity(PackageParser.Activity a, String type) { 7736 mActivities.remove(a.getComponentName()); 7737 if (DEBUG_SHOW_INFO) { 7738 Log.v(TAG, " " + type + " " 7739 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7740 : a.info.name) + ":"); 7741 Log.v(TAG, " Class=" + a.info.name); 7742 } 7743 final int NI = a.intents.size(); 7744 for (int j=0; j<NI; j++) { 7745 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7746 if (DEBUG_SHOW_INFO) { 7747 Log.v(TAG, " IntentFilter:"); 7748 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7749 } 7750 removeFilter(intent); 7751 } 7752 } 7753 7754 @Override 7755 protected boolean allowFilterResult( 7756 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7757 ActivityInfo filterAi = filter.activity.info; 7758 for (int i=dest.size()-1; i>=0; i--) { 7759 ActivityInfo destAi = dest.get(i).activityInfo; 7760 if (destAi.name == filterAi.name 7761 && destAi.packageName == filterAi.packageName) { 7762 return false; 7763 } 7764 } 7765 return true; 7766 } 7767 7768 @Override 7769 protected ActivityIntentInfo[] newArray(int size) { 7770 return new ActivityIntentInfo[size]; 7771 } 7772 7773 @Override 7774 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7775 if (!sUserManager.exists(userId)) return true; 7776 PackageParser.Package p = filter.activity.owner; 7777 if (p != null) { 7778 PackageSetting ps = (PackageSetting)p.mExtras; 7779 if (ps != null) { 7780 // System apps are never considered stopped for purposes of 7781 // filtering, because there may be no way for the user to 7782 // actually re-launch them. 7783 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7784 && ps.getStopped(userId); 7785 } 7786 } 7787 return false; 7788 } 7789 7790 @Override 7791 protected boolean isPackageForFilter(String packageName, 7792 PackageParser.ActivityIntentInfo info) { 7793 return packageName.equals(info.activity.owner.packageName); 7794 } 7795 7796 @Override 7797 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7798 int match, int userId) { 7799 if (!sUserManager.exists(userId)) return null; 7800 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7801 return null; 7802 } 7803 final PackageParser.Activity activity = info.activity; 7804 if (mSafeMode && (activity.info.applicationInfo.flags 7805 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7806 return null; 7807 } 7808 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7809 if (ps == null) { 7810 return null; 7811 } 7812 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7813 ps.readUserState(userId), userId); 7814 if (ai == null) { 7815 return null; 7816 } 7817 final ResolveInfo res = new ResolveInfo(); 7818 res.activityInfo = ai; 7819 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7820 res.filter = info; 7821 } 7822 if (info != null) { 7823 res.filterNeedsVerification = info.needsVerification(); 7824 } 7825 res.priority = info.getPriority(); 7826 res.preferredOrder = activity.owner.mPreferredOrder; 7827 //System.out.println("Result: " + res.activityInfo.className + 7828 // " = " + res.priority); 7829 res.match = match; 7830 res.isDefault = info.hasDefault; 7831 res.labelRes = info.labelRes; 7832 res.nonLocalizedLabel = info.nonLocalizedLabel; 7833 if (userNeedsBadging(userId)) { 7834 res.noResourceId = true; 7835 } else { 7836 res.icon = info.icon; 7837 } 7838 res.system = isSystemApp(res.activityInfo.applicationInfo); 7839 return res; 7840 } 7841 7842 @Override 7843 protected void sortResults(List<ResolveInfo> results) { 7844 Collections.sort(results, mResolvePrioritySorter); 7845 } 7846 7847 @Override 7848 protected void dumpFilter(PrintWriter out, String prefix, 7849 PackageParser.ActivityIntentInfo filter) { 7850 out.print(prefix); out.print( 7851 Integer.toHexString(System.identityHashCode(filter.activity))); 7852 out.print(' '); 7853 filter.activity.printComponentShortName(out); 7854 out.print(" filter "); 7855 out.println(Integer.toHexString(System.identityHashCode(filter))); 7856 } 7857 7858 @Override 7859 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7860 return filter.activity; 7861 } 7862 7863 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7864 PackageParser.Activity activity = (PackageParser.Activity)label; 7865 out.print(prefix); out.print( 7866 Integer.toHexString(System.identityHashCode(activity))); 7867 out.print(' '); 7868 activity.printComponentShortName(out); 7869 if (count > 1) { 7870 out.print(" ("); out.print(count); out.print(" filters)"); 7871 } 7872 out.println(); 7873 } 7874 7875// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7876// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7877// final List<ResolveInfo> retList = Lists.newArrayList(); 7878// while (i.hasNext()) { 7879// final ResolveInfo resolveInfo = i.next(); 7880// if (isEnabledLP(resolveInfo.activityInfo)) { 7881// retList.add(resolveInfo); 7882// } 7883// } 7884// return retList; 7885// } 7886 7887 // Keys are String (activity class name), values are Activity. 7888 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7889 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7890 private int mFlags; 7891 } 7892 7893 private final class ServiceIntentResolver 7894 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7895 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7896 boolean defaultOnly, int userId) { 7897 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7898 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7899 } 7900 7901 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7902 int userId) { 7903 if (!sUserManager.exists(userId)) return null; 7904 mFlags = flags; 7905 return super.queryIntent(intent, resolvedType, 7906 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7907 } 7908 7909 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7910 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7911 if (!sUserManager.exists(userId)) return null; 7912 if (packageServices == null) { 7913 return null; 7914 } 7915 mFlags = flags; 7916 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7917 final int N = packageServices.size(); 7918 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7919 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7920 7921 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7922 for (int i = 0; i < N; ++i) { 7923 intentFilters = packageServices.get(i).intents; 7924 if (intentFilters != null && intentFilters.size() > 0) { 7925 PackageParser.ServiceIntentInfo[] array = 7926 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7927 intentFilters.toArray(array); 7928 listCut.add(array); 7929 } 7930 } 7931 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7932 } 7933 7934 public final void addService(PackageParser.Service s) { 7935 mServices.put(s.getComponentName(), s); 7936 if (DEBUG_SHOW_INFO) { 7937 Log.v(TAG, " " 7938 + (s.info.nonLocalizedLabel != null 7939 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7940 Log.v(TAG, " Class=" + s.info.name); 7941 } 7942 final int NI = s.intents.size(); 7943 int j; 7944 for (j=0; j<NI; j++) { 7945 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7946 if (DEBUG_SHOW_INFO) { 7947 Log.v(TAG, " IntentFilter:"); 7948 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7949 } 7950 if (!intent.debugCheck()) { 7951 Log.w(TAG, "==> For Service " + s.info.name); 7952 } 7953 addFilter(intent); 7954 } 7955 } 7956 7957 public final void removeService(PackageParser.Service s) { 7958 mServices.remove(s.getComponentName()); 7959 if (DEBUG_SHOW_INFO) { 7960 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7961 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7962 Log.v(TAG, " Class=" + s.info.name); 7963 } 7964 final int NI = s.intents.size(); 7965 int j; 7966 for (j=0; j<NI; j++) { 7967 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7968 if (DEBUG_SHOW_INFO) { 7969 Log.v(TAG, " IntentFilter:"); 7970 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7971 } 7972 removeFilter(intent); 7973 } 7974 } 7975 7976 @Override 7977 protected boolean allowFilterResult( 7978 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7979 ServiceInfo filterSi = filter.service.info; 7980 for (int i=dest.size()-1; i>=0; i--) { 7981 ServiceInfo destAi = dest.get(i).serviceInfo; 7982 if (destAi.name == filterSi.name 7983 && destAi.packageName == filterSi.packageName) { 7984 return false; 7985 } 7986 } 7987 return true; 7988 } 7989 7990 @Override 7991 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7992 return new PackageParser.ServiceIntentInfo[size]; 7993 } 7994 7995 @Override 7996 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7997 if (!sUserManager.exists(userId)) return true; 7998 PackageParser.Package p = filter.service.owner; 7999 if (p != null) { 8000 PackageSetting ps = (PackageSetting)p.mExtras; 8001 if (ps != null) { 8002 // System apps are never considered stopped for purposes of 8003 // filtering, because there may be no way for the user to 8004 // actually re-launch them. 8005 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8006 && ps.getStopped(userId); 8007 } 8008 } 8009 return false; 8010 } 8011 8012 @Override 8013 protected boolean isPackageForFilter(String packageName, 8014 PackageParser.ServiceIntentInfo info) { 8015 return packageName.equals(info.service.owner.packageName); 8016 } 8017 8018 @Override 8019 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8020 int match, int userId) { 8021 if (!sUserManager.exists(userId)) return null; 8022 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8023 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8024 return null; 8025 } 8026 final PackageParser.Service service = info.service; 8027 if (mSafeMode && (service.info.applicationInfo.flags 8028 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8029 return null; 8030 } 8031 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8032 if (ps == null) { 8033 return null; 8034 } 8035 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8036 ps.readUserState(userId), userId); 8037 if (si == null) { 8038 return null; 8039 } 8040 final ResolveInfo res = new ResolveInfo(); 8041 res.serviceInfo = si; 8042 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8043 res.filter = filter; 8044 } 8045 res.priority = info.getPriority(); 8046 res.preferredOrder = service.owner.mPreferredOrder; 8047 res.match = match; 8048 res.isDefault = info.hasDefault; 8049 res.labelRes = info.labelRes; 8050 res.nonLocalizedLabel = info.nonLocalizedLabel; 8051 res.icon = info.icon; 8052 res.system = isSystemApp(res.serviceInfo.applicationInfo); 8053 return res; 8054 } 8055 8056 @Override 8057 protected void sortResults(List<ResolveInfo> results) { 8058 Collections.sort(results, mResolvePrioritySorter); 8059 } 8060 8061 @Override 8062 protected void dumpFilter(PrintWriter out, String prefix, 8063 PackageParser.ServiceIntentInfo filter) { 8064 out.print(prefix); out.print( 8065 Integer.toHexString(System.identityHashCode(filter.service))); 8066 out.print(' '); 8067 filter.service.printComponentShortName(out); 8068 out.print(" filter "); 8069 out.println(Integer.toHexString(System.identityHashCode(filter))); 8070 } 8071 8072 @Override 8073 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8074 return filter.service; 8075 } 8076 8077 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8078 PackageParser.Service service = (PackageParser.Service)label; 8079 out.print(prefix); out.print( 8080 Integer.toHexString(System.identityHashCode(service))); 8081 out.print(' '); 8082 service.printComponentShortName(out); 8083 if (count > 1) { 8084 out.print(" ("); out.print(count); out.print(" filters)"); 8085 } 8086 out.println(); 8087 } 8088 8089// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8090// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8091// final List<ResolveInfo> retList = Lists.newArrayList(); 8092// while (i.hasNext()) { 8093// final ResolveInfo resolveInfo = (ResolveInfo) i; 8094// if (isEnabledLP(resolveInfo.serviceInfo)) { 8095// retList.add(resolveInfo); 8096// } 8097// } 8098// return retList; 8099// } 8100 8101 // Keys are String (activity class name), values are Activity. 8102 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8103 = new ArrayMap<ComponentName, PackageParser.Service>(); 8104 private int mFlags; 8105 }; 8106 8107 private final class ProviderIntentResolver 8108 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8109 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8110 boolean defaultOnly, int userId) { 8111 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8112 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8113 } 8114 8115 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8116 int userId) { 8117 if (!sUserManager.exists(userId)) 8118 return null; 8119 mFlags = flags; 8120 return super.queryIntent(intent, resolvedType, 8121 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8122 } 8123 8124 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8125 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8126 if (!sUserManager.exists(userId)) 8127 return null; 8128 if (packageProviders == null) { 8129 return null; 8130 } 8131 mFlags = flags; 8132 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8133 final int N = packageProviders.size(); 8134 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8135 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8136 8137 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8138 for (int i = 0; i < N; ++i) { 8139 intentFilters = packageProviders.get(i).intents; 8140 if (intentFilters != null && intentFilters.size() > 0) { 8141 PackageParser.ProviderIntentInfo[] array = 8142 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8143 intentFilters.toArray(array); 8144 listCut.add(array); 8145 } 8146 } 8147 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8148 } 8149 8150 public final void addProvider(PackageParser.Provider p) { 8151 if (mProviders.containsKey(p.getComponentName())) { 8152 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8153 return; 8154 } 8155 8156 mProviders.put(p.getComponentName(), p); 8157 if (DEBUG_SHOW_INFO) { 8158 Log.v(TAG, " " 8159 + (p.info.nonLocalizedLabel != null 8160 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8161 Log.v(TAG, " Class=" + p.info.name); 8162 } 8163 final int NI = p.intents.size(); 8164 int j; 8165 for (j = 0; j < NI; j++) { 8166 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8167 if (DEBUG_SHOW_INFO) { 8168 Log.v(TAG, " IntentFilter:"); 8169 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8170 } 8171 if (!intent.debugCheck()) { 8172 Log.w(TAG, "==> For Provider " + p.info.name); 8173 } 8174 addFilter(intent); 8175 } 8176 } 8177 8178 public final void removeProvider(PackageParser.Provider p) { 8179 mProviders.remove(p.getComponentName()); 8180 if (DEBUG_SHOW_INFO) { 8181 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8182 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8183 Log.v(TAG, " Class=" + p.info.name); 8184 } 8185 final int NI = p.intents.size(); 8186 int j; 8187 for (j = 0; j < NI; j++) { 8188 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8189 if (DEBUG_SHOW_INFO) { 8190 Log.v(TAG, " IntentFilter:"); 8191 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8192 } 8193 removeFilter(intent); 8194 } 8195 } 8196 8197 @Override 8198 protected boolean allowFilterResult( 8199 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8200 ProviderInfo filterPi = filter.provider.info; 8201 for (int i = dest.size() - 1; i >= 0; i--) { 8202 ProviderInfo destPi = dest.get(i).providerInfo; 8203 if (destPi.name == filterPi.name 8204 && destPi.packageName == filterPi.packageName) { 8205 return false; 8206 } 8207 } 8208 return true; 8209 } 8210 8211 @Override 8212 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8213 return new PackageParser.ProviderIntentInfo[size]; 8214 } 8215 8216 @Override 8217 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8218 if (!sUserManager.exists(userId)) 8219 return true; 8220 PackageParser.Package p = filter.provider.owner; 8221 if (p != null) { 8222 PackageSetting ps = (PackageSetting) p.mExtras; 8223 if (ps != null) { 8224 // System apps are never considered stopped for purposes of 8225 // filtering, because there may be no way for the user to 8226 // actually re-launch them. 8227 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8228 && ps.getStopped(userId); 8229 } 8230 } 8231 return false; 8232 } 8233 8234 @Override 8235 protected boolean isPackageForFilter(String packageName, 8236 PackageParser.ProviderIntentInfo info) { 8237 return packageName.equals(info.provider.owner.packageName); 8238 } 8239 8240 @Override 8241 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8242 int match, int userId) { 8243 if (!sUserManager.exists(userId)) 8244 return null; 8245 final PackageParser.ProviderIntentInfo info = filter; 8246 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8247 return null; 8248 } 8249 final PackageParser.Provider provider = info.provider; 8250 if (mSafeMode && (provider.info.applicationInfo.flags 8251 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8252 return null; 8253 } 8254 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8255 if (ps == null) { 8256 return null; 8257 } 8258 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8259 ps.readUserState(userId), userId); 8260 if (pi == null) { 8261 return null; 8262 } 8263 final ResolveInfo res = new ResolveInfo(); 8264 res.providerInfo = pi; 8265 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8266 res.filter = filter; 8267 } 8268 res.priority = info.getPriority(); 8269 res.preferredOrder = provider.owner.mPreferredOrder; 8270 res.match = match; 8271 res.isDefault = info.hasDefault; 8272 res.labelRes = info.labelRes; 8273 res.nonLocalizedLabel = info.nonLocalizedLabel; 8274 res.icon = info.icon; 8275 res.system = isSystemApp(res.providerInfo.applicationInfo); 8276 return res; 8277 } 8278 8279 @Override 8280 protected void sortResults(List<ResolveInfo> results) { 8281 Collections.sort(results, mResolvePrioritySorter); 8282 } 8283 8284 @Override 8285 protected void dumpFilter(PrintWriter out, String prefix, 8286 PackageParser.ProviderIntentInfo filter) { 8287 out.print(prefix); 8288 out.print( 8289 Integer.toHexString(System.identityHashCode(filter.provider))); 8290 out.print(' '); 8291 filter.provider.printComponentShortName(out); 8292 out.print(" filter "); 8293 out.println(Integer.toHexString(System.identityHashCode(filter))); 8294 } 8295 8296 @Override 8297 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8298 return filter.provider; 8299 } 8300 8301 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8302 PackageParser.Provider provider = (PackageParser.Provider)label; 8303 out.print(prefix); out.print( 8304 Integer.toHexString(System.identityHashCode(provider))); 8305 out.print(' '); 8306 provider.printComponentShortName(out); 8307 if (count > 1) { 8308 out.print(" ("); out.print(count); out.print(" filters)"); 8309 } 8310 out.println(); 8311 } 8312 8313 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8314 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8315 private int mFlags; 8316 }; 8317 8318 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8319 new Comparator<ResolveInfo>() { 8320 public int compare(ResolveInfo r1, ResolveInfo r2) { 8321 int v1 = r1.priority; 8322 int v2 = r2.priority; 8323 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8324 if (v1 != v2) { 8325 return (v1 > v2) ? -1 : 1; 8326 } 8327 v1 = r1.preferredOrder; 8328 v2 = r2.preferredOrder; 8329 if (v1 != v2) { 8330 return (v1 > v2) ? -1 : 1; 8331 } 8332 if (r1.isDefault != r2.isDefault) { 8333 return r1.isDefault ? -1 : 1; 8334 } 8335 v1 = r1.match; 8336 v2 = r2.match; 8337 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8338 if (v1 != v2) { 8339 return (v1 > v2) ? -1 : 1; 8340 } 8341 if (r1.system != r2.system) { 8342 return r1.system ? -1 : 1; 8343 } 8344 return 0; 8345 } 8346 }; 8347 8348 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8349 new Comparator<ProviderInfo>() { 8350 public int compare(ProviderInfo p1, ProviderInfo p2) { 8351 final int v1 = p1.initOrder; 8352 final int v2 = p2.initOrder; 8353 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8354 } 8355 }; 8356 8357 static final void sendPackageBroadcast(String action, String pkg, 8358 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8359 int[] userIds) { 8360 IActivityManager am = ActivityManagerNative.getDefault(); 8361 if (am != null) { 8362 try { 8363 if (userIds == null) { 8364 userIds = am.getRunningUserIds(); 8365 } 8366 for (int id : userIds) { 8367 final Intent intent = new Intent(action, 8368 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8369 if (extras != null) { 8370 intent.putExtras(extras); 8371 } 8372 if (targetPkg != null) { 8373 intent.setPackage(targetPkg); 8374 } 8375 // Modify the UID when posting to other users 8376 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8377 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8378 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8379 intent.putExtra(Intent.EXTRA_UID, uid); 8380 } 8381 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8382 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8383 if (DEBUG_BROADCASTS) { 8384 RuntimeException here = new RuntimeException("here"); 8385 here.fillInStackTrace(); 8386 Slog.d(TAG, "Sending to user " + id + ": " 8387 + intent.toShortString(false, true, false, false) 8388 + " " + intent.getExtras(), here); 8389 } 8390 am.broadcastIntent(null, intent, null, finishedReceiver, 8391 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8392 finishedReceiver != null, false, id); 8393 } 8394 } catch (RemoteException ex) { 8395 } 8396 } 8397 } 8398 8399 /** 8400 * Check if the external storage media is available. This is true if there 8401 * is a mounted external storage medium or if the external storage is 8402 * emulated. 8403 */ 8404 private boolean isExternalMediaAvailable() { 8405 return mMediaMounted || Environment.isExternalStorageEmulated(); 8406 } 8407 8408 @Override 8409 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8410 // writer 8411 synchronized (mPackages) { 8412 if (!isExternalMediaAvailable()) { 8413 // If the external storage is no longer mounted at this point, 8414 // the caller may not have been able to delete all of this 8415 // packages files and can not delete any more. Bail. 8416 return null; 8417 } 8418 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8419 if (lastPackage != null) { 8420 pkgs.remove(lastPackage); 8421 } 8422 if (pkgs.size() > 0) { 8423 return pkgs.get(0); 8424 } 8425 } 8426 return null; 8427 } 8428 8429 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8430 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8431 userId, andCode ? 1 : 0, packageName); 8432 if (mSystemReady) { 8433 msg.sendToTarget(); 8434 } else { 8435 if (mPostSystemReadyMessages == null) { 8436 mPostSystemReadyMessages = new ArrayList<>(); 8437 } 8438 mPostSystemReadyMessages.add(msg); 8439 } 8440 } 8441 8442 void startCleaningPackages() { 8443 // reader 8444 synchronized (mPackages) { 8445 if (!isExternalMediaAvailable()) { 8446 return; 8447 } 8448 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8449 return; 8450 } 8451 } 8452 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8453 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8454 IActivityManager am = ActivityManagerNative.getDefault(); 8455 if (am != null) { 8456 try { 8457 am.startService(null, intent, null, UserHandle.USER_OWNER); 8458 } catch (RemoteException e) { 8459 } 8460 } 8461 } 8462 8463 @Override 8464 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8465 int installFlags, String installerPackageName, VerificationParams verificationParams, 8466 String packageAbiOverride) { 8467 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8468 packageAbiOverride, UserHandle.getCallingUserId()); 8469 } 8470 8471 @Override 8472 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8473 int installFlags, String installerPackageName, VerificationParams verificationParams, 8474 String packageAbiOverride, int userId) { 8475 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8476 8477 final int callingUid = Binder.getCallingUid(); 8478 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8479 8480 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8481 try { 8482 if (observer != null) { 8483 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8484 } 8485 } catch (RemoteException re) { 8486 } 8487 return; 8488 } 8489 8490 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8491 installFlags |= PackageManager.INSTALL_FROM_ADB; 8492 8493 } else { 8494 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8495 // about installerPackageName. 8496 8497 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8498 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8499 } 8500 8501 UserHandle user; 8502 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8503 user = UserHandle.ALL; 8504 } else { 8505 user = new UserHandle(userId); 8506 } 8507 8508 verificationParams.setInstallerUid(callingUid); 8509 8510 final File originFile = new File(originPath); 8511 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8512 8513 final Message msg = mHandler.obtainMessage(INIT_COPY); 8514 msg.obj = new InstallParams(origin, observer, installFlags, 8515 installerPackageName, verificationParams, user, packageAbiOverride); 8516 mHandler.sendMessage(msg); 8517 } 8518 8519 void installStage(String packageName, File stagedDir, String stagedCid, 8520 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8521 String installerPackageName, int installerUid, UserHandle user) { 8522 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8523 params.referrerUri, installerUid, null); 8524 8525 final OriginInfo origin; 8526 if (stagedDir != null) { 8527 origin = OriginInfo.fromStagedFile(stagedDir); 8528 } else { 8529 origin = OriginInfo.fromStagedContainer(stagedCid); 8530 } 8531 8532 final Message msg = mHandler.obtainMessage(INIT_COPY); 8533 msg.obj = new InstallParams(origin, observer, params.installFlags, 8534 installerPackageName, verifParams, user, params.abiOverride); 8535 mHandler.sendMessage(msg); 8536 } 8537 8538 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8539 Bundle extras = new Bundle(1); 8540 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8541 8542 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8543 packageName, extras, null, null, new int[] {userId}); 8544 try { 8545 IActivityManager am = ActivityManagerNative.getDefault(); 8546 final boolean isSystem = 8547 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8548 if (isSystem && am.isUserRunning(userId, false)) { 8549 // The just-installed/enabled app is bundled on the system, so presumed 8550 // to be able to run automatically without needing an explicit launch. 8551 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8552 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8553 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8554 .setPackage(packageName); 8555 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8556 android.app.AppOpsManager.OP_NONE, false, false, userId); 8557 } 8558 } catch (RemoteException e) { 8559 // shouldn't happen 8560 Slog.w(TAG, "Unable to bootstrap installed package", e); 8561 } 8562 } 8563 8564 @Override 8565 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8566 int userId) { 8567 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8568 PackageSetting pkgSetting; 8569 final int uid = Binder.getCallingUid(); 8570 enforceCrossUserPermission(uid, userId, true, true, 8571 "setApplicationHiddenSetting for user " + userId); 8572 8573 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8574 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8575 return false; 8576 } 8577 8578 long callingId = Binder.clearCallingIdentity(); 8579 try { 8580 boolean sendAdded = false; 8581 boolean sendRemoved = false; 8582 // writer 8583 synchronized (mPackages) { 8584 pkgSetting = mSettings.mPackages.get(packageName); 8585 if (pkgSetting == null) { 8586 return false; 8587 } 8588 if (pkgSetting.getHidden(userId) != hidden) { 8589 pkgSetting.setHidden(hidden, userId); 8590 mSettings.writePackageRestrictionsLPr(userId); 8591 if (hidden) { 8592 sendRemoved = true; 8593 } else { 8594 sendAdded = true; 8595 } 8596 } 8597 } 8598 if (sendAdded) { 8599 sendPackageAddedForUser(packageName, pkgSetting, userId); 8600 return true; 8601 } 8602 if (sendRemoved) { 8603 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8604 "hiding pkg"); 8605 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8606 } 8607 } finally { 8608 Binder.restoreCallingIdentity(callingId); 8609 } 8610 return false; 8611 } 8612 8613 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8614 int userId) { 8615 final PackageRemovedInfo info = new PackageRemovedInfo(); 8616 info.removedPackage = packageName; 8617 info.removedUsers = new int[] {userId}; 8618 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8619 info.sendBroadcast(false, false, false); 8620 } 8621 8622 /** 8623 * Returns true if application is not found or there was an error. Otherwise it returns 8624 * the hidden state of the package for the given user. 8625 */ 8626 @Override 8627 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8628 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8629 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8630 false, "getApplicationHidden for user " + userId); 8631 PackageSetting pkgSetting; 8632 long callingId = Binder.clearCallingIdentity(); 8633 try { 8634 // writer 8635 synchronized (mPackages) { 8636 pkgSetting = mSettings.mPackages.get(packageName); 8637 if (pkgSetting == null) { 8638 return true; 8639 } 8640 return pkgSetting.getHidden(userId); 8641 } 8642 } finally { 8643 Binder.restoreCallingIdentity(callingId); 8644 } 8645 } 8646 8647 /** 8648 * @hide 8649 */ 8650 @Override 8651 public int installExistingPackageAsUser(String packageName, int userId) { 8652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8653 null); 8654 PackageSetting pkgSetting; 8655 final int uid = Binder.getCallingUid(); 8656 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8657 + userId); 8658 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8659 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8660 } 8661 8662 long callingId = Binder.clearCallingIdentity(); 8663 try { 8664 boolean sendAdded = false; 8665 Bundle extras = new Bundle(1); 8666 8667 // writer 8668 synchronized (mPackages) { 8669 pkgSetting = mSettings.mPackages.get(packageName); 8670 if (pkgSetting == null) { 8671 return PackageManager.INSTALL_FAILED_INVALID_URI; 8672 } 8673 if (!pkgSetting.getInstalled(userId)) { 8674 pkgSetting.setInstalled(true, userId); 8675 pkgSetting.setHidden(false, userId); 8676 mSettings.writePackageRestrictionsLPr(userId); 8677 sendAdded = true; 8678 } 8679 } 8680 8681 if (sendAdded) { 8682 sendPackageAddedForUser(packageName, pkgSetting, userId); 8683 } 8684 } finally { 8685 Binder.restoreCallingIdentity(callingId); 8686 } 8687 8688 return PackageManager.INSTALL_SUCCEEDED; 8689 } 8690 8691 boolean isUserRestricted(int userId, String restrictionKey) { 8692 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8693 if (restrictions.getBoolean(restrictionKey, false)) { 8694 Log.w(TAG, "User is restricted: " + restrictionKey); 8695 return true; 8696 } 8697 return false; 8698 } 8699 8700 @Override 8701 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8702 mContext.enforceCallingOrSelfPermission( 8703 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8704 "Only package verification agents can verify applications"); 8705 8706 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8707 final PackageVerificationResponse response = new PackageVerificationResponse( 8708 verificationCode, Binder.getCallingUid()); 8709 msg.arg1 = id; 8710 msg.obj = response; 8711 mHandler.sendMessage(msg); 8712 } 8713 8714 @Override 8715 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8716 long millisecondsToDelay) { 8717 mContext.enforceCallingOrSelfPermission( 8718 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8719 "Only package verification agents can extend verification timeouts"); 8720 8721 final PackageVerificationState state = mPendingVerification.get(id); 8722 final PackageVerificationResponse response = new PackageVerificationResponse( 8723 verificationCodeAtTimeout, Binder.getCallingUid()); 8724 8725 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8726 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8727 } 8728 if (millisecondsToDelay < 0) { 8729 millisecondsToDelay = 0; 8730 } 8731 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8732 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8733 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8734 } 8735 8736 if ((state != null) && !state.timeoutExtended()) { 8737 state.extendTimeout(); 8738 8739 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8740 msg.arg1 = id; 8741 msg.obj = response; 8742 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8743 } 8744 } 8745 8746 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8747 int verificationCode, UserHandle user) { 8748 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8749 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8750 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8751 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8752 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8753 8754 mContext.sendBroadcastAsUser(intent, user, 8755 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8756 } 8757 8758 private ComponentName matchComponentForVerifier(String packageName, 8759 List<ResolveInfo> receivers) { 8760 ActivityInfo targetReceiver = null; 8761 8762 final int NR = receivers.size(); 8763 for (int i = 0; i < NR; i++) { 8764 final ResolveInfo info = receivers.get(i); 8765 if (info.activityInfo == null) { 8766 continue; 8767 } 8768 8769 if (packageName.equals(info.activityInfo.packageName)) { 8770 targetReceiver = info.activityInfo; 8771 break; 8772 } 8773 } 8774 8775 if (targetReceiver == null) { 8776 return null; 8777 } 8778 8779 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8780 } 8781 8782 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8783 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8784 if (pkgInfo.verifiers.length == 0) { 8785 return null; 8786 } 8787 8788 final int N = pkgInfo.verifiers.length; 8789 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8790 for (int i = 0; i < N; i++) { 8791 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8792 8793 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8794 receivers); 8795 if (comp == null) { 8796 continue; 8797 } 8798 8799 final int verifierUid = getUidForVerifier(verifierInfo); 8800 if (verifierUid == -1) { 8801 continue; 8802 } 8803 8804 if (DEBUG_VERIFY) { 8805 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8806 + " with the correct signature"); 8807 } 8808 sufficientVerifiers.add(comp); 8809 verificationState.addSufficientVerifier(verifierUid); 8810 } 8811 8812 return sufficientVerifiers; 8813 } 8814 8815 private int getUidForVerifier(VerifierInfo verifierInfo) { 8816 synchronized (mPackages) { 8817 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8818 if (pkg == null) { 8819 return -1; 8820 } else if (pkg.mSignatures.length != 1) { 8821 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8822 + " has more than one signature; ignoring"); 8823 return -1; 8824 } 8825 8826 /* 8827 * If the public key of the package's signature does not match 8828 * our expected public key, then this is a different package and 8829 * we should skip. 8830 */ 8831 8832 final byte[] expectedPublicKey; 8833 try { 8834 final Signature verifierSig = pkg.mSignatures[0]; 8835 final PublicKey publicKey = verifierSig.getPublicKey(); 8836 expectedPublicKey = publicKey.getEncoded(); 8837 } catch (CertificateException e) { 8838 return -1; 8839 } 8840 8841 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8842 8843 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8844 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8845 + " does not have the expected public key; ignoring"); 8846 return -1; 8847 } 8848 8849 return pkg.applicationInfo.uid; 8850 } 8851 } 8852 8853 @Override 8854 public void finishPackageInstall(int token) { 8855 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8856 8857 if (DEBUG_INSTALL) { 8858 Slog.v(TAG, "BM finishing package install for " + token); 8859 } 8860 8861 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8862 mHandler.sendMessage(msg); 8863 } 8864 8865 /** 8866 * Get the verification agent timeout. 8867 * 8868 * @return verification timeout in milliseconds 8869 */ 8870 private long getVerificationTimeout() { 8871 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8872 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8873 DEFAULT_VERIFICATION_TIMEOUT); 8874 } 8875 8876 /** 8877 * Get the default verification agent response code. 8878 * 8879 * @return default verification response code 8880 */ 8881 private int getDefaultVerificationResponse() { 8882 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8883 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8884 DEFAULT_VERIFICATION_RESPONSE); 8885 } 8886 8887 /** 8888 * Check whether or not package verification has been enabled. 8889 * 8890 * @return true if verification should be performed 8891 */ 8892 private boolean isVerificationEnabled(int userId, int installFlags) { 8893 if (!DEFAULT_VERIFY_ENABLE) { 8894 return false; 8895 } 8896 8897 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8898 8899 // Check if installing from ADB 8900 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8901 // Do not run verification in a test harness environment 8902 if (ActivityManager.isRunningInTestHarness()) { 8903 return false; 8904 } 8905 if (ensureVerifyAppsEnabled) { 8906 return true; 8907 } 8908 // Check if the developer does not want package verification for ADB installs 8909 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8910 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8911 return false; 8912 } 8913 } 8914 8915 if (ensureVerifyAppsEnabled) { 8916 return true; 8917 } 8918 8919 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8920 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8921 } 8922 8923 @Override 8924 public void verifyIntentFilter(int id, int verificationCode, List<String> outFailedDomains) 8925 throws RemoteException { 8926 mContext.enforceCallingOrSelfPermission( 8927 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8928 "Only intentfilter verification agents can verify applications"); 8929 8930 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8931 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8932 Binder.getCallingUid(), verificationCode, outFailedDomains); 8933 msg.arg1 = id; 8934 msg.obj = response; 8935 mHandler.sendMessage(msg); 8936 } 8937 8938 @Override 8939 public int getIntentVerificationStatus(String packageName, int userId) { 8940 synchronized (mPackages) { 8941 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8942 } 8943 } 8944 8945 @Override 8946 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8947 boolean result = false; 8948 synchronized (mPackages) { 8949 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8950 } 8951 scheduleWritePackageRestrictionsLocked(userId); 8952 return result; 8953 } 8954 8955 @Override 8956 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8957 synchronized (mPackages) { 8958 return mSettings.getIntentFilterVerificationsLPr(packageName); 8959 } 8960 } 8961 8962 /** 8963 * Get the "allow unknown sources" setting. 8964 * 8965 * @return the current "allow unknown sources" setting 8966 */ 8967 private int getUnknownSourcesSettings() { 8968 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8969 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8970 -1); 8971 } 8972 8973 @Override 8974 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8975 final int uid = Binder.getCallingUid(); 8976 // writer 8977 synchronized (mPackages) { 8978 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8979 if (targetPackageSetting == null) { 8980 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8981 } 8982 8983 PackageSetting installerPackageSetting; 8984 if (installerPackageName != null) { 8985 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8986 if (installerPackageSetting == null) { 8987 throw new IllegalArgumentException("Unknown installer package: " 8988 + installerPackageName); 8989 } 8990 } else { 8991 installerPackageSetting = null; 8992 } 8993 8994 Signature[] callerSignature; 8995 Object obj = mSettings.getUserIdLPr(uid); 8996 if (obj != null) { 8997 if (obj instanceof SharedUserSetting) { 8998 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8999 } else if (obj instanceof PackageSetting) { 9000 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9001 } else { 9002 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9003 } 9004 } else { 9005 throw new SecurityException("Unknown calling uid " + uid); 9006 } 9007 9008 // Verify: can't set installerPackageName to a package that is 9009 // not signed with the same cert as the caller. 9010 if (installerPackageSetting != null) { 9011 if (compareSignatures(callerSignature, 9012 installerPackageSetting.signatures.mSignatures) 9013 != PackageManager.SIGNATURE_MATCH) { 9014 throw new SecurityException( 9015 "Caller does not have same cert as new installer package " 9016 + installerPackageName); 9017 } 9018 } 9019 9020 // Verify: if target already has an installer package, it must 9021 // be signed with the same cert as the caller. 9022 if (targetPackageSetting.installerPackageName != null) { 9023 PackageSetting setting = mSettings.mPackages.get( 9024 targetPackageSetting.installerPackageName); 9025 // If the currently set package isn't valid, then it's always 9026 // okay to change it. 9027 if (setting != null) { 9028 if (compareSignatures(callerSignature, 9029 setting.signatures.mSignatures) 9030 != PackageManager.SIGNATURE_MATCH) { 9031 throw new SecurityException( 9032 "Caller does not have same cert as old installer package " 9033 + targetPackageSetting.installerPackageName); 9034 } 9035 } 9036 } 9037 9038 // Okay! 9039 targetPackageSetting.installerPackageName = installerPackageName; 9040 scheduleWriteSettingsLocked(); 9041 } 9042 } 9043 9044 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9045 // Queue up an async operation since the package installation may take a little while. 9046 mHandler.post(new Runnable() { 9047 public void run() { 9048 mHandler.removeCallbacks(this); 9049 // Result object to be returned 9050 PackageInstalledInfo res = new PackageInstalledInfo(); 9051 res.returnCode = currentStatus; 9052 res.uid = -1; 9053 res.pkg = null; 9054 res.removedInfo = new PackageRemovedInfo(); 9055 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9056 args.doPreInstall(res.returnCode); 9057 synchronized (mInstallLock) { 9058 installPackageLI(args, res); 9059 } 9060 args.doPostInstall(res.returnCode, res.uid); 9061 } 9062 9063 // A restore should be performed at this point if (a) the install 9064 // succeeded, (b) the operation is not an update, and (c) the new 9065 // package has not opted out of backup participation. 9066 final boolean update = res.removedInfo.removedPackage != null; 9067 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9068 boolean doRestore = !update 9069 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9070 9071 // Set up the post-install work request bookkeeping. This will be used 9072 // and cleaned up by the post-install event handling regardless of whether 9073 // there's a restore pass performed. Token values are >= 1. 9074 int token; 9075 if (mNextInstallToken < 0) mNextInstallToken = 1; 9076 token = mNextInstallToken++; 9077 9078 PostInstallData data = new PostInstallData(args, res); 9079 mRunningInstalls.put(token, data); 9080 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9081 9082 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9083 // Pass responsibility to the Backup Manager. It will perform a 9084 // restore if appropriate, then pass responsibility back to the 9085 // Package Manager to run the post-install observer callbacks 9086 // and broadcasts. 9087 IBackupManager bm = IBackupManager.Stub.asInterface( 9088 ServiceManager.getService(Context.BACKUP_SERVICE)); 9089 if (bm != null) { 9090 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9091 + " to BM for possible restore"); 9092 try { 9093 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9094 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9095 } else { 9096 doRestore = false; 9097 } 9098 } catch (RemoteException e) { 9099 // can't happen; the backup manager is local 9100 } catch (Exception e) { 9101 Slog.e(TAG, "Exception trying to enqueue restore", e); 9102 doRestore = false; 9103 } 9104 } else { 9105 Slog.e(TAG, "Backup Manager not found!"); 9106 doRestore = false; 9107 } 9108 } 9109 9110 if (!doRestore) { 9111 // No restore possible, or the Backup Manager was mysteriously not 9112 // available -- just fire the post-install work request directly. 9113 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9114 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9115 mHandler.sendMessage(msg); 9116 } 9117 } 9118 }); 9119 } 9120 9121 private abstract class HandlerParams { 9122 private static final int MAX_RETRIES = 4; 9123 9124 /** 9125 * Number of times startCopy() has been attempted and had a non-fatal 9126 * error. 9127 */ 9128 private int mRetries = 0; 9129 9130 /** User handle for the user requesting the information or installation. */ 9131 private final UserHandle mUser; 9132 9133 HandlerParams(UserHandle user) { 9134 mUser = user; 9135 } 9136 9137 UserHandle getUser() { 9138 return mUser; 9139 } 9140 9141 final boolean startCopy() { 9142 boolean res; 9143 try { 9144 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9145 9146 if (++mRetries > MAX_RETRIES) { 9147 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9148 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9149 handleServiceError(); 9150 return false; 9151 } else { 9152 handleStartCopy(); 9153 res = true; 9154 } 9155 } catch (RemoteException e) { 9156 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9157 mHandler.sendEmptyMessage(MCS_RECONNECT); 9158 res = false; 9159 } 9160 handleReturnCode(); 9161 return res; 9162 } 9163 9164 final void serviceError() { 9165 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9166 handleServiceError(); 9167 handleReturnCode(); 9168 } 9169 9170 abstract void handleStartCopy() throws RemoteException; 9171 abstract void handleServiceError(); 9172 abstract void handleReturnCode(); 9173 } 9174 9175 class MeasureParams extends HandlerParams { 9176 private final PackageStats mStats; 9177 private boolean mSuccess; 9178 9179 private final IPackageStatsObserver mObserver; 9180 9181 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9182 super(new UserHandle(stats.userHandle)); 9183 mObserver = observer; 9184 mStats = stats; 9185 } 9186 9187 @Override 9188 public String toString() { 9189 return "MeasureParams{" 9190 + Integer.toHexString(System.identityHashCode(this)) 9191 + " " + mStats.packageName + "}"; 9192 } 9193 9194 @Override 9195 void handleStartCopy() throws RemoteException { 9196 synchronized (mInstallLock) { 9197 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9198 } 9199 9200 if (mSuccess) { 9201 final boolean mounted; 9202 if (Environment.isExternalStorageEmulated()) { 9203 mounted = true; 9204 } else { 9205 final String status = Environment.getExternalStorageState(); 9206 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9207 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9208 } 9209 9210 if (mounted) { 9211 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9212 9213 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9214 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9215 9216 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9217 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9218 9219 // Always subtract cache size, since it's a subdirectory 9220 mStats.externalDataSize -= mStats.externalCacheSize; 9221 9222 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9223 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9224 9225 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9226 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9227 } 9228 } 9229 } 9230 9231 @Override 9232 void handleReturnCode() { 9233 if (mObserver != null) { 9234 try { 9235 mObserver.onGetStatsCompleted(mStats, mSuccess); 9236 } catch (RemoteException e) { 9237 Slog.i(TAG, "Observer no longer exists."); 9238 } 9239 } 9240 } 9241 9242 @Override 9243 void handleServiceError() { 9244 Slog.e(TAG, "Could not measure application " + mStats.packageName 9245 + " external storage"); 9246 } 9247 } 9248 9249 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9250 throws RemoteException { 9251 long result = 0; 9252 for (File path : paths) { 9253 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9254 } 9255 return result; 9256 } 9257 9258 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9259 for (File path : paths) { 9260 try { 9261 mcs.clearDirectory(path.getAbsolutePath()); 9262 } catch (RemoteException e) { 9263 } 9264 } 9265 } 9266 9267 static class OriginInfo { 9268 /** 9269 * Location where install is coming from, before it has been 9270 * copied/renamed into place. This could be a single monolithic APK 9271 * file, or a cluster directory. This location may be untrusted. 9272 */ 9273 final File file; 9274 final String cid; 9275 9276 /** 9277 * Flag indicating that {@link #file} or {@link #cid} has already been 9278 * staged, meaning downstream users don't need to defensively copy the 9279 * contents. 9280 */ 9281 final boolean staged; 9282 9283 /** 9284 * Flag indicating that {@link #file} or {@link #cid} is an already 9285 * installed app that is being moved. 9286 */ 9287 final boolean existing; 9288 9289 final String resolvedPath; 9290 final File resolvedFile; 9291 9292 static OriginInfo fromNothing() { 9293 return new OriginInfo(null, null, false, false); 9294 } 9295 9296 static OriginInfo fromUntrustedFile(File file) { 9297 return new OriginInfo(file, null, false, false); 9298 } 9299 9300 static OriginInfo fromExistingFile(File file) { 9301 return new OriginInfo(file, null, false, true); 9302 } 9303 9304 static OriginInfo fromStagedFile(File file) { 9305 return new OriginInfo(file, null, true, false); 9306 } 9307 9308 static OriginInfo fromStagedContainer(String cid) { 9309 return new OriginInfo(null, cid, true, false); 9310 } 9311 9312 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9313 this.file = file; 9314 this.cid = cid; 9315 this.staged = staged; 9316 this.existing = existing; 9317 9318 if (cid != null) { 9319 resolvedPath = PackageHelper.getSdDir(cid); 9320 resolvedFile = new File(resolvedPath); 9321 } else if (file != null) { 9322 resolvedPath = file.getAbsolutePath(); 9323 resolvedFile = file; 9324 } else { 9325 resolvedPath = null; 9326 resolvedFile = null; 9327 } 9328 } 9329 } 9330 9331 class InstallParams extends HandlerParams { 9332 final OriginInfo origin; 9333 final IPackageInstallObserver2 observer; 9334 int installFlags; 9335 final String installerPackageName; 9336 final VerificationParams verificationParams; 9337 private InstallArgs mArgs; 9338 private int mRet; 9339 final String packageAbiOverride; 9340 9341 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9342 String installerPackageName, VerificationParams verificationParams, UserHandle user, 9343 String packageAbiOverride) { 9344 super(user); 9345 this.origin = origin; 9346 this.observer = observer; 9347 this.installFlags = installFlags; 9348 this.installerPackageName = installerPackageName; 9349 this.verificationParams = verificationParams; 9350 this.packageAbiOverride = packageAbiOverride; 9351 } 9352 9353 @Override 9354 public String toString() { 9355 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9356 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9357 } 9358 9359 public ManifestDigest getManifestDigest() { 9360 if (verificationParams == null) { 9361 return null; 9362 } 9363 return verificationParams.getManifestDigest(); 9364 } 9365 9366 private int installLocationPolicy(PackageInfoLite pkgLite) { 9367 String packageName = pkgLite.packageName; 9368 int installLocation = pkgLite.installLocation; 9369 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9370 // reader 9371 synchronized (mPackages) { 9372 PackageParser.Package pkg = mPackages.get(packageName); 9373 if (pkg != null) { 9374 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9375 // Check for downgrading. 9376 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9377 try { 9378 checkDowngrade(pkg, pkgLite); 9379 } catch (PackageManagerException e) { 9380 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9381 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9382 } 9383 } 9384 // Check for updated system application. 9385 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9386 if (onSd) { 9387 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9388 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9389 } 9390 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9391 } else { 9392 if (onSd) { 9393 // Install flag overrides everything. 9394 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9395 } 9396 // If current upgrade specifies particular preference 9397 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9398 // Application explicitly specified internal. 9399 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9400 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9401 // App explictly prefers external. Let policy decide 9402 } else { 9403 // Prefer previous location 9404 if (isExternal(pkg)) { 9405 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9406 } 9407 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9408 } 9409 } 9410 } else { 9411 // Invalid install. Return error code 9412 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9413 } 9414 } 9415 } 9416 // All the special cases have been taken care of. 9417 // Return result based on recommended install location. 9418 if (onSd) { 9419 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9420 } 9421 return pkgLite.recommendedInstallLocation; 9422 } 9423 9424 /* 9425 * Invoke remote method to get package information and install 9426 * location values. Override install location based on default 9427 * policy if needed and then create install arguments based 9428 * on the install location. 9429 */ 9430 public void handleStartCopy() throws RemoteException { 9431 int ret = PackageManager.INSTALL_SUCCEEDED; 9432 9433 // If we're already staged, we've firmly committed to an install location 9434 if (origin.staged) { 9435 if (origin.file != null) { 9436 installFlags |= PackageManager.INSTALL_INTERNAL; 9437 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9438 } else if (origin.cid != null) { 9439 installFlags |= PackageManager.INSTALL_EXTERNAL; 9440 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9441 } else { 9442 throw new IllegalStateException("Invalid stage location"); 9443 } 9444 } 9445 9446 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9447 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9448 9449 PackageInfoLite pkgLite = null; 9450 9451 if (onInt && onSd) { 9452 // Check if both bits are set. 9453 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9454 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9455 } else { 9456 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9457 packageAbiOverride); 9458 9459 /* 9460 * If we have too little free space, try to free cache 9461 * before giving up. 9462 */ 9463 if (!origin.staged && pkgLite.recommendedInstallLocation 9464 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9465 // TODO: focus freeing disk space on the target device 9466 final StorageManager storage = StorageManager.from(mContext); 9467 final long lowThreshold = storage.getStorageLowBytes( 9468 Environment.getDataDirectory()); 9469 9470 final long sizeBytes = mContainerService.calculateInstalledSize( 9471 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9472 9473 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9474 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9475 installFlags, packageAbiOverride); 9476 } 9477 9478 /* 9479 * The cache free must have deleted the file we 9480 * downloaded to install. 9481 * 9482 * TODO: fix the "freeCache" call to not delete 9483 * the file we care about. 9484 */ 9485 if (pkgLite.recommendedInstallLocation 9486 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9487 pkgLite.recommendedInstallLocation 9488 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9489 } 9490 } 9491 } 9492 9493 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9494 int loc = pkgLite.recommendedInstallLocation; 9495 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9496 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9497 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9498 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9499 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9500 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9501 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9502 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9503 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9504 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9505 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9506 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9507 } else { 9508 // Override with defaults if needed. 9509 loc = installLocationPolicy(pkgLite); 9510 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9511 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9512 } else if (!onSd && !onInt) { 9513 // Override install location with flags 9514 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9515 // Set the flag to install on external media. 9516 installFlags |= PackageManager.INSTALL_EXTERNAL; 9517 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9518 } else { 9519 // Make sure the flag for installing on external 9520 // media is unset 9521 installFlags |= PackageManager.INSTALL_INTERNAL; 9522 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9523 } 9524 } 9525 } 9526 } 9527 9528 final InstallArgs args = createInstallArgs(this); 9529 mArgs = args; 9530 9531 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9532 /* 9533 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9534 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9535 */ 9536 int userIdentifier = getUser().getIdentifier(); 9537 if (userIdentifier == UserHandle.USER_ALL 9538 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9539 userIdentifier = UserHandle.USER_OWNER; 9540 } 9541 9542 /* 9543 * Determine if we have any installed package verifiers. If we 9544 * do, then we'll defer to them to verify the packages. 9545 */ 9546 final int requiredUid = mRequiredVerifierPackage == null ? -1 9547 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9548 if (!origin.existing && requiredUid != -1 9549 && isVerificationEnabled(userIdentifier, installFlags)) { 9550 final Intent verification = new Intent( 9551 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9552 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9553 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9554 PACKAGE_MIME_TYPE); 9555 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9556 9557 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9558 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9559 0 /* TODO: Which userId? */); 9560 9561 if (DEBUG_VERIFY) { 9562 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9563 + verification.toString() + " with " + pkgLite.verifiers.length 9564 + " optional verifiers"); 9565 } 9566 9567 final int verificationId = mPendingVerificationToken++; 9568 9569 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9570 9571 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9572 installerPackageName); 9573 9574 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9575 installFlags); 9576 9577 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9578 pkgLite.packageName); 9579 9580 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9581 pkgLite.versionCode); 9582 9583 if (verificationParams != null) { 9584 if (verificationParams.getVerificationURI() != null) { 9585 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9586 verificationParams.getVerificationURI()); 9587 } 9588 if (verificationParams.getOriginatingURI() != null) { 9589 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9590 verificationParams.getOriginatingURI()); 9591 } 9592 if (verificationParams.getReferrer() != null) { 9593 verification.putExtra(Intent.EXTRA_REFERRER, 9594 verificationParams.getReferrer()); 9595 } 9596 if (verificationParams.getOriginatingUid() >= 0) { 9597 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9598 verificationParams.getOriginatingUid()); 9599 } 9600 if (verificationParams.getInstallerUid() >= 0) { 9601 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9602 verificationParams.getInstallerUid()); 9603 } 9604 } 9605 9606 final PackageVerificationState verificationState = new PackageVerificationState( 9607 requiredUid, args); 9608 9609 mPendingVerification.append(verificationId, verificationState); 9610 9611 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9612 receivers, verificationState); 9613 9614 /* 9615 * If any sufficient verifiers were listed in the package 9616 * manifest, attempt to ask them. 9617 */ 9618 if (sufficientVerifiers != null) { 9619 final int N = sufficientVerifiers.size(); 9620 if (N == 0) { 9621 Slog.i(TAG, "Additional verifiers required, but none installed."); 9622 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9623 } else { 9624 for (int i = 0; i < N; i++) { 9625 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9626 9627 final Intent sufficientIntent = new Intent(verification); 9628 sufficientIntent.setComponent(verifierComponent); 9629 9630 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9631 } 9632 } 9633 } 9634 9635 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9636 mRequiredVerifierPackage, receivers); 9637 if (ret == PackageManager.INSTALL_SUCCEEDED 9638 && mRequiredVerifierPackage != null) { 9639 /* 9640 * Send the intent to the required verification agent, 9641 * but only start the verification timeout after the 9642 * target BroadcastReceivers have run. 9643 */ 9644 verification.setComponent(requiredVerifierComponent); 9645 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9646 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9647 new BroadcastReceiver() { 9648 @Override 9649 public void onReceive(Context context, Intent intent) { 9650 final Message msg = mHandler 9651 .obtainMessage(CHECK_PENDING_VERIFICATION); 9652 msg.arg1 = verificationId; 9653 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9654 } 9655 }, null, 0, null, null); 9656 9657 /* 9658 * We don't want the copy to proceed until verification 9659 * succeeds, so null out this field. 9660 */ 9661 mArgs = null; 9662 } 9663 } else { 9664 /* 9665 * No package verification is enabled, so immediately start 9666 * the remote call to initiate copy using temporary file. 9667 */ 9668 ret = args.copyApk(mContainerService, true); 9669 } 9670 } 9671 9672 mRet = ret; 9673 } 9674 9675 @Override 9676 void handleReturnCode() { 9677 // If mArgs is null, then MCS couldn't be reached. When it 9678 // reconnects, it will try again to install. At that point, this 9679 // will succeed. 9680 if (mArgs != null) { 9681 processPendingInstall(mArgs, mRet); 9682 } 9683 } 9684 9685 @Override 9686 void handleServiceError() { 9687 mArgs = createInstallArgs(this); 9688 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9689 } 9690 9691 public boolean isForwardLocked() { 9692 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9693 } 9694 } 9695 9696 /** 9697 * Used during creation of InstallArgs 9698 * 9699 * @param installFlags package installation flags 9700 * @return true if should be installed on external storage 9701 */ 9702 private static boolean installOnSd(int installFlags) { 9703 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9704 return false; 9705 } 9706 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9707 return true; 9708 } 9709 return false; 9710 } 9711 9712 /** 9713 * Used during creation of InstallArgs 9714 * 9715 * @param installFlags package installation flags 9716 * @return true if should be installed as forward locked 9717 */ 9718 private static boolean installForwardLocked(int installFlags) { 9719 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9720 } 9721 9722 private InstallArgs createInstallArgs(InstallParams params) { 9723 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9724 return new AsecInstallArgs(params); 9725 } else { 9726 return new FileInstallArgs(params); 9727 } 9728 } 9729 9730 /** 9731 * Create args that describe an existing installed package. Typically used 9732 * when cleaning up old installs, or used as a move source. 9733 */ 9734 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9735 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9736 final boolean isInAsec; 9737 if (installOnSd(installFlags)) { 9738 /* Apps on SD card are always in ASEC containers. */ 9739 isInAsec = true; 9740 } else if (installForwardLocked(installFlags) 9741 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9742 /* 9743 * Forward-locked apps are only in ASEC containers if they're the 9744 * new style 9745 */ 9746 isInAsec = true; 9747 } else { 9748 isInAsec = false; 9749 } 9750 9751 if (isInAsec) { 9752 return new AsecInstallArgs(codePath, instructionSets, 9753 installOnSd(installFlags), installForwardLocked(installFlags)); 9754 } else { 9755 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9756 instructionSets); 9757 } 9758 } 9759 9760 static abstract class InstallArgs { 9761 /** @see InstallParams#origin */ 9762 final OriginInfo origin; 9763 9764 final IPackageInstallObserver2 observer; 9765 // Always refers to PackageManager flags only 9766 final int installFlags; 9767 final String installerPackageName; 9768 final ManifestDigest manifestDigest; 9769 final UserHandle user; 9770 final String abiOverride; 9771 9772 // The list of instruction sets supported by this app. This is currently 9773 // only used during the rmdex() phase to clean up resources. We can get rid of this 9774 // if we move dex files under the common app path. 9775 /* nullable */ String[] instructionSets; 9776 9777 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9778 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9779 String[] instructionSets, String abiOverride) { 9780 this.origin = origin; 9781 this.installFlags = installFlags; 9782 this.observer = observer; 9783 this.installerPackageName = installerPackageName; 9784 this.manifestDigest = manifestDigest; 9785 this.user = user; 9786 this.instructionSets = instructionSets; 9787 this.abiOverride = abiOverride; 9788 } 9789 9790 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9791 abstract int doPreInstall(int status); 9792 9793 /** 9794 * Rename package into final resting place. All paths on the given 9795 * scanned package should be updated to reflect the rename. 9796 */ 9797 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9798 abstract int doPostInstall(int status, int uid); 9799 9800 /** @see PackageSettingBase#codePathString */ 9801 abstract String getCodePath(); 9802 /** @see PackageSettingBase#resourcePathString */ 9803 abstract String getResourcePath(); 9804 abstract String getLegacyNativeLibraryPath(); 9805 9806 // Need installer lock especially for dex file removal. 9807 abstract void cleanUpResourcesLI(); 9808 abstract boolean doPostDeleteLI(boolean delete); 9809 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9810 9811 /** 9812 * Called before the source arguments are copied. This is used mostly 9813 * for MoveParams when it needs to read the source file to put it in the 9814 * destination. 9815 */ 9816 int doPreCopy() { 9817 return PackageManager.INSTALL_SUCCEEDED; 9818 } 9819 9820 /** 9821 * Called after the source arguments are copied. This is used mostly for 9822 * MoveParams when it needs to read the source file to put it in the 9823 * destination. 9824 * 9825 * @return 9826 */ 9827 int doPostCopy(int uid) { 9828 return PackageManager.INSTALL_SUCCEEDED; 9829 } 9830 9831 protected boolean isFwdLocked() { 9832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9833 } 9834 9835 protected boolean isExternal() { 9836 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9837 } 9838 9839 UserHandle getUser() { 9840 return user; 9841 } 9842 } 9843 9844 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9845 if (!allCodePaths.isEmpty()) { 9846 if (instructionSets == null) { 9847 throw new IllegalStateException("instructionSet == null"); 9848 } 9849 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9850 for (String codePath : allCodePaths) { 9851 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9852 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9853 if (retCode < 0) { 9854 Slog.w(TAG, "Couldn't remove dex file for package: " 9855 + " at location " + codePath + ", retcode=" + retCode); 9856 // we don't consider this to be a failure of the core package deletion 9857 } 9858 } 9859 } 9860 } 9861 } 9862 9863 /** 9864 * Logic to handle installation of non-ASEC applications, including copying 9865 * and renaming logic. 9866 */ 9867 class FileInstallArgs extends InstallArgs { 9868 private File codeFile; 9869 private File resourceFile; 9870 private File legacyNativeLibraryPath; 9871 9872 // Example topology: 9873 // /data/app/com.example/base.apk 9874 // /data/app/com.example/split_foo.apk 9875 // /data/app/com.example/lib/arm/libfoo.so 9876 // /data/app/com.example/lib/arm64/libfoo.so 9877 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9878 9879 /** New install */ 9880 FileInstallArgs(InstallParams params) { 9881 super(params.origin, params.observer, params.installFlags, 9882 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9883 null /* instruction sets */, params.packageAbiOverride); 9884 if (isFwdLocked()) { 9885 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9886 } 9887 } 9888 9889 /** Existing install */ 9890 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9891 String[] instructionSets) { 9892 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9893 this.codeFile = (codePath != null) ? new File(codePath) : null; 9894 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9895 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9896 new File(legacyNativeLibraryPath) : null; 9897 } 9898 9899 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9900 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9901 isFwdLocked(), abiOverride); 9902 9903 final StorageManager storage = StorageManager.from(mContext); 9904 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9905 } 9906 9907 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9908 if (origin.staged) { 9909 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9910 codeFile = origin.file; 9911 resourceFile = origin.file; 9912 return PackageManager.INSTALL_SUCCEEDED; 9913 } 9914 9915 try { 9916 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9917 codeFile = tempDir; 9918 resourceFile = tempDir; 9919 } catch (IOException e) { 9920 Slog.w(TAG, "Failed to create copy file: " + e); 9921 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9922 } 9923 9924 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9925 @Override 9926 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9927 if (!FileUtils.isValidExtFilename(name)) { 9928 throw new IllegalArgumentException("Invalid filename: " + name); 9929 } 9930 try { 9931 final File file = new File(codeFile, name); 9932 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9933 O_RDWR | O_CREAT, 0644); 9934 Os.chmod(file.getAbsolutePath(), 0644); 9935 return new ParcelFileDescriptor(fd); 9936 } catch (ErrnoException e) { 9937 throw new RemoteException("Failed to open: " + e.getMessage()); 9938 } 9939 } 9940 }; 9941 9942 int ret = PackageManager.INSTALL_SUCCEEDED; 9943 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9944 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9945 Slog.e(TAG, "Failed to copy package"); 9946 return ret; 9947 } 9948 9949 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9950 NativeLibraryHelper.Handle handle = null; 9951 try { 9952 handle = NativeLibraryHelper.Handle.create(codeFile); 9953 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9954 abiOverride); 9955 } catch (IOException e) { 9956 Slog.e(TAG, "Copying native libraries failed", e); 9957 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9958 } finally { 9959 IoUtils.closeQuietly(handle); 9960 } 9961 9962 return ret; 9963 } 9964 9965 int doPreInstall(int status) { 9966 if (status != PackageManager.INSTALL_SUCCEEDED) { 9967 cleanUp(); 9968 } 9969 return status; 9970 } 9971 9972 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9973 if (status != PackageManager.INSTALL_SUCCEEDED) { 9974 cleanUp(); 9975 return false; 9976 } else { 9977 final File beforeCodeFile = codeFile; 9978 final File afterCodeFile = getNextCodePath(pkg.packageName); 9979 9980 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9981 try { 9982 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9983 } catch (ErrnoException e) { 9984 Slog.d(TAG, "Failed to rename", e); 9985 return false; 9986 } 9987 9988 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9989 Slog.d(TAG, "Failed to restorecon"); 9990 return false; 9991 } 9992 9993 // Reflect the rename internally 9994 codeFile = afterCodeFile; 9995 resourceFile = afterCodeFile; 9996 9997 // Reflect the rename in scanned details 9998 pkg.codePath = afterCodeFile.getAbsolutePath(); 9999 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10000 pkg.baseCodePath); 10001 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10002 pkg.splitCodePaths); 10003 10004 // Reflect the rename in app info 10005 pkg.applicationInfo.setCodePath(pkg.codePath); 10006 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10007 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10008 pkg.applicationInfo.setResourcePath(pkg.codePath); 10009 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10010 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10011 10012 return true; 10013 } 10014 } 10015 10016 int doPostInstall(int status, int uid) { 10017 if (status != PackageManager.INSTALL_SUCCEEDED) { 10018 cleanUp(); 10019 } 10020 return status; 10021 } 10022 10023 @Override 10024 String getCodePath() { 10025 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10026 } 10027 10028 @Override 10029 String getResourcePath() { 10030 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10031 } 10032 10033 @Override 10034 String getLegacyNativeLibraryPath() { 10035 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10036 } 10037 10038 private boolean cleanUp() { 10039 if (codeFile == null || !codeFile.exists()) { 10040 return false; 10041 } 10042 10043 if (codeFile.isDirectory()) { 10044 FileUtils.deleteContents(codeFile); 10045 } 10046 codeFile.delete(); 10047 10048 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10049 resourceFile.delete(); 10050 } 10051 10052 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10053 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10054 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10055 } 10056 legacyNativeLibraryPath.delete(); 10057 } 10058 10059 return true; 10060 } 10061 10062 void cleanUpResourcesLI() { 10063 // Try enumerating all code paths before deleting 10064 List<String> allCodePaths = Collections.EMPTY_LIST; 10065 if (codeFile != null && codeFile.exists()) { 10066 try { 10067 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10068 allCodePaths = pkg.getAllCodePaths(); 10069 } catch (PackageParserException e) { 10070 // Ignored; we tried our best 10071 } 10072 } 10073 10074 cleanUp(); 10075 removeDexFiles(allCodePaths, instructionSets); 10076 } 10077 10078 boolean doPostDeleteLI(boolean delete) { 10079 // XXX err, shouldn't we respect the delete flag? 10080 cleanUpResourcesLI(); 10081 return true; 10082 } 10083 } 10084 10085 private boolean isAsecExternal(String cid) { 10086 final String asecPath = PackageHelper.getSdFilesystem(cid); 10087 return !asecPath.startsWith(mAsecInternalPath); 10088 } 10089 10090 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10091 PackageManagerException { 10092 if (copyRet < 0) { 10093 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10094 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10095 throw new PackageManagerException(copyRet, message); 10096 } 10097 } 10098 } 10099 10100 /** 10101 * Extract the MountService "container ID" from the full code path of an 10102 * .apk. 10103 */ 10104 static String cidFromCodePath(String fullCodePath) { 10105 int eidx = fullCodePath.lastIndexOf("/"); 10106 String subStr1 = fullCodePath.substring(0, eidx); 10107 int sidx = subStr1.lastIndexOf("/"); 10108 return subStr1.substring(sidx+1, eidx); 10109 } 10110 10111 /** 10112 * Logic to handle installation of ASEC applications, including copying and 10113 * renaming logic. 10114 */ 10115 class AsecInstallArgs extends InstallArgs { 10116 static final String RES_FILE_NAME = "pkg.apk"; 10117 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10118 10119 String cid; 10120 String packagePath; 10121 String resourcePath; 10122 String legacyNativeLibraryDir; 10123 10124 /** New install */ 10125 AsecInstallArgs(InstallParams params) { 10126 super(params.origin, params.observer, params.installFlags, 10127 params.installerPackageName, params.getManifestDigest(), 10128 params.getUser(), null /* instruction sets */, 10129 params.packageAbiOverride); 10130 } 10131 10132 /** Existing install */ 10133 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10134 boolean isExternal, boolean isForwardLocked) { 10135 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10136 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10137 instructionSets, null); 10138 // Hackily pretend we're still looking at a full code path 10139 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10140 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10141 } 10142 10143 // Extract cid from fullCodePath 10144 int eidx = fullCodePath.lastIndexOf("/"); 10145 String subStr1 = fullCodePath.substring(0, eidx); 10146 int sidx = subStr1.lastIndexOf("/"); 10147 cid = subStr1.substring(sidx+1, eidx); 10148 setMountPath(subStr1); 10149 } 10150 10151 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10152 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10153 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10154 instructionSets, null); 10155 this.cid = cid; 10156 setMountPath(PackageHelper.getSdDir(cid)); 10157 } 10158 10159 void createCopyFile() { 10160 cid = mInstallerService.allocateExternalStageCidLegacy(); 10161 } 10162 10163 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10164 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10165 abiOverride); 10166 10167 final File target; 10168 if (isExternal()) { 10169 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10170 } else { 10171 target = Environment.getDataDirectory(); 10172 } 10173 10174 final StorageManager storage = StorageManager.from(mContext); 10175 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10176 } 10177 10178 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10179 if (origin.staged) { 10180 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10181 cid = origin.cid; 10182 setMountPath(PackageHelper.getSdDir(cid)); 10183 return PackageManager.INSTALL_SUCCEEDED; 10184 } 10185 10186 if (temp) { 10187 createCopyFile(); 10188 } else { 10189 /* 10190 * Pre-emptively destroy the container since it's destroyed if 10191 * copying fails due to it existing anyway. 10192 */ 10193 PackageHelper.destroySdDir(cid); 10194 } 10195 10196 final String newMountPath = imcs.copyPackageToContainer( 10197 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 10198 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10199 10200 if (newMountPath != null) { 10201 setMountPath(newMountPath); 10202 return PackageManager.INSTALL_SUCCEEDED; 10203 } else { 10204 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10205 } 10206 } 10207 10208 @Override 10209 String getCodePath() { 10210 return packagePath; 10211 } 10212 10213 @Override 10214 String getResourcePath() { 10215 return resourcePath; 10216 } 10217 10218 @Override 10219 String getLegacyNativeLibraryPath() { 10220 return legacyNativeLibraryDir; 10221 } 10222 10223 int doPreInstall(int status) { 10224 if (status != PackageManager.INSTALL_SUCCEEDED) { 10225 // Destroy container 10226 PackageHelper.destroySdDir(cid); 10227 } else { 10228 boolean mounted = PackageHelper.isContainerMounted(cid); 10229 if (!mounted) { 10230 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10231 Process.SYSTEM_UID); 10232 if (newMountPath != null) { 10233 setMountPath(newMountPath); 10234 } else { 10235 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10236 } 10237 } 10238 } 10239 return status; 10240 } 10241 10242 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10243 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10244 String newMountPath = null; 10245 if (PackageHelper.isContainerMounted(cid)) { 10246 // Unmount the container 10247 if (!PackageHelper.unMountSdDir(cid)) { 10248 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10249 return false; 10250 } 10251 } 10252 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10253 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10254 " which might be stale. Will try to clean up."); 10255 // Clean up the stale container and proceed to recreate. 10256 if (!PackageHelper.destroySdDir(newCacheId)) { 10257 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10258 return false; 10259 } 10260 // Successfully cleaned up stale container. Try to rename again. 10261 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10262 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10263 + " inspite of cleaning it up."); 10264 return false; 10265 } 10266 } 10267 if (!PackageHelper.isContainerMounted(newCacheId)) { 10268 Slog.w(TAG, "Mounting container " + newCacheId); 10269 newMountPath = PackageHelper.mountSdDir(newCacheId, 10270 getEncryptKey(), Process.SYSTEM_UID); 10271 } else { 10272 newMountPath = PackageHelper.getSdDir(newCacheId); 10273 } 10274 if (newMountPath == null) { 10275 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10276 return false; 10277 } 10278 Log.i(TAG, "Succesfully renamed " + cid + 10279 " to " + newCacheId + 10280 " at new path: " + newMountPath); 10281 cid = newCacheId; 10282 10283 final File beforeCodeFile = new File(packagePath); 10284 setMountPath(newMountPath); 10285 final File afterCodeFile = new File(packagePath); 10286 10287 // Reflect the rename in scanned details 10288 pkg.codePath = afterCodeFile.getAbsolutePath(); 10289 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10290 pkg.baseCodePath); 10291 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10292 pkg.splitCodePaths); 10293 10294 // Reflect the rename in app info 10295 pkg.applicationInfo.setCodePath(pkg.codePath); 10296 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10297 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10298 pkg.applicationInfo.setResourcePath(pkg.codePath); 10299 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10300 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10301 10302 return true; 10303 } 10304 10305 private void setMountPath(String mountPath) { 10306 final File mountFile = new File(mountPath); 10307 10308 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10309 if (monolithicFile.exists()) { 10310 packagePath = monolithicFile.getAbsolutePath(); 10311 if (isFwdLocked()) { 10312 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10313 } else { 10314 resourcePath = packagePath; 10315 } 10316 } else { 10317 packagePath = mountFile.getAbsolutePath(); 10318 resourcePath = packagePath; 10319 } 10320 10321 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10322 } 10323 10324 int doPostInstall(int status, int uid) { 10325 if (status != PackageManager.INSTALL_SUCCEEDED) { 10326 cleanUp(); 10327 } else { 10328 final int groupOwner; 10329 final String protectedFile; 10330 if (isFwdLocked()) { 10331 groupOwner = UserHandle.getSharedAppGid(uid); 10332 protectedFile = RES_FILE_NAME; 10333 } else { 10334 groupOwner = -1; 10335 protectedFile = null; 10336 } 10337 10338 if (uid < Process.FIRST_APPLICATION_UID 10339 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10340 Slog.e(TAG, "Failed to finalize " + cid); 10341 PackageHelper.destroySdDir(cid); 10342 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10343 } 10344 10345 boolean mounted = PackageHelper.isContainerMounted(cid); 10346 if (!mounted) { 10347 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10348 } 10349 } 10350 return status; 10351 } 10352 10353 private void cleanUp() { 10354 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10355 10356 // Destroy secure container 10357 PackageHelper.destroySdDir(cid); 10358 } 10359 10360 private List<String> getAllCodePaths() { 10361 final File codeFile = new File(getCodePath()); 10362 if (codeFile != null && codeFile.exists()) { 10363 try { 10364 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10365 return pkg.getAllCodePaths(); 10366 } catch (PackageParserException e) { 10367 // Ignored; we tried our best 10368 } 10369 } 10370 return Collections.EMPTY_LIST; 10371 } 10372 10373 void cleanUpResourcesLI() { 10374 // Enumerate all code paths before deleting 10375 cleanUpResourcesLI(getAllCodePaths()); 10376 } 10377 10378 private void cleanUpResourcesLI(List<String> allCodePaths) { 10379 cleanUp(); 10380 removeDexFiles(allCodePaths, instructionSets); 10381 } 10382 10383 10384 10385 String getPackageName() { 10386 return getAsecPackageName(cid); 10387 } 10388 10389 boolean doPostDeleteLI(boolean delete) { 10390 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10391 final List<String> allCodePaths = getAllCodePaths(); 10392 boolean mounted = PackageHelper.isContainerMounted(cid); 10393 if (mounted) { 10394 // Unmount first 10395 if (PackageHelper.unMountSdDir(cid)) { 10396 mounted = false; 10397 } 10398 } 10399 if (!mounted && delete) { 10400 cleanUpResourcesLI(allCodePaths); 10401 } 10402 return !mounted; 10403 } 10404 10405 @Override 10406 int doPreCopy() { 10407 if (isFwdLocked()) { 10408 if (!PackageHelper.fixSdPermissions(cid, 10409 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10410 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10411 } 10412 } 10413 10414 return PackageManager.INSTALL_SUCCEEDED; 10415 } 10416 10417 @Override 10418 int doPostCopy(int uid) { 10419 if (isFwdLocked()) { 10420 if (uid < Process.FIRST_APPLICATION_UID 10421 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10422 RES_FILE_NAME)) { 10423 Slog.e(TAG, "Failed to finalize " + cid); 10424 PackageHelper.destroySdDir(cid); 10425 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10426 } 10427 } 10428 10429 return PackageManager.INSTALL_SUCCEEDED; 10430 } 10431 } 10432 10433 static String getAsecPackageName(String packageCid) { 10434 int idx = packageCid.lastIndexOf("-"); 10435 if (idx == -1) { 10436 return packageCid; 10437 } 10438 return packageCid.substring(0, idx); 10439 } 10440 10441 // Utility method used to create code paths based on package name and available index. 10442 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10443 String idxStr = ""; 10444 int idx = 1; 10445 // Fall back to default value of idx=1 if prefix is not 10446 // part of oldCodePath 10447 if (oldCodePath != null) { 10448 String subStr = oldCodePath; 10449 // Drop the suffix right away 10450 if (suffix != null && subStr.endsWith(suffix)) { 10451 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10452 } 10453 // If oldCodePath already contains prefix find out the 10454 // ending index to either increment or decrement. 10455 int sidx = subStr.lastIndexOf(prefix); 10456 if (sidx != -1) { 10457 subStr = subStr.substring(sidx + prefix.length()); 10458 if (subStr != null) { 10459 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10460 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10461 } 10462 try { 10463 idx = Integer.parseInt(subStr); 10464 if (idx <= 1) { 10465 idx++; 10466 } else { 10467 idx--; 10468 } 10469 } catch(NumberFormatException e) { 10470 } 10471 } 10472 } 10473 } 10474 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10475 return prefix + idxStr; 10476 } 10477 10478 private File getNextCodePath(String packageName) { 10479 int suffix = 1; 10480 File result; 10481 do { 10482 result = new File(mAppInstallDir, packageName + "-" + suffix); 10483 suffix++; 10484 } while (result.exists()); 10485 return result; 10486 } 10487 10488 // Utility method used to ignore ADD/REMOVE events 10489 // by directory observer. 10490 private static boolean ignoreCodePath(String fullPathStr) { 10491 String apkName = deriveCodePathName(fullPathStr); 10492 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10493 if (idx != -1 && ((idx+1) < apkName.length())) { 10494 // Make sure the package ends with a numeral 10495 String version = apkName.substring(idx+1); 10496 try { 10497 Integer.parseInt(version); 10498 return true; 10499 } catch (NumberFormatException e) {} 10500 } 10501 return false; 10502 } 10503 10504 // Utility method that returns the relative package path with respect 10505 // to the installation directory. Like say for /data/data/com.test-1.apk 10506 // string com.test-1 is returned. 10507 static String deriveCodePathName(String codePath) { 10508 if (codePath == null) { 10509 return null; 10510 } 10511 final File codeFile = new File(codePath); 10512 final String name = codeFile.getName(); 10513 if (codeFile.isDirectory()) { 10514 return name; 10515 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10516 final int lastDot = name.lastIndexOf('.'); 10517 return name.substring(0, lastDot); 10518 } else { 10519 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10520 return null; 10521 } 10522 } 10523 10524 class PackageInstalledInfo { 10525 String name; 10526 int uid; 10527 // The set of users that originally had this package installed. 10528 int[] origUsers; 10529 // The set of users that now have this package installed. 10530 int[] newUsers; 10531 PackageParser.Package pkg; 10532 int returnCode; 10533 String returnMsg; 10534 PackageRemovedInfo removedInfo; 10535 10536 public void setError(int code, String msg) { 10537 returnCode = code; 10538 returnMsg = msg; 10539 Slog.w(TAG, msg); 10540 } 10541 10542 public void setError(String msg, PackageParserException e) { 10543 returnCode = e.error; 10544 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10545 Slog.w(TAG, msg, e); 10546 } 10547 10548 public void setError(String msg, PackageManagerException e) { 10549 returnCode = e.error; 10550 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10551 Slog.w(TAG, msg, e); 10552 } 10553 10554 // In some error cases we want to convey more info back to the observer 10555 String origPackage; 10556 String origPermission; 10557 } 10558 10559 /* 10560 * Install a non-existing package. 10561 */ 10562 private void installNewPackageLI(PackageParser.Package pkg, 10563 int parseFlags, int scanFlags, UserHandle user, 10564 String installerPackageName, PackageInstalledInfo res) { 10565 // Remember this for later, in case we need to rollback this install 10566 String pkgName = pkg.packageName; 10567 10568 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10569 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10570 synchronized(mPackages) { 10571 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10572 // A package with the same name is already installed, though 10573 // it has been renamed to an older name. The package we 10574 // are trying to install should be installed as an update to 10575 // the existing one, but that has not been requested, so bail. 10576 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10577 + " without first uninstalling package running as " 10578 + mSettings.mRenamedPackages.get(pkgName)); 10579 return; 10580 } 10581 if (mPackages.containsKey(pkgName)) { 10582 // Don't allow installation over an existing package with the same name. 10583 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10584 + " without first uninstalling."); 10585 return; 10586 } 10587 } 10588 10589 try { 10590 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10591 System.currentTimeMillis(), user); 10592 10593 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10594 // delete the partially installed application. the data directory will have to be 10595 // restored if it was already existing 10596 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10597 // remove package from internal structures. Note that we want deletePackageX to 10598 // delete the package data and cache directories that it created in 10599 // scanPackageLocked, unless those directories existed before we even tried to 10600 // install. 10601 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10602 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10603 res.removedInfo, true); 10604 } 10605 10606 } catch (PackageManagerException e) { 10607 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10608 } 10609 } 10610 10611 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10612 // Upgrade keysets are being used. Determine if new package has a superset of the 10613 // required keys. 10614 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10615 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10616 for (int i = 0; i < upgradeKeySets.length; i++) { 10617 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10618 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10619 return true; 10620 } 10621 } 10622 return false; 10623 } 10624 10625 private void replacePackageLI(PackageParser.Package pkg, 10626 int parseFlags, int scanFlags, UserHandle user, 10627 String installerPackageName, PackageInstalledInfo res) { 10628 PackageParser.Package oldPackage; 10629 String pkgName = pkg.packageName; 10630 int[] allUsers; 10631 boolean[] perUserInstalled; 10632 10633 // First find the old package info and check signatures 10634 synchronized(mPackages) { 10635 oldPackage = mPackages.get(pkgName); 10636 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10637 PackageSetting ps = mSettings.mPackages.get(pkgName); 10638 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10639 // default to original signature matching 10640 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10641 != PackageManager.SIGNATURE_MATCH) { 10642 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10643 "New package has a different signature: " + pkgName); 10644 return; 10645 } 10646 } else { 10647 if(!checkUpgradeKeySetLP(ps, pkg)) { 10648 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10649 "New package not signed by keys specified by upgrade-keysets: " 10650 + pkgName); 10651 return; 10652 } 10653 } 10654 10655 // In case of rollback, remember per-user/profile install state 10656 allUsers = sUserManager.getUserIds(); 10657 perUserInstalled = new boolean[allUsers.length]; 10658 for (int i = 0; i < allUsers.length; i++) { 10659 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10660 } 10661 } 10662 10663 boolean sysPkg = (isSystemApp(oldPackage)); 10664 if (sysPkg) { 10665 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10666 user, allUsers, perUserInstalled, installerPackageName, res); 10667 } else { 10668 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10669 user, allUsers, perUserInstalled, installerPackageName, res); 10670 } 10671 } 10672 10673 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10674 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10675 int[] allUsers, boolean[] perUserInstalled, 10676 String installerPackageName, PackageInstalledInfo res) { 10677 String pkgName = deletedPackage.packageName; 10678 boolean deletedPkg = true; 10679 boolean updatedSettings = false; 10680 10681 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10682 + deletedPackage); 10683 long origUpdateTime; 10684 if (pkg.mExtras != null) { 10685 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10686 } else { 10687 origUpdateTime = 0; 10688 } 10689 10690 // First delete the existing package while retaining the data directory 10691 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10692 res.removedInfo, true)) { 10693 // If the existing package wasn't successfully deleted 10694 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10695 deletedPkg = false; 10696 } else { 10697 // Successfully deleted the old package; proceed with replace. 10698 10699 // If deleted package lived in a container, give users a chance to 10700 // relinquish resources before killing. 10701 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10702 if (DEBUG_INSTALL) { 10703 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10704 } 10705 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10706 final ArrayList<String> pkgList = new ArrayList<String>(1); 10707 pkgList.add(deletedPackage.applicationInfo.packageName); 10708 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10709 } 10710 10711 deleteCodeCacheDirsLI(pkgName); 10712 try { 10713 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10714 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10715 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10716 user); 10717 updatedSettings = true; 10718 } catch (PackageManagerException e) { 10719 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10720 } 10721 } 10722 10723 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10724 // remove package from internal structures. Note that we want deletePackageX to 10725 // delete the package data and cache directories that it created in 10726 // scanPackageLocked, unless those directories existed before we even tried to 10727 // install. 10728 if(updatedSettings) { 10729 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10730 deletePackageLI( 10731 pkgName, null, true, allUsers, perUserInstalled, 10732 PackageManager.DELETE_KEEP_DATA, 10733 res.removedInfo, true); 10734 } 10735 // Since we failed to install the new package we need to restore the old 10736 // package that we deleted. 10737 if (deletedPkg) { 10738 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10739 File restoreFile = new File(deletedPackage.codePath); 10740 // Parse old package 10741 boolean oldOnSd = isExternal(deletedPackage); 10742 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10743 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10744 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10745 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10746 try { 10747 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10748 } catch (PackageManagerException e) { 10749 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10750 + e.getMessage()); 10751 return; 10752 } 10753 // Restore of old package succeeded. Update permissions. 10754 // writer 10755 synchronized (mPackages) { 10756 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10757 UPDATE_PERMISSIONS_ALL); 10758 // can downgrade to reader 10759 mSettings.writeLPr(); 10760 } 10761 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10762 } 10763 } 10764 } 10765 10766 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10767 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10768 int[] allUsers, boolean[] perUserInstalled, 10769 String installerPackageName, PackageInstalledInfo res) { 10770 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10771 + ", old=" + deletedPackage); 10772 boolean disabledSystem = false; 10773 boolean updatedSettings = false; 10774 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10775 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10776 != 0) { 10777 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10778 } 10779 String packageName = deletedPackage.packageName; 10780 if (packageName == null) { 10781 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10782 "Attempt to delete null packageName."); 10783 return; 10784 } 10785 PackageParser.Package oldPkg; 10786 PackageSetting oldPkgSetting; 10787 // reader 10788 synchronized (mPackages) { 10789 oldPkg = mPackages.get(packageName); 10790 oldPkgSetting = mSettings.mPackages.get(packageName); 10791 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10792 (oldPkgSetting == null)) { 10793 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10794 "Couldn't find package:" + packageName + " information"); 10795 return; 10796 } 10797 } 10798 10799 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10800 10801 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10802 res.removedInfo.removedPackage = packageName; 10803 // Remove existing system package 10804 removePackageLI(oldPkgSetting, true); 10805 // writer 10806 synchronized (mPackages) { 10807 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10808 if (!disabledSystem && deletedPackage != null) { 10809 // We didn't need to disable the .apk as a current system package, 10810 // which means we are replacing another update that is already 10811 // installed. We need to make sure to delete the older one's .apk. 10812 res.removedInfo.args = createInstallArgsForExisting(0, 10813 deletedPackage.applicationInfo.getCodePath(), 10814 deletedPackage.applicationInfo.getResourcePath(), 10815 deletedPackage.applicationInfo.nativeLibraryRootDir, 10816 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10817 } else { 10818 res.removedInfo.args = null; 10819 } 10820 } 10821 10822 // Successfully disabled the old package. Now proceed with re-installation 10823 deleteCodeCacheDirsLI(packageName); 10824 10825 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10826 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10827 10828 PackageParser.Package newPackage = null; 10829 try { 10830 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10831 if (newPackage.mExtras != null) { 10832 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10833 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10834 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10835 10836 // is the update attempting to change shared user? that isn't going to work... 10837 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10838 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10839 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10840 + " to " + newPkgSetting.sharedUser); 10841 updatedSettings = true; 10842 } 10843 } 10844 10845 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10846 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10847 user); 10848 updatedSettings = true; 10849 } 10850 10851 } catch (PackageManagerException e) { 10852 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10853 } 10854 10855 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10856 // Re installation failed. Restore old information 10857 // Remove new pkg information 10858 if (newPackage != null) { 10859 removeInstalledPackageLI(newPackage, true); 10860 } 10861 // Add back the old system package 10862 try { 10863 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10864 } catch (PackageManagerException e) { 10865 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10866 } 10867 // Restore the old system information in Settings 10868 synchronized (mPackages) { 10869 if (disabledSystem) { 10870 mSettings.enableSystemPackageLPw(packageName); 10871 } 10872 if (updatedSettings) { 10873 mSettings.setInstallerPackageName(packageName, 10874 oldPkgSetting.installerPackageName); 10875 } 10876 mSettings.writeLPr(); 10877 } 10878 } 10879 } 10880 10881 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10882 int[] allUsers, boolean[] perUserInstalled, 10883 PackageInstalledInfo res, UserHandle user) { 10884 String pkgName = newPackage.packageName; 10885 synchronized (mPackages) { 10886 //write settings. the installStatus will be incomplete at this stage. 10887 //note that the new package setting would have already been 10888 //added to mPackages. It hasn't been persisted yet. 10889 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10890 mSettings.writeLPr(); 10891 } 10892 10893 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10894 10895 synchronized (mPackages) { 10896 updatePermissionsLPw(newPackage.packageName, newPackage, 10897 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10898 ? UPDATE_PERMISSIONS_ALL : 0)); 10899 // For system-bundled packages, we assume that installing an upgraded version 10900 // of the package implies that the user actually wants to run that new code, 10901 // so we enable the package. 10902 PackageSetting ps = mSettings.mPackages.get(pkgName); 10903 if (ps != null) { 10904 if (isSystemApp(newPackage)) { 10905 // NB: implicit assumption that system package upgrades apply to all users 10906 if (DEBUG_INSTALL) { 10907 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10908 } 10909 if (res.origUsers != null) { 10910 for (int userHandle : res.origUsers) { 10911 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10912 userHandle, installerPackageName); 10913 } 10914 } 10915 // Also convey the prior install/uninstall state 10916 if (allUsers != null && perUserInstalled != null) { 10917 for (int i = 0; i < allUsers.length; i++) { 10918 if (DEBUG_INSTALL) { 10919 Slog.d(TAG, " user " + allUsers[i] 10920 + " => " + perUserInstalled[i]); 10921 } 10922 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10923 } 10924 // these install state changes will be persisted in the 10925 // upcoming call to mSettings.writeLPr(). 10926 } 10927 } 10928 // It's implied that when a user requests installation, they want the app to be 10929 // installed and enabled. 10930 int userId = user.getIdentifier(); 10931 if (userId != UserHandle.USER_ALL) { 10932 ps.setInstalled(true, userId); 10933 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10934 } 10935 } 10936 res.name = pkgName; 10937 res.uid = newPackage.applicationInfo.uid; 10938 res.pkg = newPackage; 10939 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10940 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10941 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10942 //to update install status 10943 mSettings.writeLPr(); 10944 } 10945 } 10946 10947 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10948 final int installFlags = args.installFlags; 10949 String installerPackageName = args.installerPackageName; 10950 File tmpPackageFile = new File(args.getCodePath()); 10951 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10952 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10953 boolean replace = false; 10954 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10955 // Result object to be returned 10956 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10957 10958 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10959 // Retrieve PackageSettings and parse package 10960 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10961 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10962 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10963 PackageParser pp = new PackageParser(); 10964 pp.setSeparateProcesses(mSeparateProcesses); 10965 pp.setDisplayMetrics(mMetrics); 10966 10967 final PackageParser.Package pkg; 10968 try { 10969 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10970 } catch (PackageParserException e) { 10971 res.setError("Failed parse during installPackageLI", e); 10972 return; 10973 } 10974 10975 // Mark that we have an install time CPU ABI override. 10976 pkg.cpuAbiOverride = args.abiOverride; 10977 10978 String pkgName = res.name = pkg.packageName; 10979 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10980 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10981 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10982 return; 10983 } 10984 } 10985 10986 try { 10987 pp.collectCertificates(pkg, parseFlags); 10988 pp.collectManifestDigest(pkg); 10989 } catch (PackageParserException e) { 10990 res.setError("Failed collect during installPackageLI", e); 10991 return; 10992 } 10993 10994 /* If the installer passed in a manifest digest, compare it now. */ 10995 if (args.manifestDigest != null) { 10996 if (DEBUG_INSTALL) { 10997 final String parsedManifest = pkg.manifestDigest == null ? "null" 10998 : pkg.manifestDigest.toString(); 10999 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11000 + parsedManifest); 11001 } 11002 11003 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11004 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11005 return; 11006 } 11007 } else if (DEBUG_INSTALL) { 11008 final String parsedManifest = pkg.manifestDigest == null 11009 ? "null" : pkg.manifestDigest.toString(); 11010 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11011 } 11012 11013 // Get rid of all references to package scan path via parser. 11014 pp = null; 11015 String oldCodePath = null; 11016 boolean systemApp = false; 11017 synchronized (mPackages) { 11018 // Check if installing already existing package 11019 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11020 String oldName = mSettings.mRenamedPackages.get(pkgName); 11021 if (pkg.mOriginalPackages != null 11022 && pkg.mOriginalPackages.contains(oldName) 11023 && mPackages.containsKey(oldName)) { 11024 // This package is derived from an original package, 11025 // and this device has been updating from that original 11026 // name. We must continue using the original name, so 11027 // rename the new package here. 11028 pkg.setPackageName(oldName); 11029 pkgName = pkg.packageName; 11030 replace = true; 11031 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11032 + oldName + " pkgName=" + pkgName); 11033 } else if (mPackages.containsKey(pkgName)) { 11034 // This package, under its official name, already exists 11035 // on the device; we should replace it. 11036 replace = true; 11037 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11038 } 11039 } 11040 11041 PackageSetting ps = mSettings.mPackages.get(pkgName); 11042 if (ps != null) { 11043 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11044 11045 // Quick sanity check that we're signed correctly if updating; 11046 // we'll check this again later when scanning, but we want to 11047 // bail early here before tripping over redefined permissions. 11048 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11049 try { 11050 verifySignaturesLP(ps, pkg); 11051 } catch (PackageManagerException e) { 11052 res.setError(e.error, e.getMessage()); 11053 return; 11054 } 11055 } else { 11056 if (!checkUpgradeKeySetLP(ps, pkg)) { 11057 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11058 + pkg.packageName + " upgrade keys do not match the " 11059 + "previously installed version"); 11060 return; 11061 } 11062 } 11063 11064 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11065 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11066 systemApp = (ps.pkg.applicationInfo.flags & 11067 ApplicationInfo.FLAG_SYSTEM) != 0; 11068 } 11069 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11070 } 11071 11072 // Check whether the newly-scanned package wants to define an already-defined perm 11073 int N = pkg.permissions.size(); 11074 for (int i = N-1; i >= 0; i--) { 11075 PackageParser.Permission perm = pkg.permissions.get(i); 11076 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11077 if (bp != null) { 11078 // If the defining package is signed with our cert, it's okay. This 11079 // also includes the "updating the same package" case, of course. 11080 // "updating same package" could also involve key-rotation. 11081 final boolean sigsOk; 11082 if (!bp.sourcePackage.equals(pkg.packageName) 11083 || !(bp.packageSetting instanceof PackageSetting) 11084 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11085 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11086 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11087 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11088 } else { 11089 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11090 } 11091 if (!sigsOk) { 11092 // If the owning package is the system itself, we log but allow 11093 // install to proceed; we fail the install on all other permission 11094 // redefinitions. 11095 if (!bp.sourcePackage.equals("android")) { 11096 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11097 + pkg.packageName + " attempting to redeclare permission " 11098 + perm.info.name + " already owned by " + bp.sourcePackage); 11099 res.origPermission = perm.info.name; 11100 res.origPackage = bp.sourcePackage; 11101 return; 11102 } else { 11103 Slog.w(TAG, "Package " + pkg.packageName 11104 + " attempting to redeclare system permission " 11105 + perm.info.name + "; ignoring new declaration"); 11106 pkg.permissions.remove(i); 11107 } 11108 } 11109 } 11110 } 11111 11112 } 11113 11114 if (systemApp && onSd) { 11115 // Disable updates to system apps on sdcard 11116 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11117 "Cannot install updates to system apps on sdcard"); 11118 return; 11119 } 11120 11121 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11122 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11123 return; 11124 } 11125 11126 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11127 11128 if (replace) { 11129 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11130 installerPackageName, res); 11131 } else { 11132 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11133 args.user, installerPackageName, res); 11134 } 11135 synchronized (mPackages) { 11136 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11137 if (ps != null) { 11138 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11139 } 11140 } 11141 } 11142 11143 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11144 if (mIntentFilterVerifierComponent == null) { 11145 Slog.d(TAG, "No IntentFilter verification will not be done as " 11146 + "there is no IntentFilterVerifier available!"); 11147 return; 11148 } 11149 11150 final int verifierUid = getPackageUid( 11151 mIntentFilterVerifierComponent.getPackageName(), 11152 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11153 11154 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11155 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11156 msg.obj = pkg; 11157 msg.arg1 = userId; 11158 msg.arg2 = verifierUid; 11159 11160 mHandler.sendMessage(msg); 11161 } 11162 11163 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11164 PackageParser.Package pkg) { 11165 int size = pkg.activities.size(); 11166 if (size == 0) { 11167 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11168 return; 11169 } 11170 11171 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11172 + " Activities needs verification ..."); 11173 11174 final int verificationId = mIntentFilterVerificationToken++; 11175 int count = 0; 11176 synchronized (mPackages) { 11177 for (PackageParser.Activity a : pkg.activities) { 11178 for (ActivityIntentInfo filter : a.intents) { 11179 boolean needFilterVerification = filter.needsVerification() && 11180 !filter.isVerified(); 11181 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11182 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11183 mIntentFilterVerifier.addOneIntentFilterVerification( 11184 verifierUid, userId, verificationId, filter, pkg.packageName); 11185 count++; 11186 } else { 11187 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11188 } 11189 } 11190 } 11191 } 11192 11193 if (count > 0) { 11194 mIntentFilterVerifier.startVerifications(userId); 11195 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11196 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11197 } else { 11198 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11199 } 11200 } 11201 11202 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11203 final ComponentName cn = filter.activity.getComponentName(); 11204 final String packageName = cn.getPackageName(); 11205 11206 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11207 packageName); 11208 if (ivi == null) { 11209 return true; 11210 } 11211 int status = ivi.getStatus(); 11212 switch (status) { 11213 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11214 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11215 return true; 11216 11217 default: 11218 // Nothing to do 11219 return false; 11220 } 11221 } 11222 11223 private static boolean isMultiArch(PackageSetting ps) { 11224 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11225 } 11226 11227 private static boolean isMultiArch(ApplicationInfo info) { 11228 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11229 } 11230 11231 private static boolean isExternal(PackageParser.Package pkg) { 11232 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11233 } 11234 11235 private static boolean isExternal(PackageSetting ps) { 11236 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11237 } 11238 11239 private static boolean isExternal(ApplicationInfo info) { 11240 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11241 } 11242 11243 private static boolean isSystemApp(PackageParser.Package pkg) { 11244 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11245 } 11246 11247 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11248 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11249 } 11250 11251 private static boolean isSystemApp(ApplicationInfo info) { 11252 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11253 } 11254 11255 private static boolean isSystemApp(PackageSetting ps) { 11256 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11257 } 11258 11259 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11260 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11261 } 11262 11263 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 11264 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11265 } 11266 11267 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 11268 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11269 } 11270 11271 private int packageFlagsToInstallFlags(PackageSetting ps) { 11272 int installFlags = 0; 11273 if (isExternal(ps)) { 11274 installFlags |= PackageManager.INSTALL_EXTERNAL; 11275 } 11276 if (ps.isForwardLocked()) { 11277 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11278 } 11279 return installFlags; 11280 } 11281 11282 private void deleteTempPackageFiles() { 11283 final FilenameFilter filter = new FilenameFilter() { 11284 public boolean accept(File dir, String name) { 11285 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11286 } 11287 }; 11288 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11289 file.delete(); 11290 } 11291 } 11292 11293 @Override 11294 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11295 int flags) { 11296 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11297 flags); 11298 } 11299 11300 @Override 11301 public void deletePackage(final String packageName, 11302 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11303 mContext.enforceCallingOrSelfPermission( 11304 android.Manifest.permission.DELETE_PACKAGES, null); 11305 final int uid = Binder.getCallingUid(); 11306 if (UserHandle.getUserId(uid) != userId) { 11307 mContext.enforceCallingPermission( 11308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11309 "deletePackage for user " + userId); 11310 } 11311 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11312 try { 11313 observer.onPackageDeleted(packageName, 11314 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11315 } catch (RemoteException re) { 11316 } 11317 return; 11318 } 11319 11320 boolean uninstallBlocked = false; 11321 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11322 int[] users = sUserManager.getUserIds(); 11323 for (int i = 0; i < users.length; ++i) { 11324 if (getBlockUninstallForUser(packageName, users[i])) { 11325 uninstallBlocked = true; 11326 break; 11327 } 11328 } 11329 } else { 11330 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11331 } 11332 if (uninstallBlocked) { 11333 try { 11334 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11335 null); 11336 } catch (RemoteException re) { 11337 } 11338 return; 11339 } 11340 11341 if (DEBUG_REMOVE) { 11342 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11343 } 11344 // Queue up an async operation since the package deletion may take a little while. 11345 mHandler.post(new Runnable() { 11346 public void run() { 11347 mHandler.removeCallbacks(this); 11348 final int returnCode = deletePackageX(packageName, userId, flags); 11349 if (observer != null) { 11350 try { 11351 observer.onPackageDeleted(packageName, returnCode, null); 11352 } catch (RemoteException e) { 11353 Log.i(TAG, "Observer no longer exists."); 11354 } //end catch 11355 } //end if 11356 } //end run 11357 }); 11358 } 11359 11360 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11361 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11362 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11363 try { 11364 if (dpm != null) { 11365 if (dpm.isDeviceOwner(packageName)) { 11366 return true; 11367 } 11368 int[] users; 11369 if (userId == UserHandle.USER_ALL) { 11370 users = sUserManager.getUserIds(); 11371 } else { 11372 users = new int[]{userId}; 11373 } 11374 for (int i = 0; i < users.length; ++i) { 11375 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11376 return true; 11377 } 11378 } 11379 } 11380 } catch (RemoteException e) { 11381 } 11382 return false; 11383 } 11384 11385 /** 11386 * This method is an internal method that could be get invoked either 11387 * to delete an installed package or to clean up a failed installation. 11388 * After deleting an installed package, a broadcast is sent to notify any 11389 * listeners that the package has been installed. For cleaning up a failed 11390 * installation, the broadcast is not necessary since the package's 11391 * installation wouldn't have sent the initial broadcast either 11392 * The key steps in deleting a package are 11393 * deleting the package information in internal structures like mPackages, 11394 * deleting the packages base directories through installd 11395 * updating mSettings to reflect current status 11396 * persisting settings for later use 11397 * sending a broadcast if necessary 11398 */ 11399 private int deletePackageX(String packageName, int userId, int flags) { 11400 final PackageRemovedInfo info = new PackageRemovedInfo(); 11401 final boolean res; 11402 11403 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11404 ? UserHandle.ALL : new UserHandle(userId); 11405 11406 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11407 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11408 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11409 } 11410 11411 boolean removedForAllUsers = false; 11412 boolean systemUpdate = false; 11413 11414 // for the uninstall-updates case and restricted profiles, remember the per- 11415 // userhandle installed state 11416 int[] allUsers; 11417 boolean[] perUserInstalled; 11418 synchronized (mPackages) { 11419 PackageSetting ps = mSettings.mPackages.get(packageName); 11420 allUsers = sUserManager.getUserIds(); 11421 perUserInstalled = new boolean[allUsers.length]; 11422 for (int i = 0; i < allUsers.length; i++) { 11423 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11424 } 11425 } 11426 11427 synchronized (mInstallLock) { 11428 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11429 res = deletePackageLI(packageName, removeForUser, 11430 true, allUsers, perUserInstalled, 11431 flags | REMOVE_CHATTY, info, true); 11432 systemUpdate = info.isRemovedPackageSystemUpdate; 11433 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11434 removedForAllUsers = true; 11435 } 11436 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11437 + " removedForAllUsers=" + removedForAllUsers); 11438 } 11439 11440 if (res) { 11441 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11442 11443 // If the removed package was a system update, the old system package 11444 // was re-enabled; we need to broadcast this information 11445 if (systemUpdate) { 11446 Bundle extras = new Bundle(1); 11447 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11448 ? info.removedAppId : info.uid); 11449 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11450 11451 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11452 extras, null, null, null); 11453 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11454 extras, null, null, null); 11455 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11456 null, packageName, null, null); 11457 } 11458 } 11459 // Force a gc here. 11460 Runtime.getRuntime().gc(); 11461 // Delete the resources here after sending the broadcast to let 11462 // other processes clean up before deleting resources. 11463 if (info.args != null) { 11464 synchronized (mInstallLock) { 11465 info.args.doPostDeleteLI(true); 11466 } 11467 } 11468 11469 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11470 } 11471 11472 static class PackageRemovedInfo { 11473 String removedPackage; 11474 int uid = -1; 11475 int removedAppId = -1; 11476 int[] removedUsers = null; 11477 boolean isRemovedPackageSystemUpdate = false; 11478 // Clean up resources deleted packages. 11479 InstallArgs args = null; 11480 11481 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11482 Bundle extras = new Bundle(1); 11483 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11484 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11485 if (replacing) { 11486 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11487 } 11488 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11489 if (removedPackage != null) { 11490 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11491 extras, null, null, removedUsers); 11492 if (fullRemove && !replacing) { 11493 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11494 extras, null, null, removedUsers); 11495 } 11496 } 11497 if (removedAppId >= 0) { 11498 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11499 removedUsers); 11500 } 11501 } 11502 } 11503 11504 /* 11505 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11506 * flag is not set, the data directory is removed as well. 11507 * make sure this flag is set for partially installed apps. If not its meaningless to 11508 * delete a partially installed application. 11509 */ 11510 private void removePackageDataLI(PackageSetting ps, 11511 int[] allUserHandles, boolean[] perUserInstalled, 11512 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11513 String packageName = ps.name; 11514 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11515 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11516 // Retrieve object to delete permissions for shared user later on 11517 final PackageSetting deletedPs; 11518 // reader 11519 synchronized (mPackages) { 11520 deletedPs = mSettings.mPackages.get(packageName); 11521 if (outInfo != null) { 11522 outInfo.removedPackage = packageName; 11523 outInfo.removedUsers = deletedPs != null 11524 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11525 : null; 11526 } 11527 } 11528 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11529 removeDataDirsLI(packageName); 11530 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11531 } 11532 // writer 11533 synchronized (mPackages) { 11534 if (deletedPs != null) { 11535 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11536 if (outInfo != null) { 11537 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11538 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11539 } 11540 updatePermissionsLPw(deletedPs.name, null, 0); 11541 if (deletedPs.sharedUser != null) { 11542 // Remove permissions associated with package. Since runtime 11543 // permissions are per user we have to kill the removed package 11544 // or packages running under the shared user of the removed 11545 // package if revoking the permissions requested only by the removed 11546 // package is successful and this causes a change in gids. 11547 for (int userId : UserManagerService.getInstance().getUserIds()) { 11548 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11549 userId); 11550 if (userIdToKill == UserHandle.USER_ALL 11551 || userIdToKill >= UserHandle.USER_OWNER) { 11552 // If gids changed for this user, kill all affected packages. 11553 mHandler.post(new Runnable() { 11554 @Override 11555 public void run() { 11556 // This has to happen with no lock held. 11557 killSettingPackagesForUser(deletedPs, userIdToKill, 11558 KILL_APP_REASON_GIDS_CHANGED); 11559 } 11560 }); 11561 break; 11562 } 11563 } 11564 } 11565 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11566 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11567 } 11568 // make sure to preserve per-user disabled state if this removal was just 11569 // a downgrade of a system app to the factory package 11570 if (allUserHandles != null && perUserInstalled != null) { 11571 if (DEBUG_REMOVE) { 11572 Slog.d(TAG, "Propagating install state across downgrade"); 11573 } 11574 for (int i = 0; i < allUserHandles.length; i++) { 11575 if (DEBUG_REMOVE) { 11576 Slog.d(TAG, " user " + allUserHandles[i] 11577 + " => " + perUserInstalled[i]); 11578 } 11579 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11580 } 11581 } 11582 } 11583 // can downgrade to reader 11584 if (writeSettings) { 11585 // Save settings now 11586 mSettings.writeLPr(); 11587 } 11588 } 11589 if (outInfo != null) { 11590 // A user ID was deleted here. Go through all users and remove it 11591 // from KeyStore. 11592 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11593 } 11594 } 11595 11596 static boolean locationIsPrivileged(File path) { 11597 try { 11598 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11599 .getCanonicalPath(); 11600 return path.getCanonicalPath().startsWith(privilegedAppDir); 11601 } catch (IOException e) { 11602 Slog.e(TAG, "Unable to access code path " + path); 11603 } 11604 return false; 11605 } 11606 11607 /* 11608 * Tries to delete system package. 11609 */ 11610 private boolean deleteSystemPackageLI(PackageSetting newPs, 11611 int[] allUserHandles, boolean[] perUserInstalled, 11612 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11613 final boolean applyUserRestrictions 11614 = (allUserHandles != null) && (perUserInstalled != null); 11615 PackageSetting disabledPs = null; 11616 // Confirm if the system package has been updated 11617 // An updated system app can be deleted. This will also have to restore 11618 // the system pkg from system partition 11619 // reader 11620 synchronized (mPackages) { 11621 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11622 } 11623 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11624 + " disabledPs=" + disabledPs); 11625 if (disabledPs == null) { 11626 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11627 return false; 11628 } else if (DEBUG_REMOVE) { 11629 Slog.d(TAG, "Deleting system pkg from data partition"); 11630 } 11631 if (DEBUG_REMOVE) { 11632 if (applyUserRestrictions) { 11633 Slog.d(TAG, "Remembering install states:"); 11634 for (int i = 0; i < allUserHandles.length; i++) { 11635 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11636 } 11637 } 11638 } 11639 // Delete the updated package 11640 outInfo.isRemovedPackageSystemUpdate = true; 11641 if (disabledPs.versionCode < newPs.versionCode) { 11642 // Delete data for downgrades 11643 flags &= ~PackageManager.DELETE_KEEP_DATA; 11644 } else { 11645 // Preserve data by setting flag 11646 flags |= PackageManager.DELETE_KEEP_DATA; 11647 } 11648 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11649 allUserHandles, perUserInstalled, outInfo, writeSettings); 11650 if (!ret) { 11651 return false; 11652 } 11653 // writer 11654 synchronized (mPackages) { 11655 // Reinstate the old system package 11656 mSettings.enableSystemPackageLPw(newPs.name); 11657 // Remove any native libraries from the upgraded package. 11658 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11659 } 11660 // Install the system package 11661 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11662 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11663 if (locationIsPrivileged(disabledPs.codePath)) { 11664 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11665 } 11666 11667 final PackageParser.Package newPkg; 11668 try { 11669 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11670 } catch (PackageManagerException e) { 11671 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11672 return false; 11673 } 11674 11675 // writer 11676 synchronized (mPackages) { 11677 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11678 updatePermissionsLPw(newPkg.packageName, newPkg, 11679 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11680 if (applyUserRestrictions) { 11681 if (DEBUG_REMOVE) { 11682 Slog.d(TAG, "Propagating install state across reinstall"); 11683 } 11684 for (int i = 0; i < allUserHandles.length; i++) { 11685 if (DEBUG_REMOVE) { 11686 Slog.d(TAG, " user " + allUserHandles[i] 11687 + " => " + perUserInstalled[i]); 11688 } 11689 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11690 } 11691 // Regardless of writeSettings we need to ensure that this restriction 11692 // state propagation is persisted 11693 mSettings.writeAllUsersPackageRestrictionsLPr(); 11694 } 11695 // can downgrade to reader here 11696 if (writeSettings) { 11697 mSettings.writeLPr(); 11698 } 11699 } 11700 return true; 11701 } 11702 11703 private boolean deleteInstalledPackageLI(PackageSetting ps, 11704 boolean deleteCodeAndResources, int flags, 11705 int[] allUserHandles, boolean[] perUserInstalled, 11706 PackageRemovedInfo outInfo, boolean writeSettings) { 11707 if (outInfo != null) { 11708 outInfo.uid = ps.appId; 11709 } 11710 11711 // Delete package data from internal structures and also remove data if flag is set 11712 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11713 11714 // Delete application code and resources 11715 if (deleteCodeAndResources && (outInfo != null)) { 11716 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11717 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11718 getAppDexInstructionSets(ps)); 11719 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11720 } 11721 return true; 11722 } 11723 11724 @Override 11725 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11726 int userId) { 11727 mContext.enforceCallingOrSelfPermission( 11728 android.Manifest.permission.DELETE_PACKAGES, null); 11729 synchronized (mPackages) { 11730 PackageSetting ps = mSettings.mPackages.get(packageName); 11731 if (ps == null) { 11732 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11733 return false; 11734 } 11735 if (!ps.getInstalled(userId)) { 11736 // Can't block uninstall for an app that is not installed or enabled. 11737 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11738 return false; 11739 } 11740 ps.setBlockUninstall(blockUninstall, userId); 11741 mSettings.writePackageRestrictionsLPr(userId); 11742 } 11743 return true; 11744 } 11745 11746 @Override 11747 public boolean getBlockUninstallForUser(String packageName, int userId) { 11748 synchronized (mPackages) { 11749 PackageSetting ps = mSettings.mPackages.get(packageName); 11750 if (ps == null) { 11751 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11752 return false; 11753 } 11754 return ps.getBlockUninstall(userId); 11755 } 11756 } 11757 11758 /* 11759 * This method handles package deletion in general 11760 */ 11761 private boolean deletePackageLI(String packageName, UserHandle user, 11762 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11763 int flags, PackageRemovedInfo outInfo, 11764 boolean writeSettings) { 11765 if (packageName == null) { 11766 Slog.w(TAG, "Attempt to delete null packageName."); 11767 return false; 11768 } 11769 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11770 PackageSetting ps; 11771 boolean dataOnly = false; 11772 int removeUser = -1; 11773 int appId = -1; 11774 synchronized (mPackages) { 11775 ps = mSettings.mPackages.get(packageName); 11776 if (ps == null) { 11777 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11778 return false; 11779 } 11780 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11781 && user.getIdentifier() != UserHandle.USER_ALL) { 11782 // The caller is asking that the package only be deleted for a single 11783 // user. To do this, we just mark its uninstalled state and delete 11784 // its data. If this is a system app, we only allow this to happen if 11785 // they have set the special DELETE_SYSTEM_APP which requests different 11786 // semantics than normal for uninstalling system apps. 11787 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11788 ps.setUserState(user.getIdentifier(), 11789 COMPONENT_ENABLED_STATE_DEFAULT, 11790 false, //installed 11791 true, //stopped 11792 true, //notLaunched 11793 false, //hidden 11794 null, null, null, 11795 false, // blockUninstall 11796 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11797 if (!isSystemApp(ps)) { 11798 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11799 // Other user still have this package installed, so all 11800 // we need to do is clear this user's data and save that 11801 // it is uninstalled. 11802 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11803 removeUser = user.getIdentifier(); 11804 appId = ps.appId; 11805 mSettings.writePackageRestrictionsLPr(removeUser); 11806 } else { 11807 // We need to set it back to 'installed' so the uninstall 11808 // broadcasts will be sent correctly. 11809 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11810 ps.setInstalled(true, user.getIdentifier()); 11811 } 11812 } else { 11813 // This is a system app, so we assume that the 11814 // other users still have this package installed, so all 11815 // we need to do is clear this user's data and save that 11816 // it is uninstalled. 11817 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11818 removeUser = user.getIdentifier(); 11819 appId = ps.appId; 11820 mSettings.writePackageRestrictionsLPr(removeUser); 11821 } 11822 } 11823 } 11824 11825 if (removeUser >= 0) { 11826 // From above, we determined that we are deleting this only 11827 // for a single user. Continue the work here. 11828 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11829 if (outInfo != null) { 11830 outInfo.removedPackage = packageName; 11831 outInfo.removedAppId = appId; 11832 outInfo.removedUsers = new int[] {removeUser}; 11833 } 11834 mInstaller.clearUserData(packageName, removeUser); 11835 removeKeystoreDataIfNeeded(removeUser, appId); 11836 schedulePackageCleaning(packageName, removeUser, false); 11837 return true; 11838 } 11839 11840 if (dataOnly) { 11841 // Delete application data first 11842 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11843 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11844 return true; 11845 } 11846 11847 boolean ret = false; 11848 if (isSystemApp(ps)) { 11849 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11850 // When an updated system application is deleted we delete the existing resources as well and 11851 // fall back to existing code in system partition 11852 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11853 flags, outInfo, writeSettings); 11854 } else { 11855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11856 // Kill application pre-emptively especially for apps on sd. 11857 killApplication(packageName, ps.appId, "uninstall pkg"); 11858 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11859 allUserHandles, perUserInstalled, 11860 outInfo, writeSettings); 11861 } 11862 11863 return ret; 11864 } 11865 11866 private final class ClearStorageConnection implements ServiceConnection { 11867 IMediaContainerService mContainerService; 11868 11869 @Override 11870 public void onServiceConnected(ComponentName name, IBinder service) { 11871 synchronized (this) { 11872 mContainerService = IMediaContainerService.Stub.asInterface(service); 11873 notifyAll(); 11874 } 11875 } 11876 11877 @Override 11878 public void onServiceDisconnected(ComponentName name) { 11879 } 11880 } 11881 11882 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11883 final boolean mounted; 11884 if (Environment.isExternalStorageEmulated()) { 11885 mounted = true; 11886 } else { 11887 final String status = Environment.getExternalStorageState(); 11888 11889 mounted = status.equals(Environment.MEDIA_MOUNTED) 11890 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11891 } 11892 11893 if (!mounted) { 11894 return; 11895 } 11896 11897 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11898 int[] users; 11899 if (userId == UserHandle.USER_ALL) { 11900 users = sUserManager.getUserIds(); 11901 } else { 11902 users = new int[] { userId }; 11903 } 11904 final ClearStorageConnection conn = new ClearStorageConnection(); 11905 if (mContext.bindServiceAsUser( 11906 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11907 try { 11908 for (int curUser : users) { 11909 long timeout = SystemClock.uptimeMillis() + 5000; 11910 synchronized (conn) { 11911 long now = SystemClock.uptimeMillis(); 11912 while (conn.mContainerService == null && now < timeout) { 11913 try { 11914 conn.wait(timeout - now); 11915 } catch (InterruptedException e) { 11916 } 11917 } 11918 } 11919 if (conn.mContainerService == null) { 11920 return; 11921 } 11922 11923 final UserEnvironment userEnv = new UserEnvironment(curUser); 11924 clearDirectory(conn.mContainerService, 11925 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11926 if (allData) { 11927 clearDirectory(conn.mContainerService, 11928 userEnv.buildExternalStorageAppDataDirs(packageName)); 11929 clearDirectory(conn.mContainerService, 11930 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11931 } 11932 } 11933 } finally { 11934 mContext.unbindService(conn); 11935 } 11936 } 11937 } 11938 11939 @Override 11940 public void clearApplicationUserData(final String packageName, 11941 final IPackageDataObserver observer, final int userId) { 11942 mContext.enforceCallingOrSelfPermission( 11943 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11944 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11945 // Queue up an async operation since the package deletion may take a little while. 11946 mHandler.post(new Runnable() { 11947 public void run() { 11948 mHandler.removeCallbacks(this); 11949 final boolean succeeded; 11950 synchronized (mInstallLock) { 11951 succeeded = clearApplicationUserDataLI(packageName, userId); 11952 } 11953 clearExternalStorageDataSync(packageName, userId, true); 11954 if (succeeded) { 11955 // invoke DeviceStorageMonitor's update method to clear any notifications 11956 DeviceStorageMonitorInternal 11957 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11958 if (dsm != null) { 11959 dsm.checkMemory(); 11960 } 11961 } 11962 if(observer != null) { 11963 try { 11964 observer.onRemoveCompleted(packageName, succeeded); 11965 } catch (RemoteException e) { 11966 Log.i(TAG, "Observer no longer exists."); 11967 } 11968 } //end if observer 11969 } //end run 11970 }); 11971 } 11972 11973 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11974 if (packageName == null) { 11975 Slog.w(TAG, "Attempt to delete null packageName."); 11976 return false; 11977 } 11978 11979 // Try finding details about the requested package 11980 PackageParser.Package pkg; 11981 synchronized (mPackages) { 11982 pkg = mPackages.get(packageName); 11983 if (pkg == null) { 11984 final PackageSetting ps = mSettings.mPackages.get(packageName); 11985 if (ps != null) { 11986 pkg = ps.pkg; 11987 } 11988 } 11989 } 11990 11991 if (pkg == null) { 11992 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11993 } 11994 11995 // Always delete data directories for package, even if we found no other 11996 // record of app. This helps users recover from UID mismatches without 11997 // resorting to a full data wipe. 11998 int retCode = mInstaller.clearUserData(packageName, userId); 11999 if (retCode < 0) { 12000 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12001 return false; 12002 } 12003 12004 if (pkg == null) { 12005 return false; 12006 } 12007 12008 if (pkg != null && pkg.applicationInfo != null) { 12009 final int appId = pkg.applicationInfo.uid; 12010 removeKeystoreDataIfNeeded(userId, appId); 12011 } 12012 12013 // Create a native library symlink only if we have native libraries 12014 // and if the native libraries are 32 bit libraries. We do not provide 12015 // this symlink for 64 bit libraries. 12016 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12017 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12018 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12019 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12020 Slog.w(TAG, "Failed linking native library dir"); 12021 return false; 12022 } 12023 } 12024 12025 return true; 12026 } 12027 12028 /** 12029 * Remove entries from the keystore daemon. Will only remove it if the 12030 * {@code appId} is valid. 12031 */ 12032 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12033 if (appId < 0) { 12034 return; 12035 } 12036 12037 final KeyStore keyStore = KeyStore.getInstance(); 12038 if (keyStore != null) { 12039 if (userId == UserHandle.USER_ALL) { 12040 for (final int individual : sUserManager.getUserIds()) { 12041 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12042 } 12043 } else { 12044 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12045 } 12046 } else { 12047 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12048 } 12049 } 12050 12051 @Override 12052 public void deleteApplicationCacheFiles(final String packageName, 12053 final IPackageDataObserver observer) { 12054 mContext.enforceCallingOrSelfPermission( 12055 android.Manifest.permission.DELETE_CACHE_FILES, null); 12056 // Queue up an async operation since the package deletion may take a little while. 12057 final int userId = UserHandle.getCallingUserId(); 12058 mHandler.post(new Runnable() { 12059 public void run() { 12060 mHandler.removeCallbacks(this); 12061 final boolean succeded; 12062 synchronized (mInstallLock) { 12063 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12064 } 12065 clearExternalStorageDataSync(packageName, userId, false); 12066 if(observer != null) { 12067 try { 12068 observer.onRemoveCompleted(packageName, succeded); 12069 } catch (RemoteException e) { 12070 Log.i(TAG, "Observer no longer exists."); 12071 } 12072 } //end if observer 12073 } //end run 12074 }); 12075 } 12076 12077 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12078 if (packageName == null) { 12079 Slog.w(TAG, "Attempt to delete null packageName."); 12080 return false; 12081 } 12082 PackageParser.Package p; 12083 synchronized (mPackages) { 12084 p = mPackages.get(packageName); 12085 } 12086 if (p == null) { 12087 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12088 return false; 12089 } 12090 final ApplicationInfo applicationInfo = p.applicationInfo; 12091 if (applicationInfo == null) { 12092 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12093 return false; 12094 } 12095 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12096 if (retCode < 0) { 12097 Slog.w(TAG, "Couldn't remove cache files for package: " 12098 + packageName + " u" + userId); 12099 return false; 12100 } 12101 return true; 12102 } 12103 12104 @Override 12105 public void getPackageSizeInfo(final String packageName, int userHandle, 12106 final IPackageStatsObserver observer) { 12107 mContext.enforceCallingOrSelfPermission( 12108 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12109 if (packageName == null) { 12110 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12111 } 12112 12113 PackageStats stats = new PackageStats(packageName, userHandle); 12114 12115 /* 12116 * Queue up an async operation since the package measurement may take a 12117 * little while. 12118 */ 12119 Message msg = mHandler.obtainMessage(INIT_COPY); 12120 msg.obj = new MeasureParams(stats, observer); 12121 mHandler.sendMessage(msg); 12122 } 12123 12124 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12125 PackageStats pStats) { 12126 if (packageName == null) { 12127 Slog.w(TAG, "Attempt to get size of null packageName."); 12128 return false; 12129 } 12130 PackageParser.Package p; 12131 boolean dataOnly = false; 12132 String libDirRoot = null; 12133 String asecPath = null; 12134 PackageSetting ps = null; 12135 synchronized (mPackages) { 12136 p = mPackages.get(packageName); 12137 ps = mSettings.mPackages.get(packageName); 12138 if(p == null) { 12139 dataOnly = true; 12140 if((ps == null) || (ps.pkg == null)) { 12141 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12142 return false; 12143 } 12144 p = ps.pkg; 12145 } 12146 if (ps != null) { 12147 libDirRoot = ps.legacyNativeLibraryPathString; 12148 } 12149 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12150 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12151 if (secureContainerId != null) { 12152 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12153 } 12154 } 12155 } 12156 String publicSrcDir = null; 12157 if(!dataOnly) { 12158 final ApplicationInfo applicationInfo = p.applicationInfo; 12159 if (applicationInfo == null) { 12160 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12161 return false; 12162 } 12163 if (p.isForwardLocked()) { 12164 publicSrcDir = applicationInfo.getBaseResourcePath(); 12165 } 12166 } 12167 // TODO: extend to measure size of split APKs 12168 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12169 // not just the first level. 12170 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12171 // just the primary. 12172 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12173 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12174 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12175 if (res < 0) { 12176 return false; 12177 } 12178 12179 // Fix-up for forward-locked applications in ASEC containers. 12180 if (!isExternal(p)) { 12181 pStats.codeSize += pStats.externalCodeSize; 12182 pStats.externalCodeSize = 0L; 12183 } 12184 12185 return true; 12186 } 12187 12188 12189 @Override 12190 public void addPackageToPreferred(String packageName) { 12191 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12192 } 12193 12194 @Override 12195 public void removePackageFromPreferred(String packageName) { 12196 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12197 } 12198 12199 @Override 12200 public List<PackageInfo> getPreferredPackages(int flags) { 12201 return new ArrayList<PackageInfo>(); 12202 } 12203 12204 private int getUidTargetSdkVersionLockedLPr(int uid) { 12205 Object obj = mSettings.getUserIdLPr(uid); 12206 if (obj instanceof SharedUserSetting) { 12207 final SharedUserSetting sus = (SharedUserSetting) obj; 12208 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12209 final Iterator<PackageSetting> it = sus.packages.iterator(); 12210 while (it.hasNext()) { 12211 final PackageSetting ps = it.next(); 12212 if (ps.pkg != null) { 12213 int v = ps.pkg.applicationInfo.targetSdkVersion; 12214 if (v < vers) vers = v; 12215 } 12216 } 12217 return vers; 12218 } else if (obj instanceof PackageSetting) { 12219 final PackageSetting ps = (PackageSetting) obj; 12220 if (ps.pkg != null) { 12221 return ps.pkg.applicationInfo.targetSdkVersion; 12222 } 12223 } 12224 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12225 } 12226 12227 @Override 12228 public void addPreferredActivity(IntentFilter filter, int match, 12229 ComponentName[] set, ComponentName activity, int userId) { 12230 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12231 "Adding preferred"); 12232 } 12233 12234 private void addPreferredActivityInternal(IntentFilter filter, int match, 12235 ComponentName[] set, ComponentName activity, boolean always, int userId, 12236 String opname) { 12237 // writer 12238 int callingUid = Binder.getCallingUid(); 12239 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12240 if (filter.countActions() == 0) { 12241 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12242 return; 12243 } 12244 synchronized (mPackages) { 12245 if (mContext.checkCallingOrSelfPermission( 12246 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12247 != PackageManager.PERMISSION_GRANTED) { 12248 if (getUidTargetSdkVersionLockedLPr(callingUid) 12249 < Build.VERSION_CODES.FROYO) { 12250 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12251 + callingUid); 12252 return; 12253 } 12254 mContext.enforceCallingOrSelfPermission( 12255 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12256 } 12257 12258 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12259 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12260 + userId + ":"); 12261 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12262 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12263 scheduleWritePackageRestrictionsLocked(userId); 12264 } 12265 } 12266 12267 @Override 12268 public void replacePreferredActivity(IntentFilter filter, int match, 12269 ComponentName[] set, ComponentName activity, int userId) { 12270 if (filter.countActions() != 1) { 12271 throw new IllegalArgumentException( 12272 "replacePreferredActivity expects filter to have only 1 action."); 12273 } 12274 if (filter.countDataAuthorities() != 0 12275 || filter.countDataPaths() != 0 12276 || filter.countDataSchemes() > 1 12277 || filter.countDataTypes() != 0) { 12278 throw new IllegalArgumentException( 12279 "replacePreferredActivity expects filter to have no data authorities, " + 12280 "paths, or types; and at most one scheme."); 12281 } 12282 12283 final int callingUid = Binder.getCallingUid(); 12284 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12285 synchronized (mPackages) { 12286 if (mContext.checkCallingOrSelfPermission( 12287 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12288 != PackageManager.PERMISSION_GRANTED) { 12289 if (getUidTargetSdkVersionLockedLPr(callingUid) 12290 < Build.VERSION_CODES.FROYO) { 12291 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12292 + Binder.getCallingUid()); 12293 return; 12294 } 12295 mContext.enforceCallingOrSelfPermission( 12296 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12297 } 12298 12299 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12300 if (pir != null) { 12301 // Get all of the existing entries that exactly match this filter. 12302 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12303 if (existing != null && existing.size() == 1) { 12304 PreferredActivity cur = existing.get(0); 12305 if (DEBUG_PREFERRED) { 12306 Slog.i(TAG, "Checking replace of preferred:"); 12307 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12308 if (!cur.mPref.mAlways) { 12309 Slog.i(TAG, " -- CUR; not mAlways!"); 12310 } else { 12311 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12312 Slog.i(TAG, " -- CUR: mSet=" 12313 + Arrays.toString(cur.mPref.mSetComponents)); 12314 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12315 Slog.i(TAG, " -- NEW: mMatch=" 12316 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12317 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12318 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12319 } 12320 } 12321 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12322 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12323 && cur.mPref.sameSet(set)) { 12324 // Setting the preferred activity to what it happens to be already 12325 if (DEBUG_PREFERRED) { 12326 Slog.i(TAG, "Replacing with same preferred activity " 12327 + cur.mPref.mShortComponent + " for user " 12328 + userId + ":"); 12329 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12330 } 12331 return; 12332 } 12333 } 12334 12335 if (existing != null) { 12336 if (DEBUG_PREFERRED) { 12337 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12338 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12339 } 12340 for (int i = 0; i < existing.size(); i++) { 12341 PreferredActivity pa = existing.get(i); 12342 if (DEBUG_PREFERRED) { 12343 Slog.i(TAG, "Removing existing preferred activity " 12344 + pa.mPref.mComponent + ":"); 12345 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12346 } 12347 pir.removeFilter(pa); 12348 } 12349 } 12350 } 12351 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12352 "Replacing preferred"); 12353 } 12354 } 12355 12356 @Override 12357 public void clearPackagePreferredActivities(String packageName) { 12358 final int uid = Binder.getCallingUid(); 12359 // writer 12360 synchronized (mPackages) { 12361 PackageParser.Package pkg = mPackages.get(packageName); 12362 if (pkg == null || pkg.applicationInfo.uid != uid) { 12363 if (mContext.checkCallingOrSelfPermission( 12364 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12365 != PackageManager.PERMISSION_GRANTED) { 12366 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12367 < Build.VERSION_CODES.FROYO) { 12368 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12369 + Binder.getCallingUid()); 12370 return; 12371 } 12372 mContext.enforceCallingOrSelfPermission( 12373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12374 } 12375 } 12376 12377 int user = UserHandle.getCallingUserId(); 12378 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12379 scheduleWritePackageRestrictionsLocked(user); 12380 } 12381 } 12382 } 12383 12384 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12385 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12386 ArrayList<PreferredActivity> removed = null; 12387 boolean changed = false; 12388 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12389 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12390 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12391 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12392 continue; 12393 } 12394 Iterator<PreferredActivity> it = pir.filterIterator(); 12395 while (it.hasNext()) { 12396 PreferredActivity pa = it.next(); 12397 // Mark entry for removal only if it matches the package name 12398 // and the entry is of type "always". 12399 if (packageName == null || 12400 (pa.mPref.mComponent.getPackageName().equals(packageName) 12401 && pa.mPref.mAlways)) { 12402 if (removed == null) { 12403 removed = new ArrayList<PreferredActivity>(); 12404 } 12405 removed.add(pa); 12406 } 12407 } 12408 if (removed != null) { 12409 for (int j=0; j<removed.size(); j++) { 12410 PreferredActivity pa = removed.get(j); 12411 pir.removeFilter(pa); 12412 } 12413 changed = true; 12414 } 12415 } 12416 return changed; 12417 } 12418 12419 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12420 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12421 if (userId == UserHandle.USER_ALL) { 12422 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12423 for (int oneUserId : sUserManager.getUserIds()) { 12424 scheduleWritePackageRestrictionsLocked(oneUserId); 12425 } 12426 } else { 12427 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12428 scheduleWritePackageRestrictionsLocked(userId); 12429 } 12430 } 12431 12432 @Override 12433 public void resetPreferredActivities(int userId) { 12434 /* TODO: Actually use userId. Why is it being passed in? */ 12435 mContext.enforceCallingOrSelfPermission( 12436 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12437 // writer 12438 synchronized (mPackages) { 12439 int user = UserHandle.getCallingUserId(); 12440 clearPackagePreferredActivitiesLPw(null, user); 12441 mSettings.readDefaultPreferredAppsLPw(this, user); 12442 scheduleWritePackageRestrictionsLocked(user); 12443 } 12444 } 12445 12446 @Override 12447 public int getPreferredActivities(List<IntentFilter> outFilters, 12448 List<ComponentName> outActivities, String packageName) { 12449 12450 int num = 0; 12451 final int userId = UserHandle.getCallingUserId(); 12452 // reader 12453 synchronized (mPackages) { 12454 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12455 if (pir != null) { 12456 final Iterator<PreferredActivity> it = pir.filterIterator(); 12457 while (it.hasNext()) { 12458 final PreferredActivity pa = it.next(); 12459 if (packageName == null 12460 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12461 && pa.mPref.mAlways)) { 12462 if (outFilters != null) { 12463 outFilters.add(new IntentFilter(pa)); 12464 } 12465 if (outActivities != null) { 12466 outActivities.add(pa.mPref.mComponent); 12467 } 12468 } 12469 } 12470 } 12471 } 12472 12473 return num; 12474 } 12475 12476 @Override 12477 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12478 int userId) { 12479 int callingUid = Binder.getCallingUid(); 12480 if (callingUid != Process.SYSTEM_UID) { 12481 throw new SecurityException( 12482 "addPersistentPreferredActivity can only be run by the system"); 12483 } 12484 if (filter.countActions() == 0) { 12485 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12486 return; 12487 } 12488 synchronized (mPackages) { 12489 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12490 " :"); 12491 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12492 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12493 new PersistentPreferredActivity(filter, activity)); 12494 scheduleWritePackageRestrictionsLocked(userId); 12495 } 12496 } 12497 12498 @Override 12499 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12500 int callingUid = Binder.getCallingUid(); 12501 if (callingUid != Process.SYSTEM_UID) { 12502 throw new SecurityException( 12503 "clearPackagePersistentPreferredActivities can only be run by the system"); 12504 } 12505 ArrayList<PersistentPreferredActivity> removed = null; 12506 boolean changed = false; 12507 synchronized (mPackages) { 12508 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12509 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12510 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12511 .valueAt(i); 12512 if (userId != thisUserId) { 12513 continue; 12514 } 12515 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12516 while (it.hasNext()) { 12517 PersistentPreferredActivity ppa = it.next(); 12518 // Mark entry for removal only if it matches the package name. 12519 if (ppa.mComponent.getPackageName().equals(packageName)) { 12520 if (removed == null) { 12521 removed = new ArrayList<PersistentPreferredActivity>(); 12522 } 12523 removed.add(ppa); 12524 } 12525 } 12526 if (removed != null) { 12527 for (int j=0; j<removed.size(); j++) { 12528 PersistentPreferredActivity ppa = removed.get(j); 12529 ppir.removeFilter(ppa); 12530 } 12531 changed = true; 12532 } 12533 } 12534 12535 if (changed) { 12536 scheduleWritePackageRestrictionsLocked(userId); 12537 } 12538 } 12539 } 12540 12541 @Override 12542 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12543 int sourceUserId, int targetUserId, int flags) { 12544 mContext.enforceCallingOrSelfPermission( 12545 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12546 int callingUid = Binder.getCallingUid(); 12547 enforceOwnerRights(ownerPackage, callingUid); 12548 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12549 if (intentFilter.countActions() == 0) { 12550 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12551 return; 12552 } 12553 synchronized (mPackages) { 12554 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12555 ownerPackage, targetUserId, flags); 12556 CrossProfileIntentResolver resolver = 12557 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12558 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12559 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12560 if (existing != null) { 12561 int size = existing.size(); 12562 for (int i = 0; i < size; i++) { 12563 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12564 return; 12565 } 12566 } 12567 } 12568 resolver.addFilter(newFilter); 12569 scheduleWritePackageRestrictionsLocked(sourceUserId); 12570 } 12571 } 12572 12573 @Override 12574 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12575 mContext.enforceCallingOrSelfPermission( 12576 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12577 int callingUid = Binder.getCallingUid(); 12578 enforceOwnerRights(ownerPackage, callingUid); 12579 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12580 synchronized (mPackages) { 12581 CrossProfileIntentResolver resolver = 12582 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12583 ArraySet<CrossProfileIntentFilter> set = 12584 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12585 for (CrossProfileIntentFilter filter : set) { 12586 if (filter.getOwnerPackage().equals(ownerPackage)) { 12587 resolver.removeFilter(filter); 12588 } 12589 } 12590 scheduleWritePackageRestrictionsLocked(sourceUserId); 12591 } 12592 } 12593 12594 // Enforcing that callingUid is owning pkg on userId 12595 private void enforceOwnerRights(String pkg, int callingUid) { 12596 // The system owns everything. 12597 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12598 return; 12599 } 12600 int callingUserId = UserHandle.getUserId(callingUid); 12601 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12602 if (pi == null) { 12603 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12604 + callingUserId); 12605 } 12606 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12607 throw new SecurityException("Calling uid " + callingUid 12608 + " does not own package " + pkg); 12609 } 12610 } 12611 12612 @Override 12613 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12614 Intent intent = new Intent(Intent.ACTION_MAIN); 12615 intent.addCategory(Intent.CATEGORY_HOME); 12616 12617 final int callingUserId = UserHandle.getCallingUserId(); 12618 List<ResolveInfo> list = queryIntentActivities(intent, null, 12619 PackageManager.GET_META_DATA, callingUserId); 12620 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12621 true, false, false, callingUserId); 12622 12623 allHomeCandidates.clear(); 12624 if (list != null) { 12625 for (ResolveInfo ri : list) { 12626 allHomeCandidates.add(ri); 12627 } 12628 } 12629 return (preferred == null || preferred.activityInfo == null) 12630 ? null 12631 : new ComponentName(preferred.activityInfo.packageName, 12632 preferred.activityInfo.name); 12633 } 12634 12635 @Override 12636 public void setApplicationEnabledSetting(String appPackageName, 12637 int newState, int flags, int userId, String callingPackage) { 12638 if (!sUserManager.exists(userId)) return; 12639 if (callingPackage == null) { 12640 callingPackage = Integer.toString(Binder.getCallingUid()); 12641 } 12642 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12643 } 12644 12645 @Override 12646 public void setComponentEnabledSetting(ComponentName componentName, 12647 int newState, int flags, int userId) { 12648 if (!sUserManager.exists(userId)) return; 12649 setEnabledSetting(componentName.getPackageName(), 12650 componentName.getClassName(), newState, flags, userId, null); 12651 } 12652 12653 private void setEnabledSetting(final String packageName, String className, int newState, 12654 final int flags, int userId, String callingPackage) { 12655 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12656 || newState == COMPONENT_ENABLED_STATE_ENABLED 12657 || newState == COMPONENT_ENABLED_STATE_DISABLED 12658 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12659 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12660 throw new IllegalArgumentException("Invalid new component state: " 12661 + newState); 12662 } 12663 PackageSetting pkgSetting; 12664 final int uid = Binder.getCallingUid(); 12665 final int permission = mContext.checkCallingOrSelfPermission( 12666 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12667 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12668 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12669 boolean sendNow = false; 12670 boolean isApp = (className == null); 12671 String componentName = isApp ? packageName : className; 12672 int packageUid = -1; 12673 ArrayList<String> components; 12674 12675 // writer 12676 synchronized (mPackages) { 12677 pkgSetting = mSettings.mPackages.get(packageName); 12678 if (pkgSetting == null) { 12679 if (className == null) { 12680 throw new IllegalArgumentException( 12681 "Unknown package: " + packageName); 12682 } 12683 throw new IllegalArgumentException( 12684 "Unknown component: " + packageName 12685 + "/" + className); 12686 } 12687 // Allow root and verify that userId is not being specified by a different user 12688 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12689 throw new SecurityException( 12690 "Permission Denial: attempt to change component state from pid=" 12691 + Binder.getCallingPid() 12692 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12693 } 12694 if (className == null) { 12695 // We're dealing with an application/package level state change 12696 if (pkgSetting.getEnabled(userId) == newState) { 12697 // Nothing to do 12698 return; 12699 } 12700 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12701 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12702 // Don't care about who enables an app. 12703 callingPackage = null; 12704 } 12705 pkgSetting.setEnabled(newState, userId, callingPackage); 12706 // pkgSetting.pkg.mSetEnabled = newState; 12707 } else { 12708 // We're dealing with a component level state change 12709 // First, verify that this is a valid class name. 12710 PackageParser.Package pkg = pkgSetting.pkg; 12711 if (pkg == null || !pkg.hasComponentClassName(className)) { 12712 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12713 throw new IllegalArgumentException("Component class " + className 12714 + " does not exist in " + packageName); 12715 } else { 12716 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12717 + className + " does not exist in " + packageName); 12718 } 12719 } 12720 switch (newState) { 12721 case COMPONENT_ENABLED_STATE_ENABLED: 12722 if (!pkgSetting.enableComponentLPw(className, userId)) { 12723 return; 12724 } 12725 break; 12726 case COMPONENT_ENABLED_STATE_DISABLED: 12727 if (!pkgSetting.disableComponentLPw(className, userId)) { 12728 return; 12729 } 12730 break; 12731 case COMPONENT_ENABLED_STATE_DEFAULT: 12732 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12733 return; 12734 } 12735 break; 12736 default: 12737 Slog.e(TAG, "Invalid new component state: " + newState); 12738 return; 12739 } 12740 } 12741 scheduleWritePackageRestrictionsLocked(userId); 12742 components = mPendingBroadcasts.get(userId, packageName); 12743 final boolean newPackage = components == null; 12744 if (newPackage) { 12745 components = new ArrayList<String>(); 12746 } 12747 if (!components.contains(componentName)) { 12748 components.add(componentName); 12749 } 12750 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12751 sendNow = true; 12752 // Purge entry from pending broadcast list if another one exists already 12753 // since we are sending one right away. 12754 mPendingBroadcasts.remove(userId, packageName); 12755 } else { 12756 if (newPackage) { 12757 mPendingBroadcasts.put(userId, packageName, components); 12758 } 12759 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12760 // Schedule a message 12761 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12762 } 12763 } 12764 } 12765 12766 long callingId = Binder.clearCallingIdentity(); 12767 try { 12768 if (sendNow) { 12769 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12770 sendPackageChangedBroadcast(packageName, 12771 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12772 } 12773 } finally { 12774 Binder.restoreCallingIdentity(callingId); 12775 } 12776 } 12777 12778 private void sendPackageChangedBroadcast(String packageName, 12779 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12780 if (DEBUG_INSTALL) 12781 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12782 + componentNames); 12783 Bundle extras = new Bundle(4); 12784 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12785 String nameList[] = new String[componentNames.size()]; 12786 componentNames.toArray(nameList); 12787 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12788 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12789 extras.putInt(Intent.EXTRA_UID, packageUid); 12790 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12791 new int[] {UserHandle.getUserId(packageUid)}); 12792 } 12793 12794 @Override 12795 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12796 if (!sUserManager.exists(userId)) return; 12797 final int uid = Binder.getCallingUid(); 12798 final int permission = mContext.checkCallingOrSelfPermission( 12799 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12800 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12801 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12802 // writer 12803 synchronized (mPackages) { 12804 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12805 uid, userId)) { 12806 scheduleWritePackageRestrictionsLocked(userId); 12807 } 12808 } 12809 } 12810 12811 @Override 12812 public String getInstallerPackageName(String packageName) { 12813 // reader 12814 synchronized (mPackages) { 12815 return mSettings.getInstallerPackageNameLPr(packageName); 12816 } 12817 } 12818 12819 @Override 12820 public int getApplicationEnabledSetting(String packageName, int userId) { 12821 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12822 int uid = Binder.getCallingUid(); 12823 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12824 // reader 12825 synchronized (mPackages) { 12826 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12827 } 12828 } 12829 12830 @Override 12831 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12832 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12833 int uid = Binder.getCallingUid(); 12834 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12835 // reader 12836 synchronized (mPackages) { 12837 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12838 } 12839 } 12840 12841 @Override 12842 public void enterSafeMode() { 12843 enforceSystemOrRoot("Only the system can request entering safe mode"); 12844 12845 if (!mSystemReady) { 12846 mSafeMode = true; 12847 } 12848 } 12849 12850 @Override 12851 public void systemReady() { 12852 mSystemReady = true; 12853 12854 // Read the compatibilty setting when the system is ready. 12855 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12856 mContext.getContentResolver(), 12857 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12858 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12859 if (DEBUG_SETTINGS) { 12860 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12861 } 12862 12863 synchronized (mPackages) { 12864 // Verify that all of the preferred activity components actually 12865 // exist. It is possible for applications to be updated and at 12866 // that point remove a previously declared activity component that 12867 // had been set as a preferred activity. We try to clean this up 12868 // the next time we encounter that preferred activity, but it is 12869 // possible for the user flow to never be able to return to that 12870 // situation so here we do a sanity check to make sure we haven't 12871 // left any junk around. 12872 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12873 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12874 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12875 removed.clear(); 12876 for (PreferredActivity pa : pir.filterSet()) { 12877 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12878 removed.add(pa); 12879 } 12880 } 12881 if (removed.size() > 0) { 12882 for (int r=0; r<removed.size(); r++) { 12883 PreferredActivity pa = removed.get(r); 12884 Slog.w(TAG, "Removing dangling preferred activity: " 12885 + pa.mPref.mComponent); 12886 pir.removeFilter(pa); 12887 } 12888 mSettings.writePackageRestrictionsLPr( 12889 mSettings.mPreferredActivities.keyAt(i)); 12890 } 12891 } 12892 } 12893 sUserManager.systemReady(); 12894 12895 // Kick off any messages waiting for system ready 12896 if (mPostSystemReadyMessages != null) { 12897 for (Message msg : mPostSystemReadyMessages) { 12898 msg.sendToTarget(); 12899 } 12900 mPostSystemReadyMessages = null; 12901 } 12902 } 12903 12904 @Override 12905 public boolean isSafeMode() { 12906 return mSafeMode; 12907 } 12908 12909 @Override 12910 public boolean hasSystemUidErrors() { 12911 return mHasSystemUidErrors; 12912 } 12913 12914 static String arrayToString(int[] array) { 12915 StringBuffer buf = new StringBuffer(128); 12916 buf.append('['); 12917 if (array != null) { 12918 for (int i=0; i<array.length; i++) { 12919 if (i > 0) buf.append(", "); 12920 buf.append(array[i]); 12921 } 12922 } 12923 buf.append(']'); 12924 return buf.toString(); 12925 } 12926 12927 static class DumpState { 12928 public static final int DUMP_LIBS = 1 << 0; 12929 public static final int DUMP_FEATURES = 1 << 1; 12930 public static final int DUMP_RESOLVERS = 1 << 2; 12931 public static final int DUMP_PERMISSIONS = 1 << 3; 12932 public static final int DUMP_PACKAGES = 1 << 4; 12933 public static final int DUMP_SHARED_USERS = 1 << 5; 12934 public static final int DUMP_MESSAGES = 1 << 6; 12935 public static final int DUMP_PROVIDERS = 1 << 7; 12936 public static final int DUMP_VERIFIERS = 1 << 8; 12937 public static final int DUMP_PREFERRED = 1 << 9; 12938 public static final int DUMP_PREFERRED_XML = 1 << 10; 12939 public static final int DUMP_KEYSETS = 1 << 11; 12940 public static final int DUMP_VERSION = 1 << 12; 12941 public static final int DUMP_INSTALLS = 1 << 13; 12942 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 12943 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 12944 12945 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12946 12947 private int mTypes; 12948 12949 private int mOptions; 12950 12951 private boolean mTitlePrinted; 12952 12953 private SharedUserSetting mSharedUser; 12954 12955 public boolean isDumping(int type) { 12956 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12957 return true; 12958 } 12959 12960 return (mTypes & type) != 0; 12961 } 12962 12963 public void setDump(int type) { 12964 mTypes |= type; 12965 } 12966 12967 public boolean isOptionEnabled(int option) { 12968 return (mOptions & option) != 0; 12969 } 12970 12971 public void setOptionEnabled(int option) { 12972 mOptions |= option; 12973 } 12974 12975 public boolean onTitlePrinted() { 12976 final boolean printed = mTitlePrinted; 12977 mTitlePrinted = true; 12978 return printed; 12979 } 12980 12981 public boolean getTitlePrinted() { 12982 return mTitlePrinted; 12983 } 12984 12985 public void setTitlePrinted(boolean enabled) { 12986 mTitlePrinted = enabled; 12987 } 12988 12989 public SharedUserSetting getSharedUser() { 12990 return mSharedUser; 12991 } 12992 12993 public void setSharedUser(SharedUserSetting user) { 12994 mSharedUser = user; 12995 } 12996 } 12997 12998 @Override 12999 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13000 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13001 != PackageManager.PERMISSION_GRANTED) { 13002 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13003 + Binder.getCallingPid() 13004 + ", uid=" + Binder.getCallingUid() 13005 + " without permission " 13006 + android.Manifest.permission.DUMP); 13007 return; 13008 } 13009 13010 DumpState dumpState = new DumpState(); 13011 boolean fullPreferred = false; 13012 boolean checkin = false; 13013 13014 String packageName = null; 13015 13016 int opti = 0; 13017 while (opti < args.length) { 13018 String opt = args[opti]; 13019 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13020 break; 13021 } 13022 opti++; 13023 13024 if ("-a".equals(opt)) { 13025 // Right now we only know how to print all. 13026 } else if ("-h".equals(opt)) { 13027 pw.println("Package manager dump options:"); 13028 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13029 pw.println(" --checkin: dump for a checkin"); 13030 pw.println(" -f: print details of intent filters"); 13031 pw.println(" -h: print this help"); 13032 pw.println(" cmd may be one of:"); 13033 pw.println(" l[ibraries]: list known shared libraries"); 13034 pw.println(" f[ibraries]: list device features"); 13035 pw.println(" k[eysets]: print known keysets"); 13036 pw.println(" r[esolvers]: dump intent resolvers"); 13037 pw.println(" perm[issions]: dump permissions"); 13038 pw.println(" pref[erred]: print preferred package settings"); 13039 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13040 pw.println(" prov[iders]: dump content providers"); 13041 pw.println(" p[ackages]: dump installed packages"); 13042 pw.println(" s[hared-users]: dump shared user IDs"); 13043 pw.println(" m[essages]: print collected runtime messages"); 13044 pw.println(" v[erifiers]: print package verifier info"); 13045 pw.println(" version: print database version info"); 13046 pw.println(" write: write current settings now"); 13047 pw.println(" <package.name>: info about given package"); 13048 pw.println(" installs: details about install sessions"); 13049 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13050 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13051 return; 13052 } else if ("--checkin".equals(opt)) { 13053 checkin = true; 13054 } else if ("-f".equals(opt)) { 13055 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13056 } else { 13057 pw.println("Unknown argument: " + opt + "; use -h for help"); 13058 } 13059 } 13060 13061 // Is the caller requesting to dump a particular piece of data? 13062 if (opti < args.length) { 13063 String cmd = args[opti]; 13064 opti++; 13065 // Is this a package name? 13066 if ("android".equals(cmd) || cmd.contains(".")) { 13067 packageName = cmd; 13068 // When dumping a single package, we always dump all of its 13069 // filter information since the amount of data will be reasonable. 13070 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13071 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13072 dumpState.setDump(DumpState.DUMP_LIBS); 13073 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13074 dumpState.setDump(DumpState.DUMP_FEATURES); 13075 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13076 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13077 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13078 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13079 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13080 dumpState.setDump(DumpState.DUMP_PREFERRED); 13081 } else if ("preferred-xml".equals(cmd)) { 13082 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13083 if (opti < args.length && "--full".equals(args[opti])) { 13084 fullPreferred = true; 13085 opti++; 13086 } 13087 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13088 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13089 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13090 dumpState.setDump(DumpState.DUMP_PACKAGES); 13091 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13092 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13093 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13094 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13095 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13096 dumpState.setDump(DumpState.DUMP_MESSAGES); 13097 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13098 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13099 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13100 || "intent-filter-verifiers".equals(cmd)) { 13101 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13102 } else if ("version".equals(cmd)) { 13103 dumpState.setDump(DumpState.DUMP_VERSION); 13104 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13105 dumpState.setDump(DumpState.DUMP_KEYSETS); 13106 } else if ("installs".equals(cmd)) { 13107 dumpState.setDump(DumpState.DUMP_INSTALLS); 13108 } else if ("write".equals(cmd)) { 13109 synchronized (mPackages) { 13110 mSettings.writeLPr(); 13111 pw.println("Settings written."); 13112 return; 13113 } 13114 } 13115 } 13116 13117 if (checkin) { 13118 pw.println("vers,1"); 13119 } 13120 13121 // reader 13122 synchronized (mPackages) { 13123 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13124 if (!checkin) { 13125 if (dumpState.onTitlePrinted()) 13126 pw.println(); 13127 pw.println("Database versions:"); 13128 pw.print(" SDK Version:"); 13129 pw.print(" internal="); 13130 pw.print(mSettings.mInternalSdkPlatform); 13131 pw.print(" external="); 13132 pw.println(mSettings.mExternalSdkPlatform); 13133 pw.print(" DB Version:"); 13134 pw.print(" internal="); 13135 pw.print(mSettings.mInternalDatabaseVersion); 13136 pw.print(" external="); 13137 pw.println(mSettings.mExternalDatabaseVersion); 13138 } 13139 } 13140 13141 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13142 if (!checkin) { 13143 if (dumpState.onTitlePrinted()) 13144 pw.println(); 13145 pw.println("Verifiers:"); 13146 pw.print(" Required: "); 13147 pw.print(mRequiredVerifierPackage); 13148 pw.print(" (uid="); 13149 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13150 pw.println(")"); 13151 } else if (mRequiredVerifierPackage != null) { 13152 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13153 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13154 } 13155 } 13156 13157 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13158 packageName == null) { 13159 if (mIntentFilterVerifierComponent != null) { 13160 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13161 if (!checkin) { 13162 if (dumpState.onTitlePrinted()) 13163 pw.println(); 13164 pw.println("Intent Filter Verifier:"); 13165 pw.print(" Using: "); 13166 pw.print(verifierPackageName); 13167 pw.print(" (uid="); 13168 pw.print(getPackageUid(verifierPackageName, 0)); 13169 pw.println(")"); 13170 } else if (verifierPackageName != null) { 13171 pw.print("ifv,"); pw.print(verifierPackageName); 13172 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13173 } 13174 } else { 13175 pw.println(); 13176 pw.println("No Intent Filter Verifier available!"); 13177 } 13178 } 13179 13180 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13181 boolean printedHeader = false; 13182 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13183 while (it.hasNext()) { 13184 String name = it.next(); 13185 SharedLibraryEntry ent = mSharedLibraries.get(name); 13186 if (!checkin) { 13187 if (!printedHeader) { 13188 if (dumpState.onTitlePrinted()) 13189 pw.println(); 13190 pw.println("Libraries:"); 13191 printedHeader = true; 13192 } 13193 pw.print(" "); 13194 } else { 13195 pw.print("lib,"); 13196 } 13197 pw.print(name); 13198 if (!checkin) { 13199 pw.print(" -> "); 13200 } 13201 if (ent.path != null) { 13202 if (!checkin) { 13203 pw.print("(jar) "); 13204 pw.print(ent.path); 13205 } else { 13206 pw.print(",jar,"); 13207 pw.print(ent.path); 13208 } 13209 } else { 13210 if (!checkin) { 13211 pw.print("(apk) "); 13212 pw.print(ent.apk); 13213 } else { 13214 pw.print(",apk,"); 13215 pw.print(ent.apk); 13216 } 13217 } 13218 pw.println(); 13219 } 13220 } 13221 13222 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13223 if (dumpState.onTitlePrinted()) 13224 pw.println(); 13225 if (!checkin) { 13226 pw.println("Features:"); 13227 } 13228 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13229 while (it.hasNext()) { 13230 String name = it.next(); 13231 if (!checkin) { 13232 pw.print(" "); 13233 } else { 13234 pw.print("feat,"); 13235 } 13236 pw.println(name); 13237 } 13238 } 13239 13240 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13241 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13242 : "Activity Resolver Table:", " ", packageName, 13243 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13244 dumpState.setTitlePrinted(true); 13245 } 13246 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13247 : "Receiver Resolver Table:", " ", packageName, 13248 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13249 dumpState.setTitlePrinted(true); 13250 } 13251 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13252 : "Service Resolver Table:", " ", packageName, 13253 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13254 dumpState.setTitlePrinted(true); 13255 } 13256 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13257 : "Provider Resolver Table:", " ", packageName, 13258 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13259 dumpState.setTitlePrinted(true); 13260 } 13261 } 13262 13263 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13264 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13265 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13266 int user = mSettings.mPreferredActivities.keyAt(i); 13267 if (pir.dump(pw, 13268 dumpState.getTitlePrinted() 13269 ? "\nPreferred Activities User " + user + ":" 13270 : "Preferred Activities User " + user + ":", " ", 13271 packageName, true, false)) { 13272 dumpState.setTitlePrinted(true); 13273 } 13274 } 13275 } 13276 13277 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13278 pw.flush(); 13279 FileOutputStream fout = new FileOutputStream(fd); 13280 BufferedOutputStream str = new BufferedOutputStream(fout); 13281 XmlSerializer serializer = new FastXmlSerializer(); 13282 try { 13283 serializer.setOutput(str, "utf-8"); 13284 serializer.startDocument(null, true); 13285 serializer.setFeature( 13286 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13287 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13288 serializer.endDocument(); 13289 serializer.flush(); 13290 } catch (IllegalArgumentException e) { 13291 pw.println("Failed writing: " + e); 13292 } catch (IllegalStateException e) { 13293 pw.println("Failed writing: " + e); 13294 } catch (IOException e) { 13295 pw.println("Failed writing: " + e); 13296 } 13297 } 13298 13299 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13300 pw.println(); 13301 int count = mSettings.mPackages.size(); 13302 if (count == 0) { 13303 pw.println("No domain preferred apps!"); 13304 pw.println(); 13305 } else { 13306 final String prefix = " "; 13307 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13308 if (allPackageSettings.size() == 0) { 13309 pw.println("No domain preferred apps!"); 13310 pw.println(); 13311 } else { 13312 pw.println("Domain preferred apps status:"); 13313 pw.println(); 13314 count = 0; 13315 for (PackageSetting ps : allPackageSettings) { 13316 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13317 if (ivi == null || ivi.getPackageName() == null) continue; 13318 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13319 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13320 pw.println(prefix + "Status: " + ivi.getStatusString()); 13321 pw.println(); 13322 count++; 13323 } 13324 if (count == 0) { 13325 pw.println(prefix + "No domain preferred app status!"); 13326 pw.println(); 13327 } 13328 for (int userId : sUserManager.getUserIds()) { 13329 pw.println("Domain preferred apps for User " + userId + ":"); 13330 pw.println(); 13331 count = 0; 13332 for (PackageSetting ps : allPackageSettings) { 13333 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13334 if (ivi == null || ivi.getPackageName() == null) { 13335 continue; 13336 } 13337 final int status = ps.getDomainVerificationStatusForUser(userId); 13338 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13339 continue; 13340 } 13341 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13342 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13343 String statusStr = IntentFilterVerificationInfo. 13344 getStatusStringFromValue(status); 13345 pw.println(prefix + "Status: " + statusStr); 13346 pw.println(); 13347 count++; 13348 } 13349 if (count == 0) { 13350 pw.println(prefix + "No domain preferred apps!"); 13351 pw.println(); 13352 } 13353 } 13354 } 13355 } 13356 } 13357 13358 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13359 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13360 if (packageName == null) { 13361 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13362 if (iperm == 0) { 13363 if (dumpState.onTitlePrinted()) 13364 pw.println(); 13365 pw.println("AppOp Permissions:"); 13366 } 13367 pw.print(" AppOp Permission "); 13368 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13369 pw.println(":"); 13370 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13371 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13372 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13373 } 13374 } 13375 } 13376 } 13377 13378 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13379 boolean printedSomething = false; 13380 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13381 if (packageName != null && !packageName.equals(p.info.packageName)) { 13382 continue; 13383 } 13384 if (!printedSomething) { 13385 if (dumpState.onTitlePrinted()) 13386 pw.println(); 13387 pw.println("Registered ContentProviders:"); 13388 printedSomething = true; 13389 } 13390 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13391 pw.print(" "); pw.println(p.toString()); 13392 } 13393 printedSomething = false; 13394 for (Map.Entry<String, PackageParser.Provider> entry : 13395 mProvidersByAuthority.entrySet()) { 13396 PackageParser.Provider p = entry.getValue(); 13397 if (packageName != null && !packageName.equals(p.info.packageName)) { 13398 continue; 13399 } 13400 if (!printedSomething) { 13401 if (dumpState.onTitlePrinted()) 13402 pw.println(); 13403 pw.println("ContentProvider Authorities:"); 13404 printedSomething = true; 13405 } 13406 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13407 pw.print(" "); pw.println(p.toString()); 13408 if (p.info != null && p.info.applicationInfo != null) { 13409 final String appInfo = p.info.applicationInfo.toString(); 13410 pw.print(" applicationInfo="); pw.println(appInfo); 13411 } 13412 } 13413 } 13414 13415 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13416 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13417 } 13418 13419 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13420 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13421 } 13422 13423 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13424 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13425 } 13426 13427 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13428 // XXX should handle packageName != null by dumping only install data that 13429 // the given package is involved with. 13430 if (dumpState.onTitlePrinted()) pw.println(); 13431 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13432 } 13433 13434 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13435 if (dumpState.onTitlePrinted()) pw.println(); 13436 mSettings.dumpReadMessagesLPr(pw, dumpState); 13437 13438 pw.println(); 13439 pw.println("Package warning messages:"); 13440 BufferedReader in = null; 13441 String line = null; 13442 try { 13443 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13444 while ((line = in.readLine()) != null) { 13445 if (line.contains("ignored: updated version")) continue; 13446 pw.println(line); 13447 } 13448 } catch (IOException ignored) { 13449 } finally { 13450 IoUtils.closeQuietly(in); 13451 } 13452 } 13453 13454 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13455 BufferedReader in = null; 13456 String line = null; 13457 try { 13458 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13459 while ((line = in.readLine()) != null) { 13460 if (line.contains("ignored: updated version")) continue; 13461 pw.print("msg,"); 13462 pw.println(line); 13463 } 13464 } catch (IOException ignored) { 13465 } finally { 13466 IoUtils.closeQuietly(in); 13467 } 13468 } 13469 } 13470 } 13471 13472 // ------- apps on sdcard specific code ------- 13473 static final boolean DEBUG_SD_INSTALL = false; 13474 13475 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13476 13477 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13478 13479 private boolean mMediaMounted = false; 13480 13481 static String getEncryptKey() { 13482 try { 13483 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13484 SD_ENCRYPTION_KEYSTORE_NAME); 13485 if (sdEncKey == null) { 13486 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13487 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13488 if (sdEncKey == null) { 13489 Slog.e(TAG, "Failed to create encryption keys"); 13490 return null; 13491 } 13492 } 13493 return sdEncKey; 13494 } catch (NoSuchAlgorithmException nsae) { 13495 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13496 return null; 13497 } catch (IOException ioe) { 13498 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13499 return null; 13500 } 13501 } 13502 13503 /* 13504 * Update media status on PackageManager. 13505 */ 13506 @Override 13507 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13508 int callingUid = Binder.getCallingUid(); 13509 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13510 throw new SecurityException("Media status can only be updated by the system"); 13511 } 13512 // reader; this apparently protects mMediaMounted, but should probably 13513 // be a different lock in that case. 13514 synchronized (mPackages) { 13515 Log.i(TAG, "Updating external media status from " 13516 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13517 + (mediaStatus ? "mounted" : "unmounted")); 13518 if (DEBUG_SD_INSTALL) 13519 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13520 + ", mMediaMounted=" + mMediaMounted); 13521 if (mediaStatus == mMediaMounted) { 13522 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13523 : 0, -1); 13524 mHandler.sendMessage(msg); 13525 return; 13526 } 13527 mMediaMounted = mediaStatus; 13528 } 13529 // Queue up an async operation since the package installation may take a 13530 // little while. 13531 mHandler.post(new Runnable() { 13532 public void run() { 13533 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13534 } 13535 }); 13536 } 13537 13538 /** 13539 * Called by MountService when the initial ASECs to scan are available. 13540 * Should block until all the ASEC containers are finished being scanned. 13541 */ 13542 public void scanAvailableAsecs() { 13543 updateExternalMediaStatusInner(true, false, false); 13544 if (mShouldRestoreconData) { 13545 SELinuxMMAC.setRestoreconDone(); 13546 mShouldRestoreconData = false; 13547 } 13548 } 13549 13550 /* 13551 * Collect information of applications on external media, map them against 13552 * existing containers and update information based on current mount status. 13553 * Please note that we always have to report status if reportStatus has been 13554 * set to true especially when unloading packages. 13555 */ 13556 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13557 boolean externalStorage) { 13558 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13559 int[] uidArr = EmptyArray.INT; 13560 13561 final String[] list = PackageHelper.getSecureContainerList(); 13562 if (ArrayUtils.isEmpty(list)) { 13563 Log.i(TAG, "No secure containers found"); 13564 } else { 13565 // Process list of secure containers and categorize them 13566 // as active or stale based on their package internal state. 13567 13568 // reader 13569 synchronized (mPackages) { 13570 for (String cid : list) { 13571 // Leave stages untouched for now; installer service owns them 13572 if (PackageInstallerService.isStageName(cid)) continue; 13573 13574 if (DEBUG_SD_INSTALL) 13575 Log.i(TAG, "Processing container " + cid); 13576 String pkgName = getAsecPackageName(cid); 13577 if (pkgName == null) { 13578 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13579 continue; 13580 } 13581 if (DEBUG_SD_INSTALL) 13582 Log.i(TAG, "Looking for pkg : " + pkgName); 13583 13584 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13585 if (ps == null) { 13586 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13587 continue; 13588 } 13589 13590 /* 13591 * Skip packages that are not external if we're unmounting 13592 * external storage. 13593 */ 13594 if (externalStorage && !isMounted && !isExternal(ps)) { 13595 continue; 13596 } 13597 13598 final AsecInstallArgs args = new AsecInstallArgs(cid, 13599 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13600 // The package status is changed only if the code path 13601 // matches between settings and the container id. 13602 if (ps.codePathString != null 13603 && ps.codePathString.startsWith(args.getCodePath())) { 13604 if (DEBUG_SD_INSTALL) { 13605 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13606 + " at code path: " + ps.codePathString); 13607 } 13608 13609 // We do have a valid package installed on sdcard 13610 processCids.put(args, ps.codePathString); 13611 final int uid = ps.appId; 13612 if (uid != -1) { 13613 uidArr = ArrayUtils.appendInt(uidArr, uid); 13614 } 13615 } else { 13616 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13617 + ps.codePathString); 13618 } 13619 } 13620 } 13621 13622 Arrays.sort(uidArr); 13623 } 13624 13625 // Process packages with valid entries. 13626 if (isMounted) { 13627 if (DEBUG_SD_INSTALL) 13628 Log.i(TAG, "Loading packages"); 13629 loadMediaPackages(processCids, uidArr); 13630 startCleaningPackages(); 13631 mInstallerService.onSecureContainersAvailable(); 13632 } else { 13633 if (DEBUG_SD_INSTALL) 13634 Log.i(TAG, "Unloading packages"); 13635 unloadMediaPackages(processCids, uidArr, reportStatus); 13636 } 13637 } 13638 13639 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13640 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13641 int size = pkgList.size(); 13642 if (size > 0) { 13643 // Send broadcasts here 13644 Bundle extras = new Bundle(); 13645 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13646 .toArray(new String[size])); 13647 if (uidArr != null) { 13648 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13649 } 13650 if (replacing) { 13651 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13652 } 13653 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13654 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13655 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13656 } 13657 } 13658 13659 /* 13660 * Look at potentially valid container ids from processCids If package 13661 * information doesn't match the one on record or package scanning fails, 13662 * the cid is added to list of removeCids. We currently don't delete stale 13663 * containers. 13664 */ 13665 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13666 ArrayList<String> pkgList = new ArrayList<String>(); 13667 Set<AsecInstallArgs> keys = processCids.keySet(); 13668 13669 for (AsecInstallArgs args : keys) { 13670 String codePath = processCids.get(args); 13671 if (DEBUG_SD_INSTALL) 13672 Log.i(TAG, "Loading container : " + args.cid); 13673 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13674 try { 13675 // Make sure there are no container errors first. 13676 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13677 Slog.e(TAG, "Failed to mount cid : " + args.cid 13678 + " when installing from sdcard"); 13679 continue; 13680 } 13681 // Check code path here. 13682 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13683 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13684 + " does not match one in settings " + codePath); 13685 continue; 13686 } 13687 // Parse package 13688 int parseFlags = mDefParseFlags; 13689 if (args.isExternal()) { 13690 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13691 } 13692 if (args.isFwdLocked()) { 13693 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13694 } 13695 13696 synchronized (mInstallLock) { 13697 PackageParser.Package pkg = null; 13698 try { 13699 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13700 } catch (PackageManagerException e) { 13701 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13702 } 13703 // Scan the package 13704 if (pkg != null) { 13705 /* 13706 * TODO why is the lock being held? doPostInstall is 13707 * called in other places without the lock. This needs 13708 * to be straightened out. 13709 */ 13710 // writer 13711 synchronized (mPackages) { 13712 retCode = PackageManager.INSTALL_SUCCEEDED; 13713 pkgList.add(pkg.packageName); 13714 // Post process args 13715 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13716 pkg.applicationInfo.uid); 13717 } 13718 } else { 13719 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13720 } 13721 } 13722 13723 } finally { 13724 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13725 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13726 } 13727 } 13728 } 13729 // writer 13730 synchronized (mPackages) { 13731 // If the platform SDK has changed since the last time we booted, 13732 // we need to re-grant app permission to catch any new ones that 13733 // appear. This is really a hack, and means that apps can in some 13734 // cases get permissions that the user didn't initially explicitly 13735 // allow... it would be nice to have some better way to handle 13736 // this situation. 13737 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13738 if (regrantPermissions) 13739 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13740 + mSdkVersion + "; regranting permissions for external storage"); 13741 mSettings.mExternalSdkPlatform = mSdkVersion; 13742 13743 // Make sure group IDs have been assigned, and any permission 13744 // changes in other apps are accounted for 13745 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13746 | (regrantPermissions 13747 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13748 : 0)); 13749 13750 mSettings.updateExternalDatabaseVersion(); 13751 13752 // can downgrade to reader 13753 // Persist settings 13754 mSettings.writeLPr(); 13755 } 13756 // Send a broadcast to let everyone know we are done processing 13757 if (pkgList.size() > 0) { 13758 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13759 } 13760 } 13761 13762 /* 13763 * Utility method to unload a list of specified containers 13764 */ 13765 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13766 // Just unmount all valid containers. 13767 for (AsecInstallArgs arg : cidArgs) { 13768 synchronized (mInstallLock) { 13769 arg.doPostDeleteLI(false); 13770 } 13771 } 13772 } 13773 13774 /* 13775 * Unload packages mounted on external media. This involves deleting package 13776 * data from internal structures, sending broadcasts about diabled packages, 13777 * gc'ing to free up references, unmounting all secure containers 13778 * corresponding to packages on external media, and posting a 13779 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13780 * that we always have to post this message if status has been requested no 13781 * matter what. 13782 */ 13783 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13784 final boolean reportStatus) { 13785 if (DEBUG_SD_INSTALL) 13786 Log.i(TAG, "unloading media packages"); 13787 ArrayList<String> pkgList = new ArrayList<String>(); 13788 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13789 final Set<AsecInstallArgs> keys = processCids.keySet(); 13790 for (AsecInstallArgs args : keys) { 13791 String pkgName = args.getPackageName(); 13792 if (DEBUG_SD_INSTALL) 13793 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13794 // Delete package internally 13795 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13796 synchronized (mInstallLock) { 13797 boolean res = deletePackageLI(pkgName, null, false, null, null, 13798 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13799 if (res) { 13800 pkgList.add(pkgName); 13801 } else { 13802 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13803 failedList.add(args); 13804 } 13805 } 13806 } 13807 13808 // reader 13809 synchronized (mPackages) { 13810 // We didn't update the settings after removing each package; 13811 // write them now for all packages. 13812 mSettings.writeLPr(); 13813 } 13814 13815 // We have to absolutely send UPDATED_MEDIA_STATUS only 13816 // after confirming that all the receivers processed the ordered 13817 // broadcast when packages get disabled, force a gc to clean things up. 13818 // and unload all the containers. 13819 if (pkgList.size() > 0) { 13820 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13821 new IIntentReceiver.Stub() { 13822 public void performReceive(Intent intent, int resultCode, String data, 13823 Bundle extras, boolean ordered, boolean sticky, 13824 int sendingUser) throws RemoteException { 13825 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13826 reportStatus ? 1 : 0, 1, keys); 13827 mHandler.sendMessage(msg); 13828 } 13829 }); 13830 } else { 13831 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13832 keys); 13833 mHandler.sendMessage(msg); 13834 } 13835 } 13836 13837 /** Binder call */ 13838 @Override 13839 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13840 final int flags) { 13841 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13842 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13843 int returnCode = PackageManager.MOVE_SUCCEEDED; 13844 int currInstallFlags = 0; 13845 int newInstallFlags = 0; 13846 13847 File codeFile = null; 13848 String installerPackageName = null; 13849 String packageAbiOverride = null; 13850 13851 // reader 13852 synchronized (mPackages) { 13853 final PackageParser.Package pkg = mPackages.get(packageName); 13854 final PackageSetting ps = mSettings.mPackages.get(packageName); 13855 if (pkg == null || ps == null) { 13856 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13857 } else { 13858 // Disable moving fwd locked apps and system packages 13859 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13860 Slog.w(TAG, "Cannot move system application"); 13861 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13862 } else if (pkg.mOperationPending) { 13863 Slog.w(TAG, "Attempt to move package which has pending operations"); 13864 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13865 } else { 13866 // Find install location first 13867 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13868 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13869 Slog.w(TAG, "Ambigous flags specified for move location."); 13870 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13871 } else { 13872 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13873 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13874 currInstallFlags = isExternal(pkg) 13875 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13876 13877 if (newInstallFlags == currInstallFlags) { 13878 Slog.w(TAG, "No move required. Trying to move to same location"); 13879 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13880 } else { 13881 if (pkg.isForwardLocked()) { 13882 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13883 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13884 } 13885 } 13886 } 13887 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13888 pkg.mOperationPending = true; 13889 } 13890 } 13891 13892 codeFile = new File(pkg.codePath); 13893 installerPackageName = ps.installerPackageName; 13894 packageAbiOverride = ps.cpuAbiOverrideString; 13895 } 13896 } 13897 13898 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13899 try { 13900 observer.packageMoved(packageName, returnCode); 13901 } catch (RemoteException ignored) { 13902 } 13903 return; 13904 } 13905 13906 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13907 @Override 13908 public void onUserActionRequired(Intent intent) throws RemoteException { 13909 throw new IllegalStateException(); 13910 } 13911 13912 @Override 13913 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13914 Bundle extras) throws RemoteException { 13915 Slog.d(TAG, "Install result for move: " 13916 + PackageManager.installStatusToString(returnCode, msg)); 13917 13918 // We usually have a new package now after the install, but if 13919 // we failed we need to clear the pending flag on the original 13920 // package object. 13921 synchronized (mPackages) { 13922 final PackageParser.Package pkg = mPackages.get(packageName); 13923 if (pkg != null) { 13924 pkg.mOperationPending = false; 13925 } 13926 } 13927 13928 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13929 switch (status) { 13930 case PackageInstaller.STATUS_SUCCESS: 13931 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13932 break; 13933 case PackageInstaller.STATUS_FAILURE_STORAGE: 13934 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13935 break; 13936 default: 13937 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13938 break; 13939 } 13940 } 13941 }; 13942 13943 // Treat a move like reinstalling an existing app, which ensures that we 13944 // process everythign uniformly, like unpacking native libraries. 13945 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13946 13947 final Message msg = mHandler.obtainMessage(INIT_COPY); 13948 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13949 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13950 installerPackageName, null, user, packageAbiOverride); 13951 mHandler.sendMessage(msg); 13952 } 13953 13954 @Override 13955 public boolean setInstallLocation(int loc) { 13956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13957 null); 13958 if (getInstallLocation() == loc) { 13959 return true; 13960 } 13961 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13962 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13963 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13964 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13965 return true; 13966 } 13967 return false; 13968 } 13969 13970 @Override 13971 public int getInstallLocation() { 13972 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13973 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13974 PackageHelper.APP_INSTALL_AUTO); 13975 } 13976 13977 /** Called by UserManagerService */ 13978 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13979 mDirtyUsers.remove(userHandle); 13980 mSettings.removeUserLPw(userHandle); 13981 mPendingBroadcasts.remove(userHandle); 13982 if (mInstaller != null) { 13983 // Technically, we shouldn't be doing this with the package lock 13984 // held. However, this is very rare, and there is already so much 13985 // other disk I/O going on, that we'll let it slide for now. 13986 mInstaller.removeUserDataDirs(userHandle); 13987 } 13988 mUserNeedsBadging.delete(userHandle); 13989 removeUnusedPackagesLILPw(userManager, userHandle); 13990 } 13991 13992 /** 13993 * We're removing userHandle and would like to remove any downloaded packages 13994 * that are no longer in use by any other user. 13995 * @param userHandle the user being removed 13996 */ 13997 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13998 final boolean DEBUG_CLEAN_APKS = false; 13999 int [] users = userManager.getUserIdsLPr(); 14000 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14001 while (psit.hasNext()) { 14002 PackageSetting ps = psit.next(); 14003 if (ps.pkg == null) { 14004 continue; 14005 } 14006 final String packageName = ps.pkg.packageName; 14007 // Skip over if system app 14008 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14009 continue; 14010 } 14011 if (DEBUG_CLEAN_APKS) { 14012 Slog.i(TAG, "Checking package " + packageName); 14013 } 14014 boolean keep = false; 14015 for (int i = 0; i < users.length; i++) { 14016 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14017 keep = true; 14018 if (DEBUG_CLEAN_APKS) { 14019 Slog.i(TAG, " Keeping package " + packageName + " for user " 14020 + users[i]); 14021 } 14022 break; 14023 } 14024 } 14025 if (!keep) { 14026 if (DEBUG_CLEAN_APKS) { 14027 Slog.i(TAG, " Removing package " + packageName); 14028 } 14029 mHandler.post(new Runnable() { 14030 public void run() { 14031 deletePackageX(packageName, userHandle, 0); 14032 } //end run 14033 }); 14034 } 14035 } 14036 } 14037 14038 /** Called by UserManagerService */ 14039 void createNewUserLILPw(int userHandle, File path) { 14040 if (mInstaller != null) { 14041 mInstaller.createUserConfig(userHandle); 14042 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14043 } 14044 } 14045 14046 void newUserCreatedLILPw(int userHandle) { 14047 // Adding a user requires updating runtime permissions for system apps. 14048 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14049 } 14050 14051 @Override 14052 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14053 mContext.enforceCallingOrSelfPermission( 14054 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14055 "Only package verification agents can read the verifier device identity"); 14056 14057 synchronized (mPackages) { 14058 return mSettings.getVerifierDeviceIdentityLPw(); 14059 } 14060 } 14061 14062 @Override 14063 public void setPermissionEnforced(String permission, boolean enforced) { 14064 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14065 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14066 synchronized (mPackages) { 14067 if (mSettings.mReadExternalStorageEnforced == null 14068 || mSettings.mReadExternalStorageEnforced != enforced) { 14069 mSettings.mReadExternalStorageEnforced = enforced; 14070 mSettings.writeLPr(); 14071 } 14072 } 14073 // kill any non-foreground processes so we restart them and 14074 // grant/revoke the GID. 14075 final IActivityManager am = ActivityManagerNative.getDefault(); 14076 if (am != null) { 14077 final long token = Binder.clearCallingIdentity(); 14078 try { 14079 am.killProcessesBelowForeground("setPermissionEnforcement"); 14080 } catch (RemoteException e) { 14081 } finally { 14082 Binder.restoreCallingIdentity(token); 14083 } 14084 } 14085 } else { 14086 throw new IllegalArgumentException("No selective enforcement for " + permission); 14087 } 14088 } 14089 14090 @Override 14091 @Deprecated 14092 public boolean isPermissionEnforced(String permission) { 14093 return true; 14094 } 14095 14096 @Override 14097 public boolean isStorageLow() { 14098 final long token = Binder.clearCallingIdentity(); 14099 try { 14100 final DeviceStorageMonitorInternal 14101 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14102 if (dsm != null) { 14103 return dsm.isMemoryLow(); 14104 } else { 14105 return false; 14106 } 14107 } finally { 14108 Binder.restoreCallingIdentity(token); 14109 } 14110 } 14111 14112 @Override 14113 public IPackageInstaller getPackageInstaller() { 14114 return mInstallerService; 14115 } 14116 14117 private boolean userNeedsBadging(int userId) { 14118 int index = mUserNeedsBadging.indexOfKey(userId); 14119 if (index < 0) { 14120 final UserInfo userInfo; 14121 final long token = Binder.clearCallingIdentity(); 14122 try { 14123 userInfo = sUserManager.getUserInfo(userId); 14124 } finally { 14125 Binder.restoreCallingIdentity(token); 14126 } 14127 final boolean b; 14128 if (userInfo != null && userInfo.isManagedProfile()) { 14129 b = true; 14130 } else { 14131 b = false; 14132 } 14133 mUserNeedsBadging.put(userId, b); 14134 return b; 14135 } 14136 return mUserNeedsBadging.valueAt(index); 14137 } 14138 14139 @Override 14140 public KeySet getKeySetByAlias(String packageName, String alias) { 14141 if (packageName == null || alias == null) { 14142 return null; 14143 } 14144 synchronized(mPackages) { 14145 final PackageParser.Package pkg = mPackages.get(packageName); 14146 if (pkg == null) { 14147 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14148 throw new IllegalArgumentException("Unknown package: " + packageName); 14149 } 14150 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14151 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14152 } 14153 } 14154 14155 @Override 14156 public KeySet getSigningKeySet(String packageName) { 14157 if (packageName == null) { 14158 return null; 14159 } 14160 synchronized(mPackages) { 14161 final PackageParser.Package pkg = mPackages.get(packageName); 14162 if (pkg == null) { 14163 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14164 throw new IllegalArgumentException("Unknown package: " + packageName); 14165 } 14166 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14167 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14168 throw new SecurityException("May not access signing KeySet of other apps."); 14169 } 14170 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14171 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14172 } 14173 } 14174 14175 @Override 14176 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14177 if (packageName == null || ks == null) { 14178 return false; 14179 } 14180 synchronized(mPackages) { 14181 final PackageParser.Package pkg = mPackages.get(packageName); 14182 if (pkg == null) { 14183 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14184 throw new IllegalArgumentException("Unknown package: " + packageName); 14185 } 14186 IBinder ksh = ks.getToken(); 14187 if (ksh instanceof KeySetHandle) { 14188 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14189 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14190 } 14191 return false; 14192 } 14193 } 14194 14195 @Override 14196 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14197 if (packageName == null || ks == null) { 14198 return false; 14199 } 14200 synchronized(mPackages) { 14201 final PackageParser.Package pkg = mPackages.get(packageName); 14202 if (pkg == null) { 14203 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14204 throw new IllegalArgumentException("Unknown package: " + packageName); 14205 } 14206 IBinder ksh = ks.getToken(); 14207 if (ksh instanceof KeySetHandle) { 14208 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14209 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14210 } 14211 return false; 14212 } 14213 } 14214 14215 public void getUsageStatsIfNoPackageUsageInfo() { 14216 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14217 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14218 if (usm == null) { 14219 throw new IllegalStateException("UsageStatsManager must be initialized"); 14220 } 14221 long now = System.currentTimeMillis(); 14222 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14223 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14224 String packageName = entry.getKey(); 14225 PackageParser.Package pkg = mPackages.get(packageName); 14226 if (pkg == null) { 14227 continue; 14228 } 14229 UsageStats usage = entry.getValue(); 14230 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14231 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14232 } 14233 } 14234 } 14235 14236 /** 14237 * Check and throw if the given before/after packages would be considered a 14238 * downgrade. 14239 */ 14240 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14241 throws PackageManagerException { 14242 if (after.versionCode < before.mVersionCode) { 14243 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14244 "Update version code " + after.versionCode + " is older than current " 14245 + before.mVersionCode); 14246 } else if (after.versionCode == before.mVersionCode) { 14247 if (after.baseRevisionCode < before.baseRevisionCode) { 14248 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14249 "Update base revision code " + after.baseRevisionCode 14250 + " is older than current " + before.baseRevisionCode); 14251 } 14252 14253 if (!ArrayUtils.isEmpty(after.splitNames)) { 14254 for (int i = 0; i < after.splitNames.length; i++) { 14255 final String splitName = after.splitNames[i]; 14256 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14257 if (j != -1) { 14258 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14259 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14260 "Update split " + splitName + " revision code " 14261 + after.splitRevisionCodes[i] + " is older than current " 14262 + before.splitRevisionCodes[j]); 14263 } 14264 } 14265 } 14266 } 14267 } 14268 } 14269} 14270