PackageManagerService.java revision d2cf3aec6087ba53dcbb55eb38c8e7f385ac4cbd
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 if (!ps.isSharedUser()) { 7401 origPermissions = new PermissionsState(permissionsState); 7402 permissionsState.reset(); 7403 } 7404 } 7405 7406 permissionsState.setGlobalGids(mGlobalGids); 7407 7408 final int N = pkg.requestedPermissions.size(); 7409 for (int i=0; i<N; i++) { 7410 final String name = pkg.requestedPermissions.get(i); 7411 final BasePermission bp = mSettings.mPermissions.get(name); 7412 7413 if (DEBUG_INSTALL) { 7414 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7415 } 7416 7417 if (bp == null || bp.packageSetting == null) { 7418 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7419 Slog.w(TAG, "Unknown permission " + name 7420 + " in package " + pkg.packageName); 7421 } 7422 continue; 7423 } 7424 7425 final String perm = bp.name; 7426 boolean allowedSig = false; 7427 int grant = GRANT_DENIED; 7428 7429 // Keep track of app op permissions. 7430 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7431 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7432 if (pkgs == null) { 7433 pkgs = new ArraySet<>(); 7434 mAppOpPermissionPackages.put(bp.name, pkgs); 7435 } 7436 pkgs.add(pkg.packageName); 7437 } 7438 7439 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7440 switch (level) { 7441 case PermissionInfo.PROTECTION_NORMAL: { 7442 // For all apps normal permissions are install time ones. 7443 grant = GRANT_INSTALL; 7444 } break; 7445 7446 case PermissionInfo.PROTECTION_DANGEROUS: { 7447 if (!RUNTIME_PERMISSIONS_ENABLED 7448 || pkg.applicationInfo.targetSdkVersion 7449 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7450 // For legacy apps dangerous permissions are install time ones. 7451 grant = GRANT_INSTALL; 7452 } else if (ps.isSystem()) { 7453 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7454 if (origPermissions.hasInstallPermission(bp.name)) { 7455 // If a system app had an install permission, then the app was 7456 // upgraded and we grant the permissions as runtime to all users. 7457 grant = GRANT_UPGRADE; 7458 upgradeUserIds = currentUserIds; 7459 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7460 // If users changed since the last permissions update for a 7461 // system app, we grant the permission as runtime to the new users. 7462 grant = GRANT_UPGRADE; 7463 upgradeUserIds = currentUserIds; 7464 for (int userId : updatedUserIds) { 7465 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7466 } 7467 } else { 7468 // Otherwise, we grant the permission as runtime if the app 7469 // already had it, i.e. we preserve runtime permissions. 7470 grant = GRANT_RUNTIME; 7471 } 7472 } else if (origPermissions.hasInstallPermission(bp.name)) { 7473 // For legacy apps that became modern, install becomes runtime. 7474 grant = GRANT_UPGRADE; 7475 upgradeUserIds = currentUserIds; 7476 } else if (replace) { 7477 // For upgraded modern apps keep runtime permissions unchanged. 7478 grant = GRANT_RUNTIME; 7479 } 7480 } break; 7481 7482 case PermissionInfo.PROTECTION_SIGNATURE: { 7483 // For all apps signature permissions are install time ones. 7484 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7485 if (allowedSig) { 7486 grant = GRANT_INSTALL; 7487 } 7488 } break; 7489 } 7490 7491 if (DEBUG_INSTALL) { 7492 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7493 } 7494 7495 if (grant != GRANT_DENIED) { 7496 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7497 // If this is an existing, non-system package, then 7498 // we can't add any new permissions to it. 7499 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7500 // Except... if this is a permission that was added 7501 // to the platform (note: need to only do this when 7502 // updating the platform). 7503 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7504 grant = GRANT_DENIED; 7505 } 7506 } 7507 } 7508 7509 switch (grant) { 7510 case GRANT_INSTALL: { 7511 // Grant an install permission. 7512 if (permissionsState.grantInstallPermission(bp) != 7513 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7514 changedInstallPermission = true; 7515 } 7516 } break; 7517 7518 case GRANT_RUNTIME: { 7519 // Grant previously granted runtime permissions. 7520 for (int userId : UserManagerService.getInstance().getUserIds()) { 7521 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7522 if (permissionsState.grantRuntimePermission(bp, userId) == 7523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7524 // If we cannot put the permission as it was, we have to write. 7525 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7526 changedRuntimePermissionUserIds, userId); 7527 } 7528 } 7529 } 7530 } break; 7531 7532 case GRANT_UPGRADE: { 7533 // Grant runtime permissions for a previously held install permission. 7534 permissionsState.revokeInstallPermission(bp); 7535 for (int userId : upgradeUserIds) { 7536 if (permissionsState.grantRuntimePermission(bp, userId) != 7537 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7538 // If we granted the permission, we have to write. 7539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7540 changedRuntimePermissionUserIds, userId); 7541 } 7542 } 7543 } break; 7544 7545 default: { 7546 if (packageOfInterest == null 7547 || packageOfInterest.equals(pkg.packageName)) { 7548 Slog.w(TAG, "Not granting permission " + perm 7549 + " to package " + pkg.packageName 7550 + " because it was previously installed without"); 7551 } 7552 } break; 7553 } 7554 } else { 7555 if (permissionsState.revokeInstallPermission(bp) != 7556 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7557 changedInstallPermission = true; 7558 Slog.i(TAG, "Un-granting permission " + perm 7559 + " from package " + pkg.packageName 7560 + " (protectionLevel=" + bp.protectionLevel 7561 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7562 + ")"); 7563 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7564 // Don't print warning for app op permissions, since it is fine for them 7565 // not to be granted, there is a UI for the user to decide. 7566 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7567 Slog.w(TAG, "Not granting permission " + perm 7568 + " to package " + pkg.packageName 7569 + " (protectionLevel=" + bp.protectionLevel 7570 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7571 + ")"); 7572 } 7573 } 7574 } 7575 } 7576 7577 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7578 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7579 // This is the first that we have heard about this package, so the 7580 // permissions we have now selected are fixed until explicitly 7581 // changed. 7582 ps.installPermissionsFixed = true; 7583 } 7584 7585 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7586 7587 // Persist the runtime permissions state for users with changes. 7588 if (RUNTIME_PERMISSIONS_ENABLED) { 7589 for (int userId : changedRuntimePermissionUserIds) { 7590 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7591 } 7592 } 7593 } 7594 7595 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7596 boolean allowed = false; 7597 final int NP = PackageParser.NEW_PERMISSIONS.length; 7598 for (int ip=0; ip<NP; ip++) { 7599 final PackageParser.NewPermissionInfo npi 7600 = PackageParser.NEW_PERMISSIONS[ip]; 7601 if (npi.name.equals(perm) 7602 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7603 allowed = true; 7604 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7605 + pkg.packageName); 7606 break; 7607 } 7608 } 7609 return allowed; 7610 } 7611 7612 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7613 BasePermission bp, PermissionsState origPermissions) { 7614 boolean allowed; 7615 allowed = (compareSignatures( 7616 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7617 == PackageManager.SIGNATURE_MATCH) 7618 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7619 == PackageManager.SIGNATURE_MATCH); 7620 if (!allowed && (bp.protectionLevel 7621 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7622 if (isSystemApp(pkg)) { 7623 // For updated system applications, a system permission 7624 // is granted only if it had been defined by the original application. 7625 if (isUpdatedSystemApp(pkg)) { 7626 final PackageSetting sysPs = mSettings 7627 .getDisabledSystemPkgLPr(pkg.packageName); 7628 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7629 // If the original was granted this permission, we take 7630 // that grant decision as read and propagate it to the 7631 // update. 7632 if (sysPs.isPrivileged()) { 7633 allowed = true; 7634 } 7635 } else { 7636 // The system apk may have been updated with an older 7637 // version of the one on the data partition, but which 7638 // granted a new system permission that it didn't have 7639 // before. In this case we do want to allow the app to 7640 // now get the new permission if the ancestral apk is 7641 // privileged to get it. 7642 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7643 for (int j=0; 7644 j<sysPs.pkg.requestedPermissions.size(); j++) { 7645 if (perm.equals( 7646 sysPs.pkg.requestedPermissions.get(j))) { 7647 allowed = true; 7648 break; 7649 } 7650 } 7651 } 7652 } 7653 } else { 7654 allowed = isPrivilegedApp(pkg); 7655 } 7656 } 7657 } 7658 if (!allowed && (bp.protectionLevel 7659 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7660 // For development permissions, a development permission 7661 // is granted only if it was already granted. 7662 allowed = origPermissions.hasInstallPermission(perm); 7663 } 7664 return allowed; 7665 } 7666 7667 final class ActivityIntentResolver 7668 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7669 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7670 boolean defaultOnly, int userId) { 7671 if (!sUserManager.exists(userId)) return null; 7672 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7673 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7674 } 7675 7676 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7677 int userId) { 7678 if (!sUserManager.exists(userId)) return null; 7679 mFlags = flags; 7680 return super.queryIntent(intent, resolvedType, 7681 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7682 } 7683 7684 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7685 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7686 if (!sUserManager.exists(userId)) return null; 7687 if (packageActivities == null) { 7688 return null; 7689 } 7690 mFlags = flags; 7691 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7692 final int N = packageActivities.size(); 7693 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7694 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7695 7696 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7697 for (int i = 0; i < N; ++i) { 7698 intentFilters = packageActivities.get(i).intents; 7699 if (intentFilters != null && intentFilters.size() > 0) { 7700 PackageParser.ActivityIntentInfo[] array = 7701 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7702 intentFilters.toArray(array); 7703 listCut.add(array); 7704 } 7705 } 7706 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7707 } 7708 7709 public final void addActivity(PackageParser.Activity a, String type) { 7710 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7711 mActivities.put(a.getComponentName(), a); 7712 if (DEBUG_SHOW_INFO) 7713 Log.v( 7714 TAG, " " + type + " " + 7715 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7716 if (DEBUG_SHOW_INFO) 7717 Log.v(TAG, " Class=" + a.info.name); 7718 final int NI = a.intents.size(); 7719 for (int j=0; j<NI; j++) { 7720 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7721 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7722 intent.setPriority(0); 7723 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7724 + a.className + " with priority > 0, forcing to 0"); 7725 } 7726 if (DEBUG_SHOW_INFO) { 7727 Log.v(TAG, " IntentFilter:"); 7728 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7729 } 7730 if (!intent.debugCheck()) { 7731 Log.w(TAG, "==> For Activity " + a.info.name); 7732 } 7733 addFilter(intent); 7734 } 7735 } 7736 7737 public final void removeActivity(PackageParser.Activity a, String type) { 7738 mActivities.remove(a.getComponentName()); 7739 if (DEBUG_SHOW_INFO) { 7740 Log.v(TAG, " " + type + " " 7741 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7742 : a.info.name) + ":"); 7743 Log.v(TAG, " Class=" + a.info.name); 7744 } 7745 final int NI = a.intents.size(); 7746 for (int j=0; j<NI; j++) { 7747 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7748 if (DEBUG_SHOW_INFO) { 7749 Log.v(TAG, " IntentFilter:"); 7750 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7751 } 7752 removeFilter(intent); 7753 } 7754 } 7755 7756 @Override 7757 protected boolean allowFilterResult( 7758 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7759 ActivityInfo filterAi = filter.activity.info; 7760 for (int i=dest.size()-1; i>=0; i--) { 7761 ActivityInfo destAi = dest.get(i).activityInfo; 7762 if (destAi.name == filterAi.name 7763 && destAi.packageName == filterAi.packageName) { 7764 return false; 7765 } 7766 } 7767 return true; 7768 } 7769 7770 @Override 7771 protected ActivityIntentInfo[] newArray(int size) { 7772 return new ActivityIntentInfo[size]; 7773 } 7774 7775 @Override 7776 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7777 if (!sUserManager.exists(userId)) return true; 7778 PackageParser.Package p = filter.activity.owner; 7779 if (p != null) { 7780 PackageSetting ps = (PackageSetting)p.mExtras; 7781 if (ps != null) { 7782 // System apps are never considered stopped for purposes of 7783 // filtering, because there may be no way for the user to 7784 // actually re-launch them. 7785 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7786 && ps.getStopped(userId); 7787 } 7788 } 7789 return false; 7790 } 7791 7792 @Override 7793 protected boolean isPackageForFilter(String packageName, 7794 PackageParser.ActivityIntentInfo info) { 7795 return packageName.equals(info.activity.owner.packageName); 7796 } 7797 7798 @Override 7799 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7800 int match, int userId) { 7801 if (!sUserManager.exists(userId)) return null; 7802 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7803 return null; 7804 } 7805 final PackageParser.Activity activity = info.activity; 7806 if (mSafeMode && (activity.info.applicationInfo.flags 7807 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7808 return null; 7809 } 7810 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7811 if (ps == null) { 7812 return null; 7813 } 7814 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7815 ps.readUserState(userId), userId); 7816 if (ai == null) { 7817 return null; 7818 } 7819 final ResolveInfo res = new ResolveInfo(); 7820 res.activityInfo = ai; 7821 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7822 res.filter = info; 7823 } 7824 if (info != null) { 7825 res.filterNeedsVerification = info.needsVerification(); 7826 } 7827 res.priority = info.getPriority(); 7828 res.preferredOrder = activity.owner.mPreferredOrder; 7829 //System.out.println("Result: " + res.activityInfo.className + 7830 // " = " + res.priority); 7831 res.match = match; 7832 res.isDefault = info.hasDefault; 7833 res.labelRes = info.labelRes; 7834 res.nonLocalizedLabel = info.nonLocalizedLabel; 7835 if (userNeedsBadging(userId)) { 7836 res.noResourceId = true; 7837 } else { 7838 res.icon = info.icon; 7839 } 7840 res.system = isSystemApp(res.activityInfo.applicationInfo); 7841 return res; 7842 } 7843 7844 @Override 7845 protected void sortResults(List<ResolveInfo> results) { 7846 Collections.sort(results, mResolvePrioritySorter); 7847 } 7848 7849 @Override 7850 protected void dumpFilter(PrintWriter out, String prefix, 7851 PackageParser.ActivityIntentInfo filter) { 7852 out.print(prefix); out.print( 7853 Integer.toHexString(System.identityHashCode(filter.activity))); 7854 out.print(' '); 7855 filter.activity.printComponentShortName(out); 7856 out.print(" filter "); 7857 out.println(Integer.toHexString(System.identityHashCode(filter))); 7858 } 7859 7860 @Override 7861 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7862 return filter.activity; 7863 } 7864 7865 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7866 PackageParser.Activity activity = (PackageParser.Activity)label; 7867 out.print(prefix); out.print( 7868 Integer.toHexString(System.identityHashCode(activity))); 7869 out.print(' '); 7870 activity.printComponentShortName(out); 7871 if (count > 1) { 7872 out.print(" ("); out.print(count); out.print(" filters)"); 7873 } 7874 out.println(); 7875 } 7876 7877// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7878// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7879// final List<ResolveInfo> retList = Lists.newArrayList(); 7880// while (i.hasNext()) { 7881// final ResolveInfo resolveInfo = i.next(); 7882// if (isEnabledLP(resolveInfo.activityInfo)) { 7883// retList.add(resolveInfo); 7884// } 7885// } 7886// return retList; 7887// } 7888 7889 // Keys are String (activity class name), values are Activity. 7890 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7891 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7892 private int mFlags; 7893 } 7894 7895 private final class ServiceIntentResolver 7896 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7897 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7898 boolean defaultOnly, int userId) { 7899 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7900 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7901 } 7902 7903 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7904 int userId) { 7905 if (!sUserManager.exists(userId)) return null; 7906 mFlags = flags; 7907 return super.queryIntent(intent, resolvedType, 7908 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7909 } 7910 7911 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7912 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7913 if (!sUserManager.exists(userId)) return null; 7914 if (packageServices == null) { 7915 return null; 7916 } 7917 mFlags = flags; 7918 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7919 final int N = packageServices.size(); 7920 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7921 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7922 7923 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7924 for (int i = 0; i < N; ++i) { 7925 intentFilters = packageServices.get(i).intents; 7926 if (intentFilters != null && intentFilters.size() > 0) { 7927 PackageParser.ServiceIntentInfo[] array = 7928 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7929 intentFilters.toArray(array); 7930 listCut.add(array); 7931 } 7932 } 7933 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7934 } 7935 7936 public final void addService(PackageParser.Service s) { 7937 mServices.put(s.getComponentName(), s); 7938 if (DEBUG_SHOW_INFO) { 7939 Log.v(TAG, " " 7940 + (s.info.nonLocalizedLabel != null 7941 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7942 Log.v(TAG, " Class=" + s.info.name); 7943 } 7944 final int NI = s.intents.size(); 7945 int j; 7946 for (j=0; j<NI; j++) { 7947 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7948 if (DEBUG_SHOW_INFO) { 7949 Log.v(TAG, " IntentFilter:"); 7950 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7951 } 7952 if (!intent.debugCheck()) { 7953 Log.w(TAG, "==> For Service " + s.info.name); 7954 } 7955 addFilter(intent); 7956 } 7957 } 7958 7959 public final void removeService(PackageParser.Service s) { 7960 mServices.remove(s.getComponentName()); 7961 if (DEBUG_SHOW_INFO) { 7962 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7963 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7964 Log.v(TAG, " Class=" + s.info.name); 7965 } 7966 final int NI = s.intents.size(); 7967 int j; 7968 for (j=0; j<NI; j++) { 7969 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7970 if (DEBUG_SHOW_INFO) { 7971 Log.v(TAG, " IntentFilter:"); 7972 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7973 } 7974 removeFilter(intent); 7975 } 7976 } 7977 7978 @Override 7979 protected boolean allowFilterResult( 7980 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7981 ServiceInfo filterSi = filter.service.info; 7982 for (int i=dest.size()-1; i>=0; i--) { 7983 ServiceInfo destAi = dest.get(i).serviceInfo; 7984 if (destAi.name == filterSi.name 7985 && destAi.packageName == filterSi.packageName) { 7986 return false; 7987 } 7988 } 7989 return true; 7990 } 7991 7992 @Override 7993 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7994 return new PackageParser.ServiceIntentInfo[size]; 7995 } 7996 7997 @Override 7998 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7999 if (!sUserManager.exists(userId)) return true; 8000 PackageParser.Package p = filter.service.owner; 8001 if (p != null) { 8002 PackageSetting ps = (PackageSetting)p.mExtras; 8003 if (ps != null) { 8004 // System apps are never considered stopped for purposes of 8005 // filtering, because there may be no way for the user to 8006 // actually re-launch them. 8007 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8008 && ps.getStopped(userId); 8009 } 8010 } 8011 return false; 8012 } 8013 8014 @Override 8015 protected boolean isPackageForFilter(String packageName, 8016 PackageParser.ServiceIntentInfo info) { 8017 return packageName.equals(info.service.owner.packageName); 8018 } 8019 8020 @Override 8021 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8022 int match, int userId) { 8023 if (!sUserManager.exists(userId)) return null; 8024 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8025 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8026 return null; 8027 } 8028 final PackageParser.Service service = info.service; 8029 if (mSafeMode && (service.info.applicationInfo.flags 8030 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8031 return null; 8032 } 8033 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8034 if (ps == null) { 8035 return null; 8036 } 8037 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8038 ps.readUserState(userId), userId); 8039 if (si == null) { 8040 return null; 8041 } 8042 final ResolveInfo res = new ResolveInfo(); 8043 res.serviceInfo = si; 8044 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8045 res.filter = filter; 8046 } 8047 res.priority = info.getPriority(); 8048 res.preferredOrder = service.owner.mPreferredOrder; 8049 res.match = match; 8050 res.isDefault = info.hasDefault; 8051 res.labelRes = info.labelRes; 8052 res.nonLocalizedLabel = info.nonLocalizedLabel; 8053 res.icon = info.icon; 8054 res.system = isSystemApp(res.serviceInfo.applicationInfo); 8055 return res; 8056 } 8057 8058 @Override 8059 protected void sortResults(List<ResolveInfo> results) { 8060 Collections.sort(results, mResolvePrioritySorter); 8061 } 8062 8063 @Override 8064 protected void dumpFilter(PrintWriter out, String prefix, 8065 PackageParser.ServiceIntentInfo filter) { 8066 out.print(prefix); out.print( 8067 Integer.toHexString(System.identityHashCode(filter.service))); 8068 out.print(' '); 8069 filter.service.printComponentShortName(out); 8070 out.print(" filter "); 8071 out.println(Integer.toHexString(System.identityHashCode(filter))); 8072 } 8073 8074 @Override 8075 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8076 return filter.service; 8077 } 8078 8079 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8080 PackageParser.Service service = (PackageParser.Service)label; 8081 out.print(prefix); out.print( 8082 Integer.toHexString(System.identityHashCode(service))); 8083 out.print(' '); 8084 service.printComponentShortName(out); 8085 if (count > 1) { 8086 out.print(" ("); out.print(count); out.print(" filters)"); 8087 } 8088 out.println(); 8089 } 8090 8091// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8092// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8093// final List<ResolveInfo> retList = Lists.newArrayList(); 8094// while (i.hasNext()) { 8095// final ResolveInfo resolveInfo = (ResolveInfo) i; 8096// if (isEnabledLP(resolveInfo.serviceInfo)) { 8097// retList.add(resolveInfo); 8098// } 8099// } 8100// return retList; 8101// } 8102 8103 // Keys are String (activity class name), values are Activity. 8104 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8105 = new ArrayMap<ComponentName, PackageParser.Service>(); 8106 private int mFlags; 8107 }; 8108 8109 private final class ProviderIntentResolver 8110 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8111 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8112 boolean defaultOnly, int userId) { 8113 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8114 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8115 } 8116 8117 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8118 int userId) { 8119 if (!sUserManager.exists(userId)) 8120 return null; 8121 mFlags = flags; 8122 return super.queryIntent(intent, resolvedType, 8123 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8124 } 8125 8126 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8127 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8128 if (!sUserManager.exists(userId)) 8129 return null; 8130 if (packageProviders == null) { 8131 return null; 8132 } 8133 mFlags = flags; 8134 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8135 final int N = packageProviders.size(); 8136 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8137 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8138 8139 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8140 for (int i = 0; i < N; ++i) { 8141 intentFilters = packageProviders.get(i).intents; 8142 if (intentFilters != null && intentFilters.size() > 0) { 8143 PackageParser.ProviderIntentInfo[] array = 8144 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8145 intentFilters.toArray(array); 8146 listCut.add(array); 8147 } 8148 } 8149 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8150 } 8151 8152 public final void addProvider(PackageParser.Provider p) { 8153 if (mProviders.containsKey(p.getComponentName())) { 8154 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8155 return; 8156 } 8157 8158 mProviders.put(p.getComponentName(), p); 8159 if (DEBUG_SHOW_INFO) { 8160 Log.v(TAG, " " 8161 + (p.info.nonLocalizedLabel != null 8162 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8163 Log.v(TAG, " Class=" + p.info.name); 8164 } 8165 final int NI = p.intents.size(); 8166 int j; 8167 for (j = 0; j < NI; j++) { 8168 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8169 if (DEBUG_SHOW_INFO) { 8170 Log.v(TAG, " IntentFilter:"); 8171 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8172 } 8173 if (!intent.debugCheck()) { 8174 Log.w(TAG, "==> For Provider " + p.info.name); 8175 } 8176 addFilter(intent); 8177 } 8178 } 8179 8180 public final void removeProvider(PackageParser.Provider p) { 8181 mProviders.remove(p.getComponentName()); 8182 if (DEBUG_SHOW_INFO) { 8183 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8184 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8185 Log.v(TAG, " Class=" + p.info.name); 8186 } 8187 final int NI = p.intents.size(); 8188 int j; 8189 for (j = 0; j < NI; j++) { 8190 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8191 if (DEBUG_SHOW_INFO) { 8192 Log.v(TAG, " IntentFilter:"); 8193 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8194 } 8195 removeFilter(intent); 8196 } 8197 } 8198 8199 @Override 8200 protected boolean allowFilterResult( 8201 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8202 ProviderInfo filterPi = filter.provider.info; 8203 for (int i = dest.size() - 1; i >= 0; i--) { 8204 ProviderInfo destPi = dest.get(i).providerInfo; 8205 if (destPi.name == filterPi.name 8206 && destPi.packageName == filterPi.packageName) { 8207 return false; 8208 } 8209 } 8210 return true; 8211 } 8212 8213 @Override 8214 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8215 return new PackageParser.ProviderIntentInfo[size]; 8216 } 8217 8218 @Override 8219 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8220 if (!sUserManager.exists(userId)) 8221 return true; 8222 PackageParser.Package p = filter.provider.owner; 8223 if (p != null) { 8224 PackageSetting ps = (PackageSetting) p.mExtras; 8225 if (ps != null) { 8226 // System apps are never considered stopped for purposes of 8227 // filtering, because there may be no way for the user to 8228 // actually re-launch them. 8229 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8230 && ps.getStopped(userId); 8231 } 8232 } 8233 return false; 8234 } 8235 8236 @Override 8237 protected boolean isPackageForFilter(String packageName, 8238 PackageParser.ProviderIntentInfo info) { 8239 return packageName.equals(info.provider.owner.packageName); 8240 } 8241 8242 @Override 8243 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8244 int match, int userId) { 8245 if (!sUserManager.exists(userId)) 8246 return null; 8247 final PackageParser.ProviderIntentInfo info = filter; 8248 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8249 return null; 8250 } 8251 final PackageParser.Provider provider = info.provider; 8252 if (mSafeMode && (provider.info.applicationInfo.flags 8253 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8254 return null; 8255 } 8256 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8257 if (ps == null) { 8258 return null; 8259 } 8260 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8261 ps.readUserState(userId), userId); 8262 if (pi == null) { 8263 return null; 8264 } 8265 final ResolveInfo res = new ResolveInfo(); 8266 res.providerInfo = pi; 8267 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8268 res.filter = filter; 8269 } 8270 res.priority = info.getPriority(); 8271 res.preferredOrder = provider.owner.mPreferredOrder; 8272 res.match = match; 8273 res.isDefault = info.hasDefault; 8274 res.labelRes = info.labelRes; 8275 res.nonLocalizedLabel = info.nonLocalizedLabel; 8276 res.icon = info.icon; 8277 res.system = isSystemApp(res.providerInfo.applicationInfo); 8278 return res; 8279 } 8280 8281 @Override 8282 protected void sortResults(List<ResolveInfo> results) { 8283 Collections.sort(results, mResolvePrioritySorter); 8284 } 8285 8286 @Override 8287 protected void dumpFilter(PrintWriter out, String prefix, 8288 PackageParser.ProviderIntentInfo filter) { 8289 out.print(prefix); 8290 out.print( 8291 Integer.toHexString(System.identityHashCode(filter.provider))); 8292 out.print(' '); 8293 filter.provider.printComponentShortName(out); 8294 out.print(" filter "); 8295 out.println(Integer.toHexString(System.identityHashCode(filter))); 8296 } 8297 8298 @Override 8299 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8300 return filter.provider; 8301 } 8302 8303 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8304 PackageParser.Provider provider = (PackageParser.Provider)label; 8305 out.print(prefix); out.print( 8306 Integer.toHexString(System.identityHashCode(provider))); 8307 out.print(' '); 8308 provider.printComponentShortName(out); 8309 if (count > 1) { 8310 out.print(" ("); out.print(count); out.print(" filters)"); 8311 } 8312 out.println(); 8313 } 8314 8315 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8316 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8317 private int mFlags; 8318 }; 8319 8320 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8321 new Comparator<ResolveInfo>() { 8322 public int compare(ResolveInfo r1, ResolveInfo r2) { 8323 int v1 = r1.priority; 8324 int v2 = r2.priority; 8325 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8326 if (v1 != v2) { 8327 return (v1 > v2) ? -1 : 1; 8328 } 8329 v1 = r1.preferredOrder; 8330 v2 = r2.preferredOrder; 8331 if (v1 != v2) { 8332 return (v1 > v2) ? -1 : 1; 8333 } 8334 if (r1.isDefault != r2.isDefault) { 8335 return r1.isDefault ? -1 : 1; 8336 } 8337 v1 = r1.match; 8338 v2 = r2.match; 8339 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8340 if (v1 != v2) { 8341 return (v1 > v2) ? -1 : 1; 8342 } 8343 if (r1.system != r2.system) { 8344 return r1.system ? -1 : 1; 8345 } 8346 return 0; 8347 } 8348 }; 8349 8350 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8351 new Comparator<ProviderInfo>() { 8352 public int compare(ProviderInfo p1, ProviderInfo p2) { 8353 final int v1 = p1.initOrder; 8354 final int v2 = p2.initOrder; 8355 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8356 } 8357 }; 8358 8359 static final void sendPackageBroadcast(String action, String pkg, 8360 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8361 int[] userIds) { 8362 IActivityManager am = ActivityManagerNative.getDefault(); 8363 if (am != null) { 8364 try { 8365 if (userIds == null) { 8366 userIds = am.getRunningUserIds(); 8367 } 8368 for (int id : userIds) { 8369 final Intent intent = new Intent(action, 8370 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8371 if (extras != null) { 8372 intent.putExtras(extras); 8373 } 8374 if (targetPkg != null) { 8375 intent.setPackage(targetPkg); 8376 } 8377 // Modify the UID when posting to other users 8378 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8379 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8380 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8381 intent.putExtra(Intent.EXTRA_UID, uid); 8382 } 8383 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8384 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8385 if (DEBUG_BROADCASTS) { 8386 RuntimeException here = new RuntimeException("here"); 8387 here.fillInStackTrace(); 8388 Slog.d(TAG, "Sending to user " + id + ": " 8389 + intent.toShortString(false, true, false, false) 8390 + " " + intent.getExtras(), here); 8391 } 8392 am.broadcastIntent(null, intent, null, finishedReceiver, 8393 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8394 finishedReceiver != null, false, id); 8395 } 8396 } catch (RemoteException ex) { 8397 } 8398 } 8399 } 8400 8401 /** 8402 * Check if the external storage media is available. This is true if there 8403 * is a mounted external storage medium or if the external storage is 8404 * emulated. 8405 */ 8406 private boolean isExternalMediaAvailable() { 8407 return mMediaMounted || Environment.isExternalStorageEmulated(); 8408 } 8409 8410 @Override 8411 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8412 // writer 8413 synchronized (mPackages) { 8414 if (!isExternalMediaAvailable()) { 8415 // If the external storage is no longer mounted at this point, 8416 // the caller may not have been able to delete all of this 8417 // packages files and can not delete any more. Bail. 8418 return null; 8419 } 8420 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8421 if (lastPackage != null) { 8422 pkgs.remove(lastPackage); 8423 } 8424 if (pkgs.size() > 0) { 8425 return pkgs.get(0); 8426 } 8427 } 8428 return null; 8429 } 8430 8431 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8432 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8433 userId, andCode ? 1 : 0, packageName); 8434 if (mSystemReady) { 8435 msg.sendToTarget(); 8436 } else { 8437 if (mPostSystemReadyMessages == null) { 8438 mPostSystemReadyMessages = new ArrayList<>(); 8439 } 8440 mPostSystemReadyMessages.add(msg); 8441 } 8442 } 8443 8444 void startCleaningPackages() { 8445 // reader 8446 synchronized (mPackages) { 8447 if (!isExternalMediaAvailable()) { 8448 return; 8449 } 8450 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8451 return; 8452 } 8453 } 8454 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8455 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8456 IActivityManager am = ActivityManagerNative.getDefault(); 8457 if (am != null) { 8458 try { 8459 am.startService(null, intent, null, UserHandle.USER_OWNER); 8460 } catch (RemoteException e) { 8461 } 8462 } 8463 } 8464 8465 @Override 8466 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8467 int installFlags, String installerPackageName, VerificationParams verificationParams, 8468 String packageAbiOverride) { 8469 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8470 packageAbiOverride, UserHandle.getCallingUserId()); 8471 } 8472 8473 @Override 8474 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8475 int installFlags, String installerPackageName, VerificationParams verificationParams, 8476 String packageAbiOverride, int userId) { 8477 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8478 8479 final int callingUid = Binder.getCallingUid(); 8480 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8481 8482 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8483 try { 8484 if (observer != null) { 8485 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8486 } 8487 } catch (RemoteException re) { 8488 } 8489 return; 8490 } 8491 8492 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8493 installFlags |= PackageManager.INSTALL_FROM_ADB; 8494 8495 } else { 8496 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8497 // about installerPackageName. 8498 8499 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8500 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8501 } 8502 8503 UserHandle user; 8504 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8505 user = UserHandle.ALL; 8506 } else { 8507 user = new UserHandle(userId); 8508 } 8509 8510 verificationParams.setInstallerUid(callingUid); 8511 8512 final File originFile = new File(originPath); 8513 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8514 8515 final Message msg = mHandler.obtainMessage(INIT_COPY); 8516 msg.obj = new InstallParams(origin, observer, installFlags, 8517 installerPackageName, verificationParams, user, packageAbiOverride); 8518 mHandler.sendMessage(msg); 8519 } 8520 8521 void installStage(String packageName, File stagedDir, String stagedCid, 8522 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8523 String installerPackageName, int installerUid, UserHandle user) { 8524 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8525 params.referrerUri, installerUid, null); 8526 8527 final OriginInfo origin; 8528 if (stagedDir != null) { 8529 origin = OriginInfo.fromStagedFile(stagedDir); 8530 } else { 8531 origin = OriginInfo.fromStagedContainer(stagedCid); 8532 } 8533 8534 final Message msg = mHandler.obtainMessage(INIT_COPY); 8535 msg.obj = new InstallParams(origin, observer, params.installFlags, 8536 installerPackageName, verifParams, user, params.abiOverride); 8537 mHandler.sendMessage(msg); 8538 } 8539 8540 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8541 Bundle extras = new Bundle(1); 8542 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8543 8544 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8545 packageName, extras, null, null, new int[] {userId}); 8546 try { 8547 IActivityManager am = ActivityManagerNative.getDefault(); 8548 final boolean isSystem = 8549 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8550 if (isSystem && am.isUserRunning(userId, false)) { 8551 // The just-installed/enabled app is bundled on the system, so presumed 8552 // to be able to run automatically without needing an explicit launch. 8553 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8554 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8555 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8556 .setPackage(packageName); 8557 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8558 android.app.AppOpsManager.OP_NONE, false, false, userId); 8559 } 8560 } catch (RemoteException e) { 8561 // shouldn't happen 8562 Slog.w(TAG, "Unable to bootstrap installed package", e); 8563 } 8564 } 8565 8566 @Override 8567 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8568 int userId) { 8569 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8570 PackageSetting pkgSetting; 8571 final int uid = Binder.getCallingUid(); 8572 enforceCrossUserPermission(uid, userId, true, true, 8573 "setApplicationHiddenSetting for user " + userId); 8574 8575 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8576 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8577 return false; 8578 } 8579 8580 long callingId = Binder.clearCallingIdentity(); 8581 try { 8582 boolean sendAdded = false; 8583 boolean sendRemoved = false; 8584 // writer 8585 synchronized (mPackages) { 8586 pkgSetting = mSettings.mPackages.get(packageName); 8587 if (pkgSetting == null) { 8588 return false; 8589 } 8590 if (pkgSetting.getHidden(userId) != hidden) { 8591 pkgSetting.setHidden(hidden, userId); 8592 mSettings.writePackageRestrictionsLPr(userId); 8593 if (hidden) { 8594 sendRemoved = true; 8595 } else { 8596 sendAdded = true; 8597 } 8598 } 8599 } 8600 if (sendAdded) { 8601 sendPackageAddedForUser(packageName, pkgSetting, userId); 8602 return true; 8603 } 8604 if (sendRemoved) { 8605 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8606 "hiding pkg"); 8607 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8608 } 8609 } finally { 8610 Binder.restoreCallingIdentity(callingId); 8611 } 8612 return false; 8613 } 8614 8615 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8616 int userId) { 8617 final PackageRemovedInfo info = new PackageRemovedInfo(); 8618 info.removedPackage = packageName; 8619 info.removedUsers = new int[] {userId}; 8620 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8621 info.sendBroadcast(false, false, false); 8622 } 8623 8624 /** 8625 * Returns true if application is not found or there was an error. Otherwise it returns 8626 * the hidden state of the package for the given user. 8627 */ 8628 @Override 8629 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8630 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8631 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8632 false, "getApplicationHidden for user " + userId); 8633 PackageSetting pkgSetting; 8634 long callingId = Binder.clearCallingIdentity(); 8635 try { 8636 // writer 8637 synchronized (mPackages) { 8638 pkgSetting = mSettings.mPackages.get(packageName); 8639 if (pkgSetting == null) { 8640 return true; 8641 } 8642 return pkgSetting.getHidden(userId); 8643 } 8644 } finally { 8645 Binder.restoreCallingIdentity(callingId); 8646 } 8647 } 8648 8649 /** 8650 * @hide 8651 */ 8652 @Override 8653 public int installExistingPackageAsUser(String packageName, int userId) { 8654 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8655 null); 8656 PackageSetting pkgSetting; 8657 final int uid = Binder.getCallingUid(); 8658 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8659 + userId); 8660 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8661 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8662 } 8663 8664 long callingId = Binder.clearCallingIdentity(); 8665 try { 8666 boolean sendAdded = false; 8667 Bundle extras = new Bundle(1); 8668 8669 // writer 8670 synchronized (mPackages) { 8671 pkgSetting = mSettings.mPackages.get(packageName); 8672 if (pkgSetting == null) { 8673 return PackageManager.INSTALL_FAILED_INVALID_URI; 8674 } 8675 if (!pkgSetting.getInstalled(userId)) { 8676 pkgSetting.setInstalled(true, userId); 8677 pkgSetting.setHidden(false, userId); 8678 mSettings.writePackageRestrictionsLPr(userId); 8679 sendAdded = true; 8680 } 8681 } 8682 8683 if (sendAdded) { 8684 sendPackageAddedForUser(packageName, pkgSetting, userId); 8685 } 8686 } finally { 8687 Binder.restoreCallingIdentity(callingId); 8688 } 8689 8690 return PackageManager.INSTALL_SUCCEEDED; 8691 } 8692 8693 boolean isUserRestricted(int userId, String restrictionKey) { 8694 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8695 if (restrictions.getBoolean(restrictionKey, false)) { 8696 Log.w(TAG, "User is restricted: " + restrictionKey); 8697 return true; 8698 } 8699 return false; 8700 } 8701 8702 @Override 8703 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8704 mContext.enforceCallingOrSelfPermission( 8705 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8706 "Only package verification agents can verify applications"); 8707 8708 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8709 final PackageVerificationResponse response = new PackageVerificationResponse( 8710 verificationCode, Binder.getCallingUid()); 8711 msg.arg1 = id; 8712 msg.obj = response; 8713 mHandler.sendMessage(msg); 8714 } 8715 8716 @Override 8717 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8718 long millisecondsToDelay) { 8719 mContext.enforceCallingOrSelfPermission( 8720 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8721 "Only package verification agents can extend verification timeouts"); 8722 8723 final PackageVerificationState state = mPendingVerification.get(id); 8724 final PackageVerificationResponse response = new PackageVerificationResponse( 8725 verificationCodeAtTimeout, Binder.getCallingUid()); 8726 8727 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8728 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8729 } 8730 if (millisecondsToDelay < 0) { 8731 millisecondsToDelay = 0; 8732 } 8733 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8734 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8735 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8736 } 8737 8738 if ((state != null) && !state.timeoutExtended()) { 8739 state.extendTimeout(); 8740 8741 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8742 msg.arg1 = id; 8743 msg.obj = response; 8744 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8745 } 8746 } 8747 8748 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8749 int verificationCode, UserHandle user) { 8750 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8751 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8752 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8753 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8754 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8755 8756 mContext.sendBroadcastAsUser(intent, user, 8757 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8758 } 8759 8760 private ComponentName matchComponentForVerifier(String packageName, 8761 List<ResolveInfo> receivers) { 8762 ActivityInfo targetReceiver = null; 8763 8764 final int NR = receivers.size(); 8765 for (int i = 0; i < NR; i++) { 8766 final ResolveInfo info = receivers.get(i); 8767 if (info.activityInfo == null) { 8768 continue; 8769 } 8770 8771 if (packageName.equals(info.activityInfo.packageName)) { 8772 targetReceiver = info.activityInfo; 8773 break; 8774 } 8775 } 8776 8777 if (targetReceiver == null) { 8778 return null; 8779 } 8780 8781 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8782 } 8783 8784 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8785 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8786 if (pkgInfo.verifiers.length == 0) { 8787 return null; 8788 } 8789 8790 final int N = pkgInfo.verifiers.length; 8791 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8792 for (int i = 0; i < N; i++) { 8793 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8794 8795 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8796 receivers); 8797 if (comp == null) { 8798 continue; 8799 } 8800 8801 final int verifierUid = getUidForVerifier(verifierInfo); 8802 if (verifierUid == -1) { 8803 continue; 8804 } 8805 8806 if (DEBUG_VERIFY) { 8807 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8808 + " with the correct signature"); 8809 } 8810 sufficientVerifiers.add(comp); 8811 verificationState.addSufficientVerifier(verifierUid); 8812 } 8813 8814 return sufficientVerifiers; 8815 } 8816 8817 private int getUidForVerifier(VerifierInfo verifierInfo) { 8818 synchronized (mPackages) { 8819 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8820 if (pkg == null) { 8821 return -1; 8822 } else if (pkg.mSignatures.length != 1) { 8823 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8824 + " has more than one signature; ignoring"); 8825 return -1; 8826 } 8827 8828 /* 8829 * If the public key of the package's signature does not match 8830 * our expected public key, then this is a different package and 8831 * we should skip. 8832 */ 8833 8834 final byte[] expectedPublicKey; 8835 try { 8836 final Signature verifierSig = pkg.mSignatures[0]; 8837 final PublicKey publicKey = verifierSig.getPublicKey(); 8838 expectedPublicKey = publicKey.getEncoded(); 8839 } catch (CertificateException e) { 8840 return -1; 8841 } 8842 8843 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8844 8845 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8846 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8847 + " does not have the expected public key; ignoring"); 8848 return -1; 8849 } 8850 8851 return pkg.applicationInfo.uid; 8852 } 8853 } 8854 8855 @Override 8856 public void finishPackageInstall(int token) { 8857 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8858 8859 if (DEBUG_INSTALL) { 8860 Slog.v(TAG, "BM finishing package install for " + token); 8861 } 8862 8863 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8864 mHandler.sendMessage(msg); 8865 } 8866 8867 /** 8868 * Get the verification agent timeout. 8869 * 8870 * @return verification timeout in milliseconds 8871 */ 8872 private long getVerificationTimeout() { 8873 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8874 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8875 DEFAULT_VERIFICATION_TIMEOUT); 8876 } 8877 8878 /** 8879 * Get the default verification agent response code. 8880 * 8881 * @return default verification response code 8882 */ 8883 private int getDefaultVerificationResponse() { 8884 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8885 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8886 DEFAULT_VERIFICATION_RESPONSE); 8887 } 8888 8889 /** 8890 * Check whether or not package verification has been enabled. 8891 * 8892 * @return true if verification should be performed 8893 */ 8894 private boolean isVerificationEnabled(int userId, int installFlags) { 8895 if (!DEFAULT_VERIFY_ENABLE) { 8896 return false; 8897 } 8898 8899 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8900 8901 // Check if installing from ADB 8902 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8903 // Do not run verification in a test harness environment 8904 if (ActivityManager.isRunningInTestHarness()) { 8905 return false; 8906 } 8907 if (ensureVerifyAppsEnabled) { 8908 return true; 8909 } 8910 // Check if the developer does not want package verification for ADB installs 8911 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8912 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8913 return false; 8914 } 8915 } 8916 8917 if (ensureVerifyAppsEnabled) { 8918 return true; 8919 } 8920 8921 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8922 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8923 } 8924 8925 @Override 8926 public void verifyIntentFilter(int id, int verificationCode, List<String> outFailedDomains) 8927 throws RemoteException { 8928 mContext.enforceCallingOrSelfPermission( 8929 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8930 "Only intentfilter verification agents can verify applications"); 8931 8932 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8933 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8934 Binder.getCallingUid(), verificationCode, outFailedDomains); 8935 msg.arg1 = id; 8936 msg.obj = response; 8937 mHandler.sendMessage(msg); 8938 } 8939 8940 @Override 8941 public int getIntentVerificationStatus(String packageName, int userId) { 8942 synchronized (mPackages) { 8943 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8944 } 8945 } 8946 8947 @Override 8948 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8949 boolean result = false; 8950 synchronized (mPackages) { 8951 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8952 } 8953 scheduleWritePackageRestrictionsLocked(userId); 8954 return result; 8955 } 8956 8957 @Override 8958 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8959 synchronized (mPackages) { 8960 return mSettings.getIntentFilterVerificationsLPr(packageName); 8961 } 8962 } 8963 8964 /** 8965 * Get the "allow unknown sources" setting. 8966 * 8967 * @return the current "allow unknown sources" setting 8968 */ 8969 private int getUnknownSourcesSettings() { 8970 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8971 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8972 -1); 8973 } 8974 8975 @Override 8976 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8977 final int uid = Binder.getCallingUid(); 8978 // writer 8979 synchronized (mPackages) { 8980 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8981 if (targetPackageSetting == null) { 8982 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8983 } 8984 8985 PackageSetting installerPackageSetting; 8986 if (installerPackageName != null) { 8987 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8988 if (installerPackageSetting == null) { 8989 throw new IllegalArgumentException("Unknown installer package: " 8990 + installerPackageName); 8991 } 8992 } else { 8993 installerPackageSetting = null; 8994 } 8995 8996 Signature[] callerSignature; 8997 Object obj = mSettings.getUserIdLPr(uid); 8998 if (obj != null) { 8999 if (obj instanceof SharedUserSetting) { 9000 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9001 } else if (obj instanceof PackageSetting) { 9002 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9003 } else { 9004 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9005 } 9006 } else { 9007 throw new SecurityException("Unknown calling uid " + uid); 9008 } 9009 9010 // Verify: can't set installerPackageName to a package that is 9011 // not signed with the same cert as the caller. 9012 if (installerPackageSetting != null) { 9013 if (compareSignatures(callerSignature, 9014 installerPackageSetting.signatures.mSignatures) 9015 != PackageManager.SIGNATURE_MATCH) { 9016 throw new SecurityException( 9017 "Caller does not have same cert as new installer package " 9018 + installerPackageName); 9019 } 9020 } 9021 9022 // Verify: if target already has an installer package, it must 9023 // be signed with the same cert as the caller. 9024 if (targetPackageSetting.installerPackageName != null) { 9025 PackageSetting setting = mSettings.mPackages.get( 9026 targetPackageSetting.installerPackageName); 9027 // If the currently set package isn't valid, then it's always 9028 // okay to change it. 9029 if (setting != null) { 9030 if (compareSignatures(callerSignature, 9031 setting.signatures.mSignatures) 9032 != PackageManager.SIGNATURE_MATCH) { 9033 throw new SecurityException( 9034 "Caller does not have same cert as old installer package " 9035 + targetPackageSetting.installerPackageName); 9036 } 9037 } 9038 } 9039 9040 // Okay! 9041 targetPackageSetting.installerPackageName = installerPackageName; 9042 scheduleWriteSettingsLocked(); 9043 } 9044 } 9045 9046 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9047 // Queue up an async operation since the package installation may take a little while. 9048 mHandler.post(new Runnable() { 9049 public void run() { 9050 mHandler.removeCallbacks(this); 9051 // Result object to be returned 9052 PackageInstalledInfo res = new PackageInstalledInfo(); 9053 res.returnCode = currentStatus; 9054 res.uid = -1; 9055 res.pkg = null; 9056 res.removedInfo = new PackageRemovedInfo(); 9057 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9058 args.doPreInstall(res.returnCode); 9059 synchronized (mInstallLock) { 9060 installPackageLI(args, res); 9061 } 9062 args.doPostInstall(res.returnCode, res.uid); 9063 } 9064 9065 // A restore should be performed at this point if (a) the install 9066 // succeeded, (b) the operation is not an update, and (c) the new 9067 // package has not opted out of backup participation. 9068 final boolean update = res.removedInfo.removedPackage != null; 9069 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9070 boolean doRestore = !update 9071 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9072 9073 // Set up the post-install work request bookkeeping. This will be used 9074 // and cleaned up by the post-install event handling regardless of whether 9075 // there's a restore pass performed. Token values are >= 1. 9076 int token; 9077 if (mNextInstallToken < 0) mNextInstallToken = 1; 9078 token = mNextInstallToken++; 9079 9080 PostInstallData data = new PostInstallData(args, res); 9081 mRunningInstalls.put(token, data); 9082 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9083 9084 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9085 // Pass responsibility to the Backup Manager. It will perform a 9086 // restore if appropriate, then pass responsibility back to the 9087 // Package Manager to run the post-install observer callbacks 9088 // and broadcasts. 9089 IBackupManager bm = IBackupManager.Stub.asInterface( 9090 ServiceManager.getService(Context.BACKUP_SERVICE)); 9091 if (bm != null) { 9092 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9093 + " to BM for possible restore"); 9094 try { 9095 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9096 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9097 } else { 9098 doRestore = false; 9099 } 9100 } catch (RemoteException e) { 9101 // can't happen; the backup manager is local 9102 } catch (Exception e) { 9103 Slog.e(TAG, "Exception trying to enqueue restore", e); 9104 doRestore = false; 9105 } 9106 } else { 9107 Slog.e(TAG, "Backup Manager not found!"); 9108 doRestore = false; 9109 } 9110 } 9111 9112 if (!doRestore) { 9113 // No restore possible, or the Backup Manager was mysteriously not 9114 // available -- just fire the post-install work request directly. 9115 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9116 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9117 mHandler.sendMessage(msg); 9118 } 9119 } 9120 }); 9121 } 9122 9123 private abstract class HandlerParams { 9124 private static final int MAX_RETRIES = 4; 9125 9126 /** 9127 * Number of times startCopy() has been attempted and had a non-fatal 9128 * error. 9129 */ 9130 private int mRetries = 0; 9131 9132 /** User handle for the user requesting the information or installation. */ 9133 private final UserHandle mUser; 9134 9135 HandlerParams(UserHandle user) { 9136 mUser = user; 9137 } 9138 9139 UserHandle getUser() { 9140 return mUser; 9141 } 9142 9143 final boolean startCopy() { 9144 boolean res; 9145 try { 9146 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9147 9148 if (++mRetries > MAX_RETRIES) { 9149 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9150 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9151 handleServiceError(); 9152 return false; 9153 } else { 9154 handleStartCopy(); 9155 res = true; 9156 } 9157 } catch (RemoteException e) { 9158 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9159 mHandler.sendEmptyMessage(MCS_RECONNECT); 9160 res = false; 9161 } 9162 handleReturnCode(); 9163 return res; 9164 } 9165 9166 final void serviceError() { 9167 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9168 handleServiceError(); 9169 handleReturnCode(); 9170 } 9171 9172 abstract void handleStartCopy() throws RemoteException; 9173 abstract void handleServiceError(); 9174 abstract void handleReturnCode(); 9175 } 9176 9177 class MeasureParams extends HandlerParams { 9178 private final PackageStats mStats; 9179 private boolean mSuccess; 9180 9181 private final IPackageStatsObserver mObserver; 9182 9183 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9184 super(new UserHandle(stats.userHandle)); 9185 mObserver = observer; 9186 mStats = stats; 9187 } 9188 9189 @Override 9190 public String toString() { 9191 return "MeasureParams{" 9192 + Integer.toHexString(System.identityHashCode(this)) 9193 + " " + mStats.packageName + "}"; 9194 } 9195 9196 @Override 9197 void handleStartCopy() throws RemoteException { 9198 synchronized (mInstallLock) { 9199 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9200 } 9201 9202 if (mSuccess) { 9203 final boolean mounted; 9204 if (Environment.isExternalStorageEmulated()) { 9205 mounted = true; 9206 } else { 9207 final String status = Environment.getExternalStorageState(); 9208 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9209 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9210 } 9211 9212 if (mounted) { 9213 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9214 9215 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9216 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9217 9218 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9219 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9220 9221 // Always subtract cache size, since it's a subdirectory 9222 mStats.externalDataSize -= mStats.externalCacheSize; 9223 9224 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9225 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9226 9227 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9228 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9229 } 9230 } 9231 } 9232 9233 @Override 9234 void handleReturnCode() { 9235 if (mObserver != null) { 9236 try { 9237 mObserver.onGetStatsCompleted(mStats, mSuccess); 9238 } catch (RemoteException e) { 9239 Slog.i(TAG, "Observer no longer exists."); 9240 } 9241 } 9242 } 9243 9244 @Override 9245 void handleServiceError() { 9246 Slog.e(TAG, "Could not measure application " + mStats.packageName 9247 + " external storage"); 9248 } 9249 } 9250 9251 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9252 throws RemoteException { 9253 long result = 0; 9254 for (File path : paths) { 9255 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9256 } 9257 return result; 9258 } 9259 9260 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9261 for (File path : paths) { 9262 try { 9263 mcs.clearDirectory(path.getAbsolutePath()); 9264 } catch (RemoteException e) { 9265 } 9266 } 9267 } 9268 9269 static class OriginInfo { 9270 /** 9271 * Location where install is coming from, before it has been 9272 * copied/renamed into place. This could be a single monolithic APK 9273 * file, or a cluster directory. This location may be untrusted. 9274 */ 9275 final File file; 9276 final String cid; 9277 9278 /** 9279 * Flag indicating that {@link #file} or {@link #cid} has already been 9280 * staged, meaning downstream users don't need to defensively copy the 9281 * contents. 9282 */ 9283 final boolean staged; 9284 9285 /** 9286 * Flag indicating that {@link #file} or {@link #cid} is an already 9287 * installed app that is being moved. 9288 */ 9289 final boolean existing; 9290 9291 final String resolvedPath; 9292 final File resolvedFile; 9293 9294 static OriginInfo fromNothing() { 9295 return new OriginInfo(null, null, false, false); 9296 } 9297 9298 static OriginInfo fromUntrustedFile(File file) { 9299 return new OriginInfo(file, null, false, false); 9300 } 9301 9302 static OriginInfo fromExistingFile(File file) { 9303 return new OriginInfo(file, null, false, true); 9304 } 9305 9306 static OriginInfo fromStagedFile(File file) { 9307 return new OriginInfo(file, null, true, false); 9308 } 9309 9310 static OriginInfo fromStagedContainer(String cid) { 9311 return new OriginInfo(null, cid, true, false); 9312 } 9313 9314 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9315 this.file = file; 9316 this.cid = cid; 9317 this.staged = staged; 9318 this.existing = existing; 9319 9320 if (cid != null) { 9321 resolvedPath = PackageHelper.getSdDir(cid); 9322 resolvedFile = new File(resolvedPath); 9323 } else if (file != null) { 9324 resolvedPath = file.getAbsolutePath(); 9325 resolvedFile = file; 9326 } else { 9327 resolvedPath = null; 9328 resolvedFile = null; 9329 } 9330 } 9331 } 9332 9333 class InstallParams extends HandlerParams { 9334 final OriginInfo origin; 9335 final IPackageInstallObserver2 observer; 9336 int installFlags; 9337 final String installerPackageName; 9338 final VerificationParams verificationParams; 9339 private InstallArgs mArgs; 9340 private int mRet; 9341 final String packageAbiOverride; 9342 9343 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9344 String installerPackageName, VerificationParams verificationParams, UserHandle user, 9345 String packageAbiOverride) { 9346 super(user); 9347 this.origin = origin; 9348 this.observer = observer; 9349 this.installFlags = installFlags; 9350 this.installerPackageName = installerPackageName; 9351 this.verificationParams = verificationParams; 9352 this.packageAbiOverride = packageAbiOverride; 9353 } 9354 9355 @Override 9356 public String toString() { 9357 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9358 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9359 } 9360 9361 public ManifestDigest getManifestDigest() { 9362 if (verificationParams == null) { 9363 return null; 9364 } 9365 return verificationParams.getManifestDigest(); 9366 } 9367 9368 private int installLocationPolicy(PackageInfoLite pkgLite) { 9369 String packageName = pkgLite.packageName; 9370 int installLocation = pkgLite.installLocation; 9371 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9372 // reader 9373 synchronized (mPackages) { 9374 PackageParser.Package pkg = mPackages.get(packageName); 9375 if (pkg != null) { 9376 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9377 // Check for downgrading. 9378 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9379 try { 9380 checkDowngrade(pkg, pkgLite); 9381 } catch (PackageManagerException e) { 9382 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9383 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9384 } 9385 } 9386 // Check for updated system application. 9387 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9388 if (onSd) { 9389 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9390 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9391 } 9392 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9393 } else { 9394 if (onSd) { 9395 // Install flag overrides everything. 9396 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9397 } 9398 // If current upgrade specifies particular preference 9399 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9400 // Application explicitly specified internal. 9401 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9402 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9403 // App explictly prefers external. Let policy decide 9404 } else { 9405 // Prefer previous location 9406 if (isExternal(pkg)) { 9407 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9408 } 9409 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9410 } 9411 } 9412 } else { 9413 // Invalid install. Return error code 9414 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9415 } 9416 } 9417 } 9418 // All the special cases have been taken care of. 9419 // Return result based on recommended install location. 9420 if (onSd) { 9421 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9422 } 9423 return pkgLite.recommendedInstallLocation; 9424 } 9425 9426 /* 9427 * Invoke remote method to get package information and install 9428 * location values. Override install location based on default 9429 * policy if needed and then create install arguments based 9430 * on the install location. 9431 */ 9432 public void handleStartCopy() throws RemoteException { 9433 int ret = PackageManager.INSTALL_SUCCEEDED; 9434 9435 // If we're already staged, we've firmly committed to an install location 9436 if (origin.staged) { 9437 if (origin.file != null) { 9438 installFlags |= PackageManager.INSTALL_INTERNAL; 9439 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9440 } else if (origin.cid != null) { 9441 installFlags |= PackageManager.INSTALL_EXTERNAL; 9442 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9443 } else { 9444 throw new IllegalStateException("Invalid stage location"); 9445 } 9446 } 9447 9448 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9449 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9450 9451 PackageInfoLite pkgLite = null; 9452 9453 if (onInt && onSd) { 9454 // Check if both bits are set. 9455 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9456 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9457 } else { 9458 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9459 packageAbiOverride); 9460 9461 /* 9462 * If we have too little free space, try to free cache 9463 * before giving up. 9464 */ 9465 if (!origin.staged && pkgLite.recommendedInstallLocation 9466 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9467 // TODO: focus freeing disk space on the target device 9468 final StorageManager storage = StorageManager.from(mContext); 9469 final long lowThreshold = storage.getStorageLowBytes( 9470 Environment.getDataDirectory()); 9471 9472 final long sizeBytes = mContainerService.calculateInstalledSize( 9473 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9474 9475 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9476 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9477 installFlags, packageAbiOverride); 9478 } 9479 9480 /* 9481 * The cache free must have deleted the file we 9482 * downloaded to install. 9483 * 9484 * TODO: fix the "freeCache" call to not delete 9485 * the file we care about. 9486 */ 9487 if (pkgLite.recommendedInstallLocation 9488 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9489 pkgLite.recommendedInstallLocation 9490 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9491 } 9492 } 9493 } 9494 9495 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9496 int loc = pkgLite.recommendedInstallLocation; 9497 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9498 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9499 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9500 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9501 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9502 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9503 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9504 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9505 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9506 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9507 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9508 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9509 } else { 9510 // Override with defaults if needed. 9511 loc = installLocationPolicy(pkgLite); 9512 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9513 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9514 } else if (!onSd && !onInt) { 9515 // Override install location with flags 9516 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9517 // Set the flag to install on external media. 9518 installFlags |= PackageManager.INSTALL_EXTERNAL; 9519 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9520 } else { 9521 // Make sure the flag for installing on external 9522 // media is unset 9523 installFlags |= PackageManager.INSTALL_INTERNAL; 9524 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9525 } 9526 } 9527 } 9528 } 9529 9530 final InstallArgs args = createInstallArgs(this); 9531 mArgs = args; 9532 9533 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9534 /* 9535 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9536 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9537 */ 9538 int userIdentifier = getUser().getIdentifier(); 9539 if (userIdentifier == UserHandle.USER_ALL 9540 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9541 userIdentifier = UserHandle.USER_OWNER; 9542 } 9543 9544 /* 9545 * Determine if we have any installed package verifiers. If we 9546 * do, then we'll defer to them to verify the packages. 9547 */ 9548 final int requiredUid = mRequiredVerifierPackage == null ? -1 9549 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9550 if (!origin.existing && requiredUid != -1 9551 && isVerificationEnabled(userIdentifier, installFlags)) { 9552 final Intent verification = new Intent( 9553 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9554 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9555 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9556 PACKAGE_MIME_TYPE); 9557 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9558 9559 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9560 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9561 0 /* TODO: Which userId? */); 9562 9563 if (DEBUG_VERIFY) { 9564 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9565 + verification.toString() + " with " + pkgLite.verifiers.length 9566 + " optional verifiers"); 9567 } 9568 9569 final int verificationId = mPendingVerificationToken++; 9570 9571 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9572 9573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9574 installerPackageName); 9575 9576 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9577 installFlags); 9578 9579 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9580 pkgLite.packageName); 9581 9582 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9583 pkgLite.versionCode); 9584 9585 if (verificationParams != null) { 9586 if (verificationParams.getVerificationURI() != null) { 9587 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9588 verificationParams.getVerificationURI()); 9589 } 9590 if (verificationParams.getOriginatingURI() != null) { 9591 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9592 verificationParams.getOriginatingURI()); 9593 } 9594 if (verificationParams.getReferrer() != null) { 9595 verification.putExtra(Intent.EXTRA_REFERRER, 9596 verificationParams.getReferrer()); 9597 } 9598 if (verificationParams.getOriginatingUid() >= 0) { 9599 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9600 verificationParams.getOriginatingUid()); 9601 } 9602 if (verificationParams.getInstallerUid() >= 0) { 9603 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9604 verificationParams.getInstallerUid()); 9605 } 9606 } 9607 9608 final PackageVerificationState verificationState = new PackageVerificationState( 9609 requiredUid, args); 9610 9611 mPendingVerification.append(verificationId, verificationState); 9612 9613 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9614 receivers, verificationState); 9615 9616 /* 9617 * If any sufficient verifiers were listed in the package 9618 * manifest, attempt to ask them. 9619 */ 9620 if (sufficientVerifiers != null) { 9621 final int N = sufficientVerifiers.size(); 9622 if (N == 0) { 9623 Slog.i(TAG, "Additional verifiers required, but none installed."); 9624 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9625 } else { 9626 for (int i = 0; i < N; i++) { 9627 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9628 9629 final Intent sufficientIntent = new Intent(verification); 9630 sufficientIntent.setComponent(verifierComponent); 9631 9632 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9633 } 9634 } 9635 } 9636 9637 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9638 mRequiredVerifierPackage, receivers); 9639 if (ret == PackageManager.INSTALL_SUCCEEDED 9640 && mRequiredVerifierPackage != null) { 9641 /* 9642 * Send the intent to the required verification agent, 9643 * but only start the verification timeout after the 9644 * target BroadcastReceivers have run. 9645 */ 9646 verification.setComponent(requiredVerifierComponent); 9647 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9648 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9649 new BroadcastReceiver() { 9650 @Override 9651 public void onReceive(Context context, Intent intent) { 9652 final Message msg = mHandler 9653 .obtainMessage(CHECK_PENDING_VERIFICATION); 9654 msg.arg1 = verificationId; 9655 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9656 } 9657 }, null, 0, null, null); 9658 9659 /* 9660 * We don't want the copy to proceed until verification 9661 * succeeds, so null out this field. 9662 */ 9663 mArgs = null; 9664 } 9665 } else { 9666 /* 9667 * No package verification is enabled, so immediately start 9668 * the remote call to initiate copy using temporary file. 9669 */ 9670 ret = args.copyApk(mContainerService, true); 9671 } 9672 } 9673 9674 mRet = ret; 9675 } 9676 9677 @Override 9678 void handleReturnCode() { 9679 // If mArgs is null, then MCS couldn't be reached. When it 9680 // reconnects, it will try again to install. At that point, this 9681 // will succeed. 9682 if (mArgs != null) { 9683 processPendingInstall(mArgs, mRet); 9684 } 9685 } 9686 9687 @Override 9688 void handleServiceError() { 9689 mArgs = createInstallArgs(this); 9690 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9691 } 9692 9693 public boolean isForwardLocked() { 9694 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9695 } 9696 } 9697 9698 /** 9699 * Used during creation of InstallArgs 9700 * 9701 * @param installFlags package installation flags 9702 * @return true if should be installed on external storage 9703 */ 9704 private static boolean installOnSd(int installFlags) { 9705 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9706 return false; 9707 } 9708 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9709 return true; 9710 } 9711 return false; 9712 } 9713 9714 /** 9715 * Used during creation of InstallArgs 9716 * 9717 * @param installFlags package installation flags 9718 * @return true if should be installed as forward locked 9719 */ 9720 private static boolean installForwardLocked(int installFlags) { 9721 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9722 } 9723 9724 private InstallArgs createInstallArgs(InstallParams params) { 9725 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9726 return new AsecInstallArgs(params); 9727 } else { 9728 return new FileInstallArgs(params); 9729 } 9730 } 9731 9732 /** 9733 * Create args that describe an existing installed package. Typically used 9734 * when cleaning up old installs, or used as a move source. 9735 */ 9736 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9737 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9738 final boolean isInAsec; 9739 if (installOnSd(installFlags)) { 9740 /* Apps on SD card are always in ASEC containers. */ 9741 isInAsec = true; 9742 } else if (installForwardLocked(installFlags) 9743 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9744 /* 9745 * Forward-locked apps are only in ASEC containers if they're the 9746 * new style 9747 */ 9748 isInAsec = true; 9749 } else { 9750 isInAsec = false; 9751 } 9752 9753 if (isInAsec) { 9754 return new AsecInstallArgs(codePath, instructionSets, 9755 installOnSd(installFlags), installForwardLocked(installFlags)); 9756 } else { 9757 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9758 instructionSets); 9759 } 9760 } 9761 9762 static abstract class InstallArgs { 9763 /** @see InstallParams#origin */ 9764 final OriginInfo origin; 9765 9766 final IPackageInstallObserver2 observer; 9767 // Always refers to PackageManager flags only 9768 final int installFlags; 9769 final String installerPackageName; 9770 final ManifestDigest manifestDigest; 9771 final UserHandle user; 9772 final String abiOverride; 9773 9774 // The list of instruction sets supported by this app. This is currently 9775 // only used during the rmdex() phase to clean up resources. We can get rid of this 9776 // if we move dex files under the common app path. 9777 /* nullable */ String[] instructionSets; 9778 9779 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9780 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9781 String[] instructionSets, String abiOverride) { 9782 this.origin = origin; 9783 this.installFlags = installFlags; 9784 this.observer = observer; 9785 this.installerPackageName = installerPackageName; 9786 this.manifestDigest = manifestDigest; 9787 this.user = user; 9788 this.instructionSets = instructionSets; 9789 this.abiOverride = abiOverride; 9790 } 9791 9792 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9793 abstract int doPreInstall(int status); 9794 9795 /** 9796 * Rename package into final resting place. All paths on the given 9797 * scanned package should be updated to reflect the rename. 9798 */ 9799 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9800 abstract int doPostInstall(int status, int uid); 9801 9802 /** @see PackageSettingBase#codePathString */ 9803 abstract String getCodePath(); 9804 /** @see PackageSettingBase#resourcePathString */ 9805 abstract String getResourcePath(); 9806 abstract String getLegacyNativeLibraryPath(); 9807 9808 // Need installer lock especially for dex file removal. 9809 abstract void cleanUpResourcesLI(); 9810 abstract boolean doPostDeleteLI(boolean delete); 9811 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9812 9813 /** 9814 * Called before the source arguments are copied. This is used mostly 9815 * for MoveParams when it needs to read the source file to put it in the 9816 * destination. 9817 */ 9818 int doPreCopy() { 9819 return PackageManager.INSTALL_SUCCEEDED; 9820 } 9821 9822 /** 9823 * Called after the source arguments are copied. This is used mostly for 9824 * MoveParams when it needs to read the source file to put it in the 9825 * destination. 9826 * 9827 * @return 9828 */ 9829 int doPostCopy(int uid) { 9830 return PackageManager.INSTALL_SUCCEEDED; 9831 } 9832 9833 protected boolean isFwdLocked() { 9834 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9835 } 9836 9837 protected boolean isExternal() { 9838 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9839 } 9840 9841 UserHandle getUser() { 9842 return user; 9843 } 9844 } 9845 9846 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9847 if (!allCodePaths.isEmpty()) { 9848 if (instructionSets == null) { 9849 throw new IllegalStateException("instructionSet == null"); 9850 } 9851 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9852 for (String codePath : allCodePaths) { 9853 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9854 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9855 if (retCode < 0) { 9856 Slog.w(TAG, "Couldn't remove dex file for package: " 9857 + " at location " + codePath + ", retcode=" + retCode); 9858 // we don't consider this to be a failure of the core package deletion 9859 } 9860 } 9861 } 9862 } 9863 } 9864 9865 /** 9866 * Logic to handle installation of non-ASEC applications, including copying 9867 * and renaming logic. 9868 */ 9869 class FileInstallArgs extends InstallArgs { 9870 private File codeFile; 9871 private File resourceFile; 9872 private File legacyNativeLibraryPath; 9873 9874 // Example topology: 9875 // /data/app/com.example/base.apk 9876 // /data/app/com.example/split_foo.apk 9877 // /data/app/com.example/lib/arm/libfoo.so 9878 // /data/app/com.example/lib/arm64/libfoo.so 9879 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9880 9881 /** New install */ 9882 FileInstallArgs(InstallParams params) { 9883 super(params.origin, params.observer, params.installFlags, 9884 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9885 null /* instruction sets */, params.packageAbiOverride); 9886 if (isFwdLocked()) { 9887 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9888 } 9889 } 9890 9891 /** Existing install */ 9892 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9893 String[] instructionSets) { 9894 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9895 this.codeFile = (codePath != null) ? new File(codePath) : null; 9896 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9897 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9898 new File(legacyNativeLibraryPath) : null; 9899 } 9900 9901 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9902 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9903 isFwdLocked(), abiOverride); 9904 9905 final StorageManager storage = StorageManager.from(mContext); 9906 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9907 } 9908 9909 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9910 if (origin.staged) { 9911 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9912 codeFile = origin.file; 9913 resourceFile = origin.file; 9914 return PackageManager.INSTALL_SUCCEEDED; 9915 } 9916 9917 try { 9918 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9919 codeFile = tempDir; 9920 resourceFile = tempDir; 9921 } catch (IOException e) { 9922 Slog.w(TAG, "Failed to create copy file: " + e); 9923 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9924 } 9925 9926 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9927 @Override 9928 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9929 if (!FileUtils.isValidExtFilename(name)) { 9930 throw new IllegalArgumentException("Invalid filename: " + name); 9931 } 9932 try { 9933 final File file = new File(codeFile, name); 9934 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9935 O_RDWR | O_CREAT, 0644); 9936 Os.chmod(file.getAbsolutePath(), 0644); 9937 return new ParcelFileDescriptor(fd); 9938 } catch (ErrnoException e) { 9939 throw new RemoteException("Failed to open: " + e.getMessage()); 9940 } 9941 } 9942 }; 9943 9944 int ret = PackageManager.INSTALL_SUCCEEDED; 9945 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9946 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9947 Slog.e(TAG, "Failed to copy package"); 9948 return ret; 9949 } 9950 9951 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9952 NativeLibraryHelper.Handle handle = null; 9953 try { 9954 handle = NativeLibraryHelper.Handle.create(codeFile); 9955 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9956 abiOverride); 9957 } catch (IOException e) { 9958 Slog.e(TAG, "Copying native libraries failed", e); 9959 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9960 } finally { 9961 IoUtils.closeQuietly(handle); 9962 } 9963 9964 return ret; 9965 } 9966 9967 int doPreInstall(int status) { 9968 if (status != PackageManager.INSTALL_SUCCEEDED) { 9969 cleanUp(); 9970 } 9971 return status; 9972 } 9973 9974 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9975 if (status != PackageManager.INSTALL_SUCCEEDED) { 9976 cleanUp(); 9977 return false; 9978 } else { 9979 final File beforeCodeFile = codeFile; 9980 final File afterCodeFile = getNextCodePath(pkg.packageName); 9981 9982 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9983 try { 9984 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9985 } catch (ErrnoException e) { 9986 Slog.d(TAG, "Failed to rename", e); 9987 return false; 9988 } 9989 9990 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9991 Slog.d(TAG, "Failed to restorecon"); 9992 return false; 9993 } 9994 9995 // Reflect the rename internally 9996 codeFile = afterCodeFile; 9997 resourceFile = afterCodeFile; 9998 9999 // Reflect the rename in scanned details 10000 pkg.codePath = afterCodeFile.getAbsolutePath(); 10001 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10002 pkg.baseCodePath); 10003 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10004 pkg.splitCodePaths); 10005 10006 // Reflect the rename in app info 10007 pkg.applicationInfo.setCodePath(pkg.codePath); 10008 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10009 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10010 pkg.applicationInfo.setResourcePath(pkg.codePath); 10011 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10012 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10013 10014 return true; 10015 } 10016 } 10017 10018 int doPostInstall(int status, int uid) { 10019 if (status != PackageManager.INSTALL_SUCCEEDED) { 10020 cleanUp(); 10021 } 10022 return status; 10023 } 10024 10025 @Override 10026 String getCodePath() { 10027 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10028 } 10029 10030 @Override 10031 String getResourcePath() { 10032 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10033 } 10034 10035 @Override 10036 String getLegacyNativeLibraryPath() { 10037 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10038 } 10039 10040 private boolean cleanUp() { 10041 if (codeFile == null || !codeFile.exists()) { 10042 return false; 10043 } 10044 10045 if (codeFile.isDirectory()) { 10046 FileUtils.deleteContents(codeFile); 10047 } 10048 codeFile.delete(); 10049 10050 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10051 resourceFile.delete(); 10052 } 10053 10054 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10055 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10056 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10057 } 10058 legacyNativeLibraryPath.delete(); 10059 } 10060 10061 return true; 10062 } 10063 10064 void cleanUpResourcesLI() { 10065 // Try enumerating all code paths before deleting 10066 List<String> allCodePaths = Collections.EMPTY_LIST; 10067 if (codeFile != null && codeFile.exists()) { 10068 try { 10069 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10070 allCodePaths = pkg.getAllCodePaths(); 10071 } catch (PackageParserException e) { 10072 // Ignored; we tried our best 10073 } 10074 } 10075 10076 cleanUp(); 10077 removeDexFiles(allCodePaths, instructionSets); 10078 } 10079 10080 boolean doPostDeleteLI(boolean delete) { 10081 // XXX err, shouldn't we respect the delete flag? 10082 cleanUpResourcesLI(); 10083 return true; 10084 } 10085 } 10086 10087 private boolean isAsecExternal(String cid) { 10088 final String asecPath = PackageHelper.getSdFilesystem(cid); 10089 return !asecPath.startsWith(mAsecInternalPath); 10090 } 10091 10092 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10093 PackageManagerException { 10094 if (copyRet < 0) { 10095 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10096 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10097 throw new PackageManagerException(copyRet, message); 10098 } 10099 } 10100 } 10101 10102 /** 10103 * Extract the MountService "container ID" from the full code path of an 10104 * .apk. 10105 */ 10106 static String cidFromCodePath(String fullCodePath) { 10107 int eidx = fullCodePath.lastIndexOf("/"); 10108 String subStr1 = fullCodePath.substring(0, eidx); 10109 int sidx = subStr1.lastIndexOf("/"); 10110 return subStr1.substring(sidx+1, eidx); 10111 } 10112 10113 /** 10114 * Logic to handle installation of ASEC applications, including copying and 10115 * renaming logic. 10116 */ 10117 class AsecInstallArgs extends InstallArgs { 10118 static final String RES_FILE_NAME = "pkg.apk"; 10119 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10120 10121 String cid; 10122 String packagePath; 10123 String resourcePath; 10124 String legacyNativeLibraryDir; 10125 10126 /** New install */ 10127 AsecInstallArgs(InstallParams params) { 10128 super(params.origin, params.observer, params.installFlags, 10129 params.installerPackageName, params.getManifestDigest(), 10130 params.getUser(), null /* instruction sets */, 10131 params.packageAbiOverride); 10132 } 10133 10134 /** Existing install */ 10135 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10136 boolean isExternal, boolean isForwardLocked) { 10137 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10138 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10139 instructionSets, null); 10140 // Hackily pretend we're still looking at a full code path 10141 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10142 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10143 } 10144 10145 // Extract cid from fullCodePath 10146 int eidx = fullCodePath.lastIndexOf("/"); 10147 String subStr1 = fullCodePath.substring(0, eidx); 10148 int sidx = subStr1.lastIndexOf("/"); 10149 cid = subStr1.substring(sidx+1, eidx); 10150 setMountPath(subStr1); 10151 } 10152 10153 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10154 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10155 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 10156 instructionSets, null); 10157 this.cid = cid; 10158 setMountPath(PackageHelper.getSdDir(cid)); 10159 } 10160 10161 void createCopyFile() { 10162 cid = mInstallerService.allocateExternalStageCidLegacy(); 10163 } 10164 10165 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10166 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10167 abiOverride); 10168 10169 final File target; 10170 if (isExternal()) { 10171 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10172 } else { 10173 target = Environment.getDataDirectory(); 10174 } 10175 10176 final StorageManager storage = StorageManager.from(mContext); 10177 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10178 } 10179 10180 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10181 if (origin.staged) { 10182 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10183 cid = origin.cid; 10184 setMountPath(PackageHelper.getSdDir(cid)); 10185 return PackageManager.INSTALL_SUCCEEDED; 10186 } 10187 10188 if (temp) { 10189 createCopyFile(); 10190 } else { 10191 /* 10192 * Pre-emptively destroy the container since it's destroyed if 10193 * copying fails due to it existing anyway. 10194 */ 10195 PackageHelper.destroySdDir(cid); 10196 } 10197 10198 final String newMountPath = imcs.copyPackageToContainer( 10199 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 10200 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10201 10202 if (newMountPath != null) { 10203 setMountPath(newMountPath); 10204 return PackageManager.INSTALL_SUCCEEDED; 10205 } else { 10206 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10207 } 10208 } 10209 10210 @Override 10211 String getCodePath() { 10212 return packagePath; 10213 } 10214 10215 @Override 10216 String getResourcePath() { 10217 return resourcePath; 10218 } 10219 10220 @Override 10221 String getLegacyNativeLibraryPath() { 10222 return legacyNativeLibraryDir; 10223 } 10224 10225 int doPreInstall(int status) { 10226 if (status != PackageManager.INSTALL_SUCCEEDED) { 10227 // Destroy container 10228 PackageHelper.destroySdDir(cid); 10229 } else { 10230 boolean mounted = PackageHelper.isContainerMounted(cid); 10231 if (!mounted) { 10232 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10233 Process.SYSTEM_UID); 10234 if (newMountPath != null) { 10235 setMountPath(newMountPath); 10236 } else { 10237 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10238 } 10239 } 10240 } 10241 return status; 10242 } 10243 10244 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10245 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10246 String newMountPath = null; 10247 if (PackageHelper.isContainerMounted(cid)) { 10248 // Unmount the container 10249 if (!PackageHelper.unMountSdDir(cid)) { 10250 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10251 return false; 10252 } 10253 } 10254 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10255 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10256 " which might be stale. Will try to clean up."); 10257 // Clean up the stale container and proceed to recreate. 10258 if (!PackageHelper.destroySdDir(newCacheId)) { 10259 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10260 return false; 10261 } 10262 // Successfully cleaned up stale container. Try to rename again. 10263 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10264 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10265 + " inspite of cleaning it up."); 10266 return false; 10267 } 10268 } 10269 if (!PackageHelper.isContainerMounted(newCacheId)) { 10270 Slog.w(TAG, "Mounting container " + newCacheId); 10271 newMountPath = PackageHelper.mountSdDir(newCacheId, 10272 getEncryptKey(), Process.SYSTEM_UID); 10273 } else { 10274 newMountPath = PackageHelper.getSdDir(newCacheId); 10275 } 10276 if (newMountPath == null) { 10277 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10278 return false; 10279 } 10280 Log.i(TAG, "Succesfully renamed " + cid + 10281 " to " + newCacheId + 10282 " at new path: " + newMountPath); 10283 cid = newCacheId; 10284 10285 final File beforeCodeFile = new File(packagePath); 10286 setMountPath(newMountPath); 10287 final File afterCodeFile = new File(packagePath); 10288 10289 // Reflect the rename in scanned details 10290 pkg.codePath = afterCodeFile.getAbsolutePath(); 10291 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10292 pkg.baseCodePath); 10293 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10294 pkg.splitCodePaths); 10295 10296 // Reflect the rename in app info 10297 pkg.applicationInfo.setCodePath(pkg.codePath); 10298 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10299 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10300 pkg.applicationInfo.setResourcePath(pkg.codePath); 10301 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10302 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10303 10304 return true; 10305 } 10306 10307 private void setMountPath(String mountPath) { 10308 final File mountFile = new File(mountPath); 10309 10310 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10311 if (monolithicFile.exists()) { 10312 packagePath = monolithicFile.getAbsolutePath(); 10313 if (isFwdLocked()) { 10314 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10315 } else { 10316 resourcePath = packagePath; 10317 } 10318 } else { 10319 packagePath = mountFile.getAbsolutePath(); 10320 resourcePath = packagePath; 10321 } 10322 10323 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10324 } 10325 10326 int doPostInstall(int status, int uid) { 10327 if (status != PackageManager.INSTALL_SUCCEEDED) { 10328 cleanUp(); 10329 } else { 10330 final int groupOwner; 10331 final String protectedFile; 10332 if (isFwdLocked()) { 10333 groupOwner = UserHandle.getSharedAppGid(uid); 10334 protectedFile = RES_FILE_NAME; 10335 } else { 10336 groupOwner = -1; 10337 protectedFile = null; 10338 } 10339 10340 if (uid < Process.FIRST_APPLICATION_UID 10341 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10342 Slog.e(TAG, "Failed to finalize " + cid); 10343 PackageHelper.destroySdDir(cid); 10344 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10345 } 10346 10347 boolean mounted = PackageHelper.isContainerMounted(cid); 10348 if (!mounted) { 10349 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10350 } 10351 } 10352 return status; 10353 } 10354 10355 private void cleanUp() { 10356 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10357 10358 // Destroy secure container 10359 PackageHelper.destroySdDir(cid); 10360 } 10361 10362 private List<String> getAllCodePaths() { 10363 final File codeFile = new File(getCodePath()); 10364 if (codeFile != null && codeFile.exists()) { 10365 try { 10366 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10367 return pkg.getAllCodePaths(); 10368 } catch (PackageParserException e) { 10369 // Ignored; we tried our best 10370 } 10371 } 10372 return Collections.EMPTY_LIST; 10373 } 10374 10375 void cleanUpResourcesLI() { 10376 // Enumerate all code paths before deleting 10377 cleanUpResourcesLI(getAllCodePaths()); 10378 } 10379 10380 private void cleanUpResourcesLI(List<String> allCodePaths) { 10381 cleanUp(); 10382 removeDexFiles(allCodePaths, instructionSets); 10383 } 10384 10385 10386 10387 String getPackageName() { 10388 return getAsecPackageName(cid); 10389 } 10390 10391 boolean doPostDeleteLI(boolean delete) { 10392 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10393 final List<String> allCodePaths = getAllCodePaths(); 10394 boolean mounted = PackageHelper.isContainerMounted(cid); 10395 if (mounted) { 10396 // Unmount first 10397 if (PackageHelper.unMountSdDir(cid)) { 10398 mounted = false; 10399 } 10400 } 10401 if (!mounted && delete) { 10402 cleanUpResourcesLI(allCodePaths); 10403 } 10404 return !mounted; 10405 } 10406 10407 @Override 10408 int doPreCopy() { 10409 if (isFwdLocked()) { 10410 if (!PackageHelper.fixSdPermissions(cid, 10411 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10412 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10413 } 10414 } 10415 10416 return PackageManager.INSTALL_SUCCEEDED; 10417 } 10418 10419 @Override 10420 int doPostCopy(int uid) { 10421 if (isFwdLocked()) { 10422 if (uid < Process.FIRST_APPLICATION_UID 10423 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10424 RES_FILE_NAME)) { 10425 Slog.e(TAG, "Failed to finalize " + cid); 10426 PackageHelper.destroySdDir(cid); 10427 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10428 } 10429 } 10430 10431 return PackageManager.INSTALL_SUCCEEDED; 10432 } 10433 } 10434 10435 static String getAsecPackageName(String packageCid) { 10436 int idx = packageCid.lastIndexOf("-"); 10437 if (idx == -1) { 10438 return packageCid; 10439 } 10440 return packageCid.substring(0, idx); 10441 } 10442 10443 // Utility method used to create code paths based on package name and available index. 10444 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10445 String idxStr = ""; 10446 int idx = 1; 10447 // Fall back to default value of idx=1 if prefix is not 10448 // part of oldCodePath 10449 if (oldCodePath != null) { 10450 String subStr = oldCodePath; 10451 // Drop the suffix right away 10452 if (suffix != null && subStr.endsWith(suffix)) { 10453 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10454 } 10455 // If oldCodePath already contains prefix find out the 10456 // ending index to either increment or decrement. 10457 int sidx = subStr.lastIndexOf(prefix); 10458 if (sidx != -1) { 10459 subStr = subStr.substring(sidx + prefix.length()); 10460 if (subStr != null) { 10461 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10462 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10463 } 10464 try { 10465 idx = Integer.parseInt(subStr); 10466 if (idx <= 1) { 10467 idx++; 10468 } else { 10469 idx--; 10470 } 10471 } catch(NumberFormatException e) { 10472 } 10473 } 10474 } 10475 } 10476 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10477 return prefix + idxStr; 10478 } 10479 10480 private File getNextCodePath(String packageName) { 10481 int suffix = 1; 10482 File result; 10483 do { 10484 result = new File(mAppInstallDir, packageName + "-" + suffix); 10485 suffix++; 10486 } while (result.exists()); 10487 return result; 10488 } 10489 10490 // Utility method used to ignore ADD/REMOVE events 10491 // by directory observer. 10492 private static boolean ignoreCodePath(String fullPathStr) { 10493 String apkName = deriveCodePathName(fullPathStr); 10494 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10495 if (idx != -1 && ((idx+1) < apkName.length())) { 10496 // Make sure the package ends with a numeral 10497 String version = apkName.substring(idx+1); 10498 try { 10499 Integer.parseInt(version); 10500 return true; 10501 } catch (NumberFormatException e) {} 10502 } 10503 return false; 10504 } 10505 10506 // Utility method that returns the relative package path with respect 10507 // to the installation directory. Like say for /data/data/com.test-1.apk 10508 // string com.test-1 is returned. 10509 static String deriveCodePathName(String codePath) { 10510 if (codePath == null) { 10511 return null; 10512 } 10513 final File codeFile = new File(codePath); 10514 final String name = codeFile.getName(); 10515 if (codeFile.isDirectory()) { 10516 return name; 10517 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10518 final int lastDot = name.lastIndexOf('.'); 10519 return name.substring(0, lastDot); 10520 } else { 10521 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10522 return null; 10523 } 10524 } 10525 10526 class PackageInstalledInfo { 10527 String name; 10528 int uid; 10529 // The set of users that originally had this package installed. 10530 int[] origUsers; 10531 // The set of users that now have this package installed. 10532 int[] newUsers; 10533 PackageParser.Package pkg; 10534 int returnCode; 10535 String returnMsg; 10536 PackageRemovedInfo removedInfo; 10537 10538 public void setError(int code, String msg) { 10539 returnCode = code; 10540 returnMsg = msg; 10541 Slog.w(TAG, msg); 10542 } 10543 10544 public void setError(String msg, PackageParserException e) { 10545 returnCode = e.error; 10546 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10547 Slog.w(TAG, msg, e); 10548 } 10549 10550 public void setError(String msg, PackageManagerException e) { 10551 returnCode = e.error; 10552 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10553 Slog.w(TAG, msg, e); 10554 } 10555 10556 // In some error cases we want to convey more info back to the observer 10557 String origPackage; 10558 String origPermission; 10559 } 10560 10561 /* 10562 * Install a non-existing package. 10563 */ 10564 private void installNewPackageLI(PackageParser.Package pkg, 10565 int parseFlags, int scanFlags, UserHandle user, 10566 String installerPackageName, PackageInstalledInfo res) { 10567 // Remember this for later, in case we need to rollback this install 10568 String pkgName = pkg.packageName; 10569 10570 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10571 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10572 synchronized(mPackages) { 10573 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10574 // A package with the same name is already installed, though 10575 // it has been renamed to an older name. The package we 10576 // are trying to install should be installed as an update to 10577 // the existing one, but that has not been requested, so bail. 10578 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10579 + " without first uninstalling package running as " 10580 + mSettings.mRenamedPackages.get(pkgName)); 10581 return; 10582 } 10583 if (mPackages.containsKey(pkgName)) { 10584 // Don't allow installation over an existing package with the same name. 10585 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10586 + " without first uninstalling."); 10587 return; 10588 } 10589 } 10590 10591 try { 10592 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10593 System.currentTimeMillis(), user); 10594 10595 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 10596 // delete the partially installed application. the data directory will have to be 10597 // restored if it was already existing 10598 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10599 // remove package from internal structures. Note that we want deletePackageX to 10600 // delete the package data and cache directories that it created in 10601 // scanPackageLocked, unless those directories existed before we even tried to 10602 // install. 10603 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10604 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10605 res.removedInfo, true); 10606 } 10607 10608 } catch (PackageManagerException e) { 10609 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10610 } 10611 } 10612 10613 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10614 // Upgrade keysets are being used. Determine if new package has a superset of the 10615 // required keys. 10616 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10617 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10618 for (int i = 0; i < upgradeKeySets.length; i++) { 10619 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10620 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10621 return true; 10622 } 10623 } 10624 return false; 10625 } 10626 10627 private void replacePackageLI(PackageParser.Package pkg, 10628 int parseFlags, int scanFlags, UserHandle user, 10629 String installerPackageName, PackageInstalledInfo res) { 10630 PackageParser.Package oldPackage; 10631 String pkgName = pkg.packageName; 10632 int[] allUsers; 10633 boolean[] perUserInstalled; 10634 10635 // First find the old package info and check signatures 10636 synchronized(mPackages) { 10637 oldPackage = mPackages.get(pkgName); 10638 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10639 PackageSetting ps = mSettings.mPackages.get(pkgName); 10640 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10641 // default to original signature matching 10642 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10643 != PackageManager.SIGNATURE_MATCH) { 10644 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10645 "New package has a different signature: " + pkgName); 10646 return; 10647 } 10648 } else { 10649 if(!checkUpgradeKeySetLP(ps, pkg)) { 10650 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10651 "New package not signed by keys specified by upgrade-keysets: " 10652 + pkgName); 10653 return; 10654 } 10655 } 10656 10657 // In case of rollback, remember per-user/profile install state 10658 allUsers = sUserManager.getUserIds(); 10659 perUserInstalled = new boolean[allUsers.length]; 10660 for (int i = 0; i < allUsers.length; i++) { 10661 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10662 } 10663 } 10664 10665 boolean sysPkg = (isSystemApp(oldPackage)); 10666 if (sysPkg) { 10667 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10668 user, allUsers, perUserInstalled, installerPackageName, res); 10669 } else { 10670 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10671 user, allUsers, perUserInstalled, installerPackageName, res); 10672 } 10673 } 10674 10675 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10676 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10677 int[] allUsers, boolean[] perUserInstalled, 10678 String installerPackageName, PackageInstalledInfo res) { 10679 String pkgName = deletedPackage.packageName; 10680 boolean deletedPkg = true; 10681 boolean updatedSettings = false; 10682 10683 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10684 + deletedPackage); 10685 long origUpdateTime; 10686 if (pkg.mExtras != null) { 10687 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10688 } else { 10689 origUpdateTime = 0; 10690 } 10691 10692 // First delete the existing package while retaining the data directory 10693 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10694 res.removedInfo, true)) { 10695 // If the existing package wasn't successfully deleted 10696 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10697 deletedPkg = false; 10698 } else { 10699 // Successfully deleted the old package; proceed with replace. 10700 10701 // If deleted package lived in a container, give users a chance to 10702 // relinquish resources before killing. 10703 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10704 if (DEBUG_INSTALL) { 10705 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10706 } 10707 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10708 final ArrayList<String> pkgList = new ArrayList<String>(1); 10709 pkgList.add(deletedPackage.applicationInfo.packageName); 10710 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10711 } 10712 10713 deleteCodeCacheDirsLI(pkgName); 10714 try { 10715 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10716 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10717 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10718 user); 10719 updatedSettings = true; 10720 } catch (PackageManagerException e) { 10721 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10722 } 10723 } 10724 10725 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10726 // remove package from internal structures. Note that we want deletePackageX to 10727 // delete the package data and cache directories that it created in 10728 // scanPackageLocked, unless those directories existed before we even tried to 10729 // install. 10730 if(updatedSettings) { 10731 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10732 deletePackageLI( 10733 pkgName, null, true, allUsers, perUserInstalled, 10734 PackageManager.DELETE_KEEP_DATA, 10735 res.removedInfo, true); 10736 } 10737 // Since we failed to install the new package we need to restore the old 10738 // package that we deleted. 10739 if (deletedPkg) { 10740 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10741 File restoreFile = new File(deletedPackage.codePath); 10742 // Parse old package 10743 boolean oldOnSd = isExternal(deletedPackage); 10744 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10745 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10746 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10747 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10748 try { 10749 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10750 } catch (PackageManagerException e) { 10751 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10752 + e.getMessage()); 10753 return; 10754 } 10755 // Restore of old package succeeded. Update permissions. 10756 // writer 10757 synchronized (mPackages) { 10758 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10759 UPDATE_PERMISSIONS_ALL); 10760 // can downgrade to reader 10761 mSettings.writeLPr(); 10762 } 10763 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10764 } 10765 } 10766 } 10767 10768 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10769 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10770 int[] allUsers, boolean[] perUserInstalled, 10771 String installerPackageName, PackageInstalledInfo res) { 10772 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10773 + ", old=" + deletedPackage); 10774 boolean disabledSystem = false; 10775 boolean updatedSettings = false; 10776 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10777 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10778 != 0) { 10779 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10780 } 10781 String packageName = deletedPackage.packageName; 10782 if (packageName == null) { 10783 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10784 "Attempt to delete null packageName."); 10785 return; 10786 } 10787 PackageParser.Package oldPkg; 10788 PackageSetting oldPkgSetting; 10789 // reader 10790 synchronized (mPackages) { 10791 oldPkg = mPackages.get(packageName); 10792 oldPkgSetting = mSettings.mPackages.get(packageName); 10793 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10794 (oldPkgSetting == null)) { 10795 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10796 "Couldn't find package:" + packageName + " information"); 10797 return; 10798 } 10799 } 10800 10801 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10802 10803 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10804 res.removedInfo.removedPackage = packageName; 10805 // Remove existing system package 10806 removePackageLI(oldPkgSetting, true); 10807 // writer 10808 synchronized (mPackages) { 10809 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10810 if (!disabledSystem && deletedPackage != null) { 10811 // We didn't need to disable the .apk as a current system package, 10812 // which means we are replacing another update that is already 10813 // installed. We need to make sure to delete the older one's .apk. 10814 res.removedInfo.args = createInstallArgsForExisting(0, 10815 deletedPackage.applicationInfo.getCodePath(), 10816 deletedPackage.applicationInfo.getResourcePath(), 10817 deletedPackage.applicationInfo.nativeLibraryRootDir, 10818 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10819 } else { 10820 res.removedInfo.args = null; 10821 } 10822 } 10823 10824 // Successfully disabled the old package. Now proceed with re-installation 10825 deleteCodeCacheDirsLI(packageName); 10826 10827 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10828 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10829 10830 PackageParser.Package newPackage = null; 10831 try { 10832 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10833 if (newPackage.mExtras != null) { 10834 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10835 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10836 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10837 10838 // is the update attempting to change shared user? that isn't going to work... 10839 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10840 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10841 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10842 + " to " + newPkgSetting.sharedUser); 10843 updatedSettings = true; 10844 } 10845 } 10846 10847 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10848 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res, 10849 user); 10850 updatedSettings = true; 10851 } 10852 10853 } catch (PackageManagerException e) { 10854 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10855 } 10856 10857 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10858 // Re installation failed. Restore old information 10859 // Remove new pkg information 10860 if (newPackage != null) { 10861 removeInstalledPackageLI(newPackage, true); 10862 } 10863 // Add back the old system package 10864 try { 10865 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10866 } catch (PackageManagerException e) { 10867 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10868 } 10869 // Restore the old system information in Settings 10870 synchronized (mPackages) { 10871 if (disabledSystem) { 10872 mSettings.enableSystemPackageLPw(packageName); 10873 } 10874 if (updatedSettings) { 10875 mSettings.setInstallerPackageName(packageName, 10876 oldPkgSetting.installerPackageName); 10877 } 10878 mSettings.writeLPr(); 10879 } 10880 } 10881 } 10882 10883 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10884 int[] allUsers, boolean[] perUserInstalled, 10885 PackageInstalledInfo res, UserHandle user) { 10886 String pkgName = newPackage.packageName; 10887 synchronized (mPackages) { 10888 //write settings. the installStatus will be incomplete at this stage. 10889 //note that the new package setting would have already been 10890 //added to mPackages. It hasn't been persisted yet. 10891 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10892 mSettings.writeLPr(); 10893 } 10894 10895 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10896 10897 synchronized (mPackages) { 10898 updatePermissionsLPw(newPackage.packageName, newPackage, 10899 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10900 ? UPDATE_PERMISSIONS_ALL : 0)); 10901 // For system-bundled packages, we assume that installing an upgraded version 10902 // of the package implies that the user actually wants to run that new code, 10903 // so we enable the package. 10904 PackageSetting ps = mSettings.mPackages.get(pkgName); 10905 if (ps != null) { 10906 if (isSystemApp(newPackage)) { 10907 // NB: implicit assumption that system package upgrades apply to all users 10908 if (DEBUG_INSTALL) { 10909 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10910 } 10911 if (res.origUsers != null) { 10912 for (int userHandle : res.origUsers) { 10913 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10914 userHandle, installerPackageName); 10915 } 10916 } 10917 // Also convey the prior install/uninstall state 10918 if (allUsers != null && perUserInstalled != null) { 10919 for (int i = 0; i < allUsers.length; i++) { 10920 if (DEBUG_INSTALL) { 10921 Slog.d(TAG, " user " + allUsers[i] 10922 + " => " + perUserInstalled[i]); 10923 } 10924 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10925 } 10926 // these install state changes will be persisted in the 10927 // upcoming call to mSettings.writeLPr(). 10928 } 10929 } 10930 // It's implied that when a user requests installation, they want the app to be 10931 // installed and enabled. 10932 int userId = user.getIdentifier(); 10933 if (userId != UserHandle.USER_ALL) { 10934 ps.setInstalled(true, userId); 10935 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10936 } 10937 } 10938 res.name = pkgName; 10939 res.uid = newPackage.applicationInfo.uid; 10940 res.pkg = newPackage; 10941 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10942 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10943 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10944 //to update install status 10945 mSettings.writeLPr(); 10946 } 10947 } 10948 10949 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10950 final int installFlags = args.installFlags; 10951 String installerPackageName = args.installerPackageName; 10952 File tmpPackageFile = new File(args.getCodePath()); 10953 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10954 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10955 boolean replace = false; 10956 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10957 // Result object to be returned 10958 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10959 10960 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10961 // Retrieve PackageSettings and parse package 10962 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10963 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10964 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10965 PackageParser pp = new PackageParser(); 10966 pp.setSeparateProcesses(mSeparateProcesses); 10967 pp.setDisplayMetrics(mMetrics); 10968 10969 final PackageParser.Package pkg; 10970 try { 10971 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10972 } catch (PackageParserException e) { 10973 res.setError("Failed parse during installPackageLI", e); 10974 return; 10975 } 10976 10977 // Mark that we have an install time CPU ABI override. 10978 pkg.cpuAbiOverride = args.abiOverride; 10979 10980 String pkgName = res.name = pkg.packageName; 10981 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10982 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10983 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10984 return; 10985 } 10986 } 10987 10988 try { 10989 pp.collectCertificates(pkg, parseFlags); 10990 pp.collectManifestDigest(pkg); 10991 } catch (PackageParserException e) { 10992 res.setError("Failed collect during installPackageLI", e); 10993 return; 10994 } 10995 10996 /* If the installer passed in a manifest digest, compare it now. */ 10997 if (args.manifestDigest != null) { 10998 if (DEBUG_INSTALL) { 10999 final String parsedManifest = pkg.manifestDigest == null ? "null" 11000 : pkg.manifestDigest.toString(); 11001 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11002 + parsedManifest); 11003 } 11004 11005 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11006 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11007 return; 11008 } 11009 } else if (DEBUG_INSTALL) { 11010 final String parsedManifest = pkg.manifestDigest == null 11011 ? "null" : pkg.manifestDigest.toString(); 11012 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11013 } 11014 11015 // Get rid of all references to package scan path via parser. 11016 pp = null; 11017 String oldCodePath = null; 11018 boolean systemApp = false; 11019 synchronized (mPackages) { 11020 // Check if installing already existing package 11021 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11022 String oldName = mSettings.mRenamedPackages.get(pkgName); 11023 if (pkg.mOriginalPackages != null 11024 && pkg.mOriginalPackages.contains(oldName) 11025 && mPackages.containsKey(oldName)) { 11026 // This package is derived from an original package, 11027 // and this device has been updating from that original 11028 // name. We must continue using the original name, so 11029 // rename the new package here. 11030 pkg.setPackageName(oldName); 11031 pkgName = pkg.packageName; 11032 replace = true; 11033 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11034 + oldName + " pkgName=" + pkgName); 11035 } else if (mPackages.containsKey(pkgName)) { 11036 // This package, under its official name, already exists 11037 // on the device; we should replace it. 11038 replace = true; 11039 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11040 } 11041 } 11042 11043 PackageSetting ps = mSettings.mPackages.get(pkgName); 11044 if (ps != null) { 11045 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11046 11047 // Quick sanity check that we're signed correctly if updating; 11048 // we'll check this again later when scanning, but we want to 11049 // bail early here before tripping over redefined permissions. 11050 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11051 try { 11052 verifySignaturesLP(ps, pkg); 11053 } catch (PackageManagerException e) { 11054 res.setError(e.error, e.getMessage()); 11055 return; 11056 } 11057 } else { 11058 if (!checkUpgradeKeySetLP(ps, pkg)) { 11059 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11060 + pkg.packageName + " upgrade keys do not match the " 11061 + "previously installed version"); 11062 return; 11063 } 11064 } 11065 11066 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11067 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11068 systemApp = (ps.pkg.applicationInfo.flags & 11069 ApplicationInfo.FLAG_SYSTEM) != 0; 11070 } 11071 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11072 } 11073 11074 // Check whether the newly-scanned package wants to define an already-defined perm 11075 int N = pkg.permissions.size(); 11076 for (int i = N-1; i >= 0; i--) { 11077 PackageParser.Permission perm = pkg.permissions.get(i); 11078 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11079 if (bp != null) { 11080 // If the defining package is signed with our cert, it's okay. This 11081 // also includes the "updating the same package" case, of course. 11082 // "updating same package" could also involve key-rotation. 11083 final boolean sigsOk; 11084 if (!bp.sourcePackage.equals(pkg.packageName) 11085 || !(bp.packageSetting instanceof PackageSetting) 11086 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11087 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11088 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11089 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11090 } else { 11091 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11092 } 11093 if (!sigsOk) { 11094 // If the owning package is the system itself, we log but allow 11095 // install to proceed; we fail the install on all other permission 11096 // redefinitions. 11097 if (!bp.sourcePackage.equals("android")) { 11098 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11099 + pkg.packageName + " attempting to redeclare permission " 11100 + perm.info.name + " already owned by " + bp.sourcePackage); 11101 res.origPermission = perm.info.name; 11102 res.origPackage = bp.sourcePackage; 11103 return; 11104 } else { 11105 Slog.w(TAG, "Package " + pkg.packageName 11106 + " attempting to redeclare system permission " 11107 + perm.info.name + "; ignoring new declaration"); 11108 pkg.permissions.remove(i); 11109 } 11110 } 11111 } 11112 } 11113 11114 } 11115 11116 if (systemApp && onSd) { 11117 // Disable updates to system apps on sdcard 11118 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11119 "Cannot install updates to system apps on sdcard"); 11120 return; 11121 } 11122 11123 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11124 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11125 return; 11126 } 11127 11128 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11129 11130 if (replace) { 11131 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11132 installerPackageName, res); 11133 } else { 11134 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11135 args.user, installerPackageName, res); 11136 } 11137 synchronized (mPackages) { 11138 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11139 if (ps != null) { 11140 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11141 } 11142 } 11143 } 11144 11145 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11146 if (mIntentFilterVerifierComponent == null) { 11147 Slog.d(TAG, "No IntentFilter verification will not be done as " 11148 + "there is no IntentFilterVerifier available!"); 11149 return; 11150 } 11151 11152 final int verifierUid = getPackageUid( 11153 mIntentFilterVerifierComponent.getPackageName(), 11154 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11155 11156 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11157 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11158 msg.obj = pkg; 11159 msg.arg1 = userId; 11160 msg.arg2 = verifierUid; 11161 11162 mHandler.sendMessage(msg); 11163 } 11164 11165 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11166 PackageParser.Package pkg) { 11167 int size = pkg.activities.size(); 11168 if (size == 0) { 11169 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11170 return; 11171 } 11172 11173 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11174 + " Activities needs verification ..."); 11175 11176 final int verificationId = mIntentFilterVerificationToken++; 11177 int count = 0; 11178 synchronized (mPackages) { 11179 for (PackageParser.Activity a : pkg.activities) { 11180 for (ActivityIntentInfo filter : a.intents) { 11181 boolean needFilterVerification = filter.needsVerification() && 11182 !filter.isVerified(); 11183 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11184 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11185 mIntentFilterVerifier.addOneIntentFilterVerification( 11186 verifierUid, userId, verificationId, filter, pkg.packageName); 11187 count++; 11188 } else { 11189 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11190 } 11191 } 11192 } 11193 } 11194 11195 if (count > 0) { 11196 mIntentFilterVerifier.startVerifications(userId); 11197 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11198 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11199 } else { 11200 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11201 } 11202 } 11203 11204 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11205 final ComponentName cn = filter.activity.getComponentName(); 11206 final String packageName = cn.getPackageName(); 11207 11208 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11209 packageName); 11210 if (ivi == null) { 11211 return true; 11212 } 11213 int status = ivi.getStatus(); 11214 switch (status) { 11215 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11216 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11217 return true; 11218 11219 default: 11220 // Nothing to do 11221 return false; 11222 } 11223 } 11224 11225 private static boolean isMultiArch(PackageSetting ps) { 11226 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11227 } 11228 11229 private static boolean isMultiArch(ApplicationInfo info) { 11230 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11231 } 11232 11233 private static boolean isExternal(PackageParser.Package pkg) { 11234 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11235 } 11236 11237 private static boolean isExternal(PackageSetting ps) { 11238 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11239 } 11240 11241 private static boolean isExternal(ApplicationInfo info) { 11242 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11243 } 11244 11245 private static boolean isSystemApp(PackageParser.Package pkg) { 11246 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11247 } 11248 11249 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11250 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11251 } 11252 11253 private static boolean isSystemApp(ApplicationInfo info) { 11254 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11255 } 11256 11257 private static boolean isSystemApp(PackageSetting ps) { 11258 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11259 } 11260 11261 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11262 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11263 } 11264 11265 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 11266 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11267 } 11268 11269 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 11270 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11271 } 11272 11273 private int packageFlagsToInstallFlags(PackageSetting ps) { 11274 int installFlags = 0; 11275 if (isExternal(ps)) { 11276 installFlags |= PackageManager.INSTALL_EXTERNAL; 11277 } 11278 if (ps.isForwardLocked()) { 11279 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11280 } 11281 return installFlags; 11282 } 11283 11284 private void deleteTempPackageFiles() { 11285 final FilenameFilter filter = new FilenameFilter() { 11286 public boolean accept(File dir, String name) { 11287 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11288 } 11289 }; 11290 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11291 file.delete(); 11292 } 11293 } 11294 11295 @Override 11296 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11297 int flags) { 11298 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11299 flags); 11300 } 11301 11302 @Override 11303 public void deletePackage(final String packageName, 11304 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11305 mContext.enforceCallingOrSelfPermission( 11306 android.Manifest.permission.DELETE_PACKAGES, null); 11307 final int uid = Binder.getCallingUid(); 11308 if (UserHandle.getUserId(uid) != userId) { 11309 mContext.enforceCallingPermission( 11310 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11311 "deletePackage for user " + userId); 11312 } 11313 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11314 try { 11315 observer.onPackageDeleted(packageName, 11316 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11317 } catch (RemoteException re) { 11318 } 11319 return; 11320 } 11321 11322 boolean uninstallBlocked = false; 11323 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11324 int[] users = sUserManager.getUserIds(); 11325 for (int i = 0; i < users.length; ++i) { 11326 if (getBlockUninstallForUser(packageName, users[i])) { 11327 uninstallBlocked = true; 11328 break; 11329 } 11330 } 11331 } else { 11332 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11333 } 11334 if (uninstallBlocked) { 11335 try { 11336 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11337 null); 11338 } catch (RemoteException re) { 11339 } 11340 return; 11341 } 11342 11343 if (DEBUG_REMOVE) { 11344 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11345 } 11346 // Queue up an async operation since the package deletion may take a little while. 11347 mHandler.post(new Runnable() { 11348 public void run() { 11349 mHandler.removeCallbacks(this); 11350 final int returnCode = deletePackageX(packageName, userId, flags); 11351 if (observer != null) { 11352 try { 11353 observer.onPackageDeleted(packageName, returnCode, null); 11354 } catch (RemoteException e) { 11355 Log.i(TAG, "Observer no longer exists."); 11356 } //end catch 11357 } //end if 11358 } //end run 11359 }); 11360 } 11361 11362 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11363 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11364 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11365 try { 11366 if (dpm != null) { 11367 if (dpm.isDeviceOwner(packageName)) { 11368 return true; 11369 } 11370 int[] users; 11371 if (userId == UserHandle.USER_ALL) { 11372 users = sUserManager.getUserIds(); 11373 } else { 11374 users = new int[]{userId}; 11375 } 11376 for (int i = 0; i < users.length; ++i) { 11377 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11378 return true; 11379 } 11380 } 11381 } 11382 } catch (RemoteException e) { 11383 } 11384 return false; 11385 } 11386 11387 /** 11388 * This method is an internal method that could be get invoked either 11389 * to delete an installed package or to clean up a failed installation. 11390 * After deleting an installed package, a broadcast is sent to notify any 11391 * listeners that the package has been installed. For cleaning up a failed 11392 * installation, the broadcast is not necessary since the package's 11393 * installation wouldn't have sent the initial broadcast either 11394 * The key steps in deleting a package are 11395 * deleting the package information in internal structures like mPackages, 11396 * deleting the packages base directories through installd 11397 * updating mSettings to reflect current status 11398 * persisting settings for later use 11399 * sending a broadcast if necessary 11400 */ 11401 private int deletePackageX(String packageName, int userId, int flags) { 11402 final PackageRemovedInfo info = new PackageRemovedInfo(); 11403 final boolean res; 11404 11405 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11406 ? UserHandle.ALL : new UserHandle(userId); 11407 11408 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11409 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11410 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11411 } 11412 11413 boolean removedForAllUsers = false; 11414 boolean systemUpdate = false; 11415 11416 // for the uninstall-updates case and restricted profiles, remember the per- 11417 // userhandle installed state 11418 int[] allUsers; 11419 boolean[] perUserInstalled; 11420 synchronized (mPackages) { 11421 PackageSetting ps = mSettings.mPackages.get(packageName); 11422 allUsers = sUserManager.getUserIds(); 11423 perUserInstalled = new boolean[allUsers.length]; 11424 for (int i = 0; i < allUsers.length; i++) { 11425 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11426 } 11427 } 11428 11429 synchronized (mInstallLock) { 11430 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11431 res = deletePackageLI(packageName, removeForUser, 11432 true, allUsers, perUserInstalled, 11433 flags | REMOVE_CHATTY, info, true); 11434 systemUpdate = info.isRemovedPackageSystemUpdate; 11435 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11436 removedForAllUsers = true; 11437 } 11438 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11439 + " removedForAllUsers=" + removedForAllUsers); 11440 } 11441 11442 if (res) { 11443 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11444 11445 // If the removed package was a system update, the old system package 11446 // was re-enabled; we need to broadcast this information 11447 if (systemUpdate) { 11448 Bundle extras = new Bundle(1); 11449 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11450 ? info.removedAppId : info.uid); 11451 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11452 11453 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11454 extras, null, null, null); 11455 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11456 extras, null, null, null); 11457 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11458 null, packageName, null, null); 11459 } 11460 } 11461 // Force a gc here. 11462 Runtime.getRuntime().gc(); 11463 // Delete the resources here after sending the broadcast to let 11464 // other processes clean up before deleting resources. 11465 if (info.args != null) { 11466 synchronized (mInstallLock) { 11467 info.args.doPostDeleteLI(true); 11468 } 11469 } 11470 11471 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11472 } 11473 11474 static class PackageRemovedInfo { 11475 String removedPackage; 11476 int uid = -1; 11477 int removedAppId = -1; 11478 int[] removedUsers = null; 11479 boolean isRemovedPackageSystemUpdate = false; 11480 // Clean up resources deleted packages. 11481 InstallArgs args = null; 11482 11483 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11484 Bundle extras = new Bundle(1); 11485 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11486 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11487 if (replacing) { 11488 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11489 } 11490 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11491 if (removedPackage != null) { 11492 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11493 extras, null, null, removedUsers); 11494 if (fullRemove && !replacing) { 11495 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11496 extras, null, null, removedUsers); 11497 } 11498 } 11499 if (removedAppId >= 0) { 11500 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11501 removedUsers); 11502 } 11503 } 11504 } 11505 11506 /* 11507 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11508 * flag is not set, the data directory is removed as well. 11509 * make sure this flag is set for partially installed apps. If not its meaningless to 11510 * delete a partially installed application. 11511 */ 11512 private void removePackageDataLI(PackageSetting ps, 11513 int[] allUserHandles, boolean[] perUserInstalled, 11514 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11515 String packageName = ps.name; 11516 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11517 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11518 // Retrieve object to delete permissions for shared user later on 11519 final PackageSetting deletedPs; 11520 // reader 11521 synchronized (mPackages) { 11522 deletedPs = mSettings.mPackages.get(packageName); 11523 if (outInfo != null) { 11524 outInfo.removedPackage = packageName; 11525 outInfo.removedUsers = deletedPs != null 11526 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11527 : null; 11528 } 11529 } 11530 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11531 removeDataDirsLI(packageName); 11532 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11533 } 11534 // writer 11535 synchronized (mPackages) { 11536 if (deletedPs != null) { 11537 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11538 if (outInfo != null) { 11539 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11540 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11541 } 11542 updatePermissionsLPw(deletedPs.name, null, 0); 11543 if (deletedPs.sharedUser != null) { 11544 // Remove permissions associated with package. Since runtime 11545 // permissions are per user we have to kill the removed package 11546 // or packages running under the shared user of the removed 11547 // package if revoking the permissions requested only by the removed 11548 // package is successful and this causes a change in gids. 11549 for (int userId : UserManagerService.getInstance().getUserIds()) { 11550 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11551 userId); 11552 if (userIdToKill == UserHandle.USER_ALL 11553 || userIdToKill >= UserHandle.USER_OWNER) { 11554 // If gids changed for this user, kill all affected packages. 11555 mHandler.post(new Runnable() { 11556 @Override 11557 public void run() { 11558 // This has to happen with no lock held. 11559 killSettingPackagesForUser(deletedPs, userIdToKill, 11560 KILL_APP_REASON_GIDS_CHANGED); 11561 } 11562 }); 11563 break; 11564 } 11565 } 11566 } 11567 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11568 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11569 } 11570 // make sure to preserve per-user disabled state if this removal was just 11571 // a downgrade of a system app to the factory package 11572 if (allUserHandles != null && perUserInstalled != null) { 11573 if (DEBUG_REMOVE) { 11574 Slog.d(TAG, "Propagating install state across downgrade"); 11575 } 11576 for (int i = 0; i < allUserHandles.length; i++) { 11577 if (DEBUG_REMOVE) { 11578 Slog.d(TAG, " user " + allUserHandles[i] 11579 + " => " + perUserInstalled[i]); 11580 } 11581 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11582 } 11583 } 11584 } 11585 // can downgrade to reader 11586 if (writeSettings) { 11587 // Save settings now 11588 mSettings.writeLPr(); 11589 } 11590 } 11591 if (outInfo != null) { 11592 // A user ID was deleted here. Go through all users and remove it 11593 // from KeyStore. 11594 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11595 } 11596 } 11597 11598 static boolean locationIsPrivileged(File path) { 11599 try { 11600 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11601 .getCanonicalPath(); 11602 return path.getCanonicalPath().startsWith(privilegedAppDir); 11603 } catch (IOException e) { 11604 Slog.e(TAG, "Unable to access code path " + path); 11605 } 11606 return false; 11607 } 11608 11609 /* 11610 * Tries to delete system package. 11611 */ 11612 private boolean deleteSystemPackageLI(PackageSetting newPs, 11613 int[] allUserHandles, boolean[] perUserInstalled, 11614 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11615 final boolean applyUserRestrictions 11616 = (allUserHandles != null) && (perUserInstalled != null); 11617 PackageSetting disabledPs = null; 11618 // Confirm if the system package has been updated 11619 // An updated system app can be deleted. This will also have to restore 11620 // the system pkg from system partition 11621 // reader 11622 synchronized (mPackages) { 11623 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11624 } 11625 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11626 + " disabledPs=" + disabledPs); 11627 if (disabledPs == null) { 11628 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11629 return false; 11630 } else if (DEBUG_REMOVE) { 11631 Slog.d(TAG, "Deleting system pkg from data partition"); 11632 } 11633 if (DEBUG_REMOVE) { 11634 if (applyUserRestrictions) { 11635 Slog.d(TAG, "Remembering install states:"); 11636 for (int i = 0; i < allUserHandles.length; i++) { 11637 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11638 } 11639 } 11640 } 11641 // Delete the updated package 11642 outInfo.isRemovedPackageSystemUpdate = true; 11643 if (disabledPs.versionCode < newPs.versionCode) { 11644 // Delete data for downgrades 11645 flags &= ~PackageManager.DELETE_KEEP_DATA; 11646 } else { 11647 // Preserve data by setting flag 11648 flags |= PackageManager.DELETE_KEEP_DATA; 11649 } 11650 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11651 allUserHandles, perUserInstalled, outInfo, writeSettings); 11652 if (!ret) { 11653 return false; 11654 } 11655 // writer 11656 synchronized (mPackages) { 11657 // Reinstate the old system package 11658 mSettings.enableSystemPackageLPw(newPs.name); 11659 // Remove any native libraries from the upgraded package. 11660 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11661 } 11662 // Install the system package 11663 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11664 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11665 if (locationIsPrivileged(disabledPs.codePath)) { 11666 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11667 } 11668 11669 final PackageParser.Package newPkg; 11670 try { 11671 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11672 } catch (PackageManagerException e) { 11673 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11674 return false; 11675 } 11676 11677 // writer 11678 synchronized (mPackages) { 11679 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11680 updatePermissionsLPw(newPkg.packageName, newPkg, 11681 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11682 if (applyUserRestrictions) { 11683 if (DEBUG_REMOVE) { 11684 Slog.d(TAG, "Propagating install state across reinstall"); 11685 } 11686 for (int i = 0; i < allUserHandles.length; i++) { 11687 if (DEBUG_REMOVE) { 11688 Slog.d(TAG, " user " + allUserHandles[i] 11689 + " => " + perUserInstalled[i]); 11690 } 11691 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11692 } 11693 // Regardless of writeSettings we need to ensure that this restriction 11694 // state propagation is persisted 11695 mSettings.writeAllUsersPackageRestrictionsLPr(); 11696 } 11697 // can downgrade to reader here 11698 if (writeSettings) { 11699 mSettings.writeLPr(); 11700 } 11701 } 11702 return true; 11703 } 11704 11705 private boolean deleteInstalledPackageLI(PackageSetting ps, 11706 boolean deleteCodeAndResources, int flags, 11707 int[] allUserHandles, boolean[] perUserInstalled, 11708 PackageRemovedInfo outInfo, boolean writeSettings) { 11709 if (outInfo != null) { 11710 outInfo.uid = ps.appId; 11711 } 11712 11713 // Delete package data from internal structures and also remove data if flag is set 11714 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11715 11716 // Delete application code and resources 11717 if (deleteCodeAndResources && (outInfo != null)) { 11718 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11719 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11720 getAppDexInstructionSets(ps)); 11721 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11722 } 11723 return true; 11724 } 11725 11726 @Override 11727 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11728 int userId) { 11729 mContext.enforceCallingOrSelfPermission( 11730 android.Manifest.permission.DELETE_PACKAGES, null); 11731 synchronized (mPackages) { 11732 PackageSetting ps = mSettings.mPackages.get(packageName); 11733 if (ps == null) { 11734 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11735 return false; 11736 } 11737 if (!ps.getInstalled(userId)) { 11738 // Can't block uninstall for an app that is not installed or enabled. 11739 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11740 return false; 11741 } 11742 ps.setBlockUninstall(blockUninstall, userId); 11743 mSettings.writePackageRestrictionsLPr(userId); 11744 } 11745 return true; 11746 } 11747 11748 @Override 11749 public boolean getBlockUninstallForUser(String packageName, int userId) { 11750 synchronized (mPackages) { 11751 PackageSetting ps = mSettings.mPackages.get(packageName); 11752 if (ps == null) { 11753 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11754 return false; 11755 } 11756 return ps.getBlockUninstall(userId); 11757 } 11758 } 11759 11760 /* 11761 * This method handles package deletion in general 11762 */ 11763 private boolean deletePackageLI(String packageName, UserHandle user, 11764 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11765 int flags, PackageRemovedInfo outInfo, 11766 boolean writeSettings) { 11767 if (packageName == null) { 11768 Slog.w(TAG, "Attempt to delete null packageName."); 11769 return false; 11770 } 11771 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11772 PackageSetting ps; 11773 boolean dataOnly = false; 11774 int removeUser = -1; 11775 int appId = -1; 11776 synchronized (mPackages) { 11777 ps = mSettings.mPackages.get(packageName); 11778 if (ps == null) { 11779 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11780 return false; 11781 } 11782 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11783 && user.getIdentifier() != UserHandle.USER_ALL) { 11784 // The caller is asking that the package only be deleted for a single 11785 // user. To do this, we just mark its uninstalled state and delete 11786 // its data. If this is a system app, we only allow this to happen if 11787 // they have set the special DELETE_SYSTEM_APP which requests different 11788 // semantics than normal for uninstalling system apps. 11789 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11790 ps.setUserState(user.getIdentifier(), 11791 COMPONENT_ENABLED_STATE_DEFAULT, 11792 false, //installed 11793 true, //stopped 11794 true, //notLaunched 11795 false, //hidden 11796 null, null, null, 11797 false, // blockUninstall 11798 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11799 if (!isSystemApp(ps)) { 11800 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11801 // Other user still have this package installed, so all 11802 // we need to do is clear this user's data and save that 11803 // it is uninstalled. 11804 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11805 removeUser = user.getIdentifier(); 11806 appId = ps.appId; 11807 mSettings.writePackageRestrictionsLPr(removeUser); 11808 } else { 11809 // We need to set it back to 'installed' so the uninstall 11810 // broadcasts will be sent correctly. 11811 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11812 ps.setInstalled(true, user.getIdentifier()); 11813 } 11814 } else { 11815 // This is a system app, so we assume that the 11816 // other users still have this package installed, so all 11817 // we need to do is clear this user's data and save that 11818 // it is uninstalled. 11819 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11820 removeUser = user.getIdentifier(); 11821 appId = ps.appId; 11822 mSettings.writePackageRestrictionsLPr(removeUser); 11823 } 11824 } 11825 } 11826 11827 if (removeUser >= 0) { 11828 // From above, we determined that we are deleting this only 11829 // for a single user. Continue the work here. 11830 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11831 if (outInfo != null) { 11832 outInfo.removedPackage = packageName; 11833 outInfo.removedAppId = appId; 11834 outInfo.removedUsers = new int[] {removeUser}; 11835 } 11836 mInstaller.clearUserData(packageName, removeUser); 11837 removeKeystoreDataIfNeeded(removeUser, appId); 11838 schedulePackageCleaning(packageName, removeUser, false); 11839 return true; 11840 } 11841 11842 if (dataOnly) { 11843 // Delete application data first 11844 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11845 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11846 return true; 11847 } 11848 11849 boolean ret = false; 11850 if (isSystemApp(ps)) { 11851 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11852 // When an updated system application is deleted we delete the existing resources as well and 11853 // fall back to existing code in system partition 11854 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11855 flags, outInfo, writeSettings); 11856 } else { 11857 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11858 // Kill application pre-emptively especially for apps on sd. 11859 killApplication(packageName, ps.appId, "uninstall pkg"); 11860 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11861 allUserHandles, perUserInstalled, 11862 outInfo, writeSettings); 11863 } 11864 11865 return ret; 11866 } 11867 11868 private final class ClearStorageConnection implements ServiceConnection { 11869 IMediaContainerService mContainerService; 11870 11871 @Override 11872 public void onServiceConnected(ComponentName name, IBinder service) { 11873 synchronized (this) { 11874 mContainerService = IMediaContainerService.Stub.asInterface(service); 11875 notifyAll(); 11876 } 11877 } 11878 11879 @Override 11880 public void onServiceDisconnected(ComponentName name) { 11881 } 11882 } 11883 11884 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11885 final boolean mounted; 11886 if (Environment.isExternalStorageEmulated()) { 11887 mounted = true; 11888 } else { 11889 final String status = Environment.getExternalStorageState(); 11890 11891 mounted = status.equals(Environment.MEDIA_MOUNTED) 11892 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11893 } 11894 11895 if (!mounted) { 11896 return; 11897 } 11898 11899 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11900 int[] users; 11901 if (userId == UserHandle.USER_ALL) { 11902 users = sUserManager.getUserIds(); 11903 } else { 11904 users = new int[] { userId }; 11905 } 11906 final ClearStorageConnection conn = new ClearStorageConnection(); 11907 if (mContext.bindServiceAsUser( 11908 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11909 try { 11910 for (int curUser : users) { 11911 long timeout = SystemClock.uptimeMillis() + 5000; 11912 synchronized (conn) { 11913 long now = SystemClock.uptimeMillis(); 11914 while (conn.mContainerService == null && now < timeout) { 11915 try { 11916 conn.wait(timeout - now); 11917 } catch (InterruptedException e) { 11918 } 11919 } 11920 } 11921 if (conn.mContainerService == null) { 11922 return; 11923 } 11924 11925 final UserEnvironment userEnv = new UserEnvironment(curUser); 11926 clearDirectory(conn.mContainerService, 11927 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11928 if (allData) { 11929 clearDirectory(conn.mContainerService, 11930 userEnv.buildExternalStorageAppDataDirs(packageName)); 11931 clearDirectory(conn.mContainerService, 11932 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11933 } 11934 } 11935 } finally { 11936 mContext.unbindService(conn); 11937 } 11938 } 11939 } 11940 11941 @Override 11942 public void clearApplicationUserData(final String packageName, 11943 final IPackageDataObserver observer, final int userId) { 11944 mContext.enforceCallingOrSelfPermission( 11945 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11946 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11947 // Queue up an async operation since the package deletion may take a little while. 11948 mHandler.post(new Runnable() { 11949 public void run() { 11950 mHandler.removeCallbacks(this); 11951 final boolean succeeded; 11952 synchronized (mInstallLock) { 11953 succeeded = clearApplicationUserDataLI(packageName, userId); 11954 } 11955 clearExternalStorageDataSync(packageName, userId, true); 11956 if (succeeded) { 11957 // invoke DeviceStorageMonitor's update method to clear any notifications 11958 DeviceStorageMonitorInternal 11959 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11960 if (dsm != null) { 11961 dsm.checkMemory(); 11962 } 11963 } 11964 if(observer != null) { 11965 try { 11966 observer.onRemoveCompleted(packageName, succeeded); 11967 } catch (RemoteException e) { 11968 Log.i(TAG, "Observer no longer exists."); 11969 } 11970 } //end if observer 11971 } //end run 11972 }); 11973 } 11974 11975 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11976 if (packageName == null) { 11977 Slog.w(TAG, "Attempt to delete null packageName."); 11978 return false; 11979 } 11980 11981 // Try finding details about the requested package 11982 PackageParser.Package pkg; 11983 synchronized (mPackages) { 11984 pkg = mPackages.get(packageName); 11985 if (pkg == null) { 11986 final PackageSetting ps = mSettings.mPackages.get(packageName); 11987 if (ps != null) { 11988 pkg = ps.pkg; 11989 } 11990 } 11991 } 11992 11993 if (pkg == null) { 11994 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11995 } 11996 11997 // Always delete data directories for package, even if we found no other 11998 // record of app. This helps users recover from UID mismatches without 11999 // resorting to a full data wipe. 12000 int retCode = mInstaller.clearUserData(packageName, userId); 12001 if (retCode < 0) { 12002 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12003 return false; 12004 } 12005 12006 if (pkg == null) { 12007 return false; 12008 } 12009 12010 if (pkg != null && pkg.applicationInfo != null) { 12011 final int appId = pkg.applicationInfo.uid; 12012 removeKeystoreDataIfNeeded(userId, appId); 12013 } 12014 12015 // Create a native library symlink only if we have native libraries 12016 // and if the native libraries are 32 bit libraries. We do not provide 12017 // this symlink for 64 bit libraries. 12018 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12019 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12020 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12021 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12022 Slog.w(TAG, "Failed linking native library dir"); 12023 return false; 12024 } 12025 } 12026 12027 return true; 12028 } 12029 12030 /** 12031 * Remove entries from the keystore daemon. Will only remove it if the 12032 * {@code appId} is valid. 12033 */ 12034 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12035 if (appId < 0) { 12036 return; 12037 } 12038 12039 final KeyStore keyStore = KeyStore.getInstance(); 12040 if (keyStore != null) { 12041 if (userId == UserHandle.USER_ALL) { 12042 for (final int individual : sUserManager.getUserIds()) { 12043 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12044 } 12045 } else { 12046 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12047 } 12048 } else { 12049 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12050 } 12051 } 12052 12053 @Override 12054 public void deleteApplicationCacheFiles(final String packageName, 12055 final IPackageDataObserver observer) { 12056 mContext.enforceCallingOrSelfPermission( 12057 android.Manifest.permission.DELETE_CACHE_FILES, null); 12058 // Queue up an async operation since the package deletion may take a little while. 12059 final int userId = UserHandle.getCallingUserId(); 12060 mHandler.post(new Runnable() { 12061 public void run() { 12062 mHandler.removeCallbacks(this); 12063 final boolean succeded; 12064 synchronized (mInstallLock) { 12065 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12066 } 12067 clearExternalStorageDataSync(packageName, userId, false); 12068 if(observer != null) { 12069 try { 12070 observer.onRemoveCompleted(packageName, succeded); 12071 } catch (RemoteException e) { 12072 Log.i(TAG, "Observer no longer exists."); 12073 } 12074 } //end if observer 12075 } //end run 12076 }); 12077 } 12078 12079 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12080 if (packageName == null) { 12081 Slog.w(TAG, "Attempt to delete null packageName."); 12082 return false; 12083 } 12084 PackageParser.Package p; 12085 synchronized (mPackages) { 12086 p = mPackages.get(packageName); 12087 } 12088 if (p == null) { 12089 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12090 return false; 12091 } 12092 final ApplicationInfo applicationInfo = p.applicationInfo; 12093 if (applicationInfo == null) { 12094 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12095 return false; 12096 } 12097 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12098 if (retCode < 0) { 12099 Slog.w(TAG, "Couldn't remove cache files for package: " 12100 + packageName + " u" + userId); 12101 return false; 12102 } 12103 return true; 12104 } 12105 12106 @Override 12107 public void getPackageSizeInfo(final String packageName, int userHandle, 12108 final IPackageStatsObserver observer) { 12109 mContext.enforceCallingOrSelfPermission( 12110 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12111 if (packageName == null) { 12112 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12113 } 12114 12115 PackageStats stats = new PackageStats(packageName, userHandle); 12116 12117 /* 12118 * Queue up an async operation since the package measurement may take a 12119 * little while. 12120 */ 12121 Message msg = mHandler.obtainMessage(INIT_COPY); 12122 msg.obj = new MeasureParams(stats, observer); 12123 mHandler.sendMessage(msg); 12124 } 12125 12126 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12127 PackageStats pStats) { 12128 if (packageName == null) { 12129 Slog.w(TAG, "Attempt to get size of null packageName."); 12130 return false; 12131 } 12132 PackageParser.Package p; 12133 boolean dataOnly = false; 12134 String libDirRoot = null; 12135 String asecPath = null; 12136 PackageSetting ps = null; 12137 synchronized (mPackages) { 12138 p = mPackages.get(packageName); 12139 ps = mSettings.mPackages.get(packageName); 12140 if(p == null) { 12141 dataOnly = true; 12142 if((ps == null) || (ps.pkg == null)) { 12143 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12144 return false; 12145 } 12146 p = ps.pkg; 12147 } 12148 if (ps != null) { 12149 libDirRoot = ps.legacyNativeLibraryPathString; 12150 } 12151 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12152 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12153 if (secureContainerId != null) { 12154 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12155 } 12156 } 12157 } 12158 String publicSrcDir = null; 12159 if(!dataOnly) { 12160 final ApplicationInfo applicationInfo = p.applicationInfo; 12161 if (applicationInfo == null) { 12162 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12163 return false; 12164 } 12165 if (p.isForwardLocked()) { 12166 publicSrcDir = applicationInfo.getBaseResourcePath(); 12167 } 12168 } 12169 // TODO: extend to measure size of split APKs 12170 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12171 // not just the first level. 12172 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12173 // just the primary. 12174 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12175 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12176 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12177 if (res < 0) { 12178 return false; 12179 } 12180 12181 // Fix-up for forward-locked applications in ASEC containers. 12182 if (!isExternal(p)) { 12183 pStats.codeSize += pStats.externalCodeSize; 12184 pStats.externalCodeSize = 0L; 12185 } 12186 12187 return true; 12188 } 12189 12190 12191 @Override 12192 public void addPackageToPreferred(String packageName) { 12193 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12194 } 12195 12196 @Override 12197 public void removePackageFromPreferred(String packageName) { 12198 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12199 } 12200 12201 @Override 12202 public List<PackageInfo> getPreferredPackages(int flags) { 12203 return new ArrayList<PackageInfo>(); 12204 } 12205 12206 private int getUidTargetSdkVersionLockedLPr(int uid) { 12207 Object obj = mSettings.getUserIdLPr(uid); 12208 if (obj instanceof SharedUserSetting) { 12209 final SharedUserSetting sus = (SharedUserSetting) obj; 12210 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12211 final Iterator<PackageSetting> it = sus.packages.iterator(); 12212 while (it.hasNext()) { 12213 final PackageSetting ps = it.next(); 12214 if (ps.pkg != null) { 12215 int v = ps.pkg.applicationInfo.targetSdkVersion; 12216 if (v < vers) vers = v; 12217 } 12218 } 12219 return vers; 12220 } else if (obj instanceof PackageSetting) { 12221 final PackageSetting ps = (PackageSetting) obj; 12222 if (ps.pkg != null) { 12223 return ps.pkg.applicationInfo.targetSdkVersion; 12224 } 12225 } 12226 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12227 } 12228 12229 @Override 12230 public void addPreferredActivity(IntentFilter filter, int match, 12231 ComponentName[] set, ComponentName activity, int userId) { 12232 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12233 "Adding preferred"); 12234 } 12235 12236 private void addPreferredActivityInternal(IntentFilter filter, int match, 12237 ComponentName[] set, ComponentName activity, boolean always, int userId, 12238 String opname) { 12239 // writer 12240 int callingUid = Binder.getCallingUid(); 12241 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12242 if (filter.countActions() == 0) { 12243 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12244 return; 12245 } 12246 synchronized (mPackages) { 12247 if (mContext.checkCallingOrSelfPermission( 12248 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12249 != PackageManager.PERMISSION_GRANTED) { 12250 if (getUidTargetSdkVersionLockedLPr(callingUid) 12251 < Build.VERSION_CODES.FROYO) { 12252 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12253 + callingUid); 12254 return; 12255 } 12256 mContext.enforceCallingOrSelfPermission( 12257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12258 } 12259 12260 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12261 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12262 + userId + ":"); 12263 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12264 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12265 scheduleWritePackageRestrictionsLocked(userId); 12266 } 12267 } 12268 12269 @Override 12270 public void replacePreferredActivity(IntentFilter filter, int match, 12271 ComponentName[] set, ComponentName activity, int userId) { 12272 if (filter.countActions() != 1) { 12273 throw new IllegalArgumentException( 12274 "replacePreferredActivity expects filter to have only 1 action."); 12275 } 12276 if (filter.countDataAuthorities() != 0 12277 || filter.countDataPaths() != 0 12278 || filter.countDataSchemes() > 1 12279 || filter.countDataTypes() != 0) { 12280 throw new IllegalArgumentException( 12281 "replacePreferredActivity expects filter to have no data authorities, " + 12282 "paths, or types; and at most one scheme."); 12283 } 12284 12285 final int callingUid = Binder.getCallingUid(); 12286 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12287 synchronized (mPackages) { 12288 if (mContext.checkCallingOrSelfPermission( 12289 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12290 != PackageManager.PERMISSION_GRANTED) { 12291 if (getUidTargetSdkVersionLockedLPr(callingUid) 12292 < Build.VERSION_CODES.FROYO) { 12293 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12294 + Binder.getCallingUid()); 12295 return; 12296 } 12297 mContext.enforceCallingOrSelfPermission( 12298 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12299 } 12300 12301 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12302 if (pir != null) { 12303 // Get all of the existing entries that exactly match this filter. 12304 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12305 if (existing != null && existing.size() == 1) { 12306 PreferredActivity cur = existing.get(0); 12307 if (DEBUG_PREFERRED) { 12308 Slog.i(TAG, "Checking replace of preferred:"); 12309 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12310 if (!cur.mPref.mAlways) { 12311 Slog.i(TAG, " -- CUR; not mAlways!"); 12312 } else { 12313 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12314 Slog.i(TAG, " -- CUR: mSet=" 12315 + Arrays.toString(cur.mPref.mSetComponents)); 12316 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12317 Slog.i(TAG, " -- NEW: mMatch=" 12318 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12319 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12320 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12321 } 12322 } 12323 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12324 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12325 && cur.mPref.sameSet(set)) { 12326 // Setting the preferred activity to what it happens to be already 12327 if (DEBUG_PREFERRED) { 12328 Slog.i(TAG, "Replacing with same preferred activity " 12329 + cur.mPref.mShortComponent + " for user " 12330 + userId + ":"); 12331 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12332 } 12333 return; 12334 } 12335 } 12336 12337 if (existing != null) { 12338 if (DEBUG_PREFERRED) { 12339 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12340 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12341 } 12342 for (int i = 0; i < existing.size(); i++) { 12343 PreferredActivity pa = existing.get(i); 12344 if (DEBUG_PREFERRED) { 12345 Slog.i(TAG, "Removing existing preferred activity " 12346 + pa.mPref.mComponent + ":"); 12347 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12348 } 12349 pir.removeFilter(pa); 12350 } 12351 } 12352 } 12353 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12354 "Replacing preferred"); 12355 } 12356 } 12357 12358 @Override 12359 public void clearPackagePreferredActivities(String packageName) { 12360 final int uid = Binder.getCallingUid(); 12361 // writer 12362 synchronized (mPackages) { 12363 PackageParser.Package pkg = mPackages.get(packageName); 12364 if (pkg == null || pkg.applicationInfo.uid != uid) { 12365 if (mContext.checkCallingOrSelfPermission( 12366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12367 != PackageManager.PERMISSION_GRANTED) { 12368 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12369 < Build.VERSION_CODES.FROYO) { 12370 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12371 + Binder.getCallingUid()); 12372 return; 12373 } 12374 mContext.enforceCallingOrSelfPermission( 12375 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12376 } 12377 } 12378 12379 int user = UserHandle.getCallingUserId(); 12380 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12381 scheduleWritePackageRestrictionsLocked(user); 12382 } 12383 } 12384 } 12385 12386 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12387 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12388 ArrayList<PreferredActivity> removed = null; 12389 boolean changed = false; 12390 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12391 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12392 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12393 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12394 continue; 12395 } 12396 Iterator<PreferredActivity> it = pir.filterIterator(); 12397 while (it.hasNext()) { 12398 PreferredActivity pa = it.next(); 12399 // Mark entry for removal only if it matches the package name 12400 // and the entry is of type "always". 12401 if (packageName == null || 12402 (pa.mPref.mComponent.getPackageName().equals(packageName) 12403 && pa.mPref.mAlways)) { 12404 if (removed == null) { 12405 removed = new ArrayList<PreferredActivity>(); 12406 } 12407 removed.add(pa); 12408 } 12409 } 12410 if (removed != null) { 12411 for (int j=0; j<removed.size(); j++) { 12412 PreferredActivity pa = removed.get(j); 12413 pir.removeFilter(pa); 12414 } 12415 changed = true; 12416 } 12417 } 12418 return changed; 12419 } 12420 12421 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12422 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12423 if (userId == UserHandle.USER_ALL) { 12424 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12425 for (int oneUserId : sUserManager.getUserIds()) { 12426 scheduleWritePackageRestrictionsLocked(oneUserId); 12427 } 12428 } else { 12429 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12430 scheduleWritePackageRestrictionsLocked(userId); 12431 } 12432 } 12433 12434 @Override 12435 public void resetPreferredActivities(int userId) { 12436 /* TODO: Actually use userId. Why is it being passed in? */ 12437 mContext.enforceCallingOrSelfPermission( 12438 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12439 // writer 12440 synchronized (mPackages) { 12441 int user = UserHandle.getCallingUserId(); 12442 clearPackagePreferredActivitiesLPw(null, user); 12443 mSettings.readDefaultPreferredAppsLPw(this, user); 12444 scheduleWritePackageRestrictionsLocked(user); 12445 } 12446 } 12447 12448 @Override 12449 public int getPreferredActivities(List<IntentFilter> outFilters, 12450 List<ComponentName> outActivities, String packageName) { 12451 12452 int num = 0; 12453 final int userId = UserHandle.getCallingUserId(); 12454 // reader 12455 synchronized (mPackages) { 12456 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12457 if (pir != null) { 12458 final Iterator<PreferredActivity> it = pir.filterIterator(); 12459 while (it.hasNext()) { 12460 final PreferredActivity pa = it.next(); 12461 if (packageName == null 12462 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12463 && pa.mPref.mAlways)) { 12464 if (outFilters != null) { 12465 outFilters.add(new IntentFilter(pa)); 12466 } 12467 if (outActivities != null) { 12468 outActivities.add(pa.mPref.mComponent); 12469 } 12470 } 12471 } 12472 } 12473 } 12474 12475 return num; 12476 } 12477 12478 @Override 12479 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12480 int userId) { 12481 int callingUid = Binder.getCallingUid(); 12482 if (callingUid != Process.SYSTEM_UID) { 12483 throw new SecurityException( 12484 "addPersistentPreferredActivity can only be run by the system"); 12485 } 12486 if (filter.countActions() == 0) { 12487 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12488 return; 12489 } 12490 synchronized (mPackages) { 12491 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12492 " :"); 12493 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12494 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12495 new PersistentPreferredActivity(filter, activity)); 12496 scheduleWritePackageRestrictionsLocked(userId); 12497 } 12498 } 12499 12500 @Override 12501 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12502 int callingUid = Binder.getCallingUid(); 12503 if (callingUid != Process.SYSTEM_UID) { 12504 throw new SecurityException( 12505 "clearPackagePersistentPreferredActivities can only be run by the system"); 12506 } 12507 ArrayList<PersistentPreferredActivity> removed = null; 12508 boolean changed = false; 12509 synchronized (mPackages) { 12510 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12511 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12512 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12513 .valueAt(i); 12514 if (userId != thisUserId) { 12515 continue; 12516 } 12517 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12518 while (it.hasNext()) { 12519 PersistentPreferredActivity ppa = it.next(); 12520 // Mark entry for removal only if it matches the package name. 12521 if (ppa.mComponent.getPackageName().equals(packageName)) { 12522 if (removed == null) { 12523 removed = new ArrayList<PersistentPreferredActivity>(); 12524 } 12525 removed.add(ppa); 12526 } 12527 } 12528 if (removed != null) { 12529 for (int j=0; j<removed.size(); j++) { 12530 PersistentPreferredActivity ppa = removed.get(j); 12531 ppir.removeFilter(ppa); 12532 } 12533 changed = true; 12534 } 12535 } 12536 12537 if (changed) { 12538 scheduleWritePackageRestrictionsLocked(userId); 12539 } 12540 } 12541 } 12542 12543 @Override 12544 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12545 int sourceUserId, int targetUserId, int flags) { 12546 mContext.enforceCallingOrSelfPermission( 12547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12548 int callingUid = Binder.getCallingUid(); 12549 enforceOwnerRights(ownerPackage, callingUid); 12550 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12551 if (intentFilter.countActions() == 0) { 12552 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12553 return; 12554 } 12555 synchronized (mPackages) { 12556 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12557 ownerPackage, targetUserId, flags); 12558 CrossProfileIntentResolver resolver = 12559 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12560 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12561 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12562 if (existing != null) { 12563 int size = existing.size(); 12564 for (int i = 0; i < size; i++) { 12565 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12566 return; 12567 } 12568 } 12569 } 12570 resolver.addFilter(newFilter); 12571 scheduleWritePackageRestrictionsLocked(sourceUserId); 12572 } 12573 } 12574 12575 @Override 12576 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12577 mContext.enforceCallingOrSelfPermission( 12578 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12579 int callingUid = Binder.getCallingUid(); 12580 enforceOwnerRights(ownerPackage, callingUid); 12581 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12582 synchronized (mPackages) { 12583 CrossProfileIntentResolver resolver = 12584 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12585 ArraySet<CrossProfileIntentFilter> set = 12586 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12587 for (CrossProfileIntentFilter filter : set) { 12588 if (filter.getOwnerPackage().equals(ownerPackage)) { 12589 resolver.removeFilter(filter); 12590 } 12591 } 12592 scheduleWritePackageRestrictionsLocked(sourceUserId); 12593 } 12594 } 12595 12596 // Enforcing that callingUid is owning pkg on userId 12597 private void enforceOwnerRights(String pkg, int callingUid) { 12598 // The system owns everything. 12599 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12600 return; 12601 } 12602 int callingUserId = UserHandle.getUserId(callingUid); 12603 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12604 if (pi == null) { 12605 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12606 + callingUserId); 12607 } 12608 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12609 throw new SecurityException("Calling uid " + callingUid 12610 + " does not own package " + pkg); 12611 } 12612 } 12613 12614 @Override 12615 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12616 Intent intent = new Intent(Intent.ACTION_MAIN); 12617 intent.addCategory(Intent.CATEGORY_HOME); 12618 12619 final int callingUserId = UserHandle.getCallingUserId(); 12620 List<ResolveInfo> list = queryIntentActivities(intent, null, 12621 PackageManager.GET_META_DATA, callingUserId); 12622 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12623 true, false, false, callingUserId); 12624 12625 allHomeCandidates.clear(); 12626 if (list != null) { 12627 for (ResolveInfo ri : list) { 12628 allHomeCandidates.add(ri); 12629 } 12630 } 12631 return (preferred == null || preferred.activityInfo == null) 12632 ? null 12633 : new ComponentName(preferred.activityInfo.packageName, 12634 preferred.activityInfo.name); 12635 } 12636 12637 @Override 12638 public void setApplicationEnabledSetting(String appPackageName, 12639 int newState, int flags, int userId, String callingPackage) { 12640 if (!sUserManager.exists(userId)) return; 12641 if (callingPackage == null) { 12642 callingPackage = Integer.toString(Binder.getCallingUid()); 12643 } 12644 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12645 } 12646 12647 @Override 12648 public void setComponentEnabledSetting(ComponentName componentName, 12649 int newState, int flags, int userId) { 12650 if (!sUserManager.exists(userId)) return; 12651 setEnabledSetting(componentName.getPackageName(), 12652 componentName.getClassName(), newState, flags, userId, null); 12653 } 12654 12655 private void setEnabledSetting(final String packageName, String className, int newState, 12656 final int flags, int userId, String callingPackage) { 12657 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12658 || newState == COMPONENT_ENABLED_STATE_ENABLED 12659 || newState == COMPONENT_ENABLED_STATE_DISABLED 12660 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12661 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12662 throw new IllegalArgumentException("Invalid new component state: " 12663 + newState); 12664 } 12665 PackageSetting pkgSetting; 12666 final int uid = Binder.getCallingUid(); 12667 final int permission = mContext.checkCallingOrSelfPermission( 12668 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12669 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12670 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12671 boolean sendNow = false; 12672 boolean isApp = (className == null); 12673 String componentName = isApp ? packageName : className; 12674 int packageUid = -1; 12675 ArrayList<String> components; 12676 12677 // writer 12678 synchronized (mPackages) { 12679 pkgSetting = mSettings.mPackages.get(packageName); 12680 if (pkgSetting == null) { 12681 if (className == null) { 12682 throw new IllegalArgumentException( 12683 "Unknown package: " + packageName); 12684 } 12685 throw new IllegalArgumentException( 12686 "Unknown component: " + packageName 12687 + "/" + className); 12688 } 12689 // Allow root and verify that userId is not being specified by a different user 12690 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12691 throw new SecurityException( 12692 "Permission Denial: attempt to change component state from pid=" 12693 + Binder.getCallingPid() 12694 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12695 } 12696 if (className == null) { 12697 // We're dealing with an application/package level state change 12698 if (pkgSetting.getEnabled(userId) == newState) { 12699 // Nothing to do 12700 return; 12701 } 12702 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12703 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12704 // Don't care about who enables an app. 12705 callingPackage = null; 12706 } 12707 pkgSetting.setEnabled(newState, userId, callingPackage); 12708 // pkgSetting.pkg.mSetEnabled = newState; 12709 } else { 12710 // We're dealing with a component level state change 12711 // First, verify that this is a valid class name. 12712 PackageParser.Package pkg = pkgSetting.pkg; 12713 if (pkg == null || !pkg.hasComponentClassName(className)) { 12714 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12715 throw new IllegalArgumentException("Component class " + className 12716 + " does not exist in " + packageName); 12717 } else { 12718 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12719 + className + " does not exist in " + packageName); 12720 } 12721 } 12722 switch (newState) { 12723 case COMPONENT_ENABLED_STATE_ENABLED: 12724 if (!pkgSetting.enableComponentLPw(className, userId)) { 12725 return; 12726 } 12727 break; 12728 case COMPONENT_ENABLED_STATE_DISABLED: 12729 if (!pkgSetting.disableComponentLPw(className, userId)) { 12730 return; 12731 } 12732 break; 12733 case COMPONENT_ENABLED_STATE_DEFAULT: 12734 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12735 return; 12736 } 12737 break; 12738 default: 12739 Slog.e(TAG, "Invalid new component state: " + newState); 12740 return; 12741 } 12742 } 12743 scheduleWritePackageRestrictionsLocked(userId); 12744 components = mPendingBroadcasts.get(userId, packageName); 12745 final boolean newPackage = components == null; 12746 if (newPackage) { 12747 components = new ArrayList<String>(); 12748 } 12749 if (!components.contains(componentName)) { 12750 components.add(componentName); 12751 } 12752 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12753 sendNow = true; 12754 // Purge entry from pending broadcast list if another one exists already 12755 // since we are sending one right away. 12756 mPendingBroadcasts.remove(userId, packageName); 12757 } else { 12758 if (newPackage) { 12759 mPendingBroadcasts.put(userId, packageName, components); 12760 } 12761 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12762 // Schedule a message 12763 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12764 } 12765 } 12766 } 12767 12768 long callingId = Binder.clearCallingIdentity(); 12769 try { 12770 if (sendNow) { 12771 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12772 sendPackageChangedBroadcast(packageName, 12773 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12774 } 12775 } finally { 12776 Binder.restoreCallingIdentity(callingId); 12777 } 12778 } 12779 12780 private void sendPackageChangedBroadcast(String packageName, 12781 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12782 if (DEBUG_INSTALL) 12783 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12784 + componentNames); 12785 Bundle extras = new Bundle(4); 12786 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12787 String nameList[] = new String[componentNames.size()]; 12788 componentNames.toArray(nameList); 12789 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12790 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12791 extras.putInt(Intent.EXTRA_UID, packageUid); 12792 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12793 new int[] {UserHandle.getUserId(packageUid)}); 12794 } 12795 12796 @Override 12797 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12798 if (!sUserManager.exists(userId)) return; 12799 final int uid = Binder.getCallingUid(); 12800 final int permission = mContext.checkCallingOrSelfPermission( 12801 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12802 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12803 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12804 // writer 12805 synchronized (mPackages) { 12806 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12807 uid, userId)) { 12808 scheduleWritePackageRestrictionsLocked(userId); 12809 } 12810 } 12811 } 12812 12813 @Override 12814 public String getInstallerPackageName(String packageName) { 12815 // reader 12816 synchronized (mPackages) { 12817 return mSettings.getInstallerPackageNameLPr(packageName); 12818 } 12819 } 12820 12821 @Override 12822 public int getApplicationEnabledSetting(String packageName, int userId) { 12823 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12824 int uid = Binder.getCallingUid(); 12825 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12826 // reader 12827 synchronized (mPackages) { 12828 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12829 } 12830 } 12831 12832 @Override 12833 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12834 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12835 int uid = Binder.getCallingUid(); 12836 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12837 // reader 12838 synchronized (mPackages) { 12839 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12840 } 12841 } 12842 12843 @Override 12844 public void enterSafeMode() { 12845 enforceSystemOrRoot("Only the system can request entering safe mode"); 12846 12847 if (!mSystemReady) { 12848 mSafeMode = true; 12849 } 12850 } 12851 12852 @Override 12853 public void systemReady() { 12854 mSystemReady = true; 12855 12856 // Read the compatibilty setting when the system is ready. 12857 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12858 mContext.getContentResolver(), 12859 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12860 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12861 if (DEBUG_SETTINGS) { 12862 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12863 } 12864 12865 synchronized (mPackages) { 12866 // Verify that all of the preferred activity components actually 12867 // exist. It is possible for applications to be updated and at 12868 // that point remove a previously declared activity component that 12869 // had been set as a preferred activity. We try to clean this up 12870 // the next time we encounter that preferred activity, but it is 12871 // possible for the user flow to never be able to return to that 12872 // situation so here we do a sanity check to make sure we haven't 12873 // left any junk around. 12874 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12875 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12876 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12877 removed.clear(); 12878 for (PreferredActivity pa : pir.filterSet()) { 12879 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12880 removed.add(pa); 12881 } 12882 } 12883 if (removed.size() > 0) { 12884 for (int r=0; r<removed.size(); r++) { 12885 PreferredActivity pa = removed.get(r); 12886 Slog.w(TAG, "Removing dangling preferred activity: " 12887 + pa.mPref.mComponent); 12888 pir.removeFilter(pa); 12889 } 12890 mSettings.writePackageRestrictionsLPr( 12891 mSettings.mPreferredActivities.keyAt(i)); 12892 } 12893 } 12894 } 12895 sUserManager.systemReady(); 12896 12897 // Kick off any messages waiting for system ready 12898 if (mPostSystemReadyMessages != null) { 12899 for (Message msg : mPostSystemReadyMessages) { 12900 msg.sendToTarget(); 12901 } 12902 mPostSystemReadyMessages = null; 12903 } 12904 } 12905 12906 @Override 12907 public boolean isSafeMode() { 12908 return mSafeMode; 12909 } 12910 12911 @Override 12912 public boolean hasSystemUidErrors() { 12913 return mHasSystemUidErrors; 12914 } 12915 12916 static String arrayToString(int[] array) { 12917 StringBuffer buf = new StringBuffer(128); 12918 buf.append('['); 12919 if (array != null) { 12920 for (int i=0; i<array.length; i++) { 12921 if (i > 0) buf.append(", "); 12922 buf.append(array[i]); 12923 } 12924 } 12925 buf.append(']'); 12926 return buf.toString(); 12927 } 12928 12929 static class DumpState { 12930 public static final int DUMP_LIBS = 1 << 0; 12931 public static final int DUMP_FEATURES = 1 << 1; 12932 public static final int DUMP_RESOLVERS = 1 << 2; 12933 public static final int DUMP_PERMISSIONS = 1 << 3; 12934 public static final int DUMP_PACKAGES = 1 << 4; 12935 public static final int DUMP_SHARED_USERS = 1 << 5; 12936 public static final int DUMP_MESSAGES = 1 << 6; 12937 public static final int DUMP_PROVIDERS = 1 << 7; 12938 public static final int DUMP_VERIFIERS = 1 << 8; 12939 public static final int DUMP_PREFERRED = 1 << 9; 12940 public static final int DUMP_PREFERRED_XML = 1 << 10; 12941 public static final int DUMP_KEYSETS = 1 << 11; 12942 public static final int DUMP_VERSION = 1 << 12; 12943 public static final int DUMP_INSTALLS = 1 << 13; 12944 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 12945 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 12946 12947 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12948 12949 private int mTypes; 12950 12951 private int mOptions; 12952 12953 private boolean mTitlePrinted; 12954 12955 private SharedUserSetting mSharedUser; 12956 12957 public boolean isDumping(int type) { 12958 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12959 return true; 12960 } 12961 12962 return (mTypes & type) != 0; 12963 } 12964 12965 public void setDump(int type) { 12966 mTypes |= type; 12967 } 12968 12969 public boolean isOptionEnabled(int option) { 12970 return (mOptions & option) != 0; 12971 } 12972 12973 public void setOptionEnabled(int option) { 12974 mOptions |= option; 12975 } 12976 12977 public boolean onTitlePrinted() { 12978 final boolean printed = mTitlePrinted; 12979 mTitlePrinted = true; 12980 return printed; 12981 } 12982 12983 public boolean getTitlePrinted() { 12984 return mTitlePrinted; 12985 } 12986 12987 public void setTitlePrinted(boolean enabled) { 12988 mTitlePrinted = enabled; 12989 } 12990 12991 public SharedUserSetting getSharedUser() { 12992 return mSharedUser; 12993 } 12994 12995 public void setSharedUser(SharedUserSetting user) { 12996 mSharedUser = user; 12997 } 12998 } 12999 13000 @Override 13001 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13002 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13003 != PackageManager.PERMISSION_GRANTED) { 13004 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13005 + Binder.getCallingPid() 13006 + ", uid=" + Binder.getCallingUid() 13007 + " without permission " 13008 + android.Manifest.permission.DUMP); 13009 return; 13010 } 13011 13012 DumpState dumpState = new DumpState(); 13013 boolean fullPreferred = false; 13014 boolean checkin = false; 13015 13016 String packageName = null; 13017 13018 int opti = 0; 13019 while (opti < args.length) { 13020 String opt = args[opti]; 13021 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13022 break; 13023 } 13024 opti++; 13025 13026 if ("-a".equals(opt)) { 13027 // Right now we only know how to print all. 13028 } else if ("-h".equals(opt)) { 13029 pw.println("Package manager dump options:"); 13030 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13031 pw.println(" --checkin: dump for a checkin"); 13032 pw.println(" -f: print details of intent filters"); 13033 pw.println(" -h: print this help"); 13034 pw.println(" cmd may be one of:"); 13035 pw.println(" l[ibraries]: list known shared libraries"); 13036 pw.println(" f[ibraries]: list device features"); 13037 pw.println(" k[eysets]: print known keysets"); 13038 pw.println(" r[esolvers]: dump intent resolvers"); 13039 pw.println(" perm[issions]: dump permissions"); 13040 pw.println(" pref[erred]: print preferred package settings"); 13041 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13042 pw.println(" prov[iders]: dump content providers"); 13043 pw.println(" p[ackages]: dump installed packages"); 13044 pw.println(" s[hared-users]: dump shared user IDs"); 13045 pw.println(" m[essages]: print collected runtime messages"); 13046 pw.println(" v[erifiers]: print package verifier info"); 13047 pw.println(" version: print database version info"); 13048 pw.println(" write: write current settings now"); 13049 pw.println(" <package.name>: info about given package"); 13050 pw.println(" installs: details about install sessions"); 13051 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13052 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13053 return; 13054 } else if ("--checkin".equals(opt)) { 13055 checkin = true; 13056 } else if ("-f".equals(opt)) { 13057 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13058 } else { 13059 pw.println("Unknown argument: " + opt + "; use -h for help"); 13060 } 13061 } 13062 13063 // Is the caller requesting to dump a particular piece of data? 13064 if (opti < args.length) { 13065 String cmd = args[opti]; 13066 opti++; 13067 // Is this a package name? 13068 if ("android".equals(cmd) || cmd.contains(".")) { 13069 packageName = cmd; 13070 // When dumping a single package, we always dump all of its 13071 // filter information since the amount of data will be reasonable. 13072 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13073 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13074 dumpState.setDump(DumpState.DUMP_LIBS); 13075 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13076 dumpState.setDump(DumpState.DUMP_FEATURES); 13077 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13078 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13079 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13080 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13081 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13082 dumpState.setDump(DumpState.DUMP_PREFERRED); 13083 } else if ("preferred-xml".equals(cmd)) { 13084 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13085 if (opti < args.length && "--full".equals(args[opti])) { 13086 fullPreferred = true; 13087 opti++; 13088 } 13089 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13090 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13091 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13092 dumpState.setDump(DumpState.DUMP_PACKAGES); 13093 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13094 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13095 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13096 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13097 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13098 dumpState.setDump(DumpState.DUMP_MESSAGES); 13099 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13100 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13101 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13102 || "intent-filter-verifiers".equals(cmd)) { 13103 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13104 } else if ("version".equals(cmd)) { 13105 dumpState.setDump(DumpState.DUMP_VERSION); 13106 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13107 dumpState.setDump(DumpState.DUMP_KEYSETS); 13108 } else if ("installs".equals(cmd)) { 13109 dumpState.setDump(DumpState.DUMP_INSTALLS); 13110 } else if ("write".equals(cmd)) { 13111 synchronized (mPackages) { 13112 mSettings.writeLPr(); 13113 pw.println("Settings written."); 13114 return; 13115 } 13116 } 13117 } 13118 13119 if (checkin) { 13120 pw.println("vers,1"); 13121 } 13122 13123 // reader 13124 synchronized (mPackages) { 13125 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13126 if (!checkin) { 13127 if (dumpState.onTitlePrinted()) 13128 pw.println(); 13129 pw.println("Database versions:"); 13130 pw.print(" SDK Version:"); 13131 pw.print(" internal="); 13132 pw.print(mSettings.mInternalSdkPlatform); 13133 pw.print(" external="); 13134 pw.println(mSettings.mExternalSdkPlatform); 13135 pw.print(" DB Version:"); 13136 pw.print(" internal="); 13137 pw.print(mSettings.mInternalDatabaseVersion); 13138 pw.print(" external="); 13139 pw.println(mSettings.mExternalDatabaseVersion); 13140 } 13141 } 13142 13143 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13144 if (!checkin) { 13145 if (dumpState.onTitlePrinted()) 13146 pw.println(); 13147 pw.println("Verifiers:"); 13148 pw.print(" Required: "); 13149 pw.print(mRequiredVerifierPackage); 13150 pw.print(" (uid="); 13151 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13152 pw.println(")"); 13153 } else if (mRequiredVerifierPackage != null) { 13154 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13155 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13156 } 13157 } 13158 13159 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13160 packageName == null) { 13161 if (mIntentFilterVerifierComponent != null) { 13162 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13163 if (!checkin) { 13164 if (dumpState.onTitlePrinted()) 13165 pw.println(); 13166 pw.println("Intent Filter Verifier:"); 13167 pw.print(" Using: "); 13168 pw.print(verifierPackageName); 13169 pw.print(" (uid="); 13170 pw.print(getPackageUid(verifierPackageName, 0)); 13171 pw.println(")"); 13172 } else if (verifierPackageName != null) { 13173 pw.print("ifv,"); pw.print(verifierPackageName); 13174 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13175 } 13176 } else { 13177 pw.println(); 13178 pw.println("No Intent Filter Verifier available!"); 13179 } 13180 } 13181 13182 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13183 boolean printedHeader = false; 13184 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13185 while (it.hasNext()) { 13186 String name = it.next(); 13187 SharedLibraryEntry ent = mSharedLibraries.get(name); 13188 if (!checkin) { 13189 if (!printedHeader) { 13190 if (dumpState.onTitlePrinted()) 13191 pw.println(); 13192 pw.println("Libraries:"); 13193 printedHeader = true; 13194 } 13195 pw.print(" "); 13196 } else { 13197 pw.print("lib,"); 13198 } 13199 pw.print(name); 13200 if (!checkin) { 13201 pw.print(" -> "); 13202 } 13203 if (ent.path != null) { 13204 if (!checkin) { 13205 pw.print("(jar) "); 13206 pw.print(ent.path); 13207 } else { 13208 pw.print(",jar,"); 13209 pw.print(ent.path); 13210 } 13211 } else { 13212 if (!checkin) { 13213 pw.print("(apk) "); 13214 pw.print(ent.apk); 13215 } else { 13216 pw.print(",apk,"); 13217 pw.print(ent.apk); 13218 } 13219 } 13220 pw.println(); 13221 } 13222 } 13223 13224 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13225 if (dumpState.onTitlePrinted()) 13226 pw.println(); 13227 if (!checkin) { 13228 pw.println("Features:"); 13229 } 13230 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13231 while (it.hasNext()) { 13232 String name = it.next(); 13233 if (!checkin) { 13234 pw.print(" "); 13235 } else { 13236 pw.print("feat,"); 13237 } 13238 pw.println(name); 13239 } 13240 } 13241 13242 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13243 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13244 : "Activity Resolver Table:", " ", packageName, 13245 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13246 dumpState.setTitlePrinted(true); 13247 } 13248 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13249 : "Receiver Resolver Table:", " ", packageName, 13250 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13251 dumpState.setTitlePrinted(true); 13252 } 13253 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13254 : "Service Resolver Table:", " ", packageName, 13255 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13256 dumpState.setTitlePrinted(true); 13257 } 13258 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13259 : "Provider Resolver Table:", " ", packageName, 13260 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13261 dumpState.setTitlePrinted(true); 13262 } 13263 } 13264 13265 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13266 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13267 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13268 int user = mSettings.mPreferredActivities.keyAt(i); 13269 if (pir.dump(pw, 13270 dumpState.getTitlePrinted() 13271 ? "\nPreferred Activities User " + user + ":" 13272 : "Preferred Activities User " + user + ":", " ", 13273 packageName, true, false)) { 13274 dumpState.setTitlePrinted(true); 13275 } 13276 } 13277 } 13278 13279 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13280 pw.flush(); 13281 FileOutputStream fout = new FileOutputStream(fd); 13282 BufferedOutputStream str = new BufferedOutputStream(fout); 13283 XmlSerializer serializer = new FastXmlSerializer(); 13284 try { 13285 serializer.setOutput(str, "utf-8"); 13286 serializer.startDocument(null, true); 13287 serializer.setFeature( 13288 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13289 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13290 serializer.endDocument(); 13291 serializer.flush(); 13292 } catch (IllegalArgumentException e) { 13293 pw.println("Failed writing: " + e); 13294 } catch (IllegalStateException e) { 13295 pw.println("Failed writing: " + e); 13296 } catch (IOException e) { 13297 pw.println("Failed writing: " + e); 13298 } 13299 } 13300 13301 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13302 pw.println(); 13303 int count = mSettings.mPackages.size(); 13304 if (count == 0) { 13305 pw.println("No domain preferred apps!"); 13306 pw.println(); 13307 } else { 13308 final String prefix = " "; 13309 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13310 if (allPackageSettings.size() == 0) { 13311 pw.println("No domain preferred apps!"); 13312 pw.println(); 13313 } else { 13314 pw.println("Domain preferred apps status:"); 13315 pw.println(); 13316 count = 0; 13317 for (PackageSetting ps : allPackageSettings) { 13318 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13319 if (ivi == null || ivi.getPackageName() == null) continue; 13320 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13321 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13322 pw.println(prefix + "Status: " + ivi.getStatusString()); 13323 pw.println(); 13324 count++; 13325 } 13326 if (count == 0) { 13327 pw.println(prefix + "No domain preferred app status!"); 13328 pw.println(); 13329 } 13330 for (int userId : sUserManager.getUserIds()) { 13331 pw.println("Domain preferred apps for User " + userId + ":"); 13332 pw.println(); 13333 count = 0; 13334 for (PackageSetting ps : allPackageSettings) { 13335 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13336 if (ivi == null || ivi.getPackageName() == null) { 13337 continue; 13338 } 13339 final int status = ps.getDomainVerificationStatusForUser(userId); 13340 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13341 continue; 13342 } 13343 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13344 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13345 String statusStr = IntentFilterVerificationInfo. 13346 getStatusStringFromValue(status); 13347 pw.println(prefix + "Status: " + statusStr); 13348 pw.println(); 13349 count++; 13350 } 13351 if (count == 0) { 13352 pw.println(prefix + "No domain preferred apps!"); 13353 pw.println(); 13354 } 13355 } 13356 } 13357 } 13358 } 13359 13360 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13361 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13362 if (packageName == null) { 13363 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13364 if (iperm == 0) { 13365 if (dumpState.onTitlePrinted()) 13366 pw.println(); 13367 pw.println("AppOp Permissions:"); 13368 } 13369 pw.print(" AppOp Permission "); 13370 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13371 pw.println(":"); 13372 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13373 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13374 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13375 } 13376 } 13377 } 13378 } 13379 13380 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13381 boolean printedSomething = false; 13382 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13383 if (packageName != null && !packageName.equals(p.info.packageName)) { 13384 continue; 13385 } 13386 if (!printedSomething) { 13387 if (dumpState.onTitlePrinted()) 13388 pw.println(); 13389 pw.println("Registered ContentProviders:"); 13390 printedSomething = true; 13391 } 13392 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13393 pw.print(" "); pw.println(p.toString()); 13394 } 13395 printedSomething = false; 13396 for (Map.Entry<String, PackageParser.Provider> entry : 13397 mProvidersByAuthority.entrySet()) { 13398 PackageParser.Provider p = entry.getValue(); 13399 if (packageName != null && !packageName.equals(p.info.packageName)) { 13400 continue; 13401 } 13402 if (!printedSomething) { 13403 if (dumpState.onTitlePrinted()) 13404 pw.println(); 13405 pw.println("ContentProvider Authorities:"); 13406 printedSomething = true; 13407 } 13408 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13409 pw.print(" "); pw.println(p.toString()); 13410 if (p.info != null && p.info.applicationInfo != null) { 13411 final String appInfo = p.info.applicationInfo.toString(); 13412 pw.print(" applicationInfo="); pw.println(appInfo); 13413 } 13414 } 13415 } 13416 13417 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13418 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13419 } 13420 13421 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13422 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13423 } 13424 13425 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13426 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13427 } 13428 13429 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13430 // XXX should handle packageName != null by dumping only install data that 13431 // the given package is involved with. 13432 if (dumpState.onTitlePrinted()) pw.println(); 13433 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13434 } 13435 13436 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13437 if (dumpState.onTitlePrinted()) pw.println(); 13438 mSettings.dumpReadMessagesLPr(pw, dumpState); 13439 13440 pw.println(); 13441 pw.println("Package warning messages:"); 13442 BufferedReader in = null; 13443 String line = null; 13444 try { 13445 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13446 while ((line = in.readLine()) != null) { 13447 if (line.contains("ignored: updated version")) continue; 13448 pw.println(line); 13449 } 13450 } catch (IOException ignored) { 13451 } finally { 13452 IoUtils.closeQuietly(in); 13453 } 13454 } 13455 13456 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13457 BufferedReader in = null; 13458 String line = null; 13459 try { 13460 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13461 while ((line = in.readLine()) != null) { 13462 if (line.contains("ignored: updated version")) continue; 13463 pw.print("msg,"); 13464 pw.println(line); 13465 } 13466 } catch (IOException ignored) { 13467 } finally { 13468 IoUtils.closeQuietly(in); 13469 } 13470 } 13471 } 13472 } 13473 13474 // ------- apps on sdcard specific code ------- 13475 static final boolean DEBUG_SD_INSTALL = false; 13476 13477 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13478 13479 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13480 13481 private boolean mMediaMounted = false; 13482 13483 static String getEncryptKey() { 13484 try { 13485 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13486 SD_ENCRYPTION_KEYSTORE_NAME); 13487 if (sdEncKey == null) { 13488 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13489 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13490 if (sdEncKey == null) { 13491 Slog.e(TAG, "Failed to create encryption keys"); 13492 return null; 13493 } 13494 } 13495 return sdEncKey; 13496 } catch (NoSuchAlgorithmException nsae) { 13497 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13498 return null; 13499 } catch (IOException ioe) { 13500 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13501 return null; 13502 } 13503 } 13504 13505 /* 13506 * Update media status on PackageManager. 13507 */ 13508 @Override 13509 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13510 int callingUid = Binder.getCallingUid(); 13511 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13512 throw new SecurityException("Media status can only be updated by the system"); 13513 } 13514 // reader; this apparently protects mMediaMounted, but should probably 13515 // be a different lock in that case. 13516 synchronized (mPackages) { 13517 Log.i(TAG, "Updating external media status from " 13518 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13519 + (mediaStatus ? "mounted" : "unmounted")); 13520 if (DEBUG_SD_INSTALL) 13521 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13522 + ", mMediaMounted=" + mMediaMounted); 13523 if (mediaStatus == mMediaMounted) { 13524 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13525 : 0, -1); 13526 mHandler.sendMessage(msg); 13527 return; 13528 } 13529 mMediaMounted = mediaStatus; 13530 } 13531 // Queue up an async operation since the package installation may take a 13532 // little while. 13533 mHandler.post(new Runnable() { 13534 public void run() { 13535 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13536 } 13537 }); 13538 } 13539 13540 /** 13541 * Called by MountService when the initial ASECs to scan are available. 13542 * Should block until all the ASEC containers are finished being scanned. 13543 */ 13544 public void scanAvailableAsecs() { 13545 updateExternalMediaStatusInner(true, false, false); 13546 if (mShouldRestoreconData) { 13547 SELinuxMMAC.setRestoreconDone(); 13548 mShouldRestoreconData = false; 13549 } 13550 } 13551 13552 /* 13553 * Collect information of applications on external media, map them against 13554 * existing containers and update information based on current mount status. 13555 * Please note that we always have to report status if reportStatus has been 13556 * set to true especially when unloading packages. 13557 */ 13558 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13559 boolean externalStorage) { 13560 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13561 int[] uidArr = EmptyArray.INT; 13562 13563 final String[] list = PackageHelper.getSecureContainerList(); 13564 if (ArrayUtils.isEmpty(list)) { 13565 Log.i(TAG, "No secure containers found"); 13566 } else { 13567 // Process list of secure containers and categorize them 13568 // as active or stale based on their package internal state. 13569 13570 // reader 13571 synchronized (mPackages) { 13572 for (String cid : list) { 13573 // Leave stages untouched for now; installer service owns them 13574 if (PackageInstallerService.isStageName(cid)) continue; 13575 13576 if (DEBUG_SD_INSTALL) 13577 Log.i(TAG, "Processing container " + cid); 13578 String pkgName = getAsecPackageName(cid); 13579 if (pkgName == null) { 13580 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13581 continue; 13582 } 13583 if (DEBUG_SD_INSTALL) 13584 Log.i(TAG, "Looking for pkg : " + pkgName); 13585 13586 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13587 if (ps == null) { 13588 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13589 continue; 13590 } 13591 13592 /* 13593 * Skip packages that are not external if we're unmounting 13594 * external storage. 13595 */ 13596 if (externalStorage && !isMounted && !isExternal(ps)) { 13597 continue; 13598 } 13599 13600 final AsecInstallArgs args = new AsecInstallArgs(cid, 13601 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13602 // The package status is changed only if the code path 13603 // matches between settings and the container id. 13604 if (ps.codePathString != null 13605 && ps.codePathString.startsWith(args.getCodePath())) { 13606 if (DEBUG_SD_INSTALL) { 13607 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13608 + " at code path: " + ps.codePathString); 13609 } 13610 13611 // We do have a valid package installed on sdcard 13612 processCids.put(args, ps.codePathString); 13613 final int uid = ps.appId; 13614 if (uid != -1) { 13615 uidArr = ArrayUtils.appendInt(uidArr, uid); 13616 } 13617 } else { 13618 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13619 + ps.codePathString); 13620 } 13621 } 13622 } 13623 13624 Arrays.sort(uidArr); 13625 } 13626 13627 // Process packages with valid entries. 13628 if (isMounted) { 13629 if (DEBUG_SD_INSTALL) 13630 Log.i(TAG, "Loading packages"); 13631 loadMediaPackages(processCids, uidArr); 13632 startCleaningPackages(); 13633 mInstallerService.onSecureContainersAvailable(); 13634 } else { 13635 if (DEBUG_SD_INSTALL) 13636 Log.i(TAG, "Unloading packages"); 13637 unloadMediaPackages(processCids, uidArr, reportStatus); 13638 } 13639 } 13640 13641 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13642 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13643 int size = pkgList.size(); 13644 if (size > 0) { 13645 // Send broadcasts here 13646 Bundle extras = new Bundle(); 13647 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13648 .toArray(new String[size])); 13649 if (uidArr != null) { 13650 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13651 } 13652 if (replacing) { 13653 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13654 } 13655 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13656 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13657 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13658 } 13659 } 13660 13661 /* 13662 * Look at potentially valid container ids from processCids If package 13663 * information doesn't match the one on record or package scanning fails, 13664 * the cid is added to list of removeCids. We currently don't delete stale 13665 * containers. 13666 */ 13667 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13668 ArrayList<String> pkgList = new ArrayList<String>(); 13669 Set<AsecInstallArgs> keys = processCids.keySet(); 13670 13671 for (AsecInstallArgs args : keys) { 13672 String codePath = processCids.get(args); 13673 if (DEBUG_SD_INSTALL) 13674 Log.i(TAG, "Loading container : " + args.cid); 13675 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13676 try { 13677 // Make sure there are no container errors first. 13678 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13679 Slog.e(TAG, "Failed to mount cid : " + args.cid 13680 + " when installing from sdcard"); 13681 continue; 13682 } 13683 // Check code path here. 13684 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13685 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13686 + " does not match one in settings " + codePath); 13687 continue; 13688 } 13689 // Parse package 13690 int parseFlags = mDefParseFlags; 13691 if (args.isExternal()) { 13692 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13693 } 13694 if (args.isFwdLocked()) { 13695 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13696 } 13697 13698 synchronized (mInstallLock) { 13699 PackageParser.Package pkg = null; 13700 try { 13701 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13702 } catch (PackageManagerException e) { 13703 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13704 } 13705 // Scan the package 13706 if (pkg != null) { 13707 /* 13708 * TODO why is the lock being held? doPostInstall is 13709 * called in other places without the lock. This needs 13710 * to be straightened out. 13711 */ 13712 // writer 13713 synchronized (mPackages) { 13714 retCode = PackageManager.INSTALL_SUCCEEDED; 13715 pkgList.add(pkg.packageName); 13716 // Post process args 13717 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13718 pkg.applicationInfo.uid); 13719 } 13720 } else { 13721 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13722 } 13723 } 13724 13725 } finally { 13726 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13727 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13728 } 13729 } 13730 } 13731 // writer 13732 synchronized (mPackages) { 13733 // If the platform SDK has changed since the last time we booted, 13734 // we need to re-grant app permission to catch any new ones that 13735 // appear. This is really a hack, and means that apps can in some 13736 // cases get permissions that the user didn't initially explicitly 13737 // allow... it would be nice to have some better way to handle 13738 // this situation. 13739 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13740 if (regrantPermissions) 13741 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13742 + mSdkVersion + "; regranting permissions for external storage"); 13743 mSettings.mExternalSdkPlatform = mSdkVersion; 13744 13745 // Make sure group IDs have been assigned, and any permission 13746 // changes in other apps are accounted for 13747 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13748 | (regrantPermissions 13749 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13750 : 0)); 13751 13752 mSettings.updateExternalDatabaseVersion(); 13753 13754 // can downgrade to reader 13755 // Persist settings 13756 mSettings.writeLPr(); 13757 } 13758 // Send a broadcast to let everyone know we are done processing 13759 if (pkgList.size() > 0) { 13760 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13761 } 13762 } 13763 13764 /* 13765 * Utility method to unload a list of specified containers 13766 */ 13767 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13768 // Just unmount all valid containers. 13769 for (AsecInstallArgs arg : cidArgs) { 13770 synchronized (mInstallLock) { 13771 arg.doPostDeleteLI(false); 13772 } 13773 } 13774 } 13775 13776 /* 13777 * Unload packages mounted on external media. This involves deleting package 13778 * data from internal structures, sending broadcasts about diabled packages, 13779 * gc'ing to free up references, unmounting all secure containers 13780 * corresponding to packages on external media, and posting a 13781 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13782 * that we always have to post this message if status has been requested no 13783 * matter what. 13784 */ 13785 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13786 final boolean reportStatus) { 13787 if (DEBUG_SD_INSTALL) 13788 Log.i(TAG, "unloading media packages"); 13789 ArrayList<String> pkgList = new ArrayList<String>(); 13790 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13791 final Set<AsecInstallArgs> keys = processCids.keySet(); 13792 for (AsecInstallArgs args : keys) { 13793 String pkgName = args.getPackageName(); 13794 if (DEBUG_SD_INSTALL) 13795 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13796 // Delete package internally 13797 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13798 synchronized (mInstallLock) { 13799 boolean res = deletePackageLI(pkgName, null, false, null, null, 13800 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13801 if (res) { 13802 pkgList.add(pkgName); 13803 } else { 13804 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13805 failedList.add(args); 13806 } 13807 } 13808 } 13809 13810 // reader 13811 synchronized (mPackages) { 13812 // We didn't update the settings after removing each package; 13813 // write them now for all packages. 13814 mSettings.writeLPr(); 13815 } 13816 13817 // We have to absolutely send UPDATED_MEDIA_STATUS only 13818 // after confirming that all the receivers processed the ordered 13819 // broadcast when packages get disabled, force a gc to clean things up. 13820 // and unload all the containers. 13821 if (pkgList.size() > 0) { 13822 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13823 new IIntentReceiver.Stub() { 13824 public void performReceive(Intent intent, int resultCode, String data, 13825 Bundle extras, boolean ordered, boolean sticky, 13826 int sendingUser) throws RemoteException { 13827 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13828 reportStatus ? 1 : 0, 1, keys); 13829 mHandler.sendMessage(msg); 13830 } 13831 }); 13832 } else { 13833 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13834 keys); 13835 mHandler.sendMessage(msg); 13836 } 13837 } 13838 13839 /** Binder call */ 13840 @Override 13841 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13842 final int flags) { 13843 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13844 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13845 int returnCode = PackageManager.MOVE_SUCCEEDED; 13846 int currInstallFlags = 0; 13847 int newInstallFlags = 0; 13848 13849 File codeFile = null; 13850 String installerPackageName = null; 13851 String packageAbiOverride = null; 13852 13853 // reader 13854 synchronized (mPackages) { 13855 final PackageParser.Package pkg = mPackages.get(packageName); 13856 final PackageSetting ps = mSettings.mPackages.get(packageName); 13857 if (pkg == null || ps == null) { 13858 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13859 } else { 13860 // Disable moving fwd locked apps and system packages 13861 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13862 Slog.w(TAG, "Cannot move system application"); 13863 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13864 } else if (pkg.mOperationPending) { 13865 Slog.w(TAG, "Attempt to move package which has pending operations"); 13866 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13867 } else { 13868 // Find install location first 13869 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13870 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13871 Slog.w(TAG, "Ambigous flags specified for move location."); 13872 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13873 } else { 13874 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13875 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13876 currInstallFlags = isExternal(pkg) 13877 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13878 13879 if (newInstallFlags == currInstallFlags) { 13880 Slog.w(TAG, "No move required. Trying to move to same location"); 13881 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13882 } else { 13883 if (pkg.isForwardLocked()) { 13884 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13885 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13886 } 13887 } 13888 } 13889 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13890 pkg.mOperationPending = true; 13891 } 13892 } 13893 13894 codeFile = new File(pkg.codePath); 13895 installerPackageName = ps.installerPackageName; 13896 packageAbiOverride = ps.cpuAbiOverrideString; 13897 } 13898 } 13899 13900 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13901 try { 13902 observer.packageMoved(packageName, returnCode); 13903 } catch (RemoteException ignored) { 13904 } 13905 return; 13906 } 13907 13908 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13909 @Override 13910 public void onUserActionRequired(Intent intent) throws RemoteException { 13911 throw new IllegalStateException(); 13912 } 13913 13914 @Override 13915 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13916 Bundle extras) throws RemoteException { 13917 Slog.d(TAG, "Install result for move: " 13918 + PackageManager.installStatusToString(returnCode, msg)); 13919 13920 // We usually have a new package now after the install, but if 13921 // we failed we need to clear the pending flag on the original 13922 // package object. 13923 synchronized (mPackages) { 13924 final PackageParser.Package pkg = mPackages.get(packageName); 13925 if (pkg != null) { 13926 pkg.mOperationPending = false; 13927 } 13928 } 13929 13930 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13931 switch (status) { 13932 case PackageInstaller.STATUS_SUCCESS: 13933 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13934 break; 13935 case PackageInstaller.STATUS_FAILURE_STORAGE: 13936 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13937 break; 13938 default: 13939 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13940 break; 13941 } 13942 } 13943 }; 13944 13945 // Treat a move like reinstalling an existing app, which ensures that we 13946 // process everythign uniformly, like unpacking native libraries. 13947 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13948 13949 final Message msg = mHandler.obtainMessage(INIT_COPY); 13950 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13951 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13952 installerPackageName, null, user, packageAbiOverride); 13953 mHandler.sendMessage(msg); 13954 } 13955 13956 @Override 13957 public boolean setInstallLocation(int loc) { 13958 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13959 null); 13960 if (getInstallLocation() == loc) { 13961 return true; 13962 } 13963 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13964 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13965 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13966 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13967 return true; 13968 } 13969 return false; 13970 } 13971 13972 @Override 13973 public int getInstallLocation() { 13974 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13975 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13976 PackageHelper.APP_INSTALL_AUTO); 13977 } 13978 13979 /** Called by UserManagerService */ 13980 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13981 mDirtyUsers.remove(userHandle); 13982 mSettings.removeUserLPw(userHandle); 13983 mPendingBroadcasts.remove(userHandle); 13984 if (mInstaller != null) { 13985 // Technically, we shouldn't be doing this with the package lock 13986 // held. However, this is very rare, and there is already so much 13987 // other disk I/O going on, that we'll let it slide for now. 13988 mInstaller.removeUserDataDirs(userHandle); 13989 } 13990 mUserNeedsBadging.delete(userHandle); 13991 removeUnusedPackagesLILPw(userManager, userHandle); 13992 } 13993 13994 /** 13995 * We're removing userHandle and would like to remove any downloaded packages 13996 * that are no longer in use by any other user. 13997 * @param userHandle the user being removed 13998 */ 13999 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14000 final boolean DEBUG_CLEAN_APKS = false; 14001 int [] users = userManager.getUserIdsLPr(); 14002 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14003 while (psit.hasNext()) { 14004 PackageSetting ps = psit.next(); 14005 if (ps.pkg == null) { 14006 continue; 14007 } 14008 final String packageName = ps.pkg.packageName; 14009 // Skip over if system app 14010 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14011 continue; 14012 } 14013 if (DEBUG_CLEAN_APKS) { 14014 Slog.i(TAG, "Checking package " + packageName); 14015 } 14016 boolean keep = false; 14017 for (int i = 0; i < users.length; i++) { 14018 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14019 keep = true; 14020 if (DEBUG_CLEAN_APKS) { 14021 Slog.i(TAG, " Keeping package " + packageName + " for user " 14022 + users[i]); 14023 } 14024 break; 14025 } 14026 } 14027 if (!keep) { 14028 if (DEBUG_CLEAN_APKS) { 14029 Slog.i(TAG, " Removing package " + packageName); 14030 } 14031 mHandler.post(new Runnable() { 14032 public void run() { 14033 deletePackageX(packageName, userHandle, 0); 14034 } //end run 14035 }); 14036 } 14037 } 14038 } 14039 14040 /** Called by UserManagerService */ 14041 void createNewUserLILPw(int userHandle, File path) { 14042 if (mInstaller != null) { 14043 mInstaller.createUserConfig(userHandle); 14044 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14045 } 14046 } 14047 14048 void newUserCreatedLILPw(int userHandle) { 14049 // Adding a user requires updating runtime permissions for system apps. 14050 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14051 } 14052 14053 @Override 14054 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14055 mContext.enforceCallingOrSelfPermission( 14056 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14057 "Only package verification agents can read the verifier device identity"); 14058 14059 synchronized (mPackages) { 14060 return mSettings.getVerifierDeviceIdentityLPw(); 14061 } 14062 } 14063 14064 @Override 14065 public void setPermissionEnforced(String permission, boolean enforced) { 14066 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14067 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14068 synchronized (mPackages) { 14069 if (mSettings.mReadExternalStorageEnforced == null 14070 || mSettings.mReadExternalStorageEnforced != enforced) { 14071 mSettings.mReadExternalStorageEnforced = enforced; 14072 mSettings.writeLPr(); 14073 } 14074 } 14075 // kill any non-foreground processes so we restart them and 14076 // grant/revoke the GID. 14077 final IActivityManager am = ActivityManagerNative.getDefault(); 14078 if (am != null) { 14079 final long token = Binder.clearCallingIdentity(); 14080 try { 14081 am.killProcessesBelowForeground("setPermissionEnforcement"); 14082 } catch (RemoteException e) { 14083 } finally { 14084 Binder.restoreCallingIdentity(token); 14085 } 14086 } 14087 } else { 14088 throw new IllegalArgumentException("No selective enforcement for " + permission); 14089 } 14090 } 14091 14092 @Override 14093 @Deprecated 14094 public boolean isPermissionEnforced(String permission) { 14095 return true; 14096 } 14097 14098 @Override 14099 public boolean isStorageLow() { 14100 final long token = Binder.clearCallingIdentity(); 14101 try { 14102 final DeviceStorageMonitorInternal 14103 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14104 if (dsm != null) { 14105 return dsm.isMemoryLow(); 14106 } else { 14107 return false; 14108 } 14109 } finally { 14110 Binder.restoreCallingIdentity(token); 14111 } 14112 } 14113 14114 @Override 14115 public IPackageInstaller getPackageInstaller() { 14116 return mInstallerService; 14117 } 14118 14119 private boolean userNeedsBadging(int userId) { 14120 int index = mUserNeedsBadging.indexOfKey(userId); 14121 if (index < 0) { 14122 final UserInfo userInfo; 14123 final long token = Binder.clearCallingIdentity(); 14124 try { 14125 userInfo = sUserManager.getUserInfo(userId); 14126 } finally { 14127 Binder.restoreCallingIdentity(token); 14128 } 14129 final boolean b; 14130 if (userInfo != null && userInfo.isManagedProfile()) { 14131 b = true; 14132 } else { 14133 b = false; 14134 } 14135 mUserNeedsBadging.put(userId, b); 14136 return b; 14137 } 14138 return mUserNeedsBadging.valueAt(index); 14139 } 14140 14141 @Override 14142 public KeySet getKeySetByAlias(String packageName, String alias) { 14143 if (packageName == null || alias == null) { 14144 return null; 14145 } 14146 synchronized(mPackages) { 14147 final PackageParser.Package pkg = mPackages.get(packageName); 14148 if (pkg == null) { 14149 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14150 throw new IllegalArgumentException("Unknown package: " + packageName); 14151 } 14152 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14153 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14154 } 14155 } 14156 14157 @Override 14158 public KeySet getSigningKeySet(String packageName) { 14159 if (packageName == null) { 14160 return null; 14161 } 14162 synchronized(mPackages) { 14163 final PackageParser.Package pkg = mPackages.get(packageName); 14164 if (pkg == null) { 14165 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14166 throw new IllegalArgumentException("Unknown package: " + packageName); 14167 } 14168 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14169 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14170 throw new SecurityException("May not access signing KeySet of other apps."); 14171 } 14172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14173 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14174 } 14175 } 14176 14177 @Override 14178 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14179 if (packageName == null || ks == null) { 14180 return false; 14181 } 14182 synchronized(mPackages) { 14183 final PackageParser.Package pkg = mPackages.get(packageName); 14184 if (pkg == null) { 14185 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14186 throw new IllegalArgumentException("Unknown package: " + packageName); 14187 } 14188 IBinder ksh = ks.getToken(); 14189 if (ksh instanceof KeySetHandle) { 14190 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14191 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14192 } 14193 return false; 14194 } 14195 } 14196 14197 @Override 14198 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14199 if (packageName == null || ks == null) { 14200 return false; 14201 } 14202 synchronized(mPackages) { 14203 final PackageParser.Package pkg = mPackages.get(packageName); 14204 if (pkg == null) { 14205 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14206 throw new IllegalArgumentException("Unknown package: " + packageName); 14207 } 14208 IBinder ksh = ks.getToken(); 14209 if (ksh instanceof KeySetHandle) { 14210 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14211 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14212 } 14213 return false; 14214 } 14215 } 14216 14217 public void getUsageStatsIfNoPackageUsageInfo() { 14218 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14219 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14220 if (usm == null) { 14221 throw new IllegalStateException("UsageStatsManager must be initialized"); 14222 } 14223 long now = System.currentTimeMillis(); 14224 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14225 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14226 String packageName = entry.getKey(); 14227 PackageParser.Package pkg = mPackages.get(packageName); 14228 if (pkg == null) { 14229 continue; 14230 } 14231 UsageStats usage = entry.getValue(); 14232 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14233 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14234 } 14235 } 14236 } 14237 14238 /** 14239 * Check and throw if the given before/after packages would be considered a 14240 * downgrade. 14241 */ 14242 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14243 throws PackageManagerException { 14244 if (after.versionCode < before.mVersionCode) { 14245 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14246 "Update version code " + after.versionCode + " is older than current " 14247 + before.mVersionCode); 14248 } else if (after.versionCode == before.mVersionCode) { 14249 if (after.baseRevisionCode < before.baseRevisionCode) { 14250 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14251 "Update base revision code " + after.baseRevisionCode 14252 + " is older than current " + before.baseRevisionCode); 14253 } 14254 14255 if (!ArrayUtils.isEmpty(after.splitNames)) { 14256 for (int i = 0; i < after.splitNames.length; i++) { 14257 final String splitName = after.splitNames[i]; 14258 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14259 if (j != -1) { 14260 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14261 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14262 "Update split " + splitName + " revision code " 14263 + after.splitRevisionCodes[i] + " is older than current " 14264 + before.splitRevisionCodes[j]); 14265 } 14266 } 14267 } 14268 } 14269 } 14270 } 14271} 14272