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