PackageManagerService.java revision 8aa61000021ed32480599c7dea875f0b27ba44f0
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MOVE_EXTERNAL_MEDIA; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 56import static android.content.pm.PackageManager.MOVE_INTERNAL; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import org.xmlpull.v1.XmlPullParser; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.text.format.DateUtils; 165import android.util.ArrayMap; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.util.Xml; 178import android.view.Display; 179 180import dalvik.system.DexFile; 181import dalvik.system.VMRuntime; 182 183import libcore.io.IoUtils; 184import libcore.util.EmptyArray; 185 186import com.android.internal.R; 187import com.android.internal.app.IMediaContainerService; 188import com.android.internal.app.ResolverActivity; 189import com.android.internal.content.NativeLibraryHelper; 190import com.android.internal.content.PackageHelper; 191import com.android.internal.os.IParcelFileDescriptorFactory; 192import com.android.internal.util.ArrayUtils; 193import com.android.internal.util.FastPrintWriter; 194import com.android.internal.util.FastXmlSerializer; 195import com.android.internal.util.IndentingPrintWriter; 196import com.android.server.EventLogTags; 197import com.android.server.IntentResolver; 198import com.android.server.LocalServices; 199import com.android.server.ServiceThread; 200import com.android.server.SystemConfig; 201import com.android.server.Watchdog; 202import com.android.server.pm.Settings.DatabaseVersion; 203import com.android.server.storage.DeviceStorageMonitorInternal; 204 205import org.xmlpull.v1.XmlSerializer; 206 207import java.io.BufferedInputStream; 208import java.io.BufferedOutputStream; 209import java.io.BufferedReader; 210import java.io.ByteArrayInputStream; 211import java.io.ByteArrayOutputStream; 212import java.io.File; 213import java.io.FileDescriptor; 214import java.io.FileNotFoundException; 215import java.io.FileOutputStream; 216import java.io.FileReader; 217import java.io.FilenameFilter; 218import java.io.IOException; 219import java.io.InputStream; 220import java.io.PrintWriter; 221import java.nio.charset.StandardCharsets; 222import java.security.NoSuchAlgorithmException; 223import java.security.PublicKey; 224import java.security.cert.CertificateEncodingException; 225import java.security.cert.CertificateException; 226import java.text.SimpleDateFormat; 227import java.util.ArrayList; 228import java.util.Arrays; 229import java.util.Collection; 230import java.util.Collections; 231import java.util.Comparator; 232import java.util.Date; 233import java.util.Iterator; 234import java.util.List; 235import java.util.Map; 236import java.util.Objects; 237import java.util.Set; 238import java.util.concurrent.atomic.AtomicBoolean; 239import java.util.concurrent.atomic.AtomicLong; 240 241/** 242 * Keep track of all those .apks everywhere. 243 * 244 * This is very central to the platform's security; please run the unit 245 * tests whenever making modifications here: 246 * 247mmm frameworks/base/tests/AndroidTests 248adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 249adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 250 * 251 * {@hide} 252 */ 253public class PackageManagerService extends IPackageManager.Stub { 254 static final String TAG = "PackageManager"; 255 static final boolean DEBUG_SETTINGS = false; 256 static final boolean DEBUG_PREFERRED = false; 257 static final boolean DEBUG_UPGRADE = false; 258 private static final boolean DEBUG_BACKUP = true; 259 private static final boolean DEBUG_INSTALL = false; 260 private static final boolean DEBUG_REMOVE = false; 261 private static final boolean DEBUG_BROADCASTS = false; 262 private static final boolean DEBUG_SHOW_INFO = false; 263 private static final boolean DEBUG_PACKAGE_INFO = false; 264 private static final boolean DEBUG_INTENT_MATCHING = false; 265 private static final boolean DEBUG_PACKAGE_SCANNING = false; 266 private static final boolean DEBUG_VERIFY = false; 267 private static final boolean DEBUG_DEXOPT = false; 268 private static final boolean DEBUG_ABI_SELECTION = false; 269 270 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 271 272 private static final int RADIO_UID = Process.PHONE_UID; 273 private static final int LOG_UID = Process.LOG_UID; 274 private static final int NFC_UID = Process.NFC_UID; 275 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 276 private static final int SHELL_UID = Process.SHELL_UID; 277 278 // Cap the size of permission trees that 3rd party apps can define 279 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 280 281 // Suffix used during package installation when copying/moving 282 // package apks to install directory. 283 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 284 285 static final int SCAN_NO_DEX = 1<<1; 286 static final int SCAN_FORCE_DEX = 1<<2; 287 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 288 static final int SCAN_NEW_INSTALL = 1<<4; 289 static final int SCAN_NO_PATHS = 1<<5; 290 static final int SCAN_UPDATE_TIME = 1<<6; 291 static final int SCAN_DEFER_DEX = 1<<7; 292 static final int SCAN_BOOTING = 1<<8; 293 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 294 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 295 static final int SCAN_REPLACING = 1<<11; 296 static final int SCAN_REQUIRE_KNOWN = 1<<12; 297 298 static final int REMOVE_CHATTY = 1<<16; 299 300 /** 301 * Timeout (in milliseconds) after which the watchdog should declare that 302 * our handler thread is wedged. The usual default for such things is one 303 * minute but we sometimes do very lengthy I/O operations on this thread, 304 * such as installing multi-gigabyte applications, so ours needs to be longer. 305 */ 306 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 307 308 /** 309 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 310 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 311 * settings entry if available, otherwise we use the hardcoded default. If it's been 312 * more than this long since the last fstrim, we force one during the boot sequence. 313 * 314 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 315 * one gets run at the next available charging+idle time. This final mandatory 316 * no-fstrim check kicks in only of the other scheduling criteria is never met. 317 */ 318 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 319 320 /** 321 * Whether verification is enabled by default. 322 */ 323 private static final boolean DEFAULT_VERIFY_ENABLE = true; 324 325 /** 326 * The default maximum time to wait for the verification agent to return in 327 * milliseconds. 328 */ 329 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 330 331 /** 332 * The default response for package verification timeout. 333 * 334 * This can be either PackageManager.VERIFICATION_ALLOW or 335 * PackageManager.VERIFICATION_REJECT. 336 */ 337 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 338 339 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 340 341 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 342 DEFAULT_CONTAINER_PACKAGE, 343 "com.android.defcontainer.DefaultContainerService"); 344 345 private static final String KILL_APP_REASON_GIDS_CHANGED = 346 "permission grant or revoke changed gids"; 347 348 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 349 "permissions revoked"; 350 351 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 352 353 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 354 355 /** Permission grant: not grant the permission. */ 356 private static final int GRANT_DENIED = 1; 357 358 /** Permission grant: grant the permission as an install permission. */ 359 private static final int GRANT_INSTALL = 2; 360 361 /** Permission grant: grant the permission as a runtime one. */ 362 private static final int GRANT_RUNTIME = 3; 363 364 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 365 private static final int GRANT_UPGRADE = 4; 366 367 final ServiceThread mHandlerThread; 368 369 final PackageHandler mHandler; 370 371 /** 372 * Messages for {@link #mHandler} that need to wait for system ready before 373 * being dispatched. 374 */ 375 private ArrayList<Message> mPostSystemReadyMessages; 376 377 final int mSdkVersion = Build.VERSION.SDK_INT; 378 379 final Context mContext; 380 final boolean mFactoryTest; 381 final boolean mOnlyCore; 382 final boolean mLazyDexOpt; 383 final long mDexOptLRUThresholdInMills; 384 final DisplayMetrics mMetrics; 385 final int mDefParseFlags; 386 final String[] mSeparateProcesses; 387 final boolean mIsUpgrade; 388 389 // This is where all application persistent data goes. 390 final File mAppDataDir; 391 392 // This is where all application persistent data goes for secondary users. 393 final File mUserAppDataDir; 394 395 /** The location for ASEC container files on internal storage. */ 396 final String mAsecInternalPath; 397 398 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 399 // LOCK HELD. Can be called with mInstallLock held. 400 final Installer mInstaller; 401 402 /** Directory where installed third-party apps stored */ 403 final File mAppInstallDir; 404 405 /** 406 * Directory to which applications installed internally have their 407 * 32 bit native libraries copied. 408 */ 409 private File mAppLib32InstallDir; 410 411 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 412 // apps. 413 final File mDrmAppPrivateInstallDir; 414 415 // ---------------------------------------------------------------- 416 417 // Lock for state used when installing and doing other long running 418 // operations. Methods that must be called with this lock held have 419 // the suffix "LI". 420 final Object mInstallLock = new Object(); 421 422 // ---------------------------------------------------------------- 423 424 // Keys are String (package name), values are Package. This also serves 425 // as the lock for the global state. Methods that must be called with 426 // this lock held have the prefix "LP". 427 final ArrayMap<String, PackageParser.Package> mPackages = 428 new ArrayMap<String, PackageParser.Package>(); 429 430 // Tracks available target package names -> overlay package paths. 431 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 432 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 433 434 final Settings mSettings; 435 boolean mRestoredSettings; 436 437 // System configuration read by SystemConfig. 438 final int[] mGlobalGids; 439 final SparseArray<ArraySet<String>> mSystemPermissions; 440 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 441 442 // If mac_permissions.xml was found for seinfo labeling. 443 boolean mFoundPolicyFile; 444 445 // If a recursive restorecon of /data/data/<pkg> is needed. 446 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 447 448 public static final class SharedLibraryEntry { 449 public final String path; 450 public final String apk; 451 452 SharedLibraryEntry(String _path, String _apk) { 453 path = _path; 454 apk = _apk; 455 } 456 } 457 458 // Currently known shared libraries. 459 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 460 new ArrayMap<String, SharedLibraryEntry>(); 461 462 // All available activities, for your resolving pleasure. 463 final ActivityIntentResolver mActivities = 464 new ActivityIntentResolver(); 465 466 // All available receivers, for your resolving pleasure. 467 final ActivityIntentResolver mReceivers = 468 new ActivityIntentResolver(); 469 470 // All available services, for your resolving pleasure. 471 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 472 473 // All available providers, for your resolving pleasure. 474 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 475 476 // Mapping from provider base names (first directory in content URI codePath) 477 // to the provider information. 478 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 479 new ArrayMap<String, PackageParser.Provider>(); 480 481 // Mapping from instrumentation class names to info about them. 482 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 483 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 484 485 // Mapping from permission names to info about them. 486 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 487 new ArrayMap<String, PackageParser.PermissionGroup>(); 488 489 // Packages whose data we have transfered into another package, thus 490 // should no longer exist. 491 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 492 493 // Broadcast actions that are only available to the system. 494 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 495 496 /** List of packages waiting for verification. */ 497 final SparseArray<PackageVerificationState> mPendingVerification 498 = new SparseArray<PackageVerificationState>(); 499 500 /** Set of packages associated with each app op permission. */ 501 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 502 503 final PackageInstallerService mInstallerService; 504 505 private final PackageDexOptimizer mPackageDexOptimizer; 506 // Cache of users who need badging. 507 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 508 509 /** Token for keys in mPendingVerification. */ 510 private int mPendingVerificationToken = 0; 511 512 volatile boolean mSystemReady; 513 volatile boolean mSafeMode; 514 volatile boolean mHasSystemUidErrors; 515 516 ApplicationInfo mAndroidApplication; 517 final ActivityInfo mResolveActivity = new ActivityInfo(); 518 final ResolveInfo mResolveInfo = new ResolveInfo(); 519 ComponentName mResolveComponentName; 520 PackageParser.Package mPlatformPackage; 521 ComponentName mCustomResolverComponentName; 522 523 boolean mResolverReplaced = false; 524 525 private final ComponentName mIntentFilterVerifierComponent; 526 private int mIntentFilterVerificationToken = 0; 527 528 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 529 = new SparseArray<IntentFilterVerificationState>(); 530 531 private interface IntentFilterVerifier<T extends IntentFilter> { 532 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 533 T filter, String packageName); 534 void startVerifications(int userId); 535 void receiveVerificationResponse(int verificationId); 536 } 537 538 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 539 private Context mContext; 540 private ComponentName mIntentFilterVerifierComponent; 541 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 542 543 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 544 mContext = context; 545 mIntentFilterVerifierComponent = verifierComponent; 546 } 547 548 private String getDefaultScheme() { 549 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 550 return IntentFilter.SCHEME_HTTP; 551 } 552 553 @Override 554 public void startVerifications(int userId) { 555 // Launch verifications requests 556 int count = mCurrentIntentFilterVerifications.size(); 557 for (int n=0; n<count; n++) { 558 int verificationId = mCurrentIntentFilterVerifications.get(n); 559 final IntentFilterVerificationState ivs = 560 mIntentFilterVerificationStates.get(verificationId); 561 562 String packageName = ivs.getPackageName(); 563 boolean modified = false; 564 565 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 566 final int filterCount = filters.size(); 567 for (int m=0; m<filterCount; m++) { 568 PackageParser.ActivityIntentInfo filter = filters.get(m); 569 synchronized (mPackages) { 570 modified = mSettings.createIntentFilterVerificationIfNeededLPw( 571 packageName, filter.getHosts()); 572 } 573 } 574 synchronized (mPackages) { 575 if (modified) { 576 scheduleWriteSettingsLocked(); 577 } 578 } 579 sendVerificationRequest(userId, verificationId, ivs); 580 } 581 mCurrentIntentFilterVerifications.clear(); 582 } 583 584 private void sendVerificationRequest(int userId, int verificationId, 585 IntentFilterVerificationState ivs) { 586 587 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 588 verificationIntent.putExtra( 589 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 590 verificationId); 591 verificationIntent.putExtra( 592 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 593 getDefaultScheme()); 594 verificationIntent.putExtra( 595 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 596 ivs.getHostsString()); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 599 ivs.getPackageName()); 600 verificationIntent.setComponent(mIntentFilterVerifierComponent); 601 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 602 603 UserHandle user = new UserHandle(userId); 604 mContext.sendBroadcastAsUser(verificationIntent, user); 605 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 606 } 607 608 public void receiveVerificationResponse(int verificationId) { 609 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 610 611 final boolean verified = ivs.isVerified(); 612 613 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 614 final int count = filters.size(); 615 for (int n=0; n<count; n++) { 616 PackageParser.ActivityIntentInfo filter = filters.get(n); 617 filter.setVerified(verified); 618 619 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 620 + verified + " and hosts:" + ivs.getHostsString()); 621 } 622 623 mIntentFilterVerificationStates.remove(verificationId); 624 625 final String packageName = ivs.getPackageName(); 626 IntentFilterVerificationInfo ivi = null; 627 628 synchronized (mPackages) { 629 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 630 } 631 if (ivi == null) { 632 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 633 + verificationId + " packageName:" + packageName); 634 return; 635 } 636 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 637 + verificationId); 638 639 synchronized (mPackages) { 640 if (verified) { 641 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 642 } else { 643 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 644 } 645 scheduleWriteSettingsLocked(); 646 647 final int userId = ivs.getUserId(); 648 if (userId != UserHandle.USER_ALL) { 649 final int userStatus = 650 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 651 652 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 653 boolean needUpdate = false; 654 655 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 656 // already been set by the User thru the Disambiguation dialog 657 switch (userStatus) { 658 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 659 if (verified) { 660 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 661 } else { 662 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 663 } 664 needUpdate = true; 665 break; 666 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 needUpdate = true; 671 } 672 break; 673 674 default: 675 // Nothing to do 676 } 677 678 if (needUpdate) { 679 mSettings.updateIntentFilterVerificationStatusLPw( 680 packageName, updatedStatus, userId); 681 scheduleWritePackageRestrictionsLocked(userId); 682 } 683 } 684 } 685 } 686 687 @Override 688 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 689 ActivityIntentInfo filter, String packageName) { 690 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 691 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 692 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 693 return false; 694 } 695 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 696 if (ivs == null) { 697 ivs = createDomainVerificationState(verifierId, userId, verificationId, 698 packageName); 699 } 700 ArrayList<String> hosts = filter.getHostsList(); 701 if (!hasValidHosts(hosts)) { 702 return false; 703 } 704 ivs.addFilter(filter); 705 return true; 706 } 707 708 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 709 int userId, int verificationId, String packageName) { 710 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 711 verifierId, userId, packageName); 712 ivs.setPendingState(); 713 synchronized (mPackages) { 714 mIntentFilterVerificationStates.append(verificationId, ivs); 715 mCurrentIntentFilterVerifications.add(verificationId); 716 } 717 return ivs; 718 } 719 720 private boolean hasValidHosts(ArrayList<String> hosts) { 721 if (hosts.size() == 0) { 722 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 723 return false; 724 } 725 String hostEndBase = null; 726 for (String host : hosts) { 727 String[] hostParts = host.split("\\."); 728 // Should be at minimum a host like "example.com" 729 if (hostParts.length < 2) { 730 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 731 return false; 732 } 733 // Verify that we have the same ending domain 734 int length = hostParts.length; 735 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 736 if (hostEndBase == null) { 737 hostEndBase = hostEnd; 738 } 739 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 740 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 741 return false; 742 } 743 } 744 return true; 745 } 746 } 747 748 private IntentFilterVerifier mIntentFilterVerifier; 749 750 // Set of pending broadcasts for aggregating enable/disable of components. 751 static class PendingPackageBroadcasts { 752 // for each user id, a map of <package name -> components within that package> 753 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 754 755 public PendingPackageBroadcasts() { 756 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 757 } 758 759 public ArrayList<String> get(int userId, String packageName) { 760 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 761 return packages.get(packageName); 762 } 763 764 public void put(int userId, String packageName, ArrayList<String> components) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 packages.put(packageName, components); 767 } 768 769 public void remove(int userId, String packageName) { 770 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 771 if (packages != null) { 772 packages.remove(packageName); 773 } 774 } 775 776 public void remove(int userId) { 777 mUidMap.remove(userId); 778 } 779 780 public int userIdCount() { 781 return mUidMap.size(); 782 } 783 784 public int userIdAt(int n) { 785 return mUidMap.keyAt(n); 786 } 787 788 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 789 return mUidMap.get(userId); 790 } 791 792 public int size() { 793 // total number of pending broadcast entries across all userIds 794 int num = 0; 795 for (int i = 0; i< mUidMap.size(); i++) { 796 num += mUidMap.valueAt(i).size(); 797 } 798 return num; 799 } 800 801 public void clear() { 802 mUidMap.clear(); 803 } 804 805 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 806 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 807 if (map == null) { 808 map = new ArrayMap<String, ArrayList<String>>(); 809 mUidMap.put(userId, map); 810 } 811 return map; 812 } 813 } 814 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 815 816 // Service Connection to remote media container service to copy 817 // package uri's from external media onto secure containers 818 // or internal storage. 819 private IMediaContainerService mContainerService = null; 820 821 static final int SEND_PENDING_BROADCAST = 1; 822 static final int MCS_BOUND = 3; 823 static final int END_COPY = 4; 824 static final int INIT_COPY = 5; 825 static final int MCS_UNBIND = 6; 826 static final int START_CLEANING_PACKAGE = 7; 827 static final int FIND_INSTALL_LOC = 8; 828 static final int POST_INSTALL = 9; 829 static final int MCS_RECONNECT = 10; 830 static final int MCS_GIVE_UP = 11; 831 static final int UPDATED_MEDIA_STATUS = 12; 832 static final int WRITE_SETTINGS = 13; 833 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 834 static final int PACKAGE_VERIFIED = 15; 835 static final int CHECK_PENDING_VERIFICATION = 16; 836 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 837 static final int INTENT_FILTER_VERIFIED = 18; 838 839 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 840 841 // Delay time in millisecs 842 static final int BROADCAST_DELAY = 10 * 1000; 843 844 static UserManagerService sUserManager; 845 846 // Stores a list of users whose package restrictions file needs to be updated 847 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 848 849 final private DefaultContainerConnection mDefContainerConn = 850 new DefaultContainerConnection(); 851 class DefaultContainerConnection implements ServiceConnection { 852 public void onServiceConnected(ComponentName name, IBinder service) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 854 IMediaContainerService imcs = 855 IMediaContainerService.Stub.asInterface(service); 856 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 857 } 858 859 public void onServiceDisconnected(ComponentName name) { 860 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 861 } 862 }; 863 864 // Recordkeeping of restore-after-install operations that are currently in flight 865 // between the Package Manager and the Backup Manager 866 class PostInstallData { 867 public InstallArgs args; 868 public PackageInstalledInfo res; 869 870 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 871 args = _a; 872 res = _r; 873 } 874 }; 875 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 876 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 877 878 // backup/restore of preferred activity state 879 private static final String TAG_PREFERRED_BACKUP = "pa"; 880 881 private final String mRequiredVerifierPackage; 882 883 private final PackageUsage mPackageUsage = new PackageUsage(); 884 885 private class PackageUsage { 886 private static final int WRITE_INTERVAL 887 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 888 889 private final Object mFileLock = new Object(); 890 private final AtomicLong mLastWritten = new AtomicLong(0); 891 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 892 893 private boolean mIsHistoricalPackageUsageAvailable = true; 894 895 boolean isHistoricalPackageUsageAvailable() { 896 return mIsHistoricalPackageUsageAvailable; 897 } 898 899 void write(boolean force) { 900 if (force) { 901 writeInternal(); 902 return; 903 } 904 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 905 && !DEBUG_DEXOPT) { 906 return; 907 } 908 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 909 new Thread("PackageUsage_DiskWriter") { 910 @Override 911 public void run() { 912 try { 913 writeInternal(); 914 } finally { 915 mBackgroundWriteRunning.set(false); 916 } 917 } 918 }.start(); 919 } 920 } 921 922 private void writeInternal() { 923 synchronized (mPackages) { 924 synchronized (mFileLock) { 925 AtomicFile file = getFile(); 926 FileOutputStream f = null; 927 try { 928 f = file.startWrite(); 929 BufferedOutputStream out = new BufferedOutputStream(f); 930 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 931 StringBuilder sb = new StringBuilder(); 932 for (PackageParser.Package pkg : mPackages.values()) { 933 if (pkg.mLastPackageUsageTimeInMills == 0) { 934 continue; 935 } 936 sb.setLength(0); 937 sb.append(pkg.packageName); 938 sb.append(' '); 939 sb.append((long)pkg.mLastPackageUsageTimeInMills); 940 sb.append('\n'); 941 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 942 } 943 out.flush(); 944 file.finishWrite(f); 945 } catch (IOException e) { 946 if (f != null) { 947 file.failWrite(f); 948 } 949 Log.e(TAG, "Failed to write package usage times", e); 950 } 951 } 952 } 953 mLastWritten.set(SystemClock.elapsedRealtime()); 954 } 955 956 void readLP() { 957 synchronized (mFileLock) { 958 AtomicFile file = getFile(); 959 BufferedInputStream in = null; 960 try { 961 in = new BufferedInputStream(file.openRead()); 962 StringBuffer sb = new StringBuffer(); 963 while (true) { 964 String packageName = readToken(in, sb, ' '); 965 if (packageName == null) { 966 break; 967 } 968 String timeInMillisString = readToken(in, sb, '\n'); 969 if (timeInMillisString == null) { 970 throw new IOException("Failed to find last usage time for package " 971 + packageName); 972 } 973 PackageParser.Package pkg = mPackages.get(packageName); 974 if (pkg == null) { 975 continue; 976 } 977 long timeInMillis; 978 try { 979 timeInMillis = Long.parseLong(timeInMillisString.toString()); 980 } catch (NumberFormatException e) { 981 throw new IOException("Failed to parse " + timeInMillisString 982 + " as a long.", e); 983 } 984 pkg.mLastPackageUsageTimeInMills = timeInMillis; 985 } 986 } catch (FileNotFoundException expected) { 987 mIsHistoricalPackageUsageAvailable = false; 988 } catch (IOException e) { 989 Log.w(TAG, "Failed to read package usage times", e); 990 } finally { 991 IoUtils.closeQuietly(in); 992 } 993 } 994 mLastWritten.set(SystemClock.elapsedRealtime()); 995 } 996 997 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 998 throws IOException { 999 sb.setLength(0); 1000 while (true) { 1001 int ch = in.read(); 1002 if (ch == -1) { 1003 if (sb.length() == 0) { 1004 return null; 1005 } 1006 throw new IOException("Unexpected EOF"); 1007 } 1008 if (ch == endOfToken) { 1009 return sb.toString(); 1010 } 1011 sb.append((char)ch); 1012 } 1013 } 1014 1015 private AtomicFile getFile() { 1016 File dataDir = Environment.getDataDirectory(); 1017 File systemDir = new File(dataDir, "system"); 1018 File fname = new File(systemDir, "package-usage.list"); 1019 return new AtomicFile(fname); 1020 } 1021 } 1022 1023 class PackageHandler extends Handler { 1024 private boolean mBound = false; 1025 final ArrayList<HandlerParams> mPendingInstalls = 1026 new ArrayList<HandlerParams>(); 1027 1028 private boolean connectToService() { 1029 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1030 " DefaultContainerService"); 1031 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1033 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1034 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1035 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1036 mBound = true; 1037 return true; 1038 } 1039 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1040 return false; 1041 } 1042 1043 private void disconnectService() { 1044 mContainerService = null; 1045 mBound = false; 1046 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1047 mContext.unbindService(mDefContainerConn); 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 } 1050 1051 PackageHandler(Looper looper) { 1052 super(looper); 1053 } 1054 1055 public void handleMessage(Message msg) { 1056 try { 1057 doHandleMessage(msg); 1058 } finally { 1059 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1060 } 1061 } 1062 1063 void doHandleMessage(Message msg) { 1064 switch (msg.what) { 1065 case INIT_COPY: { 1066 HandlerParams params = (HandlerParams) msg.obj; 1067 int idx = mPendingInstalls.size(); 1068 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1069 // If a bind was already initiated we dont really 1070 // need to do anything. The pending install 1071 // will be processed later on. 1072 if (!mBound) { 1073 // If this is the only one pending we might 1074 // have to bind to the service again. 1075 if (!connectToService()) { 1076 Slog.e(TAG, "Failed to bind to media container service"); 1077 params.serviceError(); 1078 return; 1079 } else { 1080 // Once we bind to the service, the first 1081 // pending request will be processed. 1082 mPendingInstalls.add(idx, params); 1083 } 1084 } else { 1085 mPendingInstalls.add(idx, params); 1086 // Already bound to the service. Just make 1087 // sure we trigger off processing the first request. 1088 if (idx == 0) { 1089 mHandler.sendEmptyMessage(MCS_BOUND); 1090 } 1091 } 1092 break; 1093 } 1094 case MCS_BOUND: { 1095 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1096 if (msg.obj != null) { 1097 mContainerService = (IMediaContainerService) msg.obj; 1098 } 1099 if (mContainerService == null) { 1100 // Something seriously wrong. Bail out 1101 Slog.e(TAG, "Cannot bind to media container service"); 1102 for (HandlerParams params : mPendingInstalls) { 1103 // Indicate service bind error 1104 params.serviceError(); 1105 } 1106 mPendingInstalls.clear(); 1107 } else if (mPendingInstalls.size() > 0) { 1108 HandlerParams params = mPendingInstalls.get(0); 1109 if (params != null) { 1110 if (params.startCopy()) { 1111 // We are done... look for more work or to 1112 // go idle. 1113 if (DEBUG_SD_INSTALL) Log.i(TAG, 1114 "Checking for more work or unbind..."); 1115 // Delete pending install 1116 if (mPendingInstalls.size() > 0) { 1117 mPendingInstalls.remove(0); 1118 } 1119 if (mPendingInstalls.size() == 0) { 1120 if (mBound) { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Posting delayed MCS_UNBIND"); 1123 removeMessages(MCS_UNBIND); 1124 Message ubmsg = obtainMessage(MCS_UNBIND); 1125 // Unbind after a little delay, to avoid 1126 // continual thrashing. 1127 sendMessageDelayed(ubmsg, 10000); 1128 } 1129 } else { 1130 // There are more pending requests in queue. 1131 // Just post MCS_BOUND message to trigger processing 1132 // of next pending install. 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, 1134 "Posting MCS_BOUND for next work"); 1135 mHandler.sendEmptyMessage(MCS_BOUND); 1136 } 1137 } 1138 } 1139 } else { 1140 // Should never happen ideally. 1141 Slog.w(TAG, "Empty queue"); 1142 } 1143 break; 1144 } 1145 case MCS_RECONNECT: { 1146 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1147 if (mPendingInstalls.size() > 0) { 1148 if (mBound) { 1149 disconnectService(); 1150 } 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 for (HandlerParams params : mPendingInstalls) { 1154 // Indicate service bind error 1155 params.serviceError(); 1156 } 1157 mPendingInstalls.clear(); 1158 } 1159 } 1160 break; 1161 } 1162 case MCS_UNBIND: { 1163 // If there is no actual work left, then time to unbind. 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1165 1166 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1167 if (mBound) { 1168 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1169 1170 disconnectService(); 1171 } 1172 } else if (mPendingInstalls.size() > 0) { 1173 // There are more pending requests in queue. 1174 // Just post MCS_BOUND message to trigger processing 1175 // of next pending install. 1176 mHandler.sendEmptyMessage(MCS_BOUND); 1177 } 1178 1179 break; 1180 } 1181 case MCS_GIVE_UP: { 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1183 mPendingInstalls.remove(0); 1184 break; 1185 } 1186 case SEND_PENDING_BROADCAST: { 1187 String packages[]; 1188 ArrayList<String> components[]; 1189 int size = 0; 1190 int uids[]; 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1192 synchronized (mPackages) { 1193 if (mPendingBroadcasts == null) { 1194 return; 1195 } 1196 size = mPendingBroadcasts.size(); 1197 if (size <= 0) { 1198 // Nothing to be done. Just return 1199 return; 1200 } 1201 packages = new String[size]; 1202 components = new ArrayList[size]; 1203 uids = new int[size]; 1204 int i = 0; // filling out the above arrays 1205 1206 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1207 int packageUserId = mPendingBroadcasts.userIdAt(n); 1208 Iterator<Map.Entry<String, ArrayList<String>>> it 1209 = mPendingBroadcasts.packagesForUserId(packageUserId) 1210 .entrySet().iterator(); 1211 while (it.hasNext() && i < size) { 1212 Map.Entry<String, ArrayList<String>> ent = it.next(); 1213 packages[i] = ent.getKey(); 1214 components[i] = ent.getValue(); 1215 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1216 uids[i] = (ps != null) 1217 ? UserHandle.getUid(packageUserId, ps.appId) 1218 : -1; 1219 i++; 1220 } 1221 } 1222 size = i; 1223 mPendingBroadcasts.clear(); 1224 } 1225 // Send broadcasts 1226 for (int i = 0; i < size; i++) { 1227 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1228 } 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1230 break; 1231 } 1232 case START_CLEANING_PACKAGE: { 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 final String packageName = (String)msg.obj; 1235 final int userId = msg.arg1; 1236 final boolean andCode = msg.arg2 != 0; 1237 synchronized (mPackages) { 1238 if (userId == UserHandle.USER_ALL) { 1239 int[] users = sUserManager.getUserIds(); 1240 for (int user : users) { 1241 mSettings.addPackageToCleanLPw( 1242 new PackageCleanItem(user, packageName, andCode)); 1243 } 1244 } else { 1245 mSettings.addPackageToCleanLPw( 1246 new PackageCleanItem(userId, packageName, andCode)); 1247 } 1248 } 1249 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1250 startCleaningPackages(); 1251 } break; 1252 case POST_INSTALL: { 1253 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1254 PostInstallData data = mRunningInstalls.get(msg.arg1); 1255 mRunningInstalls.delete(msg.arg1); 1256 boolean deleteOld = false; 1257 1258 if (data != null) { 1259 InstallArgs args = data.args; 1260 PackageInstalledInfo res = data.res; 1261 1262 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1263 res.removedInfo.sendBroadcast(false, true, false); 1264 Bundle extras = new Bundle(1); 1265 extras.putInt(Intent.EXTRA_UID, res.uid); 1266 1267 // Now that we successfully installed the package, grant runtime 1268 // permissions if requested before broadcasting the install. 1269 if ((args.installFlags 1270 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1271 grantRequestedRuntimePermissions(res.pkg, 1272 args.user.getIdentifier()); 1273 } 1274 1275 // Determine the set of users who are adding this 1276 // package for the first time vs. those who are seeing 1277 // an update. 1278 int[] firstUsers; 1279 int[] updateUsers = new int[0]; 1280 if (res.origUsers == null || res.origUsers.length == 0) { 1281 firstUsers = res.newUsers; 1282 } else { 1283 firstUsers = new int[0]; 1284 for (int i=0; i<res.newUsers.length; i++) { 1285 int user = res.newUsers[i]; 1286 boolean isNew = true; 1287 for (int j=0; j<res.origUsers.length; j++) { 1288 if (res.origUsers[j] == user) { 1289 isNew = false; 1290 break; 1291 } 1292 } 1293 if (isNew) { 1294 int[] newFirst = new int[firstUsers.length+1]; 1295 System.arraycopy(firstUsers, 0, newFirst, 0, 1296 firstUsers.length); 1297 newFirst[firstUsers.length] = user; 1298 firstUsers = newFirst; 1299 } else { 1300 int[] newUpdate = new int[updateUsers.length+1]; 1301 System.arraycopy(updateUsers, 0, newUpdate, 0, 1302 updateUsers.length); 1303 newUpdate[updateUsers.length] = user; 1304 updateUsers = newUpdate; 1305 } 1306 } 1307 } 1308 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1309 res.pkg.applicationInfo.packageName, 1310 extras, null, null, firstUsers); 1311 final boolean update = res.removedInfo.removedPackage != null; 1312 if (update) { 1313 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1314 } 1315 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1316 res.pkg.applicationInfo.packageName, 1317 extras, null, null, updateUsers); 1318 if (update) { 1319 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1320 res.pkg.applicationInfo.packageName, 1321 extras, null, null, updateUsers); 1322 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1323 null, null, 1324 res.pkg.applicationInfo.packageName, null, updateUsers); 1325 1326 // treat asec-hosted packages like removable media on upgrade 1327 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1328 if (DEBUG_INSTALL) { 1329 Slog.i(TAG, "upgrading pkg " + res.pkg 1330 + " is ASEC-hosted -> AVAILABLE"); 1331 } 1332 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1333 ArrayList<String> pkgList = new ArrayList<String>(1); 1334 pkgList.add(res.pkg.applicationInfo.packageName); 1335 sendResourcesChangedBroadcast(true, true, 1336 pkgList,uidArray, null); 1337 } 1338 } 1339 if (res.removedInfo.args != null) { 1340 // Remove the replaced package's older resources safely now 1341 deleteOld = true; 1342 } 1343 1344 // Log current value of "unknown sources" setting 1345 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1346 getUnknownSourcesSettings()); 1347 } 1348 // Force a gc to clear up things 1349 Runtime.getRuntime().gc(); 1350 // We delete after a gc for applications on sdcard. 1351 if (deleteOld) { 1352 synchronized (mInstallLock) { 1353 res.removedInfo.args.doPostDeleteLI(true); 1354 } 1355 } 1356 if (args.observer != null) { 1357 try { 1358 Bundle extras = extrasForInstallResult(res); 1359 args.observer.onPackageInstalled(res.name, res.returnCode, 1360 res.returnMsg, extras); 1361 } catch (RemoteException e) { 1362 Slog.i(TAG, "Observer no longer exists."); 1363 } 1364 } 1365 } else { 1366 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1367 } 1368 } break; 1369 case UPDATED_MEDIA_STATUS: { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1371 boolean reportStatus = msg.arg1 == 1; 1372 boolean doGc = msg.arg2 == 1; 1373 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1374 if (doGc) { 1375 // Force a gc to clear up stale containers. 1376 Runtime.getRuntime().gc(); 1377 } 1378 if (msg.obj != null) { 1379 @SuppressWarnings("unchecked") 1380 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1382 // Unload containers 1383 unloadAllContainers(args); 1384 } 1385 if (reportStatus) { 1386 try { 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1388 PackageHelper.getMountService().finishMediaUpdate(); 1389 } catch (RemoteException e) { 1390 Log.e(TAG, "MountService not running?"); 1391 } 1392 } 1393 } break; 1394 case WRITE_SETTINGS: { 1395 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1396 synchronized (mPackages) { 1397 removeMessages(WRITE_SETTINGS); 1398 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1399 mSettings.writeLPr(); 1400 mDirtyUsers.clear(); 1401 } 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 } break; 1404 case WRITE_PACKAGE_RESTRICTIONS: { 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 synchronized (mPackages) { 1407 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1408 for (int userId : mDirtyUsers) { 1409 mSettings.writePackageRestrictionsLPr(userId); 1410 } 1411 mDirtyUsers.clear(); 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 } break; 1415 case CHECK_PENDING_VERIFICATION: { 1416 final int verificationId = msg.arg1; 1417 final PackageVerificationState state = mPendingVerification.get(verificationId); 1418 1419 if ((state != null) && !state.timeoutExtended()) { 1420 final InstallArgs args = state.getInstallArgs(); 1421 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1422 1423 Slog.i(TAG, "Verification timed out for " + originUri); 1424 mPendingVerification.remove(verificationId); 1425 1426 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1427 1428 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1429 Slog.i(TAG, "Continuing with installation of " + originUri); 1430 state.setVerifierResponse(Binder.getCallingUid(), 1431 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1432 broadcastPackageVerified(verificationId, originUri, 1433 PackageManager.VERIFICATION_ALLOW, 1434 state.getInstallArgs().getUser()); 1435 try { 1436 ret = args.copyApk(mContainerService, true); 1437 } catch (RemoteException e) { 1438 Slog.e(TAG, "Could not contact the ContainerService"); 1439 } 1440 } else { 1441 broadcastPackageVerified(verificationId, originUri, 1442 PackageManager.VERIFICATION_REJECT, 1443 state.getInstallArgs().getUser()); 1444 } 1445 1446 processPendingInstall(args, ret); 1447 mHandler.sendEmptyMessage(MCS_UNBIND); 1448 } 1449 break; 1450 } 1451 case PACKAGE_VERIFIED: { 1452 final int verificationId = msg.arg1; 1453 1454 final PackageVerificationState state = mPendingVerification.get(verificationId); 1455 if (state == null) { 1456 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1457 break; 1458 } 1459 1460 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1461 1462 state.setVerifierResponse(response.callerUid, response.code); 1463 1464 if (state.isVerificationComplete()) { 1465 mPendingVerification.remove(verificationId); 1466 1467 final InstallArgs args = state.getInstallArgs(); 1468 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1469 1470 int ret; 1471 if (state.isInstallAllowed()) { 1472 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1473 broadcastPackageVerified(verificationId, originUri, 1474 response.code, state.getInstallArgs().getUser()); 1475 try { 1476 ret = args.copyApk(mContainerService, true); 1477 } catch (RemoteException e) { 1478 Slog.e(TAG, "Could not contact the ContainerService"); 1479 } 1480 } else { 1481 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1482 } 1483 1484 processPendingInstall(args, ret); 1485 1486 mHandler.sendEmptyMessage(MCS_UNBIND); 1487 } 1488 1489 break; 1490 } 1491 case START_INTENT_FILTER_VERIFICATIONS: { 1492 int userId = msg.arg1; 1493 int verifierUid = msg.arg2; 1494 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1495 1496 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1497 break; 1498 } 1499 case INTENT_FILTER_VERIFIED: { 1500 final int verificationId = msg.arg1; 1501 1502 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1503 verificationId); 1504 if (state == null) { 1505 Slog.w(TAG, "Invalid IntentFilter verification token " 1506 + verificationId + " received"); 1507 break; 1508 } 1509 1510 final int userId = state.getUserId(); 1511 1512 Slog.d(TAG, "Processing IntentFilter verification with token:" 1513 + verificationId + " and userId:" + userId); 1514 1515 final IntentFilterVerificationResponse response = 1516 (IntentFilterVerificationResponse) msg.obj; 1517 1518 state.setVerifierResponse(response.callerUid, response.code); 1519 1520 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1521 + " and userId:" + userId 1522 + " is settings verifier response with response code:" 1523 + response.code); 1524 1525 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1526 Slog.d(TAG, "Domains failing verification: " 1527 + response.getFailedDomainsString()); 1528 } 1529 1530 if (state.isVerificationComplete()) { 1531 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1532 } else { 1533 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1534 + " was not said to be complete"); 1535 } 1536 1537 break; 1538 } 1539 } 1540 } 1541 } 1542 1543 private StorageEventListener mStorageListener = new StorageEventListener() { 1544 @Override 1545 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1546 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1547 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1548 loadPrivatePackages(vol); 1549 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1550 unloadPrivatePackages(vol); 1551 } 1552 } 1553 1554 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1555 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1556 updateExternalMediaStatus(true, false); 1557 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1558 updateExternalMediaStatus(false, false); 1559 } 1560 } 1561 } 1562 }; 1563 1564 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1565 if (userId >= UserHandle.USER_OWNER) { 1566 grantRequestedRuntimePermissionsForUser(pkg, userId); 1567 } else if (userId == UserHandle.USER_ALL) { 1568 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1569 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1570 } 1571 } 1572 } 1573 1574 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1575 SettingBase sb = (SettingBase) pkg.mExtras; 1576 if (sb == null) { 1577 return; 1578 } 1579 1580 PermissionsState permissionsState = sb.getPermissionsState(); 1581 1582 for (String permission : pkg.requestedPermissions) { 1583 BasePermission bp = mSettings.mPermissions.get(permission); 1584 if (bp != null && bp.isRuntime()) { 1585 permissionsState.grantRuntimePermission(bp, userId); 1586 } 1587 } 1588 } 1589 1590 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1591 Bundle extras = null; 1592 switch (res.returnCode) { 1593 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1594 extras = new Bundle(); 1595 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1596 res.origPermission); 1597 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1598 res.origPackage); 1599 break; 1600 } 1601 } 1602 return extras; 1603 } 1604 1605 void scheduleWriteSettingsLocked() { 1606 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1607 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1608 } 1609 } 1610 1611 void scheduleWritePackageRestrictionsLocked(int userId) { 1612 if (!sUserManager.exists(userId)) return; 1613 mDirtyUsers.add(userId); 1614 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1615 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1616 } 1617 } 1618 1619 public static PackageManagerService main(Context context, Installer installer, 1620 boolean factoryTest, boolean onlyCore) { 1621 PackageManagerService m = new PackageManagerService(context, installer, 1622 factoryTest, onlyCore); 1623 ServiceManager.addService("package", m); 1624 return m; 1625 } 1626 1627 static String[] splitString(String str, char sep) { 1628 int count = 1; 1629 int i = 0; 1630 while ((i=str.indexOf(sep, i)) >= 0) { 1631 count++; 1632 i++; 1633 } 1634 1635 String[] res = new String[count]; 1636 i=0; 1637 count = 0; 1638 int lastI=0; 1639 while ((i=str.indexOf(sep, i)) >= 0) { 1640 res[count] = str.substring(lastI, i); 1641 count++; 1642 i++; 1643 lastI = i; 1644 } 1645 res[count] = str.substring(lastI, str.length()); 1646 return res; 1647 } 1648 1649 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1650 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1651 Context.DISPLAY_SERVICE); 1652 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1653 } 1654 1655 public PackageManagerService(Context context, Installer installer, 1656 boolean factoryTest, boolean onlyCore) { 1657 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1658 SystemClock.uptimeMillis()); 1659 1660 if (mSdkVersion <= 0) { 1661 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1662 } 1663 1664 mContext = context; 1665 mFactoryTest = factoryTest; 1666 mOnlyCore = onlyCore; 1667 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1668 mMetrics = new DisplayMetrics(); 1669 mSettings = new Settings(mPackages); 1670 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1671 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1672 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1673 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1674 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1675 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1676 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1677 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1678 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1679 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1680 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1681 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1682 1683 // TODO: add a property to control this? 1684 long dexOptLRUThresholdInMinutes; 1685 if (mLazyDexOpt) { 1686 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1687 } else { 1688 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1689 } 1690 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1691 1692 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1693 if (separateProcesses != null && separateProcesses.length() > 0) { 1694 if ("*".equals(separateProcesses)) { 1695 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1696 mSeparateProcesses = null; 1697 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1698 } else { 1699 mDefParseFlags = 0; 1700 mSeparateProcesses = separateProcesses.split(","); 1701 Slog.w(TAG, "Running with debug.separate_processes: " 1702 + separateProcesses); 1703 } 1704 } else { 1705 mDefParseFlags = 0; 1706 mSeparateProcesses = null; 1707 } 1708 1709 mInstaller = installer; 1710 mPackageDexOptimizer = new PackageDexOptimizer(this); 1711 1712 getDefaultDisplayMetrics(context, mMetrics); 1713 1714 SystemConfig systemConfig = SystemConfig.getInstance(); 1715 mGlobalGids = systemConfig.getGlobalGids(); 1716 mSystemPermissions = systemConfig.getSystemPermissions(); 1717 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1718 1719 synchronized (mInstallLock) { 1720 // writer 1721 synchronized (mPackages) { 1722 mHandlerThread = new ServiceThread(TAG, 1723 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1724 mHandlerThread.start(); 1725 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1726 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1727 1728 File dataDir = Environment.getDataDirectory(); 1729 mAppDataDir = new File(dataDir, "data"); 1730 mAppInstallDir = new File(dataDir, "app"); 1731 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1732 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1733 mUserAppDataDir = new File(dataDir, "user"); 1734 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1735 1736 sUserManager = new UserManagerService(context, this, 1737 mInstallLock, mPackages); 1738 1739 // Propagate permission configuration in to package manager. 1740 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1741 = systemConfig.getPermissions(); 1742 for (int i=0; i<permConfig.size(); i++) { 1743 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1744 BasePermission bp = mSettings.mPermissions.get(perm.name); 1745 if (bp == null) { 1746 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1747 mSettings.mPermissions.put(perm.name, bp); 1748 } 1749 if (perm.gids != null) { 1750 bp.setGids(perm.gids, perm.perUser); 1751 } 1752 } 1753 1754 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1755 for (int i=0; i<libConfig.size(); i++) { 1756 mSharedLibraries.put(libConfig.keyAt(i), 1757 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1758 } 1759 1760 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1761 1762 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1763 mSdkVersion, mOnlyCore); 1764 1765 String customResolverActivity = Resources.getSystem().getString( 1766 R.string.config_customResolverActivity); 1767 if (TextUtils.isEmpty(customResolverActivity)) { 1768 customResolverActivity = null; 1769 } else { 1770 mCustomResolverComponentName = ComponentName.unflattenFromString( 1771 customResolverActivity); 1772 } 1773 1774 long startTime = SystemClock.uptimeMillis(); 1775 1776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1777 startTime); 1778 1779 // Set flag to monitor and not change apk file paths when 1780 // scanning install directories. 1781 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1782 1783 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1784 1785 /** 1786 * Add everything in the in the boot class path to the 1787 * list of process files because dexopt will have been run 1788 * if necessary during zygote startup. 1789 */ 1790 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1791 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1792 1793 if (bootClassPath != null) { 1794 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1795 for (String element : bootClassPathElements) { 1796 alreadyDexOpted.add(element); 1797 } 1798 } else { 1799 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1800 } 1801 1802 if (systemServerClassPath != null) { 1803 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1804 for (String element : systemServerClassPathElements) { 1805 alreadyDexOpted.add(element); 1806 } 1807 } else { 1808 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1809 } 1810 1811 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1812 final String[] dexCodeInstructionSets = 1813 getDexCodeInstructionSets( 1814 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1815 1816 /** 1817 * Ensure all external libraries have had dexopt run on them. 1818 */ 1819 if (mSharedLibraries.size() > 0) { 1820 // NOTE: For now, we're compiling these system "shared libraries" 1821 // (and framework jars) into all available architectures. It's possible 1822 // to compile them only when we come across an app that uses them (there's 1823 // already logic for that in scanPackageLI) but that adds some complexity. 1824 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1825 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1826 final String lib = libEntry.path; 1827 if (lib == null) { 1828 continue; 1829 } 1830 1831 try { 1832 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1833 dexCodeInstructionSet, 1834 false); 1835 if (dexoptRequired != DexFile.UP_TO_DATE) { 1836 alreadyDexOpted.add(lib); 1837 1838 // The list of "shared libraries" we have at this point is 1839 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1840 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1841 } else { 1842 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1843 } 1844 } 1845 } catch (FileNotFoundException e) { 1846 Slog.w(TAG, "Library not found: " + lib); 1847 } catch (IOException e) { 1848 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1849 + e.getMessage()); 1850 } 1851 } 1852 } 1853 } 1854 1855 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1856 1857 // Gross hack for now: we know this file doesn't contain any 1858 // code, so don't dexopt it to avoid the resulting log spew. 1859 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1860 1861 // Gross hack for now: we know this file is only part of 1862 // the boot class path for art, so don't dexopt it to 1863 // avoid the resulting log spew. 1864 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1865 1866 /** 1867 * And there are a number of commands implemented in Java, which 1868 * we currently need to do the dexopt on so that they can be 1869 * run from a non-root shell. 1870 */ 1871 String[] frameworkFiles = frameworkDir.list(); 1872 if (frameworkFiles != null) { 1873 // TODO: We could compile these only for the most preferred ABI. We should 1874 // first double check that the dex files for these commands are not referenced 1875 // by other system apps. 1876 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1877 for (int i=0; i<frameworkFiles.length; i++) { 1878 File libPath = new File(frameworkDir, frameworkFiles[i]); 1879 String path = libPath.getPath(); 1880 // Skip the file if we already did it. 1881 if (alreadyDexOpted.contains(path)) { 1882 continue; 1883 } 1884 // Skip the file if it is not a type we want to dexopt. 1885 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1886 continue; 1887 } 1888 try { 1889 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1890 dexCodeInstructionSet, 1891 false); 1892 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1893 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1894 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1895 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1896 } 1897 } catch (FileNotFoundException e) { 1898 Slog.w(TAG, "Jar not found: " + path); 1899 } catch (IOException e) { 1900 Slog.w(TAG, "Exception reading jar: " + path, e); 1901 } 1902 } 1903 } 1904 } 1905 1906 // Collect vendor overlay packages. 1907 // (Do this before scanning any apps.) 1908 // For security and version matching reason, only consider 1909 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1910 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1911 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1912 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1913 1914 // Find base frameworks (resource packages without code). 1915 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1916 | PackageParser.PARSE_IS_SYSTEM_DIR 1917 | PackageParser.PARSE_IS_PRIVILEGED, 1918 scanFlags | SCAN_NO_DEX, 0); 1919 1920 // Collected privileged system packages. 1921 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1922 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1923 | PackageParser.PARSE_IS_SYSTEM_DIR 1924 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1925 1926 // Collect ordinary system packages. 1927 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1928 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1930 1931 // Collect all vendor packages. 1932 File vendorAppDir = new File("/vendor/app"); 1933 try { 1934 vendorAppDir = vendorAppDir.getCanonicalFile(); 1935 } catch (IOException e) { 1936 // failed to look up canonical path, continue with original one 1937 } 1938 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1940 1941 // Collect all OEM packages. 1942 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1943 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1944 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1945 1946 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1947 mInstaller.moveFiles(); 1948 1949 // Prune any system packages that no longer exist. 1950 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1951 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1952 if (!mOnlyCore) { 1953 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1954 while (psit.hasNext()) { 1955 PackageSetting ps = psit.next(); 1956 1957 /* 1958 * If this is not a system app, it can't be a 1959 * disable system app. 1960 */ 1961 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1962 continue; 1963 } 1964 1965 /* 1966 * If the package is scanned, it's not erased. 1967 */ 1968 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1969 if (scannedPkg != null) { 1970 /* 1971 * If the system app is both scanned and in the 1972 * disabled packages list, then it must have been 1973 * added via OTA. Remove it from the currently 1974 * scanned package so the previously user-installed 1975 * application can be scanned. 1976 */ 1977 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1978 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1979 + ps.name + "; removing system app. Last known codePath=" 1980 + ps.codePathString + ", installStatus=" + ps.installStatus 1981 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1982 + scannedPkg.mVersionCode); 1983 removePackageLI(ps, true); 1984 expectingBetter.put(ps.name, ps.codePath); 1985 } 1986 1987 continue; 1988 } 1989 1990 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1991 psit.remove(); 1992 logCriticalInfo(Log.WARN, "System package " + ps.name 1993 + " no longer exists; wiping its data"); 1994 removeDataDirsLI(ps.name); 1995 } else { 1996 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1997 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1998 possiblyDeletedUpdatedSystemApps.add(ps.name); 1999 } 2000 } 2001 } 2002 } 2003 2004 //look for any incomplete package installations 2005 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2006 //clean up list 2007 for(int i = 0; i < deletePkgsList.size(); i++) { 2008 //clean up here 2009 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2010 } 2011 //delete tmp files 2012 deleteTempPackageFiles(); 2013 2014 // Remove any shared userIDs that have no associated packages 2015 mSettings.pruneSharedUsersLPw(); 2016 2017 if (!mOnlyCore) { 2018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2019 SystemClock.uptimeMillis()); 2020 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2021 2022 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2023 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2024 2025 /** 2026 * Remove disable package settings for any updated system 2027 * apps that were removed via an OTA. If they're not a 2028 * previously-updated app, remove them completely. 2029 * Otherwise, just revoke their system-level permissions. 2030 */ 2031 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2032 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2033 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2034 2035 String msg; 2036 if (deletedPkg == null) { 2037 msg = "Updated system package " + deletedAppName 2038 + " no longer exists; wiping its data"; 2039 removeDataDirsLI(deletedAppName); 2040 } else { 2041 msg = "Updated system app + " + deletedAppName 2042 + " no longer present; removing system privileges for " 2043 + deletedAppName; 2044 2045 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2046 2047 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2048 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2049 } 2050 logCriticalInfo(Log.WARN, msg); 2051 } 2052 2053 /** 2054 * Make sure all system apps that we expected to appear on 2055 * the userdata partition actually showed up. If they never 2056 * appeared, crawl back and revive the system version. 2057 */ 2058 for (int i = 0; i < expectingBetter.size(); i++) { 2059 final String packageName = expectingBetter.keyAt(i); 2060 if (!mPackages.containsKey(packageName)) { 2061 final File scanFile = expectingBetter.valueAt(i); 2062 2063 logCriticalInfo(Log.WARN, "Expected better " + packageName 2064 + " but never showed up; reverting to system"); 2065 2066 final int reparseFlags; 2067 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2068 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2069 | PackageParser.PARSE_IS_SYSTEM_DIR 2070 | PackageParser.PARSE_IS_PRIVILEGED; 2071 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2072 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR; 2074 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR; 2077 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else { 2081 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2082 continue; 2083 } 2084 2085 mSettings.enableSystemPackageLPw(packageName); 2086 2087 try { 2088 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2089 } catch (PackageManagerException e) { 2090 Slog.e(TAG, "Failed to parse original system package: " 2091 + e.getMessage()); 2092 } 2093 } 2094 } 2095 } 2096 2097 // Now that we know all of the shared libraries, update all clients to have 2098 // the correct library paths. 2099 updateAllSharedLibrariesLPw(); 2100 2101 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2102 // NOTE: We ignore potential failures here during a system scan (like 2103 // the rest of the commands above) because there's precious little we 2104 // can do about it. A settings error is reported, though. 2105 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2106 false /* force dexopt */, false /* defer dexopt */); 2107 } 2108 2109 // Now that we know all the packages we are keeping, 2110 // read and update their last usage times. 2111 mPackageUsage.readLP(); 2112 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2114 SystemClock.uptimeMillis()); 2115 Slog.i(TAG, "Time to scan packages: " 2116 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2117 + " seconds"); 2118 2119 // If the platform SDK has changed since the last time we booted, 2120 // we need to re-grant app permission to catch any new ones that 2121 // appear. This is really a hack, and means that apps can in some 2122 // cases get permissions that the user didn't initially explicitly 2123 // allow... it would be nice to have some better way to handle 2124 // this situation. 2125 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2126 != mSdkVersion; 2127 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2128 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2129 + "; regranting permissions for internal storage"); 2130 mSettings.mInternalSdkPlatform = mSdkVersion; 2131 2132 // For now runtime permissions are toggled via a system property. 2133 if (!RUNTIME_PERMISSIONS_ENABLED) { 2134 // Remove the runtime permissions state if the feature 2135 // was disabled by flipping the system property. 2136 mSettings.deleteRuntimePermissionsFiles(); 2137 } 2138 2139 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2140 | (regrantPermissions 2141 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2142 : 0)); 2143 2144 // If this is the first boot, and it is a normal boot, then 2145 // we need to initialize the default preferred apps. 2146 if (!mRestoredSettings && !onlyCore) { 2147 mSettings.readDefaultPreferredAppsLPw(this, 0); 2148 } 2149 2150 // If this is first boot after an OTA, and a normal boot, then 2151 // we need to clear code cache directories. 2152 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2153 if (mIsUpgrade && !onlyCore) { 2154 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2155 for (String pkgName : mSettings.mPackages.keySet()) { 2156 deleteCodeCacheDirsLI(pkgName); 2157 } 2158 mSettings.mFingerprint = Build.FINGERPRINT; 2159 } 2160 2161 // All the changes are done during package scanning. 2162 mSettings.updateInternalDatabaseVersion(); 2163 2164 // can downgrade to reader 2165 mSettings.writeLPr(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2168 SystemClock.uptimeMillis()); 2169 2170 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2171 2172 mInstallerService = new PackageInstallerService(context, this); 2173 2174 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2175 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2176 mIntentFilterVerifierComponent); 2177 2178 } // synchronized (mPackages) 2179 } // synchronized (mInstallLock) 2180 2181 // Now after opening every single application zip, make sure they 2182 // are all flushed. Not really needed, but keeps things nice and 2183 // tidy. 2184 Runtime.getRuntime().gc(); 2185 } 2186 2187 @Override 2188 public boolean isFirstBoot() { 2189 return !mRestoredSettings; 2190 } 2191 2192 @Override 2193 public boolean isOnlyCoreApps() { 2194 return mOnlyCore; 2195 } 2196 2197 @Override 2198 public boolean isUpgrade() { 2199 return mIsUpgrade; 2200 } 2201 2202 private String getRequiredVerifierLPr() { 2203 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2204 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2205 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2206 2207 String requiredVerifier = null; 2208 2209 final int N = receivers.size(); 2210 for (int i = 0; i < N; i++) { 2211 final ResolveInfo info = receivers.get(i); 2212 2213 if (info.activityInfo == null) { 2214 continue; 2215 } 2216 2217 final String packageName = info.activityInfo.packageName; 2218 2219 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2220 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2221 continue; 2222 } 2223 2224 if (requiredVerifier != null) { 2225 throw new RuntimeException("There can be only one required verifier"); 2226 } 2227 2228 requiredVerifier = packageName; 2229 } 2230 2231 return requiredVerifier; 2232 } 2233 2234 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2235 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2236 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2237 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2238 2239 ComponentName verifierComponentName = null; 2240 2241 int priority = -1000; 2242 final int N = receivers.size(); 2243 for (int i = 0; i < N; i++) { 2244 final ResolveInfo info = receivers.get(i); 2245 2246 if (info.activityInfo == null) { 2247 continue; 2248 } 2249 2250 final String packageName = info.activityInfo.packageName; 2251 2252 final PackageSetting ps = mSettings.mPackages.get(packageName); 2253 if (ps == null) { 2254 continue; 2255 } 2256 2257 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2258 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2259 continue; 2260 } 2261 2262 // Select the IntentFilterVerifier with the highest priority 2263 if (priority < info.priority) { 2264 priority = info.priority; 2265 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2266 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2267 " with priority: " + info.priority); 2268 } 2269 } 2270 2271 return verifierComponentName; 2272 } 2273 2274 @Override 2275 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2276 throws RemoteException { 2277 try { 2278 return super.onTransact(code, data, reply, flags); 2279 } catch (RuntimeException e) { 2280 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2281 Slog.wtf(TAG, "Package Manager Crash", e); 2282 } 2283 throw e; 2284 } 2285 } 2286 2287 void cleanupInstallFailedPackage(PackageSetting ps) { 2288 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2289 2290 removeDataDirsLI(ps.name); 2291 if (ps.codePath != null) { 2292 if (ps.codePath.isDirectory()) { 2293 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2294 } else { 2295 ps.codePath.delete(); 2296 } 2297 } 2298 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2299 if (ps.resourcePath.isDirectory()) { 2300 FileUtils.deleteContents(ps.resourcePath); 2301 } 2302 ps.resourcePath.delete(); 2303 } 2304 mSettings.removePackageLPw(ps.name); 2305 } 2306 2307 static int[] appendInts(int[] cur, int[] add) { 2308 if (add == null) return cur; 2309 if (cur == null) return add; 2310 final int N = add.length; 2311 for (int i=0; i<N; i++) { 2312 cur = appendInt(cur, add[i]); 2313 } 2314 return cur; 2315 } 2316 2317 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2318 if (!sUserManager.exists(userId)) return null; 2319 final PackageSetting ps = (PackageSetting) p.mExtras; 2320 if (ps == null) { 2321 return null; 2322 } 2323 2324 final PermissionsState permissionsState = ps.getPermissionsState(); 2325 2326 final int[] gids = permissionsState.computeGids(userId); 2327 final Set<String> permissions = permissionsState.getPermissions(userId); 2328 final PackageUserState state = ps.readUserState(userId); 2329 2330 return PackageParser.generatePackageInfo(p, gids, flags, 2331 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2332 } 2333 2334 @Override 2335 public boolean isPackageAvailable(String packageName, int userId) { 2336 if (!sUserManager.exists(userId)) return false; 2337 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2338 synchronized (mPackages) { 2339 PackageParser.Package p = mPackages.get(packageName); 2340 if (p != null) { 2341 final PackageSetting ps = (PackageSetting) p.mExtras; 2342 if (ps != null) { 2343 final PackageUserState state = ps.readUserState(userId); 2344 if (state != null) { 2345 return PackageParser.isAvailable(state); 2346 } 2347 } 2348 } 2349 } 2350 return false; 2351 } 2352 2353 @Override 2354 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2355 if (!sUserManager.exists(userId)) return null; 2356 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2357 // reader 2358 synchronized (mPackages) { 2359 PackageParser.Package p = mPackages.get(packageName); 2360 if (DEBUG_PACKAGE_INFO) 2361 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2362 if (p != null) { 2363 return generatePackageInfo(p, flags, userId); 2364 } 2365 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2366 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2367 } 2368 } 2369 return null; 2370 } 2371 2372 @Override 2373 public String[] currentToCanonicalPackageNames(String[] names) { 2374 String[] out = new String[names.length]; 2375 // reader 2376 synchronized (mPackages) { 2377 for (int i=names.length-1; i>=0; i--) { 2378 PackageSetting ps = mSettings.mPackages.get(names[i]); 2379 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2380 } 2381 } 2382 return out; 2383 } 2384 2385 @Override 2386 public String[] canonicalToCurrentPackageNames(String[] names) { 2387 String[] out = new String[names.length]; 2388 // reader 2389 synchronized (mPackages) { 2390 for (int i=names.length-1; i>=0; i--) { 2391 String cur = mSettings.mRenamedPackages.get(names[i]); 2392 out[i] = cur != null ? cur : names[i]; 2393 } 2394 } 2395 return out; 2396 } 2397 2398 @Override 2399 public int getPackageUid(String packageName, int userId) { 2400 if (!sUserManager.exists(userId)) return -1; 2401 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2402 2403 // reader 2404 synchronized (mPackages) { 2405 PackageParser.Package p = mPackages.get(packageName); 2406 if(p != null) { 2407 return UserHandle.getUid(userId, p.applicationInfo.uid); 2408 } 2409 PackageSetting ps = mSettings.mPackages.get(packageName); 2410 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2411 return -1; 2412 } 2413 p = ps.pkg; 2414 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2415 } 2416 } 2417 2418 @Override 2419 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2420 if (!sUserManager.exists(userId)) { 2421 return null; 2422 } 2423 2424 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2425 "getPackageGids"); 2426 2427 // reader 2428 synchronized (mPackages) { 2429 PackageParser.Package p = mPackages.get(packageName); 2430 if (DEBUG_PACKAGE_INFO) { 2431 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2432 } 2433 if (p != null) { 2434 PackageSetting ps = (PackageSetting) p.mExtras; 2435 return ps.getPermissionsState().computeGids(userId); 2436 } 2437 } 2438 2439 return null; 2440 } 2441 2442 static PermissionInfo generatePermissionInfo( 2443 BasePermission bp, int flags) { 2444 if (bp.perm != null) { 2445 return PackageParser.generatePermissionInfo(bp.perm, flags); 2446 } 2447 PermissionInfo pi = new PermissionInfo(); 2448 pi.name = bp.name; 2449 pi.packageName = bp.sourcePackage; 2450 pi.nonLocalizedLabel = bp.name; 2451 pi.protectionLevel = bp.protectionLevel; 2452 return pi; 2453 } 2454 2455 @Override 2456 public PermissionInfo getPermissionInfo(String name, int flags) { 2457 // reader 2458 synchronized (mPackages) { 2459 final BasePermission p = mSettings.mPermissions.get(name); 2460 if (p != null) { 2461 return generatePermissionInfo(p, flags); 2462 } 2463 return null; 2464 } 2465 } 2466 2467 @Override 2468 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2469 // reader 2470 synchronized (mPackages) { 2471 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2472 for (BasePermission p : mSettings.mPermissions.values()) { 2473 if (group == null) { 2474 if (p.perm == null || p.perm.info.group == null) { 2475 out.add(generatePermissionInfo(p, flags)); 2476 } 2477 } else { 2478 if (p.perm != null && group.equals(p.perm.info.group)) { 2479 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2480 } 2481 } 2482 } 2483 2484 if (out.size() > 0) { 2485 return out; 2486 } 2487 return mPermissionGroups.containsKey(group) ? out : null; 2488 } 2489 } 2490 2491 @Override 2492 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2493 // reader 2494 synchronized (mPackages) { 2495 return PackageParser.generatePermissionGroupInfo( 2496 mPermissionGroups.get(name), flags); 2497 } 2498 } 2499 2500 @Override 2501 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2502 // reader 2503 synchronized (mPackages) { 2504 final int N = mPermissionGroups.size(); 2505 ArrayList<PermissionGroupInfo> out 2506 = new ArrayList<PermissionGroupInfo>(N); 2507 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2508 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2509 } 2510 return out; 2511 } 2512 } 2513 2514 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2515 int userId) { 2516 if (!sUserManager.exists(userId)) return null; 2517 PackageSetting ps = mSettings.mPackages.get(packageName); 2518 if (ps != null) { 2519 if (ps.pkg == null) { 2520 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2521 flags, userId); 2522 if (pInfo != null) { 2523 return pInfo.applicationInfo; 2524 } 2525 return null; 2526 } 2527 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2528 ps.readUserState(userId), userId); 2529 } 2530 return null; 2531 } 2532 2533 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2534 int userId) { 2535 if (!sUserManager.exists(userId)) return null; 2536 PackageSetting ps = mSettings.mPackages.get(packageName); 2537 if (ps != null) { 2538 PackageParser.Package pkg = ps.pkg; 2539 if (pkg == null) { 2540 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2541 return null; 2542 } 2543 // Only data remains, so we aren't worried about code paths 2544 pkg = new PackageParser.Package(packageName); 2545 pkg.applicationInfo.packageName = packageName; 2546 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2547 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2548 pkg.applicationInfo.dataDir = 2549 getDataPathForPackage(packageName, 0).getPath(); 2550 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2551 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2552 } 2553 return generatePackageInfo(pkg, flags, userId); 2554 } 2555 return null; 2556 } 2557 2558 @Override 2559 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2560 if (!sUserManager.exists(userId)) return null; 2561 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2562 // writer 2563 synchronized (mPackages) { 2564 PackageParser.Package p = mPackages.get(packageName); 2565 if (DEBUG_PACKAGE_INFO) Log.v( 2566 TAG, "getApplicationInfo " + packageName 2567 + ": " + p); 2568 if (p != null) { 2569 PackageSetting ps = mSettings.mPackages.get(packageName); 2570 if (ps == null) return null; 2571 // Note: isEnabledLP() does not apply here - always return info 2572 return PackageParser.generateApplicationInfo( 2573 p, flags, ps.readUserState(userId), userId); 2574 } 2575 if ("android".equals(packageName)||"system".equals(packageName)) { 2576 return mAndroidApplication; 2577 } 2578 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2579 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2580 } 2581 } 2582 return null; 2583 } 2584 2585 2586 @Override 2587 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2588 mContext.enforceCallingOrSelfPermission( 2589 android.Manifest.permission.CLEAR_APP_CACHE, null); 2590 // Queue up an async operation since clearing cache may take a little while. 2591 mHandler.post(new Runnable() { 2592 public void run() { 2593 mHandler.removeCallbacks(this); 2594 int retCode = -1; 2595 synchronized (mInstallLock) { 2596 retCode = mInstaller.freeCache(freeStorageSize); 2597 if (retCode < 0) { 2598 Slog.w(TAG, "Couldn't clear application caches"); 2599 } 2600 } 2601 if (observer != null) { 2602 try { 2603 observer.onRemoveCompleted(null, (retCode >= 0)); 2604 } catch (RemoteException e) { 2605 Slog.w(TAG, "RemoveException when invoking call back"); 2606 } 2607 } 2608 } 2609 }); 2610 } 2611 2612 @Override 2613 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2614 mContext.enforceCallingOrSelfPermission( 2615 android.Manifest.permission.CLEAR_APP_CACHE, null); 2616 // Queue up an async operation since clearing cache may take a little while. 2617 mHandler.post(new Runnable() { 2618 public void run() { 2619 mHandler.removeCallbacks(this); 2620 int retCode = -1; 2621 synchronized (mInstallLock) { 2622 retCode = mInstaller.freeCache(freeStorageSize); 2623 if (retCode < 0) { 2624 Slog.w(TAG, "Couldn't clear application caches"); 2625 } 2626 } 2627 if(pi != null) { 2628 try { 2629 // Callback via pending intent 2630 int code = (retCode >= 0) ? 1 : 0; 2631 pi.sendIntent(null, code, null, 2632 null, null); 2633 } catch (SendIntentException e1) { 2634 Slog.i(TAG, "Failed to send pending intent"); 2635 } 2636 } 2637 } 2638 }); 2639 } 2640 2641 void freeStorage(long freeStorageSize) throws IOException { 2642 synchronized (mInstallLock) { 2643 if (mInstaller.freeCache(freeStorageSize) < 0) { 2644 throw new IOException("Failed to free enough space"); 2645 } 2646 } 2647 } 2648 2649 @Override 2650 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2651 if (!sUserManager.exists(userId)) return null; 2652 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2653 synchronized (mPackages) { 2654 PackageParser.Activity a = mActivities.mActivities.get(component); 2655 2656 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2657 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2658 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2659 if (ps == null) return null; 2660 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2661 userId); 2662 } 2663 if (mResolveComponentName.equals(component)) { 2664 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2665 new PackageUserState(), userId); 2666 } 2667 } 2668 return null; 2669 } 2670 2671 @Override 2672 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2673 String resolvedType) { 2674 synchronized (mPackages) { 2675 PackageParser.Activity a = mActivities.mActivities.get(component); 2676 if (a == null) { 2677 return false; 2678 } 2679 for (int i=0; i<a.intents.size(); i++) { 2680 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2681 intent.getData(), intent.getCategories(), TAG) >= 0) { 2682 return true; 2683 } 2684 } 2685 return false; 2686 } 2687 } 2688 2689 @Override 2690 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2691 if (!sUserManager.exists(userId)) return null; 2692 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2693 synchronized (mPackages) { 2694 PackageParser.Activity a = mReceivers.mActivities.get(component); 2695 if (DEBUG_PACKAGE_INFO) Log.v( 2696 TAG, "getReceiverInfo " + component + ": " + a); 2697 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2698 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2699 if (ps == null) return null; 2700 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2701 userId); 2702 } 2703 } 2704 return null; 2705 } 2706 2707 @Override 2708 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2709 if (!sUserManager.exists(userId)) return null; 2710 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2711 synchronized (mPackages) { 2712 PackageParser.Service s = mServices.mServices.get(component); 2713 if (DEBUG_PACKAGE_INFO) Log.v( 2714 TAG, "getServiceInfo " + component + ": " + s); 2715 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2716 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2717 if (ps == null) return null; 2718 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2719 userId); 2720 } 2721 } 2722 return null; 2723 } 2724 2725 @Override 2726 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2727 if (!sUserManager.exists(userId)) return null; 2728 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2729 synchronized (mPackages) { 2730 PackageParser.Provider p = mProviders.mProviders.get(component); 2731 if (DEBUG_PACKAGE_INFO) Log.v( 2732 TAG, "getProviderInfo " + component + ": " + p); 2733 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2734 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2735 if (ps == null) return null; 2736 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2737 userId); 2738 } 2739 } 2740 return null; 2741 } 2742 2743 @Override 2744 public String[] getSystemSharedLibraryNames() { 2745 Set<String> libSet; 2746 synchronized (mPackages) { 2747 libSet = mSharedLibraries.keySet(); 2748 int size = libSet.size(); 2749 if (size > 0) { 2750 String[] libs = new String[size]; 2751 libSet.toArray(libs); 2752 return libs; 2753 } 2754 } 2755 return null; 2756 } 2757 2758 /** 2759 * @hide 2760 */ 2761 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2762 synchronized (mPackages) { 2763 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2764 if (lib != null && lib.apk != null) { 2765 return mPackages.get(lib.apk); 2766 } 2767 } 2768 return null; 2769 } 2770 2771 @Override 2772 public FeatureInfo[] getSystemAvailableFeatures() { 2773 Collection<FeatureInfo> featSet; 2774 synchronized (mPackages) { 2775 featSet = mAvailableFeatures.values(); 2776 int size = featSet.size(); 2777 if (size > 0) { 2778 FeatureInfo[] features = new FeatureInfo[size+1]; 2779 featSet.toArray(features); 2780 FeatureInfo fi = new FeatureInfo(); 2781 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2782 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2783 features[size] = fi; 2784 return features; 2785 } 2786 } 2787 return null; 2788 } 2789 2790 @Override 2791 public boolean hasSystemFeature(String name) { 2792 synchronized (mPackages) { 2793 return mAvailableFeatures.containsKey(name); 2794 } 2795 } 2796 2797 private void checkValidCaller(int uid, int userId) { 2798 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2799 return; 2800 2801 throw new SecurityException("Caller uid=" + uid 2802 + " is not privileged to communicate with user=" + userId); 2803 } 2804 2805 @Override 2806 public int checkPermission(String permName, String pkgName, int userId) { 2807 if (!sUserManager.exists(userId)) { 2808 return PackageManager.PERMISSION_DENIED; 2809 } 2810 2811 synchronized (mPackages) { 2812 final PackageParser.Package p = mPackages.get(pkgName); 2813 if (p != null && p.mExtras != null) { 2814 final PackageSetting ps = (PackageSetting) p.mExtras; 2815 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2816 return PackageManager.PERMISSION_GRANTED; 2817 } 2818 } 2819 } 2820 2821 return PackageManager.PERMISSION_DENIED; 2822 } 2823 2824 @Override 2825 public int checkUidPermission(String permName, int uid) { 2826 final int userId = UserHandle.getUserId(uid); 2827 2828 if (!sUserManager.exists(userId)) { 2829 return PackageManager.PERMISSION_DENIED; 2830 } 2831 2832 synchronized (mPackages) { 2833 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2834 if (obj != null) { 2835 final SettingBase ps = (SettingBase) obj; 2836 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2837 return PackageManager.PERMISSION_GRANTED; 2838 } 2839 } else { 2840 ArraySet<String> perms = mSystemPermissions.get(uid); 2841 if (perms != null && perms.contains(permName)) { 2842 return PackageManager.PERMISSION_GRANTED; 2843 } 2844 } 2845 } 2846 2847 return PackageManager.PERMISSION_DENIED; 2848 } 2849 2850 /** 2851 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2852 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2853 * @param checkShell TODO(yamasani): 2854 * @param message the message to log on security exception 2855 */ 2856 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2857 boolean checkShell, String message) { 2858 if (userId < 0) { 2859 throw new IllegalArgumentException("Invalid userId " + userId); 2860 } 2861 if (checkShell) { 2862 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2863 } 2864 if (userId == UserHandle.getUserId(callingUid)) return; 2865 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2866 if (requireFullPermission) { 2867 mContext.enforceCallingOrSelfPermission( 2868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2869 } else { 2870 try { 2871 mContext.enforceCallingOrSelfPermission( 2872 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2873 } catch (SecurityException se) { 2874 mContext.enforceCallingOrSelfPermission( 2875 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2876 } 2877 } 2878 } 2879 } 2880 2881 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2882 if (callingUid == Process.SHELL_UID) { 2883 if (userHandle >= 0 2884 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2885 throw new SecurityException("Shell does not have permission to access user " 2886 + userHandle); 2887 } else if (userHandle < 0) { 2888 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2889 + Debug.getCallers(3)); 2890 } 2891 } 2892 } 2893 2894 private BasePermission findPermissionTreeLP(String permName) { 2895 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2896 if (permName.startsWith(bp.name) && 2897 permName.length() > bp.name.length() && 2898 permName.charAt(bp.name.length()) == '.') { 2899 return bp; 2900 } 2901 } 2902 return null; 2903 } 2904 2905 private BasePermission checkPermissionTreeLP(String permName) { 2906 if (permName != null) { 2907 BasePermission bp = findPermissionTreeLP(permName); 2908 if (bp != null) { 2909 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2910 return bp; 2911 } 2912 throw new SecurityException("Calling uid " 2913 + Binder.getCallingUid() 2914 + " is not allowed to add to permission tree " 2915 + bp.name + " owned by uid " + bp.uid); 2916 } 2917 } 2918 throw new SecurityException("No permission tree found for " + permName); 2919 } 2920 2921 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2922 if (s1 == null) { 2923 return s2 == null; 2924 } 2925 if (s2 == null) { 2926 return false; 2927 } 2928 if (s1.getClass() != s2.getClass()) { 2929 return false; 2930 } 2931 return s1.equals(s2); 2932 } 2933 2934 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2935 if (pi1.icon != pi2.icon) return false; 2936 if (pi1.logo != pi2.logo) return false; 2937 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2938 if (!compareStrings(pi1.name, pi2.name)) return false; 2939 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2940 // We'll take care of setting this one. 2941 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2942 // These are not currently stored in settings. 2943 //if (!compareStrings(pi1.group, pi2.group)) return false; 2944 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2945 //if (pi1.labelRes != pi2.labelRes) return false; 2946 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2947 return true; 2948 } 2949 2950 int permissionInfoFootprint(PermissionInfo info) { 2951 int size = info.name.length(); 2952 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2953 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2954 return size; 2955 } 2956 2957 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2958 int size = 0; 2959 for (BasePermission perm : mSettings.mPermissions.values()) { 2960 if (perm.uid == tree.uid) { 2961 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2962 } 2963 } 2964 return size; 2965 } 2966 2967 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2968 // We calculate the max size of permissions defined by this uid and throw 2969 // if that plus the size of 'info' would exceed our stated maximum. 2970 if (tree.uid != Process.SYSTEM_UID) { 2971 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2972 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2973 throw new SecurityException("Permission tree size cap exceeded"); 2974 } 2975 } 2976 } 2977 2978 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2979 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2980 throw new SecurityException("Label must be specified in permission"); 2981 } 2982 BasePermission tree = checkPermissionTreeLP(info.name); 2983 BasePermission bp = mSettings.mPermissions.get(info.name); 2984 boolean added = bp == null; 2985 boolean changed = true; 2986 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2987 if (added) { 2988 enforcePermissionCapLocked(info, tree); 2989 bp = new BasePermission(info.name, tree.sourcePackage, 2990 BasePermission.TYPE_DYNAMIC); 2991 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2992 throw new SecurityException( 2993 "Not allowed to modify non-dynamic permission " 2994 + info.name); 2995 } else { 2996 if (bp.protectionLevel == fixedLevel 2997 && bp.perm.owner.equals(tree.perm.owner) 2998 && bp.uid == tree.uid 2999 && comparePermissionInfos(bp.perm.info, info)) { 3000 changed = false; 3001 } 3002 } 3003 bp.protectionLevel = fixedLevel; 3004 info = new PermissionInfo(info); 3005 info.protectionLevel = fixedLevel; 3006 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3007 bp.perm.info.packageName = tree.perm.info.packageName; 3008 bp.uid = tree.uid; 3009 if (added) { 3010 mSettings.mPermissions.put(info.name, bp); 3011 } 3012 if (changed) { 3013 if (!async) { 3014 mSettings.writeLPr(); 3015 } else { 3016 scheduleWriteSettingsLocked(); 3017 } 3018 } 3019 return added; 3020 } 3021 3022 @Override 3023 public boolean addPermission(PermissionInfo info) { 3024 synchronized (mPackages) { 3025 return addPermissionLocked(info, false); 3026 } 3027 } 3028 3029 @Override 3030 public boolean addPermissionAsync(PermissionInfo info) { 3031 synchronized (mPackages) { 3032 return addPermissionLocked(info, true); 3033 } 3034 } 3035 3036 @Override 3037 public void removePermission(String name) { 3038 synchronized (mPackages) { 3039 checkPermissionTreeLP(name); 3040 BasePermission bp = mSettings.mPermissions.get(name); 3041 if (bp != null) { 3042 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3043 throw new SecurityException( 3044 "Not allowed to modify non-dynamic permission " 3045 + name); 3046 } 3047 mSettings.mPermissions.remove(name); 3048 mSettings.writeLPr(); 3049 } 3050 } 3051 } 3052 3053 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3054 BasePermission bp) { 3055 int index = pkg.requestedPermissions.indexOf(bp.name); 3056 if (index == -1) { 3057 throw new SecurityException("Package " + pkg.packageName 3058 + " has not requested permission " + bp.name); 3059 } 3060 if (!bp.isRuntime()) { 3061 throw new SecurityException("Permission " + bp.name 3062 + " is not a changeable permission type"); 3063 } 3064 } 3065 3066 @Override 3067 public boolean grantPermission(String packageName, String name, int userId) { 3068 if (!RUNTIME_PERMISSIONS_ENABLED) { 3069 return false; 3070 } 3071 3072 if (!sUserManager.exists(userId)) { 3073 return false; 3074 } 3075 3076 mContext.enforceCallingOrSelfPermission( 3077 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3078 "grantPermission"); 3079 3080 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3081 "grantPermission"); 3082 3083 boolean gidsChanged = false; 3084 final SettingBase sb; 3085 3086 synchronized (mPackages) { 3087 final PackageParser.Package pkg = mPackages.get(packageName); 3088 if (pkg == null) { 3089 throw new IllegalArgumentException("Unknown package: " + packageName); 3090 } 3091 3092 final BasePermission bp = mSettings.mPermissions.get(name); 3093 if (bp == null) { 3094 throw new IllegalArgumentException("Unknown permission: " + name); 3095 } 3096 3097 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3098 3099 sb = (SettingBase) pkg.mExtras; 3100 if (sb == null) { 3101 throw new IllegalArgumentException("Unknown package: " + packageName); 3102 } 3103 3104 final PermissionsState permissionsState = sb.getPermissionsState(); 3105 3106 final int result = permissionsState.grantRuntimePermission(bp, userId); 3107 switch (result) { 3108 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3109 return false; 3110 } 3111 3112 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3113 gidsChanged = true; 3114 } break; 3115 } 3116 3117 // Not critical if that is lost - app has to request again. 3118 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3119 } 3120 3121 if (gidsChanged) { 3122 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3123 } 3124 3125 return true; 3126 } 3127 3128 @Override 3129 public boolean revokePermission(String packageName, String name, int userId) { 3130 if (!RUNTIME_PERMISSIONS_ENABLED) { 3131 return false; 3132 } 3133 3134 if (!sUserManager.exists(userId)) { 3135 return false; 3136 } 3137 3138 mContext.enforceCallingOrSelfPermission( 3139 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3140 "revokePermission"); 3141 3142 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3143 "revokePermission"); 3144 3145 final SettingBase sb; 3146 3147 synchronized (mPackages) { 3148 final PackageParser.Package pkg = mPackages.get(packageName); 3149 if (pkg == null) { 3150 throw new IllegalArgumentException("Unknown package: " + packageName); 3151 } 3152 3153 final BasePermission bp = mSettings.mPermissions.get(name); 3154 if (bp == null) { 3155 throw new IllegalArgumentException("Unknown permission: " + name); 3156 } 3157 3158 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3159 3160 sb = (SettingBase) pkg.mExtras; 3161 if (sb == null) { 3162 throw new IllegalArgumentException("Unknown package: " + packageName); 3163 } 3164 3165 final PermissionsState permissionsState = sb.getPermissionsState(); 3166 3167 if (permissionsState.revokeRuntimePermission(bp, userId) == 3168 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3169 return false; 3170 } 3171 3172 // Critical, after this call all should never have the permission. 3173 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3174 } 3175 3176 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3177 3178 return true; 3179 } 3180 3181 @Override 3182 public boolean isProtectedBroadcast(String actionName) { 3183 synchronized (mPackages) { 3184 return mProtectedBroadcasts.contains(actionName); 3185 } 3186 } 3187 3188 @Override 3189 public int checkSignatures(String pkg1, String pkg2) { 3190 synchronized (mPackages) { 3191 final PackageParser.Package p1 = mPackages.get(pkg1); 3192 final PackageParser.Package p2 = mPackages.get(pkg2); 3193 if (p1 == null || p1.mExtras == null 3194 || p2 == null || p2.mExtras == null) { 3195 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3196 } 3197 return compareSignatures(p1.mSignatures, p2.mSignatures); 3198 } 3199 } 3200 3201 @Override 3202 public int checkUidSignatures(int uid1, int uid2) { 3203 // Map to base uids. 3204 uid1 = UserHandle.getAppId(uid1); 3205 uid2 = UserHandle.getAppId(uid2); 3206 // reader 3207 synchronized (mPackages) { 3208 Signature[] s1; 3209 Signature[] s2; 3210 Object obj = mSettings.getUserIdLPr(uid1); 3211 if (obj != null) { 3212 if (obj instanceof SharedUserSetting) { 3213 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3214 } else if (obj instanceof PackageSetting) { 3215 s1 = ((PackageSetting)obj).signatures.mSignatures; 3216 } else { 3217 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3218 } 3219 } else { 3220 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3221 } 3222 obj = mSettings.getUserIdLPr(uid2); 3223 if (obj != null) { 3224 if (obj instanceof SharedUserSetting) { 3225 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3226 } else if (obj instanceof PackageSetting) { 3227 s2 = ((PackageSetting)obj).signatures.mSignatures; 3228 } else { 3229 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3230 } 3231 } else { 3232 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3233 } 3234 return compareSignatures(s1, s2); 3235 } 3236 } 3237 3238 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3239 final long identity = Binder.clearCallingIdentity(); 3240 try { 3241 if (sb instanceof SharedUserSetting) { 3242 SharedUserSetting sus = (SharedUserSetting) sb; 3243 final int packageCount = sus.packages.size(); 3244 for (int i = 0; i < packageCount; i++) { 3245 PackageSetting susPs = sus.packages.valueAt(i); 3246 if (userId == UserHandle.USER_ALL) { 3247 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3248 } else { 3249 final int uid = UserHandle.getUid(userId, susPs.appId); 3250 killUid(uid, reason); 3251 } 3252 } 3253 } else if (sb instanceof PackageSetting) { 3254 PackageSetting ps = (PackageSetting) sb; 3255 if (userId == UserHandle.USER_ALL) { 3256 killApplication(ps.pkg.packageName, ps.appId, reason); 3257 } else { 3258 final int uid = UserHandle.getUid(userId, ps.appId); 3259 killUid(uid, reason); 3260 } 3261 } 3262 } finally { 3263 Binder.restoreCallingIdentity(identity); 3264 } 3265 } 3266 3267 private static void killUid(int uid, String reason) { 3268 IActivityManager am = ActivityManagerNative.getDefault(); 3269 if (am != null) { 3270 try { 3271 am.killUid(uid, reason); 3272 } catch (RemoteException e) { 3273 /* ignore - same process */ 3274 } 3275 } 3276 } 3277 3278 /** 3279 * Compares two sets of signatures. Returns: 3280 * <br /> 3281 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3282 * <br /> 3283 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3284 * <br /> 3285 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3286 * <br /> 3287 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3288 * <br /> 3289 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3290 */ 3291 static int compareSignatures(Signature[] s1, Signature[] s2) { 3292 if (s1 == null) { 3293 return s2 == null 3294 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3295 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3296 } 3297 3298 if (s2 == null) { 3299 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3300 } 3301 3302 if (s1.length != s2.length) { 3303 return PackageManager.SIGNATURE_NO_MATCH; 3304 } 3305 3306 // Since both signature sets are of size 1, we can compare without HashSets. 3307 if (s1.length == 1) { 3308 return s1[0].equals(s2[0]) ? 3309 PackageManager.SIGNATURE_MATCH : 3310 PackageManager.SIGNATURE_NO_MATCH; 3311 } 3312 3313 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3314 for (Signature sig : s1) { 3315 set1.add(sig); 3316 } 3317 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3318 for (Signature sig : s2) { 3319 set2.add(sig); 3320 } 3321 // Make sure s2 contains all signatures in s1. 3322 if (set1.equals(set2)) { 3323 return PackageManager.SIGNATURE_MATCH; 3324 } 3325 return PackageManager.SIGNATURE_NO_MATCH; 3326 } 3327 3328 /** 3329 * If the database version for this type of package (internal storage or 3330 * external storage) is less than the version where package signatures 3331 * were updated, return true. 3332 */ 3333 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3334 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3335 DatabaseVersion.SIGNATURE_END_ENTITY)) 3336 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3337 DatabaseVersion.SIGNATURE_END_ENTITY)); 3338 } 3339 3340 /** 3341 * Used for backward compatibility to make sure any packages with 3342 * certificate chains get upgraded to the new style. {@code existingSigs} 3343 * will be in the old format (since they were stored on disk from before the 3344 * system upgrade) and {@code scannedSigs} will be in the newer format. 3345 */ 3346 private int compareSignaturesCompat(PackageSignatures existingSigs, 3347 PackageParser.Package scannedPkg) { 3348 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3349 return PackageManager.SIGNATURE_NO_MATCH; 3350 } 3351 3352 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3353 for (Signature sig : existingSigs.mSignatures) { 3354 existingSet.add(sig); 3355 } 3356 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3357 for (Signature sig : scannedPkg.mSignatures) { 3358 try { 3359 Signature[] chainSignatures = sig.getChainSignatures(); 3360 for (Signature chainSig : chainSignatures) { 3361 scannedCompatSet.add(chainSig); 3362 } 3363 } catch (CertificateEncodingException e) { 3364 scannedCompatSet.add(sig); 3365 } 3366 } 3367 /* 3368 * Make sure the expanded scanned set contains all signatures in the 3369 * existing one. 3370 */ 3371 if (scannedCompatSet.equals(existingSet)) { 3372 // Migrate the old signatures to the new scheme. 3373 existingSigs.assignSignatures(scannedPkg.mSignatures); 3374 // The new KeySets will be re-added later in the scanning process. 3375 synchronized (mPackages) { 3376 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3377 } 3378 return PackageManager.SIGNATURE_MATCH; 3379 } 3380 return PackageManager.SIGNATURE_NO_MATCH; 3381 } 3382 3383 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3384 if (isExternal(scannedPkg)) { 3385 return mSettings.isExternalDatabaseVersionOlderThan( 3386 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3387 } else { 3388 return mSettings.isInternalDatabaseVersionOlderThan( 3389 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3390 } 3391 } 3392 3393 private int compareSignaturesRecover(PackageSignatures existingSigs, 3394 PackageParser.Package scannedPkg) { 3395 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3396 return PackageManager.SIGNATURE_NO_MATCH; 3397 } 3398 3399 String msg = null; 3400 try { 3401 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3402 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3403 + scannedPkg.packageName); 3404 return PackageManager.SIGNATURE_MATCH; 3405 } 3406 } catch (CertificateException e) { 3407 msg = e.getMessage(); 3408 } 3409 3410 logCriticalInfo(Log.INFO, 3411 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3412 return PackageManager.SIGNATURE_NO_MATCH; 3413 } 3414 3415 @Override 3416 public String[] getPackagesForUid(int uid) { 3417 uid = UserHandle.getAppId(uid); 3418 // reader 3419 synchronized (mPackages) { 3420 Object obj = mSettings.getUserIdLPr(uid); 3421 if (obj instanceof SharedUserSetting) { 3422 final SharedUserSetting sus = (SharedUserSetting) obj; 3423 final int N = sus.packages.size(); 3424 final String[] res = new String[N]; 3425 final Iterator<PackageSetting> it = sus.packages.iterator(); 3426 int i = 0; 3427 while (it.hasNext()) { 3428 res[i++] = it.next().name; 3429 } 3430 return res; 3431 } else if (obj instanceof PackageSetting) { 3432 final PackageSetting ps = (PackageSetting) obj; 3433 return new String[] { ps.name }; 3434 } 3435 } 3436 return null; 3437 } 3438 3439 @Override 3440 public String getNameForUid(int uid) { 3441 // reader 3442 synchronized (mPackages) { 3443 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3444 if (obj instanceof SharedUserSetting) { 3445 final SharedUserSetting sus = (SharedUserSetting) obj; 3446 return sus.name + ":" + sus.userId; 3447 } else if (obj instanceof PackageSetting) { 3448 final PackageSetting ps = (PackageSetting) obj; 3449 return ps.name; 3450 } 3451 } 3452 return null; 3453 } 3454 3455 @Override 3456 public int getUidForSharedUser(String sharedUserName) { 3457 if(sharedUserName == null) { 3458 return -1; 3459 } 3460 // reader 3461 synchronized (mPackages) { 3462 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3463 if (suid == null) { 3464 return -1; 3465 } 3466 return suid.userId; 3467 } 3468 } 3469 3470 @Override 3471 public int getFlagsForUid(int uid) { 3472 synchronized (mPackages) { 3473 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3474 if (obj instanceof SharedUserSetting) { 3475 final SharedUserSetting sus = (SharedUserSetting) obj; 3476 return sus.pkgFlags; 3477 } else if (obj instanceof PackageSetting) { 3478 final PackageSetting ps = (PackageSetting) obj; 3479 return ps.pkgFlags; 3480 } 3481 } 3482 return 0; 3483 } 3484 3485 @Override 3486 public int getPrivateFlagsForUid(int uid) { 3487 synchronized (mPackages) { 3488 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3489 if (obj instanceof SharedUserSetting) { 3490 final SharedUserSetting sus = (SharedUserSetting) obj; 3491 return sus.pkgPrivateFlags; 3492 } else if (obj instanceof PackageSetting) { 3493 final PackageSetting ps = (PackageSetting) obj; 3494 return ps.pkgPrivateFlags; 3495 } 3496 } 3497 return 0; 3498 } 3499 3500 @Override 3501 public boolean isUidPrivileged(int uid) { 3502 uid = UserHandle.getAppId(uid); 3503 // reader 3504 synchronized (mPackages) { 3505 Object obj = mSettings.getUserIdLPr(uid); 3506 if (obj instanceof SharedUserSetting) { 3507 final SharedUserSetting sus = (SharedUserSetting) obj; 3508 final Iterator<PackageSetting> it = sus.packages.iterator(); 3509 while (it.hasNext()) { 3510 if (it.next().isPrivileged()) { 3511 return true; 3512 } 3513 } 3514 } else if (obj instanceof PackageSetting) { 3515 final PackageSetting ps = (PackageSetting) obj; 3516 return ps.isPrivileged(); 3517 } 3518 } 3519 return false; 3520 } 3521 3522 @Override 3523 public String[] getAppOpPermissionPackages(String permissionName) { 3524 synchronized (mPackages) { 3525 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3526 if (pkgs == null) { 3527 return null; 3528 } 3529 return pkgs.toArray(new String[pkgs.size()]); 3530 } 3531 } 3532 3533 @Override 3534 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3535 int flags, int userId) { 3536 if (!sUserManager.exists(userId)) return null; 3537 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3538 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3539 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3540 } 3541 3542 @Override 3543 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3544 IntentFilter filter, int match, ComponentName activity) { 3545 final int userId = UserHandle.getCallingUserId(); 3546 if (DEBUG_PREFERRED) { 3547 Log.v(TAG, "setLastChosenActivity intent=" + intent 3548 + " resolvedType=" + resolvedType 3549 + " flags=" + flags 3550 + " filter=" + filter 3551 + " match=" + match 3552 + " activity=" + activity); 3553 filter.dump(new PrintStreamPrinter(System.out), " "); 3554 } 3555 intent.setComponent(null); 3556 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3557 // Find any earlier preferred or last chosen entries and nuke them 3558 findPreferredActivity(intent, resolvedType, 3559 flags, query, 0, false, true, false, userId); 3560 // Add the new activity as the last chosen for this filter 3561 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3562 "Setting last chosen"); 3563 } 3564 3565 @Override 3566 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3567 final int userId = UserHandle.getCallingUserId(); 3568 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3569 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3570 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3571 false, false, false, userId); 3572 } 3573 3574 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3575 int flags, List<ResolveInfo> query, int userId) { 3576 if (query != null) { 3577 final int N = query.size(); 3578 if (N == 1) { 3579 return query.get(0); 3580 } else if (N > 1) { 3581 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3582 // If there is more than one activity with the same priority, 3583 // then let the user decide between them. 3584 ResolveInfo r0 = query.get(0); 3585 ResolveInfo r1 = query.get(1); 3586 if (DEBUG_INTENT_MATCHING || debug) { 3587 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3588 + r1.activityInfo.name + "=" + r1.priority); 3589 } 3590 // If the first activity has a higher priority, or a different 3591 // default, then it is always desireable to pick it. 3592 if (r0.priority != r1.priority 3593 || r0.preferredOrder != r1.preferredOrder 3594 || r0.isDefault != r1.isDefault) { 3595 return query.get(0); 3596 } 3597 // If we have saved a preference for a preferred activity for 3598 // this Intent, use that. 3599 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3600 flags, query, r0.priority, true, false, debug, userId); 3601 if (ri != null) { 3602 return ri; 3603 } 3604 if (userId != 0) { 3605 ri = new ResolveInfo(mResolveInfo); 3606 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3607 ri.activityInfo.applicationInfo = new ApplicationInfo( 3608 ri.activityInfo.applicationInfo); 3609 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3610 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3611 return ri; 3612 } 3613 return mResolveInfo; 3614 } 3615 } 3616 return null; 3617 } 3618 3619 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3620 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3621 final int N = query.size(); 3622 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3623 .get(userId); 3624 // Get the list of persistent preferred activities that handle the intent 3625 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3626 List<PersistentPreferredActivity> pprefs = ppir != null 3627 ? ppir.queryIntent(intent, resolvedType, 3628 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3629 : null; 3630 if (pprefs != null && pprefs.size() > 0) { 3631 final int M = pprefs.size(); 3632 for (int i=0; i<M; i++) { 3633 final PersistentPreferredActivity ppa = pprefs.get(i); 3634 if (DEBUG_PREFERRED || debug) { 3635 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3636 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3637 + "\n component=" + ppa.mComponent); 3638 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3639 } 3640 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3641 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3642 if (DEBUG_PREFERRED || debug) { 3643 Slog.v(TAG, "Found persistent preferred activity:"); 3644 if (ai != null) { 3645 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3646 } else { 3647 Slog.v(TAG, " null"); 3648 } 3649 } 3650 if (ai == null) { 3651 // This previously registered persistent preferred activity 3652 // component is no longer known. Ignore it and do NOT remove it. 3653 continue; 3654 } 3655 for (int j=0; j<N; j++) { 3656 final ResolveInfo ri = query.get(j); 3657 if (!ri.activityInfo.applicationInfo.packageName 3658 .equals(ai.applicationInfo.packageName)) { 3659 continue; 3660 } 3661 if (!ri.activityInfo.name.equals(ai.name)) { 3662 continue; 3663 } 3664 // Found a persistent preference that can handle the intent. 3665 if (DEBUG_PREFERRED || debug) { 3666 Slog.v(TAG, "Returning persistent preferred activity: " + 3667 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3668 } 3669 return ri; 3670 } 3671 } 3672 } 3673 return null; 3674 } 3675 3676 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3677 List<ResolveInfo> query, int priority, boolean always, 3678 boolean removeMatches, boolean debug, int userId) { 3679 if (!sUserManager.exists(userId)) return null; 3680 // writer 3681 synchronized (mPackages) { 3682 if (intent.getSelector() != null) { 3683 intent = intent.getSelector(); 3684 } 3685 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3686 3687 // Try to find a matching persistent preferred activity. 3688 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3689 debug, userId); 3690 3691 // If a persistent preferred activity matched, use it. 3692 if (pri != null) { 3693 return pri; 3694 } 3695 3696 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3697 // Get the list of preferred activities that handle the intent 3698 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3699 List<PreferredActivity> prefs = pir != null 3700 ? pir.queryIntent(intent, resolvedType, 3701 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3702 : null; 3703 if (prefs != null && prefs.size() > 0) { 3704 boolean changed = false; 3705 try { 3706 // First figure out how good the original match set is. 3707 // We will only allow preferred activities that came 3708 // from the same match quality. 3709 int match = 0; 3710 3711 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3712 3713 final int N = query.size(); 3714 for (int j=0; j<N; j++) { 3715 final ResolveInfo ri = query.get(j); 3716 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3717 + ": 0x" + Integer.toHexString(match)); 3718 if (ri.match > match) { 3719 match = ri.match; 3720 } 3721 } 3722 3723 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3724 + Integer.toHexString(match)); 3725 3726 match &= IntentFilter.MATCH_CATEGORY_MASK; 3727 final int M = prefs.size(); 3728 for (int i=0; i<M; i++) { 3729 final PreferredActivity pa = prefs.get(i); 3730 if (DEBUG_PREFERRED || debug) { 3731 Slog.v(TAG, "Checking PreferredActivity ds=" 3732 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3733 + "\n component=" + pa.mPref.mComponent); 3734 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3735 } 3736 if (pa.mPref.mMatch != match) { 3737 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3738 + Integer.toHexString(pa.mPref.mMatch)); 3739 continue; 3740 } 3741 // If it's not an "always" type preferred activity and that's what we're 3742 // looking for, skip it. 3743 if (always && !pa.mPref.mAlways) { 3744 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3745 continue; 3746 } 3747 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3748 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3749 if (DEBUG_PREFERRED || debug) { 3750 Slog.v(TAG, "Found preferred activity:"); 3751 if (ai != null) { 3752 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3753 } else { 3754 Slog.v(TAG, " null"); 3755 } 3756 } 3757 if (ai == null) { 3758 // This previously registered preferred activity 3759 // component is no longer known. Most likely an update 3760 // to the app was installed and in the new version this 3761 // component no longer exists. Clean it up by removing 3762 // it from the preferred activities list, and skip it. 3763 Slog.w(TAG, "Removing dangling preferred activity: " 3764 + pa.mPref.mComponent); 3765 pir.removeFilter(pa); 3766 changed = true; 3767 continue; 3768 } 3769 for (int j=0; j<N; j++) { 3770 final ResolveInfo ri = query.get(j); 3771 if (!ri.activityInfo.applicationInfo.packageName 3772 .equals(ai.applicationInfo.packageName)) { 3773 continue; 3774 } 3775 if (!ri.activityInfo.name.equals(ai.name)) { 3776 continue; 3777 } 3778 3779 if (removeMatches) { 3780 pir.removeFilter(pa); 3781 changed = true; 3782 if (DEBUG_PREFERRED) { 3783 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3784 } 3785 break; 3786 } 3787 3788 // Okay we found a previously set preferred or last chosen app. 3789 // If the result set is different from when this 3790 // was created, we need to clear it and re-ask the 3791 // user their preference, if we're looking for an "always" type entry. 3792 if (always && !pa.mPref.sameSet(query)) { 3793 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3794 + intent + " type " + resolvedType); 3795 if (DEBUG_PREFERRED) { 3796 Slog.v(TAG, "Removing preferred activity since set changed " 3797 + pa.mPref.mComponent); 3798 } 3799 pir.removeFilter(pa); 3800 // Re-add the filter as a "last chosen" entry (!always) 3801 PreferredActivity lastChosen = new PreferredActivity( 3802 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3803 pir.addFilter(lastChosen); 3804 changed = true; 3805 return null; 3806 } 3807 3808 // Yay! Either the set matched or we're looking for the last chosen 3809 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3810 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3811 return ri; 3812 } 3813 } 3814 } finally { 3815 if (changed) { 3816 if (DEBUG_PREFERRED) { 3817 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3818 } 3819 scheduleWritePackageRestrictionsLocked(userId); 3820 } 3821 } 3822 } 3823 } 3824 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3825 return null; 3826 } 3827 3828 /* 3829 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3830 */ 3831 @Override 3832 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3833 int targetUserId) { 3834 mContext.enforceCallingOrSelfPermission( 3835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3836 List<CrossProfileIntentFilter> matches = 3837 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3838 if (matches != null) { 3839 int size = matches.size(); 3840 for (int i = 0; i < size; i++) { 3841 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3842 } 3843 } 3844 return false; 3845 } 3846 3847 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3848 String resolvedType, int userId) { 3849 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3850 if (resolver != null) { 3851 return resolver.queryIntent(intent, resolvedType, false, userId); 3852 } 3853 return null; 3854 } 3855 3856 @Override 3857 public List<ResolveInfo> queryIntentActivities(Intent intent, 3858 String resolvedType, int flags, int userId) { 3859 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3860 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3861 ComponentName comp = intent.getComponent(); 3862 if (comp == null) { 3863 if (intent.getSelector() != null) { 3864 intent = intent.getSelector(); 3865 comp = intent.getComponent(); 3866 } 3867 } 3868 3869 if (comp != null) { 3870 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3871 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3872 if (ai != null) { 3873 final ResolveInfo ri = new ResolveInfo(); 3874 ri.activityInfo = ai; 3875 list.add(ri); 3876 } 3877 return list; 3878 } 3879 3880 // reader 3881 synchronized (mPackages) { 3882 final String pkgName = intent.getPackage(); 3883 if (pkgName == null) { 3884 List<CrossProfileIntentFilter> matchingFilters = 3885 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3886 // Check for results that need to skip the current profile. 3887 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3888 resolvedType, flags, userId); 3889 if (resolveInfo != null) { 3890 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3891 result.add(resolveInfo); 3892 return filterIfNotPrimaryUser(result, userId); 3893 } 3894 // Check for cross profile results. 3895 resolveInfo = queryCrossProfileIntents( 3896 matchingFilters, intent, resolvedType, flags, userId); 3897 3898 // Check for results in the current profile. Adding GET_RESOLVED_FILTER flags 3899 // as we need it later 3900 List<ResolveInfo> result = mActivities.queryIntent( 3901 intent, resolvedType, flags, userId); 3902 if (resolveInfo != null) { 3903 result.add(resolveInfo); 3904 Collections.sort(result, mResolvePrioritySorter); 3905 } 3906 result = filterIfNotPrimaryUser(result, userId); 3907 if (result.size() > 1) { 3908 return filterCandidatesWithDomainPreferedActivitiesLPw(result); 3909 } 3910 3911 return result; 3912 } 3913 final PackageParser.Package pkg = mPackages.get(pkgName); 3914 if (pkg != null) { 3915 return filterIfNotPrimaryUser( 3916 mActivities.queryIntentForPackage( 3917 intent, resolvedType, flags, pkg.activities, userId), 3918 userId); 3919 } 3920 return new ArrayList<ResolveInfo>(); 3921 } 3922 } 3923 3924 /** 3925 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3926 * 3927 * @return filtered list 3928 */ 3929 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3930 if (userId == UserHandle.USER_OWNER) { 3931 return resolveInfos; 3932 } 3933 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3934 ResolveInfo info = resolveInfos.get(i); 3935 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3936 resolveInfos.remove(i); 3937 } 3938 } 3939 return resolveInfos; 3940 } 3941 3942 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPw( 3943 List<ResolveInfo> candidates) { 3944 if (DEBUG_PREFERRED) { 3945 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3946 candidates.size()); 3947 } 3948 final int userId = UserHandle.getCallingUserId(); 3949 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(candidates); 3950 synchronized (mPackages) { 3951 final int count = result.size(); 3952 for (int n = count-1; n >= 0; n--) { 3953 ResolveInfo info = result.get(n); 3954 if (!info.filterNeedsVerification) { 3955 continue; 3956 } 3957 String packageName = info.activityInfo.packageName; 3958 PackageSetting ps = mSettings.mPackages.get(packageName); 3959 if (ps != null) { 3960 // Try to get the status from User settings first 3961 int status = ps.getDomainVerificationStatusForUser(userId); 3962 // if none available, get the master status 3963 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 3964 if (ps.getIntentFilterVerificationInfo() != null) { 3965 status = ps.getIntentFilterVerificationInfo().getStatus(); 3966 } 3967 } 3968 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 3969 result.clear(); 3970 result.add(info); 3971 // We break the for loop as we are good to go 3972 break; 3973 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 3974 result.remove(n); 3975 } 3976 } 3977 } 3978 } 3979 if (DEBUG_PREFERRED) { 3980 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 3981 result.size()); 3982 } 3983 return result; 3984 } 3985 3986 private ResolveInfo querySkipCurrentProfileIntents( 3987 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3988 int flags, int sourceUserId) { 3989 if (matchingFilters != null) { 3990 int size = matchingFilters.size(); 3991 for (int i = 0; i < size; i ++) { 3992 CrossProfileIntentFilter filter = matchingFilters.get(i); 3993 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3994 // Checking if there are activities in the target user that can handle the 3995 // intent. 3996 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3997 flags, sourceUserId); 3998 if (resolveInfo != null) { 3999 return resolveInfo; 4000 } 4001 } 4002 } 4003 } 4004 return null; 4005 } 4006 4007 // Return matching ResolveInfo if any for skip current profile intent filters. 4008 private ResolveInfo queryCrossProfileIntents( 4009 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4010 int flags, int sourceUserId) { 4011 if (matchingFilters != null) { 4012 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4013 // match the same intent. For performance reasons, it is better not to 4014 // run queryIntent twice for the same userId 4015 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4016 int size = matchingFilters.size(); 4017 for (int i = 0; i < size; i++) { 4018 CrossProfileIntentFilter filter = matchingFilters.get(i); 4019 int targetUserId = filter.getTargetUserId(); 4020 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4021 && !alreadyTriedUserIds.get(targetUserId)) { 4022 // Checking if there are activities in the target user that can handle the 4023 // intent. 4024 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4025 flags, sourceUserId); 4026 if (resolveInfo != null) return resolveInfo; 4027 alreadyTriedUserIds.put(targetUserId, true); 4028 } 4029 } 4030 } 4031 return null; 4032 } 4033 4034 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4035 String resolvedType, int flags, int sourceUserId) { 4036 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4037 resolvedType, flags, filter.getTargetUserId()); 4038 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4039 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4040 } 4041 return null; 4042 } 4043 4044 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4045 int sourceUserId, int targetUserId) { 4046 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4047 String className; 4048 if (targetUserId == UserHandle.USER_OWNER) { 4049 className = FORWARD_INTENT_TO_USER_OWNER; 4050 } else { 4051 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4052 } 4053 ComponentName forwardingActivityComponentName = new ComponentName( 4054 mAndroidApplication.packageName, className); 4055 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4056 sourceUserId); 4057 if (targetUserId == UserHandle.USER_OWNER) { 4058 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4059 forwardingResolveInfo.noResourceId = true; 4060 } 4061 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4062 forwardingResolveInfo.priority = 0; 4063 forwardingResolveInfo.preferredOrder = 0; 4064 forwardingResolveInfo.match = 0; 4065 forwardingResolveInfo.isDefault = true; 4066 forwardingResolveInfo.filter = filter; 4067 forwardingResolveInfo.targetUserId = targetUserId; 4068 return forwardingResolveInfo; 4069 } 4070 4071 @Override 4072 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4073 Intent[] specifics, String[] specificTypes, Intent intent, 4074 String resolvedType, int flags, int userId) { 4075 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4076 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4077 false, "query intent activity options"); 4078 final String resultsAction = intent.getAction(); 4079 4080 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4081 | PackageManager.GET_RESOLVED_FILTER, userId); 4082 4083 if (DEBUG_INTENT_MATCHING) { 4084 Log.v(TAG, "Query " + intent + ": " + results); 4085 } 4086 4087 int specificsPos = 0; 4088 int N; 4089 4090 // todo: note that the algorithm used here is O(N^2). This 4091 // isn't a problem in our current environment, but if we start running 4092 // into situations where we have more than 5 or 10 matches then this 4093 // should probably be changed to something smarter... 4094 4095 // First we go through and resolve each of the specific items 4096 // that were supplied, taking care of removing any corresponding 4097 // duplicate items in the generic resolve list. 4098 if (specifics != null) { 4099 for (int i=0; i<specifics.length; i++) { 4100 final Intent sintent = specifics[i]; 4101 if (sintent == null) { 4102 continue; 4103 } 4104 4105 if (DEBUG_INTENT_MATCHING) { 4106 Log.v(TAG, "Specific #" + i + ": " + sintent); 4107 } 4108 4109 String action = sintent.getAction(); 4110 if (resultsAction != null && resultsAction.equals(action)) { 4111 // If this action was explicitly requested, then don't 4112 // remove things that have it. 4113 action = null; 4114 } 4115 4116 ResolveInfo ri = null; 4117 ActivityInfo ai = null; 4118 4119 ComponentName comp = sintent.getComponent(); 4120 if (comp == null) { 4121 ri = resolveIntent( 4122 sintent, 4123 specificTypes != null ? specificTypes[i] : null, 4124 flags, userId); 4125 if (ri == null) { 4126 continue; 4127 } 4128 if (ri == mResolveInfo) { 4129 // ACK! Must do something better with this. 4130 } 4131 ai = ri.activityInfo; 4132 comp = new ComponentName(ai.applicationInfo.packageName, 4133 ai.name); 4134 } else { 4135 ai = getActivityInfo(comp, flags, userId); 4136 if (ai == null) { 4137 continue; 4138 } 4139 } 4140 4141 // Look for any generic query activities that are duplicates 4142 // of this specific one, and remove them from the results. 4143 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4144 N = results.size(); 4145 int j; 4146 for (j=specificsPos; j<N; j++) { 4147 ResolveInfo sri = results.get(j); 4148 if ((sri.activityInfo.name.equals(comp.getClassName()) 4149 && sri.activityInfo.applicationInfo.packageName.equals( 4150 comp.getPackageName())) 4151 || (action != null && sri.filter.matchAction(action))) { 4152 results.remove(j); 4153 if (DEBUG_INTENT_MATCHING) Log.v( 4154 TAG, "Removing duplicate item from " + j 4155 + " due to specific " + specificsPos); 4156 if (ri == null) { 4157 ri = sri; 4158 } 4159 j--; 4160 N--; 4161 } 4162 } 4163 4164 // Add this specific item to its proper place. 4165 if (ri == null) { 4166 ri = new ResolveInfo(); 4167 ri.activityInfo = ai; 4168 } 4169 results.add(specificsPos, ri); 4170 ri.specificIndex = i; 4171 specificsPos++; 4172 } 4173 } 4174 4175 // Now we go through the remaining generic results and remove any 4176 // duplicate actions that are found here. 4177 N = results.size(); 4178 for (int i=specificsPos; i<N-1; i++) { 4179 final ResolveInfo rii = results.get(i); 4180 if (rii.filter == null) { 4181 continue; 4182 } 4183 4184 // Iterate over all of the actions of this result's intent 4185 // filter... typically this should be just one. 4186 final Iterator<String> it = rii.filter.actionsIterator(); 4187 if (it == null) { 4188 continue; 4189 } 4190 while (it.hasNext()) { 4191 final String action = it.next(); 4192 if (resultsAction != null && resultsAction.equals(action)) { 4193 // If this action was explicitly requested, then don't 4194 // remove things that have it. 4195 continue; 4196 } 4197 for (int j=i+1; j<N; j++) { 4198 final ResolveInfo rij = results.get(j); 4199 if (rij.filter != null && rij.filter.hasAction(action)) { 4200 results.remove(j); 4201 if (DEBUG_INTENT_MATCHING) Log.v( 4202 TAG, "Removing duplicate item from " + j 4203 + " due to action " + action + " at " + i); 4204 j--; 4205 N--; 4206 } 4207 } 4208 } 4209 4210 // If the caller didn't request filter information, drop it now 4211 // so we don't have to marshall/unmarshall it. 4212 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4213 rii.filter = null; 4214 } 4215 } 4216 4217 // Filter out the caller activity if so requested. 4218 if (caller != null) { 4219 N = results.size(); 4220 for (int i=0; i<N; i++) { 4221 ActivityInfo ainfo = results.get(i).activityInfo; 4222 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4223 && caller.getClassName().equals(ainfo.name)) { 4224 results.remove(i); 4225 break; 4226 } 4227 } 4228 } 4229 4230 // If the caller didn't request filter information, 4231 // drop them now so we don't have to 4232 // marshall/unmarshall it. 4233 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4234 N = results.size(); 4235 for (int i=0; i<N; i++) { 4236 results.get(i).filter = null; 4237 } 4238 } 4239 4240 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4241 return results; 4242 } 4243 4244 @Override 4245 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4246 int userId) { 4247 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4248 ComponentName comp = intent.getComponent(); 4249 if (comp == null) { 4250 if (intent.getSelector() != null) { 4251 intent = intent.getSelector(); 4252 comp = intent.getComponent(); 4253 } 4254 } 4255 if (comp != null) { 4256 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4257 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4258 if (ai != null) { 4259 ResolveInfo ri = new ResolveInfo(); 4260 ri.activityInfo = ai; 4261 list.add(ri); 4262 } 4263 return list; 4264 } 4265 4266 // reader 4267 synchronized (mPackages) { 4268 String pkgName = intent.getPackage(); 4269 if (pkgName == null) { 4270 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4271 } 4272 final PackageParser.Package pkg = mPackages.get(pkgName); 4273 if (pkg != null) { 4274 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4275 userId); 4276 } 4277 return null; 4278 } 4279 } 4280 4281 @Override 4282 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4283 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4284 if (!sUserManager.exists(userId)) return null; 4285 if (query != null) { 4286 if (query.size() >= 1) { 4287 // If there is more than one service with the same priority, 4288 // just arbitrarily pick the first one. 4289 return query.get(0); 4290 } 4291 } 4292 return null; 4293 } 4294 4295 @Override 4296 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4297 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 ServiceInfo si = getServiceInfo(comp, flags, userId); 4309 if (si != null) { 4310 final ResolveInfo ri = new ResolveInfo(); 4311 ri.serviceInfo = si; 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 mServices.queryIntent(intent, resolvedType, flags, userId); 4322 } 4323 final PackageParser.Package pkg = mPackages.get(pkgName); 4324 if (pkg != null) { 4325 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4326 userId); 4327 } 4328 return null; 4329 } 4330 } 4331 4332 @Override 4333 public List<ResolveInfo> queryIntentContentProviders( 4334 Intent intent, String resolvedType, int flags, int userId) { 4335 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4336 ComponentName comp = intent.getComponent(); 4337 if (comp == null) { 4338 if (intent.getSelector() != null) { 4339 intent = intent.getSelector(); 4340 comp = intent.getComponent(); 4341 } 4342 } 4343 if (comp != null) { 4344 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4345 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4346 if (pi != null) { 4347 final ResolveInfo ri = new ResolveInfo(); 4348 ri.providerInfo = pi; 4349 list.add(ri); 4350 } 4351 return list; 4352 } 4353 4354 // reader 4355 synchronized (mPackages) { 4356 String pkgName = intent.getPackage(); 4357 if (pkgName == null) { 4358 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4359 } 4360 final PackageParser.Package pkg = mPackages.get(pkgName); 4361 if (pkg != null) { 4362 return mProviders.queryIntentForPackage( 4363 intent, resolvedType, flags, pkg.providers, userId); 4364 } 4365 return null; 4366 } 4367 } 4368 4369 @Override 4370 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4371 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4372 4373 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4374 4375 // writer 4376 synchronized (mPackages) { 4377 ArrayList<PackageInfo> list; 4378 if (listUninstalled) { 4379 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4380 for (PackageSetting ps : mSettings.mPackages.values()) { 4381 PackageInfo pi; 4382 if (ps.pkg != null) { 4383 pi = generatePackageInfo(ps.pkg, flags, userId); 4384 } else { 4385 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4386 } 4387 if (pi != null) { 4388 list.add(pi); 4389 } 4390 } 4391 } else { 4392 list = new ArrayList<PackageInfo>(mPackages.size()); 4393 for (PackageParser.Package p : mPackages.values()) { 4394 PackageInfo pi = generatePackageInfo(p, flags, userId); 4395 if (pi != null) { 4396 list.add(pi); 4397 } 4398 } 4399 } 4400 4401 return new ParceledListSlice<PackageInfo>(list); 4402 } 4403 } 4404 4405 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4406 String[] permissions, boolean[] tmp, int flags, int userId) { 4407 int numMatch = 0; 4408 final PermissionsState permissionsState = ps.getPermissionsState(); 4409 for (int i=0; i<permissions.length; i++) { 4410 final String permission = permissions[i]; 4411 if (permissionsState.hasPermission(permission, userId)) { 4412 tmp[i] = true; 4413 numMatch++; 4414 } else { 4415 tmp[i] = false; 4416 } 4417 } 4418 if (numMatch == 0) { 4419 return; 4420 } 4421 PackageInfo pi; 4422 if (ps.pkg != null) { 4423 pi = generatePackageInfo(ps.pkg, flags, userId); 4424 } else { 4425 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4426 } 4427 // The above might return null in cases of uninstalled apps or install-state 4428 // skew across users/profiles. 4429 if (pi != null) { 4430 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4431 if (numMatch == permissions.length) { 4432 pi.requestedPermissions = permissions; 4433 } else { 4434 pi.requestedPermissions = new String[numMatch]; 4435 numMatch = 0; 4436 for (int i=0; i<permissions.length; i++) { 4437 if (tmp[i]) { 4438 pi.requestedPermissions[numMatch] = permissions[i]; 4439 numMatch++; 4440 } 4441 } 4442 } 4443 } 4444 list.add(pi); 4445 } 4446 } 4447 4448 @Override 4449 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4450 String[] permissions, int flags, int userId) { 4451 if (!sUserManager.exists(userId)) return null; 4452 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4453 4454 // writer 4455 synchronized (mPackages) { 4456 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4457 boolean[] tmpBools = new boolean[permissions.length]; 4458 if (listUninstalled) { 4459 for (PackageSetting ps : mSettings.mPackages.values()) { 4460 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4461 } 4462 } else { 4463 for (PackageParser.Package pkg : mPackages.values()) { 4464 PackageSetting ps = (PackageSetting)pkg.mExtras; 4465 if (ps != null) { 4466 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4467 userId); 4468 } 4469 } 4470 } 4471 4472 return new ParceledListSlice<PackageInfo>(list); 4473 } 4474 } 4475 4476 @Override 4477 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4478 if (!sUserManager.exists(userId)) return null; 4479 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4480 4481 // writer 4482 synchronized (mPackages) { 4483 ArrayList<ApplicationInfo> list; 4484 if (listUninstalled) { 4485 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4486 for (PackageSetting ps : mSettings.mPackages.values()) { 4487 ApplicationInfo ai; 4488 if (ps.pkg != null) { 4489 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4490 ps.readUserState(userId), userId); 4491 } else { 4492 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4493 } 4494 if (ai != null) { 4495 list.add(ai); 4496 } 4497 } 4498 } else { 4499 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4500 for (PackageParser.Package p : mPackages.values()) { 4501 if (p.mExtras != null) { 4502 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4503 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4504 if (ai != null) { 4505 list.add(ai); 4506 } 4507 } 4508 } 4509 } 4510 4511 return new ParceledListSlice<ApplicationInfo>(list); 4512 } 4513 } 4514 4515 public List<ApplicationInfo> getPersistentApplications(int flags) { 4516 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4517 4518 // reader 4519 synchronized (mPackages) { 4520 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4521 final int userId = UserHandle.getCallingUserId(); 4522 while (i.hasNext()) { 4523 final PackageParser.Package p = i.next(); 4524 if (p.applicationInfo != null 4525 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4526 && (!mSafeMode || isSystemApp(p))) { 4527 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4528 if (ps != null) { 4529 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4530 ps.readUserState(userId), userId); 4531 if (ai != null) { 4532 finalList.add(ai); 4533 } 4534 } 4535 } 4536 } 4537 } 4538 4539 return finalList; 4540 } 4541 4542 @Override 4543 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4544 if (!sUserManager.exists(userId)) return null; 4545 // reader 4546 synchronized (mPackages) { 4547 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4548 PackageSetting ps = provider != null 4549 ? mSettings.mPackages.get(provider.owner.packageName) 4550 : null; 4551 return ps != null 4552 && mSettings.isEnabledLPr(provider.info, flags, userId) 4553 && (!mSafeMode || (provider.info.applicationInfo.flags 4554 &ApplicationInfo.FLAG_SYSTEM) != 0) 4555 ? PackageParser.generateProviderInfo(provider, flags, 4556 ps.readUserState(userId), userId) 4557 : null; 4558 } 4559 } 4560 4561 /** 4562 * @deprecated 4563 */ 4564 @Deprecated 4565 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4566 // reader 4567 synchronized (mPackages) { 4568 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4569 .entrySet().iterator(); 4570 final int userId = UserHandle.getCallingUserId(); 4571 while (i.hasNext()) { 4572 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4573 PackageParser.Provider p = entry.getValue(); 4574 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4575 4576 if (ps != null && p.syncable 4577 && (!mSafeMode || (p.info.applicationInfo.flags 4578 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4579 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4580 ps.readUserState(userId), userId); 4581 if (info != null) { 4582 outNames.add(entry.getKey()); 4583 outInfo.add(info); 4584 } 4585 } 4586 } 4587 } 4588 } 4589 4590 @Override 4591 public List<ProviderInfo> queryContentProviders(String processName, 4592 int uid, int flags) { 4593 ArrayList<ProviderInfo> finalList = null; 4594 // reader 4595 synchronized (mPackages) { 4596 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4597 final int userId = processName != null ? 4598 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4599 while (i.hasNext()) { 4600 final PackageParser.Provider p = i.next(); 4601 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4602 if (ps != null && p.info.authority != null 4603 && (processName == null 4604 || (p.info.processName.equals(processName) 4605 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4606 && mSettings.isEnabledLPr(p.info, flags, userId) 4607 && (!mSafeMode 4608 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4609 if (finalList == null) { 4610 finalList = new ArrayList<ProviderInfo>(3); 4611 } 4612 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4613 ps.readUserState(userId), userId); 4614 if (info != null) { 4615 finalList.add(info); 4616 } 4617 } 4618 } 4619 } 4620 4621 if (finalList != null) { 4622 Collections.sort(finalList, mProviderInitOrderSorter); 4623 } 4624 4625 return finalList; 4626 } 4627 4628 @Override 4629 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4630 int flags) { 4631 // reader 4632 synchronized (mPackages) { 4633 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4634 return PackageParser.generateInstrumentationInfo(i, flags); 4635 } 4636 } 4637 4638 @Override 4639 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4640 int flags) { 4641 ArrayList<InstrumentationInfo> finalList = 4642 new ArrayList<InstrumentationInfo>(); 4643 4644 // reader 4645 synchronized (mPackages) { 4646 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4647 while (i.hasNext()) { 4648 final PackageParser.Instrumentation p = i.next(); 4649 if (targetPackage == null 4650 || targetPackage.equals(p.info.targetPackage)) { 4651 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4652 flags); 4653 if (ii != null) { 4654 finalList.add(ii); 4655 } 4656 } 4657 } 4658 } 4659 4660 return finalList; 4661 } 4662 4663 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4664 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4665 if (overlays == null) { 4666 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4667 return; 4668 } 4669 for (PackageParser.Package opkg : overlays.values()) { 4670 // Not much to do if idmap fails: we already logged the error 4671 // and we certainly don't want to abort installation of pkg simply 4672 // because an overlay didn't fit properly. For these reasons, 4673 // ignore the return value of createIdmapForPackagePairLI. 4674 createIdmapForPackagePairLI(pkg, opkg); 4675 } 4676 } 4677 4678 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4679 PackageParser.Package opkg) { 4680 if (!opkg.mTrustedOverlay) { 4681 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4682 opkg.baseCodePath + ": overlay not trusted"); 4683 return false; 4684 } 4685 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4686 if (overlaySet == null) { 4687 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4688 opkg.baseCodePath + " but target package has no known overlays"); 4689 return false; 4690 } 4691 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4692 // TODO: generate idmap for split APKs 4693 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4694 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4695 + opkg.baseCodePath); 4696 return false; 4697 } 4698 PackageParser.Package[] overlayArray = 4699 overlaySet.values().toArray(new PackageParser.Package[0]); 4700 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4701 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4702 return p1.mOverlayPriority - p2.mOverlayPriority; 4703 } 4704 }; 4705 Arrays.sort(overlayArray, cmp); 4706 4707 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4708 int i = 0; 4709 for (PackageParser.Package p : overlayArray) { 4710 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4711 } 4712 return true; 4713 } 4714 4715 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4716 final File[] files = dir.listFiles(); 4717 if (ArrayUtils.isEmpty(files)) { 4718 Log.d(TAG, "No files in app dir " + dir); 4719 return; 4720 } 4721 4722 if (DEBUG_PACKAGE_SCANNING) { 4723 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4724 + " flags=0x" + Integer.toHexString(parseFlags)); 4725 } 4726 4727 for (File file : files) { 4728 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4729 && !PackageInstallerService.isStageName(file.getName()); 4730 if (!isPackage) { 4731 // Ignore entries which are not packages 4732 continue; 4733 } 4734 try { 4735 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4736 scanFlags, currentTime, null); 4737 } catch (PackageManagerException e) { 4738 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4739 4740 // Delete invalid userdata apps 4741 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4742 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4743 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4744 if (file.isDirectory()) { 4745 mInstaller.rmPackageDir(file.getAbsolutePath()); 4746 } else { 4747 file.delete(); 4748 } 4749 } 4750 } 4751 } 4752 } 4753 4754 private static File getSettingsProblemFile() { 4755 File dataDir = Environment.getDataDirectory(); 4756 File systemDir = new File(dataDir, "system"); 4757 File fname = new File(systemDir, "uiderrors.txt"); 4758 return fname; 4759 } 4760 4761 static void reportSettingsProblem(int priority, String msg) { 4762 logCriticalInfo(priority, msg); 4763 } 4764 4765 static void logCriticalInfo(int priority, String msg) { 4766 Slog.println(priority, TAG, msg); 4767 EventLogTags.writePmCriticalInfo(msg); 4768 try { 4769 File fname = getSettingsProblemFile(); 4770 FileOutputStream out = new FileOutputStream(fname, true); 4771 PrintWriter pw = new FastPrintWriter(out); 4772 SimpleDateFormat formatter = new SimpleDateFormat(); 4773 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4774 pw.println(dateString + ": " + msg); 4775 pw.close(); 4776 FileUtils.setPermissions( 4777 fname.toString(), 4778 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4779 -1, -1); 4780 } catch (java.io.IOException e) { 4781 } 4782 } 4783 4784 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4785 PackageParser.Package pkg, File srcFile, int parseFlags) 4786 throws PackageManagerException { 4787 if (ps != null 4788 && ps.codePath.equals(srcFile) 4789 && ps.timeStamp == srcFile.lastModified() 4790 && !isCompatSignatureUpdateNeeded(pkg) 4791 && !isRecoverSignatureUpdateNeeded(pkg)) { 4792 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4793 if (ps.signatures.mSignatures != null 4794 && ps.signatures.mSignatures.length != 0 4795 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4796 // Optimization: reuse the existing cached certificates 4797 // if the package appears to be unchanged. 4798 pkg.mSignatures = ps.signatures.mSignatures; 4799 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4800 synchronized (mPackages) { 4801 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4802 } 4803 return; 4804 } 4805 4806 Slog.w(TAG, "PackageSetting for " + ps.name 4807 + " is missing signatures. Collecting certs again to recover them."); 4808 } else { 4809 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4810 } 4811 4812 try { 4813 pp.collectCertificates(pkg, parseFlags); 4814 pp.collectManifestDigest(pkg); 4815 } catch (PackageParserException e) { 4816 throw PackageManagerException.from(e); 4817 } 4818 } 4819 4820 /* 4821 * Scan a package and return the newly parsed package. 4822 * Returns null in case of errors and the error code is stored in mLastScanError 4823 */ 4824 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4825 long currentTime, UserHandle user) throws PackageManagerException { 4826 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4827 parseFlags |= mDefParseFlags; 4828 PackageParser pp = new PackageParser(); 4829 pp.setSeparateProcesses(mSeparateProcesses); 4830 pp.setOnlyCoreApps(mOnlyCore); 4831 pp.setDisplayMetrics(mMetrics); 4832 4833 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4834 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4835 } 4836 4837 final PackageParser.Package pkg; 4838 try { 4839 pkg = pp.parsePackage(scanFile, parseFlags); 4840 } catch (PackageParserException e) { 4841 throw PackageManagerException.from(e); 4842 } 4843 4844 PackageSetting ps = null; 4845 PackageSetting updatedPkg; 4846 // reader 4847 synchronized (mPackages) { 4848 // Look to see if we already know about this package. 4849 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4850 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4851 // This package has been renamed to its original name. Let's 4852 // use that. 4853 ps = mSettings.peekPackageLPr(oldName); 4854 } 4855 // If there was no original package, see one for the real package name. 4856 if (ps == null) { 4857 ps = mSettings.peekPackageLPr(pkg.packageName); 4858 } 4859 // Check to see if this package could be hiding/updating a system 4860 // package. Must look for it either under the original or real 4861 // package name depending on our state. 4862 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4863 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4864 } 4865 boolean updatedPkgBetter = false; 4866 // First check if this is a system package that may involve an update 4867 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4868 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4869 // it needs to drop FLAG_PRIVILEGED. 4870 if (locationIsPrivileged(scanFile)) { 4871 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4872 } else { 4873 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4874 } 4875 4876 if (ps != null && !ps.codePath.equals(scanFile)) { 4877 // The path has changed from what was last scanned... check the 4878 // version of the new path against what we have stored to determine 4879 // what to do. 4880 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4881 if (pkg.mVersionCode <= ps.versionCode) { 4882 // The system package has been updated and the code path does not match 4883 // Ignore entry. Skip it. 4884 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4885 + " ignored: updated version " + ps.versionCode 4886 + " better than this " + pkg.mVersionCode); 4887 if (!updatedPkg.codePath.equals(scanFile)) { 4888 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4889 + ps.name + " changing from " + updatedPkg.codePathString 4890 + " to " + scanFile); 4891 updatedPkg.codePath = scanFile; 4892 updatedPkg.codePathString = scanFile.toString(); 4893 updatedPkg.resourcePath = scanFile; 4894 updatedPkg.resourcePathString = scanFile.toString(); 4895 } 4896 updatedPkg.pkg = pkg; 4897 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4898 } else { 4899 // The current app on the system partition is better than 4900 // what we have updated to on the data partition; switch 4901 // back to the system partition version. 4902 // At this point, its safely assumed that package installation for 4903 // apps in system partition will go through. If not there won't be a working 4904 // version of the app 4905 // writer 4906 synchronized (mPackages) { 4907 // Just remove the loaded entries from package lists. 4908 mPackages.remove(ps.name); 4909 } 4910 4911 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4912 + " reverting from " + ps.codePathString 4913 + ": new version " + pkg.mVersionCode 4914 + " better than installed " + ps.versionCode); 4915 4916 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4917 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4918 getAppDexInstructionSets(ps)); 4919 synchronized (mInstallLock) { 4920 args.cleanUpResourcesLI(); 4921 } 4922 synchronized (mPackages) { 4923 mSettings.enableSystemPackageLPw(ps.name); 4924 } 4925 updatedPkgBetter = true; 4926 } 4927 } 4928 } 4929 4930 if (updatedPkg != null) { 4931 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4932 // initially 4933 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4934 4935 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4936 // flag set initially 4937 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4938 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4939 } 4940 } 4941 4942 // Verify certificates against what was last scanned 4943 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4944 4945 /* 4946 * A new system app appeared, but we already had a non-system one of the 4947 * same name installed earlier. 4948 */ 4949 boolean shouldHideSystemApp = false; 4950 if (updatedPkg == null && ps != null 4951 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4952 /* 4953 * Check to make sure the signatures match first. If they don't, 4954 * wipe the installed application and its data. 4955 */ 4956 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4957 != PackageManager.SIGNATURE_MATCH) { 4958 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4959 + " signatures don't match existing userdata copy; removing"); 4960 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4961 ps = null; 4962 } else { 4963 /* 4964 * If the newly-added system app is an older version than the 4965 * already installed version, hide it. It will be scanned later 4966 * and re-added like an update. 4967 */ 4968 if (pkg.mVersionCode <= ps.versionCode) { 4969 shouldHideSystemApp = true; 4970 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4971 + " but new version " + pkg.mVersionCode + " better than installed " 4972 + ps.versionCode + "; hiding system"); 4973 } else { 4974 /* 4975 * The newly found system app is a newer version that the 4976 * one previously installed. Simply remove the 4977 * already-installed application and replace it with our own 4978 * while keeping the application data. 4979 */ 4980 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4981 + " reverting from " + ps.codePathString + ": new version " 4982 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4983 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4984 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4985 getAppDexInstructionSets(ps)); 4986 synchronized (mInstallLock) { 4987 args.cleanUpResourcesLI(); 4988 } 4989 } 4990 } 4991 } 4992 4993 // The apk is forward locked (not public) if its code and resources 4994 // are kept in different files. (except for app in either system or 4995 // vendor path). 4996 // TODO grab this value from PackageSettings 4997 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4998 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4999 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5000 } 5001 } 5002 5003 // TODO: extend to support forward-locked splits 5004 String resourcePath = null; 5005 String baseResourcePath = null; 5006 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5007 if (ps != null && ps.resourcePathString != null) { 5008 resourcePath = ps.resourcePathString; 5009 baseResourcePath = ps.resourcePathString; 5010 } else { 5011 // Should not happen at all. Just log an error. 5012 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5013 } 5014 } else { 5015 resourcePath = pkg.codePath; 5016 baseResourcePath = pkg.baseCodePath; 5017 } 5018 5019 // Set application objects path explicitly. 5020 pkg.applicationInfo.setCodePath(pkg.codePath); 5021 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5022 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5023 pkg.applicationInfo.setResourcePath(resourcePath); 5024 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5025 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5026 5027 // Note that we invoke the following method only if we are about to unpack an application 5028 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5029 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5030 5031 /* 5032 * If the system app should be overridden by a previously installed 5033 * data, hide the system app now and let the /data/app scan pick it up 5034 * again. 5035 */ 5036 if (shouldHideSystemApp) { 5037 synchronized (mPackages) { 5038 /* 5039 * We have to grant systems permissions before we hide, because 5040 * grantPermissions will assume the package update is trying to 5041 * expand its permissions. 5042 */ 5043 grantPermissionsLPw(pkg, true, pkg.packageName); 5044 mSettings.disableSystemPackageLPw(pkg.packageName); 5045 } 5046 } 5047 5048 return scannedPkg; 5049 } 5050 5051 private static String fixProcessName(String defProcessName, 5052 String processName, int uid) { 5053 if (processName == null) { 5054 return defProcessName; 5055 } 5056 return processName; 5057 } 5058 5059 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5060 throws PackageManagerException { 5061 if (pkgSetting.signatures.mSignatures != null) { 5062 // Already existing package. Make sure signatures match 5063 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5064 == PackageManager.SIGNATURE_MATCH; 5065 if (!match) { 5066 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5067 == PackageManager.SIGNATURE_MATCH; 5068 } 5069 if (!match) { 5070 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5071 == PackageManager.SIGNATURE_MATCH; 5072 } 5073 if (!match) { 5074 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5075 + pkg.packageName + " signatures do not match the " 5076 + "previously installed version; ignoring!"); 5077 } 5078 } 5079 5080 // Check for shared user signatures 5081 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5082 // Already existing package. Make sure signatures match 5083 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5084 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5085 if (!match) { 5086 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5087 == PackageManager.SIGNATURE_MATCH; 5088 } 5089 if (!match) { 5090 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5091 == PackageManager.SIGNATURE_MATCH; 5092 } 5093 if (!match) { 5094 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5095 "Package " + pkg.packageName 5096 + " has no signatures that match those in shared user " 5097 + pkgSetting.sharedUser.name + "; ignoring!"); 5098 } 5099 } 5100 } 5101 5102 /** 5103 * Enforces that only the system UID or root's UID can call a method exposed 5104 * via Binder. 5105 * 5106 * @param message used as message if SecurityException is thrown 5107 * @throws SecurityException if the caller is not system or root 5108 */ 5109 private static final void enforceSystemOrRoot(String message) { 5110 final int uid = Binder.getCallingUid(); 5111 if (uid != Process.SYSTEM_UID && uid != 0) { 5112 throw new SecurityException(message); 5113 } 5114 } 5115 5116 @Override 5117 public void performBootDexOpt() { 5118 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5119 5120 // Before everything else, see whether we need to fstrim. 5121 try { 5122 IMountService ms = PackageHelper.getMountService(); 5123 if (ms != null) { 5124 final boolean isUpgrade = isUpgrade(); 5125 boolean doTrim = isUpgrade; 5126 if (doTrim) { 5127 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5128 } else { 5129 final long interval = android.provider.Settings.Global.getLong( 5130 mContext.getContentResolver(), 5131 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5132 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5133 if (interval > 0) { 5134 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5135 if (timeSinceLast > interval) { 5136 doTrim = true; 5137 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5138 + "; running immediately"); 5139 } 5140 } 5141 } 5142 if (doTrim) { 5143 if (!isFirstBoot()) { 5144 try { 5145 ActivityManagerNative.getDefault().showBootMessage( 5146 mContext.getResources().getString( 5147 R.string.android_upgrading_fstrim), true); 5148 } catch (RemoteException e) { 5149 } 5150 } 5151 ms.runMaintenance(); 5152 } 5153 } else { 5154 Slog.e(TAG, "Mount service unavailable!"); 5155 } 5156 } catch (RemoteException e) { 5157 // Can't happen; MountService is local 5158 } 5159 5160 final ArraySet<PackageParser.Package> pkgs; 5161 synchronized (mPackages) { 5162 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5163 } 5164 5165 if (pkgs != null) { 5166 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5167 // in case the device runs out of space. 5168 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5169 // Give priority to core apps. 5170 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5171 PackageParser.Package pkg = it.next(); 5172 if (pkg.coreApp) { 5173 if (DEBUG_DEXOPT) { 5174 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5175 } 5176 sortedPkgs.add(pkg); 5177 it.remove(); 5178 } 5179 } 5180 // Give priority to system apps that listen for pre boot complete. 5181 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5182 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5183 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5184 PackageParser.Package pkg = it.next(); 5185 if (pkgNames.contains(pkg.packageName)) { 5186 if (DEBUG_DEXOPT) { 5187 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5188 } 5189 sortedPkgs.add(pkg); 5190 it.remove(); 5191 } 5192 } 5193 // Give priority to system apps. 5194 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5195 PackageParser.Package pkg = it.next(); 5196 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5197 if (DEBUG_DEXOPT) { 5198 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5199 } 5200 sortedPkgs.add(pkg); 5201 it.remove(); 5202 } 5203 } 5204 // Give priority to updated system apps. 5205 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5206 PackageParser.Package pkg = it.next(); 5207 if (pkg.isUpdatedSystemApp()) { 5208 if (DEBUG_DEXOPT) { 5209 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5210 } 5211 sortedPkgs.add(pkg); 5212 it.remove(); 5213 } 5214 } 5215 // Give priority to apps that listen for boot complete. 5216 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5217 pkgNames = getPackageNamesForIntent(intent); 5218 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5219 PackageParser.Package pkg = it.next(); 5220 if (pkgNames.contains(pkg.packageName)) { 5221 if (DEBUG_DEXOPT) { 5222 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5223 } 5224 sortedPkgs.add(pkg); 5225 it.remove(); 5226 } 5227 } 5228 // Filter out packages that aren't recently used. 5229 filterRecentlyUsedApps(pkgs); 5230 // Add all remaining apps. 5231 for (PackageParser.Package pkg : pkgs) { 5232 if (DEBUG_DEXOPT) { 5233 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5234 } 5235 sortedPkgs.add(pkg); 5236 } 5237 5238 // If we want to be lazy, filter everything that wasn't recently used. 5239 if (mLazyDexOpt) { 5240 filterRecentlyUsedApps(sortedPkgs); 5241 } 5242 5243 int i = 0; 5244 int total = sortedPkgs.size(); 5245 File dataDir = Environment.getDataDirectory(); 5246 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5247 if (lowThreshold == 0) { 5248 throw new IllegalStateException("Invalid low memory threshold"); 5249 } 5250 for (PackageParser.Package pkg : sortedPkgs) { 5251 long usableSpace = dataDir.getUsableSpace(); 5252 if (usableSpace < lowThreshold) { 5253 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5254 break; 5255 } 5256 performBootDexOpt(pkg, ++i, total); 5257 } 5258 } 5259 } 5260 5261 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5262 // Filter out packages that aren't recently used. 5263 // 5264 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5265 // should do a full dexopt. 5266 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5267 int total = pkgs.size(); 5268 int skipped = 0; 5269 long now = System.currentTimeMillis(); 5270 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5271 PackageParser.Package pkg = i.next(); 5272 long then = pkg.mLastPackageUsageTimeInMills; 5273 if (then + mDexOptLRUThresholdInMills < now) { 5274 if (DEBUG_DEXOPT) { 5275 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5276 ((then == 0) ? "never" : new Date(then))); 5277 } 5278 i.remove(); 5279 skipped++; 5280 } 5281 } 5282 if (DEBUG_DEXOPT) { 5283 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5284 } 5285 } 5286 } 5287 5288 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5289 List<ResolveInfo> ris = null; 5290 try { 5291 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5292 intent, null, 0, UserHandle.USER_OWNER); 5293 } catch (RemoteException e) { 5294 } 5295 ArraySet<String> pkgNames = new ArraySet<String>(); 5296 if (ris != null) { 5297 for (ResolveInfo ri : ris) { 5298 pkgNames.add(ri.activityInfo.packageName); 5299 } 5300 } 5301 return pkgNames; 5302 } 5303 5304 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5305 if (DEBUG_DEXOPT) { 5306 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5307 } 5308 if (!isFirstBoot()) { 5309 try { 5310 ActivityManagerNative.getDefault().showBootMessage( 5311 mContext.getResources().getString(R.string.android_upgrading_apk, 5312 curr, total), true); 5313 } catch (RemoteException e) { 5314 } 5315 } 5316 PackageParser.Package p = pkg; 5317 synchronized (mInstallLock) { 5318 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5319 false /* force dex */, false /* defer */, true /* include dependencies */); 5320 } 5321 } 5322 5323 @Override 5324 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5325 return performDexOpt(packageName, instructionSet, false); 5326 } 5327 5328 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5329 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5330 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5331 if (!dexopt && !updateUsage) { 5332 // We aren't going to dexopt or update usage, so bail early. 5333 return false; 5334 } 5335 PackageParser.Package p; 5336 final String targetInstructionSet; 5337 synchronized (mPackages) { 5338 p = mPackages.get(packageName); 5339 if (p == null) { 5340 return false; 5341 } 5342 if (updateUsage) { 5343 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5344 } 5345 mPackageUsage.write(false); 5346 if (!dexopt) { 5347 // We aren't going to dexopt, so bail early. 5348 return false; 5349 } 5350 5351 targetInstructionSet = instructionSet != null ? instructionSet : 5352 getPrimaryInstructionSet(p.applicationInfo); 5353 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5354 return false; 5355 } 5356 } 5357 5358 synchronized (mInstallLock) { 5359 final String[] instructionSets = new String[] { targetInstructionSet }; 5360 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5361 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5362 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5363 } 5364 } 5365 5366 public ArraySet<String> getPackagesThatNeedDexOpt() { 5367 ArraySet<String> pkgs = null; 5368 synchronized (mPackages) { 5369 for (PackageParser.Package p : mPackages.values()) { 5370 if (DEBUG_DEXOPT) { 5371 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5372 } 5373 if (!p.mDexOptPerformed.isEmpty()) { 5374 continue; 5375 } 5376 if (pkgs == null) { 5377 pkgs = new ArraySet<String>(); 5378 } 5379 pkgs.add(p.packageName); 5380 } 5381 } 5382 return pkgs; 5383 } 5384 5385 public void shutdown() { 5386 mPackageUsage.write(true); 5387 } 5388 5389 @Override 5390 public void forceDexOpt(String packageName) { 5391 enforceSystemOrRoot("forceDexOpt"); 5392 5393 PackageParser.Package pkg; 5394 synchronized (mPackages) { 5395 pkg = mPackages.get(packageName); 5396 if (pkg == null) { 5397 throw new IllegalArgumentException("Missing package: " + packageName); 5398 } 5399 } 5400 5401 synchronized (mInstallLock) { 5402 final String[] instructionSets = new String[] { 5403 getPrimaryInstructionSet(pkg.applicationInfo) }; 5404 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5405 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5406 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5407 throw new IllegalStateException("Failed to dexopt: " + res); 5408 } 5409 } 5410 } 5411 5412 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5413 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5414 Slog.w(TAG, "Unable to update from " + oldPkg.name 5415 + " to " + newPkg.packageName 5416 + ": old package not in system partition"); 5417 return false; 5418 } else if (mPackages.get(oldPkg.name) != null) { 5419 Slog.w(TAG, "Unable to update from " + oldPkg.name 5420 + " to " + newPkg.packageName 5421 + ": old package still exists"); 5422 return false; 5423 } 5424 return true; 5425 } 5426 5427 private File getDataPathForPackage(String packageName, int userId) { 5428 /* 5429 * Until we fully support multiple users, return the directory we 5430 * previously would have. The PackageManagerTests will need to be 5431 * revised when this is changed back.. 5432 */ 5433 if (userId == 0) { 5434 return new File(mAppDataDir, packageName); 5435 } else { 5436 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5437 + File.separator + packageName); 5438 } 5439 } 5440 5441 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5442 int[] users = sUserManager.getUserIds(); 5443 int res = mInstaller.install(packageName, uid, uid, seinfo); 5444 if (res < 0) { 5445 return res; 5446 } 5447 for (int user : users) { 5448 if (user != 0) { 5449 res = mInstaller.createUserData(packageName, 5450 UserHandle.getUid(user, uid), user, seinfo); 5451 if (res < 0) { 5452 return res; 5453 } 5454 } 5455 } 5456 return res; 5457 } 5458 5459 private int removeDataDirsLI(String packageName) { 5460 int[] users = sUserManager.getUserIds(); 5461 int res = 0; 5462 for (int user : users) { 5463 int resInner = mInstaller.remove(packageName, user); 5464 if (resInner < 0) { 5465 res = resInner; 5466 } 5467 } 5468 5469 return res; 5470 } 5471 5472 private int deleteCodeCacheDirsLI(String packageName) { 5473 int[] users = sUserManager.getUserIds(); 5474 int res = 0; 5475 for (int user : users) { 5476 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5477 if (resInner < 0) { 5478 res = resInner; 5479 } 5480 } 5481 return res; 5482 } 5483 5484 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5485 PackageParser.Package changingLib) { 5486 if (file.path != null) { 5487 usesLibraryFiles.add(file.path); 5488 return; 5489 } 5490 PackageParser.Package p = mPackages.get(file.apk); 5491 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5492 // If we are doing this while in the middle of updating a library apk, 5493 // then we need to make sure to use that new apk for determining the 5494 // dependencies here. (We haven't yet finished committing the new apk 5495 // to the package manager state.) 5496 if (p == null || p.packageName.equals(changingLib.packageName)) { 5497 p = changingLib; 5498 } 5499 } 5500 if (p != null) { 5501 usesLibraryFiles.addAll(p.getAllCodePaths()); 5502 } 5503 } 5504 5505 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5506 PackageParser.Package changingLib) throws PackageManagerException { 5507 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5508 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5509 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5510 for (int i=0; i<N; i++) { 5511 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5512 if (file == null) { 5513 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5514 "Package " + pkg.packageName + " requires unavailable shared library " 5515 + pkg.usesLibraries.get(i) + "; failing!"); 5516 } 5517 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5518 } 5519 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5520 for (int i=0; i<N; i++) { 5521 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5522 if (file == null) { 5523 Slog.w(TAG, "Package " + pkg.packageName 5524 + " desires unavailable shared library " 5525 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5526 } else { 5527 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5528 } 5529 } 5530 N = usesLibraryFiles.size(); 5531 if (N > 0) { 5532 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5533 } else { 5534 pkg.usesLibraryFiles = null; 5535 } 5536 } 5537 } 5538 5539 private static boolean hasString(List<String> list, List<String> which) { 5540 if (list == null) { 5541 return false; 5542 } 5543 for (int i=list.size()-1; i>=0; i--) { 5544 for (int j=which.size()-1; j>=0; j--) { 5545 if (which.get(j).equals(list.get(i))) { 5546 return true; 5547 } 5548 } 5549 } 5550 return false; 5551 } 5552 5553 private void updateAllSharedLibrariesLPw() { 5554 for (PackageParser.Package pkg : mPackages.values()) { 5555 try { 5556 updateSharedLibrariesLPw(pkg, null); 5557 } catch (PackageManagerException e) { 5558 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5559 } 5560 } 5561 } 5562 5563 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5564 PackageParser.Package changingPkg) { 5565 ArrayList<PackageParser.Package> res = null; 5566 for (PackageParser.Package pkg : mPackages.values()) { 5567 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5568 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5569 if (res == null) { 5570 res = new ArrayList<PackageParser.Package>(); 5571 } 5572 res.add(pkg); 5573 try { 5574 updateSharedLibrariesLPw(pkg, changingPkg); 5575 } catch (PackageManagerException e) { 5576 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5577 } 5578 } 5579 } 5580 return res; 5581 } 5582 5583 /** 5584 * Derive the value of the {@code cpuAbiOverride} based on the provided 5585 * value and an optional stored value from the package settings. 5586 */ 5587 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5588 String cpuAbiOverride = null; 5589 5590 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5591 cpuAbiOverride = null; 5592 } else if (abiOverride != null) { 5593 cpuAbiOverride = abiOverride; 5594 } else if (settings != null) { 5595 cpuAbiOverride = settings.cpuAbiOverrideString; 5596 } 5597 5598 return cpuAbiOverride; 5599 } 5600 5601 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5602 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5603 boolean success = false; 5604 try { 5605 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5606 currentTime, user); 5607 success = true; 5608 return res; 5609 } finally { 5610 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5611 removeDataDirsLI(pkg.packageName); 5612 } 5613 } 5614 } 5615 5616 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5617 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5618 final File scanFile = new File(pkg.codePath); 5619 if (pkg.applicationInfo.getCodePath() == null || 5620 pkg.applicationInfo.getResourcePath() == null) { 5621 // Bail out. The resource and code paths haven't been set. 5622 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5623 "Code and resource paths haven't been set correctly"); 5624 } 5625 5626 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5627 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5628 } else { 5629 // Only allow system apps to be flagged as core apps. 5630 pkg.coreApp = false; 5631 } 5632 5633 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5634 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5635 } 5636 5637 if (mCustomResolverComponentName != null && 5638 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5639 setUpCustomResolverActivity(pkg); 5640 } 5641 5642 if (pkg.packageName.equals("android")) { 5643 synchronized (mPackages) { 5644 if (mAndroidApplication != null) { 5645 Slog.w(TAG, "*************************************************"); 5646 Slog.w(TAG, "Core android package being redefined. Skipping."); 5647 Slog.w(TAG, " file=" + scanFile); 5648 Slog.w(TAG, "*************************************************"); 5649 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5650 "Core android package being redefined. Skipping."); 5651 } 5652 5653 // Set up information for our fall-back user intent resolution activity. 5654 mPlatformPackage = pkg; 5655 pkg.mVersionCode = mSdkVersion; 5656 mAndroidApplication = pkg.applicationInfo; 5657 5658 if (!mResolverReplaced) { 5659 mResolveActivity.applicationInfo = mAndroidApplication; 5660 mResolveActivity.name = ResolverActivity.class.getName(); 5661 mResolveActivity.packageName = mAndroidApplication.packageName; 5662 mResolveActivity.processName = "system:ui"; 5663 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5664 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5665 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5666 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5667 mResolveActivity.exported = true; 5668 mResolveActivity.enabled = true; 5669 mResolveInfo.activityInfo = mResolveActivity; 5670 mResolveInfo.priority = 0; 5671 mResolveInfo.preferredOrder = 0; 5672 mResolveInfo.match = 0; 5673 mResolveComponentName = new ComponentName( 5674 mAndroidApplication.packageName, mResolveActivity.name); 5675 } 5676 } 5677 } 5678 5679 if (DEBUG_PACKAGE_SCANNING) { 5680 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5681 Log.d(TAG, "Scanning package " + pkg.packageName); 5682 } 5683 5684 if (mPackages.containsKey(pkg.packageName) 5685 || mSharedLibraries.containsKey(pkg.packageName)) { 5686 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5687 "Application package " + pkg.packageName 5688 + " already installed. Skipping duplicate."); 5689 } 5690 5691 // If we're only installing presumed-existing packages, require that the 5692 // scanned APK is both already known and at the path previously established 5693 // for it. Previously unknown packages we pick up normally, but if we have an 5694 // a priori expectation about this package's install presence, enforce it. 5695 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5696 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5697 if (known != null) { 5698 if (DEBUG_PACKAGE_SCANNING) { 5699 Log.d(TAG, "Examining " + pkg.codePath 5700 + " and requiring known paths " + known.codePathString 5701 + " & " + known.resourcePathString); 5702 } 5703 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5704 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5705 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5706 "Application package " + pkg.packageName 5707 + " found at " + pkg.applicationInfo.getCodePath() 5708 + " but expected at " + known.codePathString + "; ignoring."); 5709 } 5710 } 5711 } 5712 5713 // Initialize package source and resource directories 5714 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5715 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5716 5717 SharedUserSetting suid = null; 5718 PackageSetting pkgSetting = null; 5719 5720 if (!isSystemApp(pkg)) { 5721 // Only system apps can use these features. 5722 pkg.mOriginalPackages = null; 5723 pkg.mRealPackage = null; 5724 pkg.mAdoptPermissions = null; 5725 } 5726 5727 // writer 5728 synchronized (mPackages) { 5729 if (pkg.mSharedUserId != null) { 5730 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5731 if (suid == null) { 5732 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5733 "Creating application package " + pkg.packageName 5734 + " for shared user failed"); 5735 } 5736 if (DEBUG_PACKAGE_SCANNING) { 5737 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5738 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5739 + "): packages=" + suid.packages); 5740 } 5741 } 5742 5743 // Check if we are renaming from an original package name. 5744 PackageSetting origPackage = null; 5745 String realName = null; 5746 if (pkg.mOriginalPackages != null) { 5747 // This package may need to be renamed to a previously 5748 // installed name. Let's check on that... 5749 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5750 if (pkg.mOriginalPackages.contains(renamed)) { 5751 // This package had originally been installed as the 5752 // original name, and we have already taken care of 5753 // transitioning to the new one. Just update the new 5754 // one to continue using the old name. 5755 realName = pkg.mRealPackage; 5756 if (!pkg.packageName.equals(renamed)) { 5757 // Callers into this function may have already taken 5758 // care of renaming the package; only do it here if 5759 // it is not already done. 5760 pkg.setPackageName(renamed); 5761 } 5762 5763 } else { 5764 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5765 if ((origPackage = mSettings.peekPackageLPr( 5766 pkg.mOriginalPackages.get(i))) != null) { 5767 // We do have the package already installed under its 5768 // original name... should we use it? 5769 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5770 // New package is not compatible with original. 5771 origPackage = null; 5772 continue; 5773 } else if (origPackage.sharedUser != null) { 5774 // Make sure uid is compatible between packages. 5775 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5776 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5777 + " to " + pkg.packageName + ": old uid " 5778 + origPackage.sharedUser.name 5779 + " differs from " + pkg.mSharedUserId); 5780 origPackage = null; 5781 continue; 5782 } 5783 } else { 5784 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5785 + pkg.packageName + " to old name " + origPackage.name); 5786 } 5787 break; 5788 } 5789 } 5790 } 5791 } 5792 5793 if (mTransferedPackages.contains(pkg.packageName)) { 5794 Slog.w(TAG, "Package " + pkg.packageName 5795 + " was transferred to another, but its .apk remains"); 5796 } 5797 5798 // Just create the setting, don't add it yet. For already existing packages 5799 // the PkgSetting exists already and doesn't have to be created. 5800 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5801 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5802 pkg.applicationInfo.primaryCpuAbi, 5803 pkg.applicationInfo.secondaryCpuAbi, 5804 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5805 user, false); 5806 if (pkgSetting == null) { 5807 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5808 "Creating application package " + pkg.packageName + " failed"); 5809 } 5810 5811 if (pkgSetting.origPackage != null) { 5812 // If we are first transitioning from an original package, 5813 // fix up the new package's name now. We need to do this after 5814 // looking up the package under its new name, so getPackageLP 5815 // can take care of fiddling things correctly. 5816 pkg.setPackageName(origPackage.name); 5817 5818 // File a report about this. 5819 String msg = "New package " + pkgSetting.realName 5820 + " renamed to replace old package " + pkgSetting.name; 5821 reportSettingsProblem(Log.WARN, msg); 5822 5823 // Make a note of it. 5824 mTransferedPackages.add(origPackage.name); 5825 5826 // No longer need to retain this. 5827 pkgSetting.origPackage = null; 5828 } 5829 5830 if (realName != null) { 5831 // Make a note of it. 5832 mTransferedPackages.add(pkg.packageName); 5833 } 5834 5835 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5836 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5837 } 5838 5839 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5840 // Check all shared libraries and map to their actual file path. 5841 // We only do this here for apps not on a system dir, because those 5842 // are the only ones that can fail an install due to this. We 5843 // will take care of the system apps by updating all of their 5844 // library paths after the scan is done. 5845 updateSharedLibrariesLPw(pkg, null); 5846 } 5847 5848 if (mFoundPolicyFile) { 5849 SELinuxMMAC.assignSeinfoValue(pkg); 5850 } 5851 5852 pkg.applicationInfo.uid = pkgSetting.appId; 5853 pkg.mExtras = pkgSetting; 5854 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5855 try { 5856 verifySignaturesLP(pkgSetting, pkg); 5857 // We just determined the app is signed correctly, so bring 5858 // over the latest parsed certs. 5859 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5860 } catch (PackageManagerException e) { 5861 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5862 throw e; 5863 } 5864 // The signature has changed, but this package is in the system 5865 // image... let's recover! 5866 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5867 // However... if this package is part of a shared user, but it 5868 // doesn't match the signature of the shared user, let's fail. 5869 // What this means is that you can't change the signatures 5870 // associated with an overall shared user, which doesn't seem all 5871 // that unreasonable. 5872 if (pkgSetting.sharedUser != null) { 5873 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5874 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5875 throw new PackageManagerException( 5876 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5877 "Signature mismatch for shared user : " 5878 + pkgSetting.sharedUser); 5879 } 5880 } 5881 // File a report about this. 5882 String msg = "System package " + pkg.packageName 5883 + " signature changed; retaining data."; 5884 reportSettingsProblem(Log.WARN, msg); 5885 } 5886 } else { 5887 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5888 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5889 + pkg.packageName + " upgrade keys do not match the " 5890 + "previously installed version"); 5891 } else { 5892 // We just determined the app is signed correctly, so bring 5893 // over the latest parsed certs. 5894 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5895 } 5896 } 5897 // Verify that this new package doesn't have any content providers 5898 // that conflict with existing packages. Only do this if the 5899 // package isn't already installed, since we don't want to break 5900 // things that are installed. 5901 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5902 final int N = pkg.providers.size(); 5903 int i; 5904 for (i=0; i<N; i++) { 5905 PackageParser.Provider p = pkg.providers.get(i); 5906 if (p.info.authority != null) { 5907 String names[] = p.info.authority.split(";"); 5908 for (int j = 0; j < names.length; j++) { 5909 if (mProvidersByAuthority.containsKey(names[j])) { 5910 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5911 final String otherPackageName = 5912 ((other != null && other.getComponentName() != null) ? 5913 other.getComponentName().getPackageName() : "?"); 5914 throw new PackageManagerException( 5915 INSTALL_FAILED_CONFLICTING_PROVIDER, 5916 "Can't install because provider name " + names[j] 5917 + " (in package " + pkg.applicationInfo.packageName 5918 + ") is already used by " + otherPackageName); 5919 } 5920 } 5921 } 5922 } 5923 } 5924 5925 if (pkg.mAdoptPermissions != null) { 5926 // This package wants to adopt ownership of permissions from 5927 // another package. 5928 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5929 final String origName = pkg.mAdoptPermissions.get(i); 5930 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5931 if (orig != null) { 5932 if (verifyPackageUpdateLPr(orig, pkg)) { 5933 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5934 + pkg.packageName); 5935 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5936 } 5937 } 5938 } 5939 } 5940 } 5941 5942 final String pkgName = pkg.packageName; 5943 5944 final long scanFileTime = scanFile.lastModified(); 5945 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5946 pkg.applicationInfo.processName = fixProcessName( 5947 pkg.applicationInfo.packageName, 5948 pkg.applicationInfo.processName, 5949 pkg.applicationInfo.uid); 5950 5951 File dataPath; 5952 if (mPlatformPackage == pkg) { 5953 // The system package is special. 5954 dataPath = new File(Environment.getDataDirectory(), "system"); 5955 5956 pkg.applicationInfo.dataDir = dataPath.getPath(); 5957 5958 } else { 5959 // This is a normal package, need to make its data directory. 5960 dataPath = getDataPathForPackage(pkg.packageName, 0); 5961 5962 boolean uidError = false; 5963 if (dataPath.exists()) { 5964 int currentUid = 0; 5965 try { 5966 StructStat stat = Os.stat(dataPath.getPath()); 5967 currentUid = stat.st_uid; 5968 } catch (ErrnoException e) { 5969 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5970 } 5971 5972 // If we have mismatched owners for the data path, we have a problem. 5973 if (currentUid != pkg.applicationInfo.uid) { 5974 boolean recovered = false; 5975 if (currentUid == 0) { 5976 // The directory somehow became owned by root. Wow. 5977 // This is probably because the system was stopped while 5978 // installd was in the middle of messing with its libs 5979 // directory. Ask installd to fix that. 5980 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5981 pkg.applicationInfo.uid); 5982 if (ret >= 0) { 5983 recovered = true; 5984 String msg = "Package " + pkg.packageName 5985 + " unexpectedly changed to uid 0; recovered to " + 5986 + pkg.applicationInfo.uid; 5987 reportSettingsProblem(Log.WARN, msg); 5988 } 5989 } 5990 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5991 || (scanFlags&SCAN_BOOTING) != 0)) { 5992 // If this is a system app, we can at least delete its 5993 // current data so the application will still work. 5994 int ret = removeDataDirsLI(pkgName); 5995 if (ret >= 0) { 5996 // TODO: Kill the processes first 5997 // Old data gone! 5998 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5999 ? "System package " : "Third party package "; 6000 String msg = prefix + pkg.packageName 6001 + " has changed from uid: " 6002 + currentUid + " to " 6003 + pkg.applicationInfo.uid + "; old data erased"; 6004 reportSettingsProblem(Log.WARN, msg); 6005 recovered = true; 6006 6007 // And now re-install the app. 6008 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6009 pkg.applicationInfo.seinfo); 6010 if (ret == -1) { 6011 // Ack should not happen! 6012 msg = prefix + pkg.packageName 6013 + " could not have data directory re-created after delete."; 6014 reportSettingsProblem(Log.WARN, msg); 6015 throw new PackageManagerException( 6016 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6017 } 6018 } 6019 if (!recovered) { 6020 mHasSystemUidErrors = true; 6021 } 6022 } else if (!recovered) { 6023 // If we allow this install to proceed, we will be broken. 6024 // Abort, abort! 6025 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6026 "scanPackageLI"); 6027 } 6028 if (!recovered) { 6029 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6030 + pkg.applicationInfo.uid + "/fs_" 6031 + currentUid; 6032 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6033 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6034 String msg = "Package " + pkg.packageName 6035 + " has mismatched uid: " 6036 + currentUid + " on disk, " 6037 + pkg.applicationInfo.uid + " in settings"; 6038 // writer 6039 synchronized (mPackages) { 6040 mSettings.mReadMessages.append(msg); 6041 mSettings.mReadMessages.append('\n'); 6042 uidError = true; 6043 if (!pkgSetting.uidError) { 6044 reportSettingsProblem(Log.ERROR, msg); 6045 } 6046 } 6047 } 6048 } 6049 pkg.applicationInfo.dataDir = dataPath.getPath(); 6050 if (mShouldRestoreconData) { 6051 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6052 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6053 pkg.applicationInfo.uid); 6054 } 6055 } else { 6056 if (DEBUG_PACKAGE_SCANNING) { 6057 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6058 Log.v(TAG, "Want this data dir: " + dataPath); 6059 } 6060 //invoke installer to do the actual installation 6061 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6062 pkg.applicationInfo.seinfo); 6063 if (ret < 0) { 6064 // Error from installer 6065 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6066 "Unable to create data dirs [errorCode=" + ret + "]"); 6067 } 6068 6069 if (dataPath.exists()) { 6070 pkg.applicationInfo.dataDir = dataPath.getPath(); 6071 } else { 6072 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6073 pkg.applicationInfo.dataDir = null; 6074 } 6075 } 6076 6077 pkgSetting.uidError = uidError; 6078 } 6079 6080 final String path = scanFile.getPath(); 6081 final String codePath = pkg.applicationInfo.getCodePath(); 6082 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6083 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6084 setBundledAppAbisAndRoots(pkg, pkgSetting); 6085 6086 // If we haven't found any native libraries for the app, check if it has 6087 // renderscript code. We'll need to force the app to 32 bit if it has 6088 // renderscript bitcode. 6089 if (pkg.applicationInfo.primaryCpuAbi == null 6090 && pkg.applicationInfo.secondaryCpuAbi == null 6091 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6092 NativeLibraryHelper.Handle handle = null; 6093 try { 6094 handle = NativeLibraryHelper.Handle.create(scanFile); 6095 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6096 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6097 } 6098 } catch (IOException ioe) { 6099 Slog.w(TAG, "Error scanning system app : " + ioe); 6100 } finally { 6101 IoUtils.closeQuietly(handle); 6102 } 6103 } 6104 6105 setNativeLibraryPaths(pkg); 6106 } else { 6107 // TODO: We can probably be smarter about this stuff. For installed apps, 6108 // we can calculate this information at install time once and for all. For 6109 // system apps, we can probably assume that this information doesn't change 6110 // after the first boot scan. As things stand, we do lots of unnecessary work. 6111 6112 // Give ourselves some initial paths; we'll come back for another 6113 // pass once we've determined ABI below. 6114 setNativeLibraryPaths(pkg); 6115 6116 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6117 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6118 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6119 6120 NativeLibraryHelper.Handle handle = null; 6121 try { 6122 handle = NativeLibraryHelper.Handle.create(scanFile); 6123 // TODO(multiArch): This can be null for apps that didn't go through the 6124 // usual installation process. We can calculate it again, like we 6125 // do during install time. 6126 // 6127 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6128 // unnecessary. 6129 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6130 6131 // Null out the abis so that they can be recalculated. 6132 pkg.applicationInfo.primaryCpuAbi = null; 6133 pkg.applicationInfo.secondaryCpuAbi = null; 6134 if (isMultiArch(pkg.applicationInfo)) { 6135 // Warn if we've set an abiOverride for multi-lib packages.. 6136 // By definition, we need to copy both 32 and 64 bit libraries for 6137 // such packages. 6138 if (pkg.cpuAbiOverride != null 6139 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6140 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6141 } 6142 6143 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6144 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6145 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6146 if (isAsec) { 6147 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6148 } else { 6149 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6150 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6151 useIsaSpecificSubdirs); 6152 } 6153 } 6154 6155 maybeThrowExceptionForMultiArchCopy( 6156 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6157 6158 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6159 if (isAsec) { 6160 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6161 } else { 6162 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6163 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6164 useIsaSpecificSubdirs); 6165 } 6166 } 6167 6168 maybeThrowExceptionForMultiArchCopy( 6169 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6170 6171 if (abi64 >= 0) { 6172 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6173 } 6174 6175 if (abi32 >= 0) { 6176 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6177 if (abi64 >= 0) { 6178 pkg.applicationInfo.secondaryCpuAbi = abi; 6179 } else { 6180 pkg.applicationInfo.primaryCpuAbi = abi; 6181 } 6182 } 6183 } else { 6184 String[] abiList = (cpuAbiOverride != null) ? 6185 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6186 6187 // Enable gross and lame hacks for apps that are built with old 6188 // SDK tools. We must scan their APKs for renderscript bitcode and 6189 // not launch them if it's present. Don't bother checking on devices 6190 // that don't have 64 bit support. 6191 boolean needsRenderScriptOverride = false; 6192 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6193 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6194 abiList = Build.SUPPORTED_32_BIT_ABIS; 6195 needsRenderScriptOverride = true; 6196 } 6197 6198 final int copyRet; 6199 if (isAsec) { 6200 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6201 } else { 6202 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6203 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6204 } 6205 6206 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6207 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6208 "Error unpackaging native libs for app, errorCode=" + copyRet); 6209 } 6210 6211 if (copyRet >= 0) { 6212 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6213 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6214 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6215 } else if (needsRenderScriptOverride) { 6216 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6217 } 6218 } 6219 } catch (IOException ioe) { 6220 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6221 } finally { 6222 IoUtils.closeQuietly(handle); 6223 } 6224 6225 // Now that we've calculated the ABIs and determined if it's an internal app, 6226 // we will go ahead and populate the nativeLibraryPath. 6227 setNativeLibraryPaths(pkg); 6228 6229 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6230 final int[] userIds = sUserManager.getUserIds(); 6231 synchronized (mInstallLock) { 6232 // Create a native library symlink only if we have native libraries 6233 // and if the native libraries are 32 bit libraries. We do not provide 6234 // this symlink for 64 bit libraries. 6235 if (pkg.applicationInfo.primaryCpuAbi != null && 6236 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6237 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6238 for (int userId : userIds) { 6239 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6240 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6241 "Failed linking native library dir (user=" + userId + ")"); 6242 } 6243 } 6244 } 6245 } 6246 } 6247 6248 // This is a special case for the "system" package, where the ABI is 6249 // dictated by the zygote configuration (and init.rc). We should keep track 6250 // of this ABI so that we can deal with "normal" applications that run under 6251 // the same UID correctly. 6252 if (mPlatformPackage == pkg) { 6253 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6254 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6255 } 6256 6257 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6258 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6259 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6260 // Copy the derived override back to the parsed package, so that we can 6261 // update the package settings accordingly. 6262 pkg.cpuAbiOverride = cpuAbiOverride; 6263 6264 if (DEBUG_ABI_SELECTION) { 6265 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6266 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6267 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6268 } 6269 6270 // Push the derived path down into PackageSettings so we know what to 6271 // clean up at uninstall time. 6272 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6273 6274 if (DEBUG_ABI_SELECTION) { 6275 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6276 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6277 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6278 } 6279 6280 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6281 // We don't do this here during boot because we can do it all 6282 // at once after scanning all existing packages. 6283 // 6284 // We also do this *before* we perform dexopt on this package, so that 6285 // we can avoid redundant dexopts, and also to make sure we've got the 6286 // code and package path correct. 6287 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6288 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6289 } 6290 6291 if ((scanFlags & SCAN_NO_DEX) == 0) { 6292 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6293 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6294 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6295 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6296 } 6297 } 6298 if (mFactoryTest && pkg.requestedPermissions.contains( 6299 android.Manifest.permission.FACTORY_TEST)) { 6300 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6301 } 6302 6303 ArrayList<PackageParser.Package> clientLibPkgs = null; 6304 6305 // writer 6306 synchronized (mPackages) { 6307 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6308 // Only system apps can add new shared libraries. 6309 if (pkg.libraryNames != null) { 6310 for (int i=0; i<pkg.libraryNames.size(); i++) { 6311 String name = pkg.libraryNames.get(i); 6312 boolean allowed = false; 6313 if (pkg.isUpdatedSystemApp()) { 6314 // New library entries can only be added through the 6315 // system image. This is important to get rid of a lot 6316 // of nasty edge cases: for example if we allowed a non- 6317 // system update of the app to add a library, then uninstalling 6318 // the update would make the library go away, and assumptions 6319 // we made such as through app install filtering would now 6320 // have allowed apps on the device which aren't compatible 6321 // with it. Better to just have the restriction here, be 6322 // conservative, and create many fewer cases that can negatively 6323 // impact the user experience. 6324 final PackageSetting sysPs = mSettings 6325 .getDisabledSystemPkgLPr(pkg.packageName); 6326 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6327 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6328 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6329 allowed = true; 6330 allowed = true; 6331 break; 6332 } 6333 } 6334 } 6335 } else { 6336 allowed = true; 6337 } 6338 if (allowed) { 6339 if (!mSharedLibraries.containsKey(name)) { 6340 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6341 } else if (!name.equals(pkg.packageName)) { 6342 Slog.w(TAG, "Package " + pkg.packageName + " library " 6343 + name + " already exists; skipping"); 6344 } 6345 } else { 6346 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6347 + name + " that is not declared on system image; skipping"); 6348 } 6349 } 6350 if ((scanFlags&SCAN_BOOTING) == 0) { 6351 // If we are not booting, we need to update any applications 6352 // that are clients of our shared library. If we are booting, 6353 // this will all be done once the scan is complete. 6354 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6355 } 6356 } 6357 } 6358 } 6359 6360 // We also need to dexopt any apps that are dependent on this library. Note that 6361 // if these fail, we should abort the install since installing the library will 6362 // result in some apps being broken. 6363 if (clientLibPkgs != null) { 6364 if ((scanFlags & SCAN_NO_DEX) == 0) { 6365 for (int i = 0; i < clientLibPkgs.size(); i++) { 6366 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6367 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6368 null /* instruction sets */, forceDex, 6369 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6370 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6371 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6372 "scanPackageLI failed to dexopt clientLibPkgs"); 6373 } 6374 } 6375 } 6376 } 6377 6378 // Request the ActivityManager to kill the process(only for existing packages) 6379 // so that we do not end up in a confused state while the user is still using the older 6380 // version of the application while the new one gets installed. 6381 if ((scanFlags & SCAN_REPLACING) != 0) { 6382 killApplication(pkg.applicationInfo.packageName, 6383 pkg.applicationInfo.uid, "update pkg"); 6384 } 6385 6386 // Also need to kill any apps that are dependent on the library. 6387 if (clientLibPkgs != null) { 6388 for (int i=0; i<clientLibPkgs.size(); i++) { 6389 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6390 killApplication(clientPkg.applicationInfo.packageName, 6391 clientPkg.applicationInfo.uid, "update lib"); 6392 } 6393 } 6394 6395 // writer 6396 synchronized (mPackages) { 6397 // We don't expect installation to fail beyond this point 6398 6399 // Add the new setting to mSettings 6400 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6401 // Add the new setting to mPackages 6402 mPackages.put(pkg.applicationInfo.packageName, pkg); 6403 // Make sure we don't accidentally delete its data. 6404 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6405 while (iter.hasNext()) { 6406 PackageCleanItem item = iter.next(); 6407 if (pkgName.equals(item.packageName)) { 6408 iter.remove(); 6409 } 6410 } 6411 6412 // Take care of first install / last update times. 6413 if (currentTime != 0) { 6414 if (pkgSetting.firstInstallTime == 0) { 6415 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6416 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6417 pkgSetting.lastUpdateTime = currentTime; 6418 } 6419 } else if (pkgSetting.firstInstallTime == 0) { 6420 // We need *something*. Take time time stamp of the file. 6421 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6422 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6423 if (scanFileTime != pkgSetting.timeStamp) { 6424 // A package on the system image has changed; consider this 6425 // to be an update. 6426 pkgSetting.lastUpdateTime = scanFileTime; 6427 } 6428 } 6429 6430 // Add the package's KeySets to the global KeySetManagerService 6431 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6432 try { 6433 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6434 if (pkg.mKeySetMapping != null) { 6435 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6436 if (pkg.mUpgradeKeySets != null) { 6437 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6438 } 6439 } 6440 } catch (NullPointerException e) { 6441 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6442 } catch (IllegalArgumentException e) { 6443 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6444 } 6445 6446 int N = pkg.providers.size(); 6447 StringBuilder r = null; 6448 int i; 6449 for (i=0; i<N; i++) { 6450 PackageParser.Provider p = pkg.providers.get(i); 6451 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6452 p.info.processName, pkg.applicationInfo.uid); 6453 mProviders.addProvider(p); 6454 p.syncable = p.info.isSyncable; 6455 if (p.info.authority != null) { 6456 String names[] = p.info.authority.split(";"); 6457 p.info.authority = null; 6458 for (int j = 0; j < names.length; j++) { 6459 if (j == 1 && p.syncable) { 6460 // We only want the first authority for a provider to possibly be 6461 // syncable, so if we already added this provider using a different 6462 // authority clear the syncable flag. We copy the provider before 6463 // changing it because the mProviders object contains a reference 6464 // to a provider that we don't want to change. 6465 // Only do this for the second authority since the resulting provider 6466 // object can be the same for all future authorities for this provider. 6467 p = new PackageParser.Provider(p); 6468 p.syncable = false; 6469 } 6470 if (!mProvidersByAuthority.containsKey(names[j])) { 6471 mProvidersByAuthority.put(names[j], p); 6472 if (p.info.authority == null) { 6473 p.info.authority = names[j]; 6474 } else { 6475 p.info.authority = p.info.authority + ";" + names[j]; 6476 } 6477 if (DEBUG_PACKAGE_SCANNING) { 6478 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6479 Log.d(TAG, "Registered content provider: " + names[j] 6480 + ", className = " + p.info.name + ", isSyncable = " 6481 + p.info.isSyncable); 6482 } 6483 } else { 6484 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6485 Slog.w(TAG, "Skipping provider name " + names[j] + 6486 " (in package " + pkg.applicationInfo.packageName + 6487 "): name already used by " 6488 + ((other != null && other.getComponentName() != null) 6489 ? other.getComponentName().getPackageName() : "?")); 6490 } 6491 } 6492 } 6493 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6494 if (r == null) { 6495 r = new StringBuilder(256); 6496 } else { 6497 r.append(' '); 6498 } 6499 r.append(p.info.name); 6500 } 6501 } 6502 if (r != null) { 6503 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6504 } 6505 6506 N = pkg.services.size(); 6507 r = null; 6508 for (i=0; i<N; i++) { 6509 PackageParser.Service s = pkg.services.get(i); 6510 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6511 s.info.processName, pkg.applicationInfo.uid); 6512 mServices.addService(s); 6513 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6514 if (r == null) { 6515 r = new StringBuilder(256); 6516 } else { 6517 r.append(' '); 6518 } 6519 r.append(s.info.name); 6520 } 6521 } 6522 if (r != null) { 6523 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6524 } 6525 6526 N = pkg.receivers.size(); 6527 r = null; 6528 for (i=0; i<N; i++) { 6529 PackageParser.Activity a = pkg.receivers.get(i); 6530 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6531 a.info.processName, pkg.applicationInfo.uid); 6532 mReceivers.addActivity(a, "receiver"); 6533 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6534 if (r == null) { 6535 r = new StringBuilder(256); 6536 } else { 6537 r.append(' '); 6538 } 6539 r.append(a.info.name); 6540 } 6541 } 6542 if (r != null) { 6543 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6544 } 6545 6546 N = pkg.activities.size(); 6547 r = null; 6548 for (i=0; i<N; i++) { 6549 PackageParser.Activity a = pkg.activities.get(i); 6550 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6551 a.info.processName, pkg.applicationInfo.uid); 6552 mActivities.addActivity(a, "activity"); 6553 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6554 if (r == null) { 6555 r = new StringBuilder(256); 6556 } else { 6557 r.append(' '); 6558 } 6559 r.append(a.info.name); 6560 } 6561 } 6562 if (r != null) { 6563 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6564 } 6565 6566 N = pkg.permissionGroups.size(); 6567 r = null; 6568 for (i=0; i<N; i++) { 6569 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6570 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6571 if (cur == null) { 6572 mPermissionGroups.put(pg.info.name, pg); 6573 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6574 if (r == null) { 6575 r = new StringBuilder(256); 6576 } else { 6577 r.append(' '); 6578 } 6579 r.append(pg.info.name); 6580 } 6581 } else { 6582 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6583 + pg.info.packageName + " ignored: original from " 6584 + cur.info.packageName); 6585 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6586 if (r == null) { 6587 r = new StringBuilder(256); 6588 } else { 6589 r.append(' '); 6590 } 6591 r.append("DUP:"); 6592 r.append(pg.info.name); 6593 } 6594 } 6595 } 6596 if (r != null) { 6597 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6598 } 6599 6600 N = pkg.permissions.size(); 6601 r = null; 6602 for (i=0; i<N; i++) { 6603 PackageParser.Permission p = pkg.permissions.get(i); 6604 ArrayMap<String, BasePermission> permissionMap = 6605 p.tree ? mSettings.mPermissionTrees 6606 : mSettings.mPermissions; 6607 p.group = mPermissionGroups.get(p.info.group); 6608 if (p.info.group == null || p.group != null) { 6609 BasePermission bp = permissionMap.get(p.info.name); 6610 6611 // Allow system apps to redefine non-system permissions 6612 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6613 final boolean currentOwnerIsSystem = (bp.perm != null 6614 && isSystemApp(bp.perm.owner)); 6615 if (isSystemApp(p.owner)) { 6616 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6617 // It's a built-in permission and no owner, take ownership now 6618 bp.packageSetting = pkgSetting; 6619 bp.perm = p; 6620 bp.uid = pkg.applicationInfo.uid; 6621 bp.sourcePackage = p.info.packageName; 6622 } else if (!currentOwnerIsSystem) { 6623 String msg = "New decl " + p.owner + " of permission " 6624 + p.info.name + " is system; overriding " + bp.sourcePackage; 6625 reportSettingsProblem(Log.WARN, msg); 6626 bp = null; 6627 } 6628 } 6629 } 6630 6631 if (bp == null) { 6632 bp = new BasePermission(p.info.name, p.info.packageName, 6633 BasePermission.TYPE_NORMAL); 6634 permissionMap.put(p.info.name, bp); 6635 } 6636 6637 if (bp.perm == null) { 6638 if (bp.sourcePackage == null 6639 || bp.sourcePackage.equals(p.info.packageName)) { 6640 BasePermission tree = findPermissionTreeLP(p.info.name); 6641 if (tree == null 6642 || tree.sourcePackage.equals(p.info.packageName)) { 6643 bp.packageSetting = pkgSetting; 6644 bp.perm = p; 6645 bp.uid = pkg.applicationInfo.uid; 6646 bp.sourcePackage = p.info.packageName; 6647 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6648 if (r == null) { 6649 r = new StringBuilder(256); 6650 } else { 6651 r.append(' '); 6652 } 6653 r.append(p.info.name); 6654 } 6655 } else { 6656 Slog.w(TAG, "Permission " + p.info.name + " from package " 6657 + p.info.packageName + " ignored: base tree " 6658 + tree.name + " is from package " 6659 + tree.sourcePackage); 6660 } 6661 } else { 6662 Slog.w(TAG, "Permission " + p.info.name + " from package " 6663 + p.info.packageName + " ignored: original from " 6664 + bp.sourcePackage); 6665 } 6666 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6667 if (r == null) { 6668 r = new StringBuilder(256); 6669 } else { 6670 r.append(' '); 6671 } 6672 r.append("DUP:"); 6673 r.append(p.info.name); 6674 } 6675 if (bp.perm == p) { 6676 bp.protectionLevel = p.info.protectionLevel; 6677 } 6678 } else { 6679 Slog.w(TAG, "Permission " + p.info.name + " from package " 6680 + p.info.packageName + " ignored: no group " 6681 + p.group); 6682 } 6683 } 6684 if (r != null) { 6685 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6686 } 6687 6688 N = pkg.instrumentation.size(); 6689 r = null; 6690 for (i=0; i<N; i++) { 6691 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6692 a.info.packageName = pkg.applicationInfo.packageName; 6693 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6694 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6695 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6696 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6697 a.info.dataDir = pkg.applicationInfo.dataDir; 6698 6699 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6700 // need other information about the application, like the ABI and what not ? 6701 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6702 mInstrumentation.put(a.getComponentName(), a); 6703 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6704 if (r == null) { 6705 r = new StringBuilder(256); 6706 } else { 6707 r.append(' '); 6708 } 6709 r.append(a.info.name); 6710 } 6711 } 6712 if (r != null) { 6713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6714 } 6715 6716 if (pkg.protectedBroadcasts != null) { 6717 N = pkg.protectedBroadcasts.size(); 6718 for (i=0; i<N; i++) { 6719 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6720 } 6721 } 6722 6723 pkgSetting.setTimeStamp(scanFileTime); 6724 6725 // Create idmap files for pairs of (packages, overlay packages). 6726 // Note: "android", ie framework-res.apk, is handled by native layers. 6727 if (pkg.mOverlayTarget != null) { 6728 // This is an overlay package. 6729 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6730 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6731 mOverlays.put(pkg.mOverlayTarget, 6732 new ArrayMap<String, PackageParser.Package>()); 6733 } 6734 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6735 map.put(pkg.packageName, pkg); 6736 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6737 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6738 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6739 "scanPackageLI failed to createIdmap"); 6740 } 6741 } 6742 } else if (mOverlays.containsKey(pkg.packageName) && 6743 !pkg.packageName.equals("android")) { 6744 // This is a regular package, with one or more known overlay packages. 6745 createIdmapsForPackageLI(pkg); 6746 } 6747 } 6748 6749 return pkg; 6750 } 6751 6752 /** 6753 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6754 * i.e, so that all packages can be run inside a single process if required. 6755 * 6756 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6757 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6758 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6759 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6760 * updating a package that belongs to a shared user. 6761 * 6762 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6763 * adds unnecessary complexity. 6764 */ 6765 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6766 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6767 String requiredInstructionSet = null; 6768 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6769 requiredInstructionSet = VMRuntime.getInstructionSet( 6770 scannedPackage.applicationInfo.primaryCpuAbi); 6771 } 6772 6773 PackageSetting requirer = null; 6774 for (PackageSetting ps : packagesForUser) { 6775 // If packagesForUser contains scannedPackage, we skip it. This will happen 6776 // when scannedPackage is an update of an existing package. Without this check, 6777 // we will never be able to change the ABI of any package belonging to a shared 6778 // user, even if it's compatible with other packages. 6779 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6780 if (ps.primaryCpuAbiString == null) { 6781 continue; 6782 } 6783 6784 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6785 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6786 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6787 // this but there's not much we can do. 6788 String errorMessage = "Instruction set mismatch, " 6789 + ((requirer == null) ? "[caller]" : requirer) 6790 + " requires " + requiredInstructionSet + " whereas " + ps 6791 + " requires " + instructionSet; 6792 Slog.w(TAG, errorMessage); 6793 } 6794 6795 if (requiredInstructionSet == null) { 6796 requiredInstructionSet = instructionSet; 6797 requirer = ps; 6798 } 6799 } 6800 } 6801 6802 if (requiredInstructionSet != null) { 6803 String adjustedAbi; 6804 if (requirer != null) { 6805 // requirer != null implies that either scannedPackage was null or that scannedPackage 6806 // did not require an ABI, in which case we have to adjust scannedPackage to match 6807 // the ABI of the set (which is the same as requirer's ABI) 6808 adjustedAbi = requirer.primaryCpuAbiString; 6809 if (scannedPackage != null) { 6810 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6811 } 6812 } else { 6813 // requirer == null implies that we're updating all ABIs in the set to 6814 // match scannedPackage. 6815 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6816 } 6817 6818 for (PackageSetting ps : packagesForUser) { 6819 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6820 if (ps.primaryCpuAbiString != null) { 6821 continue; 6822 } 6823 6824 ps.primaryCpuAbiString = adjustedAbi; 6825 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6826 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6827 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6828 6829 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6830 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6831 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6832 ps.primaryCpuAbiString = null; 6833 ps.pkg.applicationInfo.primaryCpuAbi = null; 6834 return; 6835 } else { 6836 mInstaller.rmdex(ps.codePathString, 6837 getDexCodeInstructionSet(getPreferredInstructionSet())); 6838 } 6839 } 6840 } 6841 } 6842 } 6843 } 6844 6845 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6846 synchronized (mPackages) { 6847 mResolverReplaced = true; 6848 // Set up information for custom user intent resolution activity. 6849 mResolveActivity.applicationInfo = pkg.applicationInfo; 6850 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6851 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6852 mResolveActivity.processName = pkg.applicationInfo.packageName; 6853 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6854 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6855 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6856 mResolveActivity.theme = 0; 6857 mResolveActivity.exported = true; 6858 mResolveActivity.enabled = true; 6859 mResolveInfo.activityInfo = mResolveActivity; 6860 mResolveInfo.priority = 0; 6861 mResolveInfo.preferredOrder = 0; 6862 mResolveInfo.match = 0; 6863 mResolveComponentName = mCustomResolverComponentName; 6864 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6865 mResolveComponentName); 6866 } 6867 } 6868 6869 private static String calculateBundledApkRoot(final String codePathString) { 6870 final File codePath = new File(codePathString); 6871 final File codeRoot; 6872 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6873 codeRoot = Environment.getRootDirectory(); 6874 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6875 codeRoot = Environment.getOemDirectory(); 6876 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6877 codeRoot = Environment.getVendorDirectory(); 6878 } else { 6879 // Unrecognized code path; take its top real segment as the apk root: 6880 // e.g. /something/app/blah.apk => /something 6881 try { 6882 File f = codePath.getCanonicalFile(); 6883 File parent = f.getParentFile(); // non-null because codePath is a file 6884 File tmp; 6885 while ((tmp = parent.getParentFile()) != null) { 6886 f = parent; 6887 parent = tmp; 6888 } 6889 codeRoot = f; 6890 Slog.w(TAG, "Unrecognized code path " 6891 + codePath + " - using " + codeRoot); 6892 } catch (IOException e) { 6893 // Can't canonicalize the code path -- shenanigans? 6894 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6895 return Environment.getRootDirectory().getPath(); 6896 } 6897 } 6898 return codeRoot.getPath(); 6899 } 6900 6901 /** 6902 * Derive and set the location of native libraries for the given package, 6903 * which varies depending on where and how the package was installed. 6904 */ 6905 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6906 final ApplicationInfo info = pkg.applicationInfo; 6907 final String codePath = pkg.codePath; 6908 final File codeFile = new File(codePath); 6909 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6910 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6911 6912 info.nativeLibraryRootDir = null; 6913 info.nativeLibraryRootRequiresIsa = false; 6914 info.nativeLibraryDir = null; 6915 info.secondaryNativeLibraryDir = null; 6916 6917 if (isApkFile(codeFile)) { 6918 // Monolithic install 6919 if (bundledApp) { 6920 // If "/system/lib64/apkname" exists, assume that is the per-package 6921 // native library directory to use; otherwise use "/system/lib/apkname". 6922 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6923 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6924 getPrimaryInstructionSet(info)); 6925 6926 // This is a bundled system app so choose the path based on the ABI. 6927 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6928 // is just the default path. 6929 final String apkName = deriveCodePathName(codePath); 6930 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6931 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6932 apkName).getAbsolutePath(); 6933 6934 if (info.secondaryCpuAbi != null) { 6935 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6936 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6937 secondaryLibDir, apkName).getAbsolutePath(); 6938 } 6939 } else if (asecApp) { 6940 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6941 .getAbsolutePath(); 6942 } else { 6943 final String apkName = deriveCodePathName(codePath); 6944 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6945 .getAbsolutePath(); 6946 } 6947 6948 info.nativeLibraryRootRequiresIsa = false; 6949 info.nativeLibraryDir = info.nativeLibraryRootDir; 6950 } else { 6951 // Cluster install 6952 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6953 info.nativeLibraryRootRequiresIsa = true; 6954 6955 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6956 getPrimaryInstructionSet(info)).getAbsolutePath(); 6957 6958 if (info.secondaryCpuAbi != null) { 6959 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6960 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6961 } 6962 } 6963 } 6964 6965 /** 6966 * Calculate the abis and roots for a bundled app. These can uniquely 6967 * be determined from the contents of the system partition, i.e whether 6968 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6969 * of this information, and instead assume that the system was built 6970 * sensibly. 6971 */ 6972 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6973 PackageSetting pkgSetting) { 6974 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6975 6976 // If "/system/lib64/apkname" exists, assume that is the per-package 6977 // native library directory to use; otherwise use "/system/lib/apkname". 6978 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6979 setBundledAppAbi(pkg, apkRoot, apkName); 6980 // pkgSetting might be null during rescan following uninstall of updates 6981 // to a bundled app, so accommodate that possibility. The settings in 6982 // that case will be established later from the parsed package. 6983 // 6984 // If the settings aren't null, sync them up with what we've just derived. 6985 // note that apkRoot isn't stored in the package settings. 6986 if (pkgSetting != null) { 6987 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6988 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6989 } 6990 } 6991 6992 /** 6993 * Deduces the ABI of a bundled app and sets the relevant fields on the 6994 * parsed pkg object. 6995 * 6996 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6997 * under which system libraries are installed. 6998 * @param apkName the name of the installed package. 6999 */ 7000 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7001 final File codeFile = new File(pkg.codePath); 7002 7003 final boolean has64BitLibs; 7004 final boolean has32BitLibs; 7005 if (isApkFile(codeFile)) { 7006 // Monolithic install 7007 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7008 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7009 } else { 7010 // Cluster install 7011 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7012 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7013 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7014 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7015 has64BitLibs = (new File(rootDir, isa)).exists(); 7016 } else { 7017 has64BitLibs = false; 7018 } 7019 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7020 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7021 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7022 has32BitLibs = (new File(rootDir, isa)).exists(); 7023 } else { 7024 has32BitLibs = false; 7025 } 7026 } 7027 7028 if (has64BitLibs && !has32BitLibs) { 7029 // The package has 64 bit libs, but not 32 bit libs. Its primary 7030 // ABI should be 64 bit. We can safely assume here that the bundled 7031 // native libraries correspond to the most preferred ABI in the list. 7032 7033 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7034 pkg.applicationInfo.secondaryCpuAbi = null; 7035 } else if (has32BitLibs && !has64BitLibs) { 7036 // The package has 32 bit libs but not 64 bit libs. Its primary 7037 // ABI should be 32 bit. 7038 7039 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7040 pkg.applicationInfo.secondaryCpuAbi = null; 7041 } else if (has32BitLibs && has64BitLibs) { 7042 // The application has both 64 and 32 bit bundled libraries. We check 7043 // here that the app declares multiArch support, and warn if it doesn't. 7044 // 7045 // We will be lenient here and record both ABIs. The primary will be the 7046 // ABI that's higher on the list, i.e, a device that's configured to prefer 7047 // 64 bit apps will see a 64 bit primary ABI, 7048 7049 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7050 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7051 } 7052 7053 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7054 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7055 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7056 } else { 7057 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7058 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7059 } 7060 } else { 7061 pkg.applicationInfo.primaryCpuAbi = null; 7062 pkg.applicationInfo.secondaryCpuAbi = null; 7063 } 7064 } 7065 7066 private void killApplication(String pkgName, int appId, String reason) { 7067 // Request the ActivityManager to kill the process(only for existing packages) 7068 // so that we do not end up in a confused state while the user is still using the older 7069 // version of the application while the new one gets installed. 7070 IActivityManager am = ActivityManagerNative.getDefault(); 7071 if (am != null) { 7072 try { 7073 am.killApplicationWithAppId(pkgName, appId, reason); 7074 } catch (RemoteException e) { 7075 } 7076 } 7077 } 7078 7079 void removePackageLI(PackageSetting ps, boolean chatty) { 7080 if (DEBUG_INSTALL) { 7081 if (chatty) 7082 Log.d(TAG, "Removing package " + ps.name); 7083 } 7084 7085 // writer 7086 synchronized (mPackages) { 7087 mPackages.remove(ps.name); 7088 final PackageParser.Package pkg = ps.pkg; 7089 if (pkg != null) { 7090 cleanPackageDataStructuresLILPw(pkg, chatty); 7091 } 7092 } 7093 } 7094 7095 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7096 if (DEBUG_INSTALL) { 7097 if (chatty) 7098 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7099 } 7100 7101 // writer 7102 synchronized (mPackages) { 7103 mPackages.remove(pkg.applicationInfo.packageName); 7104 cleanPackageDataStructuresLILPw(pkg, chatty); 7105 } 7106 } 7107 7108 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7109 int N = pkg.providers.size(); 7110 StringBuilder r = null; 7111 int i; 7112 for (i=0; i<N; i++) { 7113 PackageParser.Provider p = pkg.providers.get(i); 7114 mProviders.removeProvider(p); 7115 if (p.info.authority == null) { 7116 7117 /* There was another ContentProvider with this authority when 7118 * this app was installed so this authority is null, 7119 * Ignore it as we don't have to unregister the provider. 7120 */ 7121 continue; 7122 } 7123 String names[] = p.info.authority.split(";"); 7124 for (int j = 0; j < names.length; j++) { 7125 if (mProvidersByAuthority.get(names[j]) == p) { 7126 mProvidersByAuthority.remove(names[j]); 7127 if (DEBUG_REMOVE) { 7128 if (chatty) 7129 Log.d(TAG, "Unregistered content provider: " + names[j] 7130 + ", className = " + p.info.name + ", isSyncable = " 7131 + p.info.isSyncable); 7132 } 7133 } 7134 } 7135 if (DEBUG_REMOVE && chatty) { 7136 if (r == null) { 7137 r = new StringBuilder(256); 7138 } else { 7139 r.append(' '); 7140 } 7141 r.append(p.info.name); 7142 } 7143 } 7144 if (r != null) { 7145 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7146 } 7147 7148 N = pkg.services.size(); 7149 r = null; 7150 for (i=0; i<N; i++) { 7151 PackageParser.Service s = pkg.services.get(i); 7152 mServices.removeService(s); 7153 if (chatty) { 7154 if (r == null) { 7155 r = new StringBuilder(256); 7156 } else { 7157 r.append(' '); 7158 } 7159 r.append(s.info.name); 7160 } 7161 } 7162 if (r != null) { 7163 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7164 } 7165 7166 N = pkg.receivers.size(); 7167 r = null; 7168 for (i=0; i<N; i++) { 7169 PackageParser.Activity a = pkg.receivers.get(i); 7170 mReceivers.removeActivity(a, "receiver"); 7171 if (DEBUG_REMOVE && chatty) { 7172 if (r == null) { 7173 r = new StringBuilder(256); 7174 } else { 7175 r.append(' '); 7176 } 7177 r.append(a.info.name); 7178 } 7179 } 7180 if (r != null) { 7181 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7182 } 7183 7184 N = pkg.activities.size(); 7185 r = null; 7186 for (i=0; i<N; i++) { 7187 PackageParser.Activity a = pkg.activities.get(i); 7188 mActivities.removeActivity(a, "activity"); 7189 if (DEBUG_REMOVE && chatty) { 7190 if (r == null) { 7191 r = new StringBuilder(256); 7192 } else { 7193 r.append(' '); 7194 } 7195 r.append(a.info.name); 7196 } 7197 } 7198 if (r != null) { 7199 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7200 } 7201 7202 N = pkg.permissions.size(); 7203 r = null; 7204 for (i=0; i<N; i++) { 7205 PackageParser.Permission p = pkg.permissions.get(i); 7206 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7207 if (bp == null) { 7208 bp = mSettings.mPermissionTrees.get(p.info.name); 7209 } 7210 if (bp != null && bp.perm == p) { 7211 bp.perm = null; 7212 if (DEBUG_REMOVE && chatty) { 7213 if (r == null) { 7214 r = new StringBuilder(256); 7215 } else { 7216 r.append(' '); 7217 } 7218 r.append(p.info.name); 7219 } 7220 } 7221 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7222 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7223 if (appOpPerms != null) { 7224 appOpPerms.remove(pkg.packageName); 7225 } 7226 } 7227 } 7228 if (r != null) { 7229 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7230 } 7231 7232 N = pkg.requestedPermissions.size(); 7233 r = null; 7234 for (i=0; i<N; i++) { 7235 String perm = pkg.requestedPermissions.get(i); 7236 BasePermission bp = mSettings.mPermissions.get(perm); 7237 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7238 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7239 if (appOpPerms != null) { 7240 appOpPerms.remove(pkg.packageName); 7241 if (appOpPerms.isEmpty()) { 7242 mAppOpPermissionPackages.remove(perm); 7243 } 7244 } 7245 } 7246 } 7247 if (r != null) { 7248 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7249 } 7250 7251 N = pkg.instrumentation.size(); 7252 r = null; 7253 for (i=0; i<N; i++) { 7254 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7255 mInstrumentation.remove(a.getComponentName()); 7256 if (DEBUG_REMOVE && chatty) { 7257 if (r == null) { 7258 r = new StringBuilder(256); 7259 } else { 7260 r.append(' '); 7261 } 7262 r.append(a.info.name); 7263 } 7264 } 7265 if (r != null) { 7266 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7267 } 7268 7269 r = null; 7270 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7271 // Only system apps can hold shared libraries. 7272 if (pkg.libraryNames != null) { 7273 for (i=0; i<pkg.libraryNames.size(); i++) { 7274 String name = pkg.libraryNames.get(i); 7275 SharedLibraryEntry cur = mSharedLibraries.get(name); 7276 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7277 mSharedLibraries.remove(name); 7278 if (DEBUG_REMOVE && chatty) { 7279 if (r == null) { 7280 r = new StringBuilder(256); 7281 } else { 7282 r.append(' '); 7283 } 7284 r.append(name); 7285 } 7286 } 7287 } 7288 } 7289 } 7290 if (r != null) { 7291 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7292 } 7293 } 7294 7295 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7296 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7297 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7298 return true; 7299 } 7300 } 7301 return false; 7302 } 7303 7304 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7305 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7306 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7307 7308 private void updatePermissionsLPw(String changingPkg, 7309 PackageParser.Package pkgInfo, int flags) { 7310 // Make sure there are no dangling permission trees. 7311 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7312 while (it.hasNext()) { 7313 final BasePermission bp = it.next(); 7314 if (bp.packageSetting == null) { 7315 // We may not yet have parsed the package, so just see if 7316 // we still know about its settings. 7317 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7318 } 7319 if (bp.packageSetting == null) { 7320 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7321 + " from package " + bp.sourcePackage); 7322 it.remove(); 7323 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7324 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7325 Slog.i(TAG, "Removing old permission tree: " + bp.name 7326 + " from package " + bp.sourcePackage); 7327 flags |= UPDATE_PERMISSIONS_ALL; 7328 it.remove(); 7329 } 7330 } 7331 } 7332 7333 // Make sure all dynamic permissions have been assigned to a package, 7334 // and make sure there are no dangling permissions. 7335 it = mSettings.mPermissions.values().iterator(); 7336 while (it.hasNext()) { 7337 final BasePermission bp = it.next(); 7338 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7339 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7340 + bp.name + " pkg=" + bp.sourcePackage 7341 + " info=" + bp.pendingInfo); 7342 if (bp.packageSetting == null && bp.pendingInfo != null) { 7343 final BasePermission tree = findPermissionTreeLP(bp.name); 7344 if (tree != null && tree.perm != null) { 7345 bp.packageSetting = tree.packageSetting; 7346 bp.perm = new PackageParser.Permission(tree.perm.owner, 7347 new PermissionInfo(bp.pendingInfo)); 7348 bp.perm.info.packageName = tree.perm.info.packageName; 7349 bp.perm.info.name = bp.name; 7350 bp.uid = tree.uid; 7351 } 7352 } 7353 } 7354 if (bp.packageSetting == null) { 7355 // We may not yet have parsed the package, so just see if 7356 // we still know about its settings. 7357 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7358 } 7359 if (bp.packageSetting == null) { 7360 Slog.w(TAG, "Removing dangling permission: " + bp.name 7361 + " from package " + bp.sourcePackage); 7362 it.remove(); 7363 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7364 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7365 Slog.i(TAG, "Removing old permission: " + bp.name 7366 + " from package " + bp.sourcePackage); 7367 flags |= UPDATE_PERMISSIONS_ALL; 7368 it.remove(); 7369 } 7370 } 7371 } 7372 7373 // Now update the permissions for all packages, in particular 7374 // replace the granted permissions of the system packages. 7375 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7376 for (PackageParser.Package pkg : mPackages.values()) { 7377 if (pkg != pkgInfo) { 7378 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7379 changingPkg); 7380 } 7381 } 7382 } 7383 7384 if (pkgInfo != null) { 7385 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7386 } 7387 } 7388 7389 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7390 String packageOfInterest) { 7391 // IMPORTANT: There are two types of permissions: install and runtime. 7392 // Install time permissions are granted when the app is installed to 7393 // all device users and users added in the future. Runtime permissions 7394 // are granted at runtime explicitly to specific users. Normal and signature 7395 // protected permissions are install time permissions. Dangerous permissions 7396 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7397 // otherwise they are runtime permissions. This function does not manage 7398 // runtime permissions except for the case an app targeting Lollipop MR1 7399 // being upgraded to target a newer SDK, in which case dangerous permissions 7400 // are transformed from install time to runtime ones. 7401 7402 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7403 if (ps == null) { 7404 return; 7405 } 7406 7407 PermissionsState permissionsState = ps.getPermissionsState(); 7408 PermissionsState origPermissions = permissionsState; 7409 7410 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7411 7412 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7413 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7414 7415 boolean changedInstallPermission = false; 7416 7417 if (replace) { 7418 ps.installPermissionsFixed = false; 7419 if (!ps.isSharedUser()) { 7420 origPermissions = new PermissionsState(permissionsState); 7421 permissionsState.reset(); 7422 } 7423 } 7424 7425 permissionsState.setGlobalGids(mGlobalGids); 7426 7427 final int N = pkg.requestedPermissions.size(); 7428 for (int i=0; i<N; i++) { 7429 final String name = pkg.requestedPermissions.get(i); 7430 final BasePermission bp = mSettings.mPermissions.get(name); 7431 7432 if (DEBUG_INSTALL) { 7433 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7434 } 7435 7436 if (bp == null || bp.packageSetting == null) { 7437 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7438 Slog.w(TAG, "Unknown permission " + name 7439 + " in package " + pkg.packageName); 7440 } 7441 continue; 7442 } 7443 7444 final String perm = bp.name; 7445 boolean allowedSig = false; 7446 int grant = GRANT_DENIED; 7447 7448 // Keep track of app op permissions. 7449 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7450 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7451 if (pkgs == null) { 7452 pkgs = new ArraySet<>(); 7453 mAppOpPermissionPackages.put(bp.name, pkgs); 7454 } 7455 pkgs.add(pkg.packageName); 7456 } 7457 7458 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7459 switch (level) { 7460 case PermissionInfo.PROTECTION_NORMAL: { 7461 // For all apps normal permissions are install time ones. 7462 grant = GRANT_INSTALL; 7463 } break; 7464 7465 case PermissionInfo.PROTECTION_DANGEROUS: { 7466 if (!RUNTIME_PERMISSIONS_ENABLED 7467 || pkg.applicationInfo.targetSdkVersion 7468 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7469 // For legacy apps dangerous permissions are install time ones. 7470 grant = GRANT_INSTALL; 7471 } else if (ps.isSystem()) { 7472 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7473 if (origPermissions.hasInstallPermission(bp.name)) { 7474 // If a system app had an install permission, then the app was 7475 // upgraded and we grant the permissions as runtime to all users. 7476 grant = GRANT_UPGRADE; 7477 upgradeUserIds = currentUserIds; 7478 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7479 // If users changed since the last permissions update for a 7480 // system app, we grant the permission as runtime to the new users. 7481 grant = GRANT_UPGRADE; 7482 upgradeUserIds = currentUserIds; 7483 for (int userId : updatedUserIds) { 7484 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7485 } 7486 } else { 7487 // Otherwise, we grant the permission as runtime if the app 7488 // already had it, i.e. we preserve runtime permissions. 7489 grant = GRANT_RUNTIME; 7490 } 7491 } else if (origPermissions.hasInstallPermission(bp.name)) { 7492 // For legacy apps that became modern, install becomes runtime. 7493 grant = GRANT_UPGRADE; 7494 upgradeUserIds = currentUserIds; 7495 } else if (replace) { 7496 // For upgraded modern apps keep runtime permissions unchanged. 7497 grant = GRANT_RUNTIME; 7498 } 7499 } break; 7500 7501 case PermissionInfo.PROTECTION_SIGNATURE: { 7502 // For all apps signature permissions are install time ones. 7503 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7504 if (allowedSig) { 7505 grant = GRANT_INSTALL; 7506 } 7507 } break; 7508 } 7509 7510 if (DEBUG_INSTALL) { 7511 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7512 } 7513 7514 if (grant != GRANT_DENIED) { 7515 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7516 // If this is an existing, non-system package, then 7517 // we can't add any new permissions to it. 7518 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7519 // Except... if this is a permission that was added 7520 // to the platform (note: need to only do this when 7521 // updating the platform). 7522 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7523 grant = GRANT_DENIED; 7524 } 7525 } 7526 } 7527 7528 switch (grant) { 7529 case GRANT_INSTALL: { 7530 // Grant an install permission. 7531 if (permissionsState.grantInstallPermission(bp) != 7532 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7533 changedInstallPermission = true; 7534 } 7535 } break; 7536 7537 case GRANT_RUNTIME: { 7538 // Grant previously granted runtime permissions. 7539 for (int userId : UserManagerService.getInstance().getUserIds()) { 7540 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7541 if (permissionsState.grantRuntimePermission(bp, userId) == 7542 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7543 // If we cannot put the permission as it was, we have to write. 7544 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7545 changedRuntimePermissionUserIds, userId); 7546 } 7547 } 7548 } 7549 } break; 7550 7551 case GRANT_UPGRADE: { 7552 // Grant runtime permissions for a previously held install permission. 7553 permissionsState.revokeInstallPermission(bp); 7554 for (int userId : upgradeUserIds) { 7555 if (permissionsState.grantRuntimePermission(bp, userId) != 7556 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7557 // If we granted the permission, we have to write. 7558 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7559 changedRuntimePermissionUserIds, userId); 7560 } 7561 } 7562 } break; 7563 7564 default: { 7565 if (packageOfInterest == null 7566 || packageOfInterest.equals(pkg.packageName)) { 7567 Slog.w(TAG, "Not granting permission " + perm 7568 + " to package " + pkg.packageName 7569 + " because it was previously installed without"); 7570 } 7571 } break; 7572 } 7573 } else { 7574 if (permissionsState.revokeInstallPermission(bp) != 7575 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7576 changedInstallPermission = true; 7577 Slog.i(TAG, "Un-granting permission " + perm 7578 + " from package " + pkg.packageName 7579 + " (protectionLevel=" + bp.protectionLevel 7580 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7581 + ")"); 7582 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7583 // Don't print warning for app op permissions, since it is fine for them 7584 // not to be granted, there is a UI for the user to decide. 7585 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7586 Slog.w(TAG, "Not granting permission " + perm 7587 + " to package " + pkg.packageName 7588 + " (protectionLevel=" + bp.protectionLevel 7589 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7590 + ")"); 7591 } 7592 } 7593 } 7594 } 7595 7596 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7597 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7598 // This is the first that we have heard about this package, so the 7599 // permissions we have now selected are fixed until explicitly 7600 // changed. 7601 ps.installPermissionsFixed = true; 7602 } 7603 7604 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7605 7606 // Persist the runtime permissions state for users with changes. 7607 if (RUNTIME_PERMISSIONS_ENABLED) { 7608 for (int userId : changedRuntimePermissionUserIds) { 7609 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7610 } 7611 } 7612 } 7613 7614 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7615 boolean allowed = false; 7616 final int NP = PackageParser.NEW_PERMISSIONS.length; 7617 for (int ip=0; ip<NP; ip++) { 7618 final PackageParser.NewPermissionInfo npi 7619 = PackageParser.NEW_PERMISSIONS[ip]; 7620 if (npi.name.equals(perm) 7621 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7622 allowed = true; 7623 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7624 + pkg.packageName); 7625 break; 7626 } 7627 } 7628 return allowed; 7629 } 7630 7631 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7632 BasePermission bp, PermissionsState origPermissions) { 7633 boolean allowed; 7634 allowed = (compareSignatures( 7635 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7636 == PackageManager.SIGNATURE_MATCH) 7637 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7638 == PackageManager.SIGNATURE_MATCH); 7639 if (!allowed && (bp.protectionLevel 7640 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7641 if (isSystemApp(pkg)) { 7642 // For updated system applications, a system permission 7643 // is granted only if it had been defined by the original application. 7644 if (pkg.isUpdatedSystemApp()) { 7645 final PackageSetting sysPs = mSettings 7646 .getDisabledSystemPkgLPr(pkg.packageName); 7647 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7648 // If the original was granted this permission, we take 7649 // that grant decision as read and propagate it to the 7650 // update. 7651 if (sysPs.isPrivileged()) { 7652 allowed = true; 7653 } 7654 } else { 7655 // The system apk may have been updated with an older 7656 // version of the one on the data partition, but which 7657 // granted a new system permission that it didn't have 7658 // before. In this case we do want to allow the app to 7659 // now get the new permission if the ancestral apk is 7660 // privileged to get it. 7661 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7662 for (int j=0; 7663 j<sysPs.pkg.requestedPermissions.size(); j++) { 7664 if (perm.equals( 7665 sysPs.pkg.requestedPermissions.get(j))) { 7666 allowed = true; 7667 break; 7668 } 7669 } 7670 } 7671 } 7672 } else { 7673 allowed = isPrivilegedApp(pkg); 7674 } 7675 } 7676 } 7677 if (!allowed && (bp.protectionLevel 7678 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7679 // For development permissions, a development permission 7680 // is granted only if it was already granted. 7681 allowed = origPermissions.hasInstallPermission(perm); 7682 } 7683 return allowed; 7684 } 7685 7686 final class ActivityIntentResolver 7687 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7688 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7689 boolean defaultOnly, int userId) { 7690 if (!sUserManager.exists(userId)) return null; 7691 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7692 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7693 } 7694 7695 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7696 int userId) { 7697 if (!sUserManager.exists(userId)) return null; 7698 mFlags = flags; 7699 return super.queryIntent(intent, resolvedType, 7700 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7701 } 7702 7703 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7704 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7705 if (!sUserManager.exists(userId)) return null; 7706 if (packageActivities == null) { 7707 return null; 7708 } 7709 mFlags = flags; 7710 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7711 final int N = packageActivities.size(); 7712 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7713 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7714 7715 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7716 for (int i = 0; i < N; ++i) { 7717 intentFilters = packageActivities.get(i).intents; 7718 if (intentFilters != null && intentFilters.size() > 0) { 7719 PackageParser.ActivityIntentInfo[] array = 7720 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7721 intentFilters.toArray(array); 7722 listCut.add(array); 7723 } 7724 } 7725 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7726 } 7727 7728 public final void addActivity(PackageParser.Activity a, String type) { 7729 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7730 mActivities.put(a.getComponentName(), a); 7731 if (DEBUG_SHOW_INFO) 7732 Log.v( 7733 TAG, " " + type + " " + 7734 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7735 if (DEBUG_SHOW_INFO) 7736 Log.v(TAG, " Class=" + a.info.name); 7737 final int NI = a.intents.size(); 7738 for (int j=0; j<NI; j++) { 7739 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7740 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7741 intent.setPriority(0); 7742 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7743 + a.className + " with priority > 0, forcing to 0"); 7744 } 7745 if (DEBUG_SHOW_INFO) { 7746 Log.v(TAG, " IntentFilter:"); 7747 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7748 } 7749 if (!intent.debugCheck()) { 7750 Log.w(TAG, "==> For Activity " + a.info.name); 7751 } 7752 addFilter(intent); 7753 } 7754 } 7755 7756 public final void removeActivity(PackageParser.Activity a, String type) { 7757 mActivities.remove(a.getComponentName()); 7758 if (DEBUG_SHOW_INFO) { 7759 Log.v(TAG, " " + type + " " 7760 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7761 : a.info.name) + ":"); 7762 Log.v(TAG, " Class=" + a.info.name); 7763 } 7764 final int NI = a.intents.size(); 7765 for (int j=0; j<NI; j++) { 7766 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7767 if (DEBUG_SHOW_INFO) { 7768 Log.v(TAG, " IntentFilter:"); 7769 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7770 } 7771 removeFilter(intent); 7772 } 7773 } 7774 7775 @Override 7776 protected boolean allowFilterResult( 7777 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7778 ActivityInfo filterAi = filter.activity.info; 7779 for (int i=dest.size()-1; i>=0; i--) { 7780 ActivityInfo destAi = dest.get(i).activityInfo; 7781 if (destAi.name == filterAi.name 7782 && destAi.packageName == filterAi.packageName) { 7783 return false; 7784 } 7785 } 7786 return true; 7787 } 7788 7789 @Override 7790 protected ActivityIntentInfo[] newArray(int size) { 7791 return new ActivityIntentInfo[size]; 7792 } 7793 7794 @Override 7795 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7796 if (!sUserManager.exists(userId)) return true; 7797 PackageParser.Package p = filter.activity.owner; 7798 if (p != null) { 7799 PackageSetting ps = (PackageSetting)p.mExtras; 7800 if (ps != null) { 7801 // System apps are never considered stopped for purposes of 7802 // filtering, because there may be no way for the user to 7803 // actually re-launch them. 7804 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7805 && ps.getStopped(userId); 7806 } 7807 } 7808 return false; 7809 } 7810 7811 @Override 7812 protected boolean isPackageForFilter(String packageName, 7813 PackageParser.ActivityIntentInfo info) { 7814 return packageName.equals(info.activity.owner.packageName); 7815 } 7816 7817 @Override 7818 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7819 int match, int userId) { 7820 if (!sUserManager.exists(userId)) return null; 7821 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7822 return null; 7823 } 7824 final PackageParser.Activity activity = info.activity; 7825 if (mSafeMode && (activity.info.applicationInfo.flags 7826 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7827 return null; 7828 } 7829 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7830 if (ps == null) { 7831 return null; 7832 } 7833 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7834 ps.readUserState(userId), userId); 7835 if (ai == null) { 7836 return null; 7837 } 7838 final ResolveInfo res = new ResolveInfo(); 7839 res.activityInfo = ai; 7840 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7841 res.filter = info; 7842 } 7843 if (info != null) { 7844 res.filterNeedsVerification = info.needsVerification(); 7845 } 7846 res.priority = info.getPriority(); 7847 res.preferredOrder = activity.owner.mPreferredOrder; 7848 //System.out.println("Result: " + res.activityInfo.className + 7849 // " = " + res.priority); 7850 res.match = match; 7851 res.isDefault = info.hasDefault; 7852 res.labelRes = info.labelRes; 7853 res.nonLocalizedLabel = info.nonLocalizedLabel; 7854 if (userNeedsBadging(userId)) { 7855 res.noResourceId = true; 7856 } else { 7857 res.icon = info.icon; 7858 } 7859 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7860 return res; 7861 } 7862 7863 @Override 7864 protected void sortResults(List<ResolveInfo> results) { 7865 Collections.sort(results, mResolvePrioritySorter); 7866 } 7867 7868 @Override 7869 protected void dumpFilter(PrintWriter out, String prefix, 7870 PackageParser.ActivityIntentInfo filter) { 7871 out.print(prefix); out.print( 7872 Integer.toHexString(System.identityHashCode(filter.activity))); 7873 out.print(' '); 7874 filter.activity.printComponentShortName(out); 7875 out.print(" filter "); 7876 out.println(Integer.toHexString(System.identityHashCode(filter))); 7877 } 7878 7879 @Override 7880 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7881 return filter.activity; 7882 } 7883 7884 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7885 PackageParser.Activity activity = (PackageParser.Activity)label; 7886 out.print(prefix); out.print( 7887 Integer.toHexString(System.identityHashCode(activity))); 7888 out.print(' '); 7889 activity.printComponentShortName(out); 7890 if (count > 1) { 7891 out.print(" ("); out.print(count); out.print(" filters)"); 7892 } 7893 out.println(); 7894 } 7895 7896// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7897// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7898// final List<ResolveInfo> retList = Lists.newArrayList(); 7899// while (i.hasNext()) { 7900// final ResolveInfo resolveInfo = i.next(); 7901// if (isEnabledLP(resolveInfo.activityInfo)) { 7902// retList.add(resolveInfo); 7903// } 7904// } 7905// return retList; 7906// } 7907 7908 // Keys are String (activity class name), values are Activity. 7909 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7910 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7911 private int mFlags; 7912 } 7913 7914 private final class ServiceIntentResolver 7915 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7916 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7917 boolean defaultOnly, int userId) { 7918 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7919 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7920 } 7921 7922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7923 int userId) { 7924 if (!sUserManager.exists(userId)) return null; 7925 mFlags = flags; 7926 return super.queryIntent(intent, resolvedType, 7927 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7928 } 7929 7930 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7931 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7932 if (!sUserManager.exists(userId)) return null; 7933 if (packageServices == null) { 7934 return null; 7935 } 7936 mFlags = flags; 7937 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7938 final int N = packageServices.size(); 7939 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7940 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7941 7942 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7943 for (int i = 0; i < N; ++i) { 7944 intentFilters = packageServices.get(i).intents; 7945 if (intentFilters != null && intentFilters.size() > 0) { 7946 PackageParser.ServiceIntentInfo[] array = 7947 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7948 intentFilters.toArray(array); 7949 listCut.add(array); 7950 } 7951 } 7952 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7953 } 7954 7955 public final void addService(PackageParser.Service s) { 7956 mServices.put(s.getComponentName(), s); 7957 if (DEBUG_SHOW_INFO) { 7958 Log.v(TAG, " " 7959 + (s.info.nonLocalizedLabel != null 7960 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7961 Log.v(TAG, " Class=" + s.info.name); 7962 } 7963 final int NI = s.intents.size(); 7964 int j; 7965 for (j=0; j<NI; j++) { 7966 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7967 if (DEBUG_SHOW_INFO) { 7968 Log.v(TAG, " IntentFilter:"); 7969 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7970 } 7971 if (!intent.debugCheck()) { 7972 Log.w(TAG, "==> For Service " + s.info.name); 7973 } 7974 addFilter(intent); 7975 } 7976 } 7977 7978 public final void removeService(PackageParser.Service s) { 7979 mServices.remove(s.getComponentName()); 7980 if (DEBUG_SHOW_INFO) { 7981 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7982 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7983 Log.v(TAG, " Class=" + s.info.name); 7984 } 7985 final int NI = s.intents.size(); 7986 int j; 7987 for (j=0; j<NI; j++) { 7988 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7989 if (DEBUG_SHOW_INFO) { 7990 Log.v(TAG, " IntentFilter:"); 7991 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7992 } 7993 removeFilter(intent); 7994 } 7995 } 7996 7997 @Override 7998 protected boolean allowFilterResult( 7999 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8000 ServiceInfo filterSi = filter.service.info; 8001 for (int i=dest.size()-1; i>=0; i--) { 8002 ServiceInfo destAi = dest.get(i).serviceInfo; 8003 if (destAi.name == filterSi.name 8004 && destAi.packageName == filterSi.packageName) { 8005 return false; 8006 } 8007 } 8008 return true; 8009 } 8010 8011 @Override 8012 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8013 return new PackageParser.ServiceIntentInfo[size]; 8014 } 8015 8016 @Override 8017 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8018 if (!sUserManager.exists(userId)) return true; 8019 PackageParser.Package p = filter.service.owner; 8020 if (p != null) { 8021 PackageSetting ps = (PackageSetting)p.mExtras; 8022 if (ps != null) { 8023 // System apps are never considered stopped for purposes of 8024 // filtering, because there may be no way for the user to 8025 // actually re-launch them. 8026 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8027 && ps.getStopped(userId); 8028 } 8029 } 8030 return false; 8031 } 8032 8033 @Override 8034 protected boolean isPackageForFilter(String packageName, 8035 PackageParser.ServiceIntentInfo info) { 8036 return packageName.equals(info.service.owner.packageName); 8037 } 8038 8039 @Override 8040 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8041 int match, int userId) { 8042 if (!sUserManager.exists(userId)) return null; 8043 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8044 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8045 return null; 8046 } 8047 final PackageParser.Service service = info.service; 8048 if (mSafeMode && (service.info.applicationInfo.flags 8049 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8050 return null; 8051 } 8052 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8053 if (ps == null) { 8054 return null; 8055 } 8056 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8057 ps.readUserState(userId), userId); 8058 if (si == null) { 8059 return null; 8060 } 8061 final ResolveInfo res = new ResolveInfo(); 8062 res.serviceInfo = si; 8063 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8064 res.filter = filter; 8065 } 8066 res.priority = info.getPriority(); 8067 res.preferredOrder = service.owner.mPreferredOrder; 8068 res.match = match; 8069 res.isDefault = info.hasDefault; 8070 res.labelRes = info.labelRes; 8071 res.nonLocalizedLabel = info.nonLocalizedLabel; 8072 res.icon = info.icon; 8073 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8074 return res; 8075 } 8076 8077 @Override 8078 protected void sortResults(List<ResolveInfo> results) { 8079 Collections.sort(results, mResolvePrioritySorter); 8080 } 8081 8082 @Override 8083 protected void dumpFilter(PrintWriter out, String prefix, 8084 PackageParser.ServiceIntentInfo filter) { 8085 out.print(prefix); out.print( 8086 Integer.toHexString(System.identityHashCode(filter.service))); 8087 out.print(' '); 8088 filter.service.printComponentShortName(out); 8089 out.print(" filter "); 8090 out.println(Integer.toHexString(System.identityHashCode(filter))); 8091 } 8092 8093 @Override 8094 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8095 return filter.service; 8096 } 8097 8098 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8099 PackageParser.Service service = (PackageParser.Service)label; 8100 out.print(prefix); out.print( 8101 Integer.toHexString(System.identityHashCode(service))); 8102 out.print(' '); 8103 service.printComponentShortName(out); 8104 if (count > 1) { 8105 out.print(" ("); out.print(count); out.print(" filters)"); 8106 } 8107 out.println(); 8108 } 8109 8110// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8111// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8112// final List<ResolveInfo> retList = Lists.newArrayList(); 8113// while (i.hasNext()) { 8114// final ResolveInfo resolveInfo = (ResolveInfo) i; 8115// if (isEnabledLP(resolveInfo.serviceInfo)) { 8116// retList.add(resolveInfo); 8117// } 8118// } 8119// return retList; 8120// } 8121 8122 // Keys are String (activity class name), values are Activity. 8123 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8124 = new ArrayMap<ComponentName, PackageParser.Service>(); 8125 private int mFlags; 8126 }; 8127 8128 private final class ProviderIntentResolver 8129 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8130 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8131 boolean defaultOnly, int userId) { 8132 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8133 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8134 } 8135 8136 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8137 int userId) { 8138 if (!sUserManager.exists(userId)) 8139 return null; 8140 mFlags = flags; 8141 return super.queryIntent(intent, resolvedType, 8142 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8143 } 8144 8145 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8146 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8147 if (!sUserManager.exists(userId)) 8148 return null; 8149 if (packageProviders == null) { 8150 return null; 8151 } 8152 mFlags = flags; 8153 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8154 final int N = packageProviders.size(); 8155 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8156 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8157 8158 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8159 for (int i = 0; i < N; ++i) { 8160 intentFilters = packageProviders.get(i).intents; 8161 if (intentFilters != null && intentFilters.size() > 0) { 8162 PackageParser.ProviderIntentInfo[] array = 8163 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8164 intentFilters.toArray(array); 8165 listCut.add(array); 8166 } 8167 } 8168 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8169 } 8170 8171 public final void addProvider(PackageParser.Provider p) { 8172 if (mProviders.containsKey(p.getComponentName())) { 8173 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8174 return; 8175 } 8176 8177 mProviders.put(p.getComponentName(), p); 8178 if (DEBUG_SHOW_INFO) { 8179 Log.v(TAG, " " 8180 + (p.info.nonLocalizedLabel != null 8181 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8182 Log.v(TAG, " Class=" + p.info.name); 8183 } 8184 final int NI = p.intents.size(); 8185 int j; 8186 for (j = 0; j < NI; j++) { 8187 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8188 if (DEBUG_SHOW_INFO) { 8189 Log.v(TAG, " IntentFilter:"); 8190 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8191 } 8192 if (!intent.debugCheck()) { 8193 Log.w(TAG, "==> For Provider " + p.info.name); 8194 } 8195 addFilter(intent); 8196 } 8197 } 8198 8199 public final void removeProvider(PackageParser.Provider p) { 8200 mProviders.remove(p.getComponentName()); 8201 if (DEBUG_SHOW_INFO) { 8202 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8203 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8204 Log.v(TAG, " Class=" + p.info.name); 8205 } 8206 final int NI = p.intents.size(); 8207 int j; 8208 for (j = 0; j < NI; j++) { 8209 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8210 if (DEBUG_SHOW_INFO) { 8211 Log.v(TAG, " IntentFilter:"); 8212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8213 } 8214 removeFilter(intent); 8215 } 8216 } 8217 8218 @Override 8219 protected boolean allowFilterResult( 8220 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8221 ProviderInfo filterPi = filter.provider.info; 8222 for (int i = dest.size() - 1; i >= 0; i--) { 8223 ProviderInfo destPi = dest.get(i).providerInfo; 8224 if (destPi.name == filterPi.name 8225 && destPi.packageName == filterPi.packageName) { 8226 return false; 8227 } 8228 } 8229 return true; 8230 } 8231 8232 @Override 8233 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8234 return new PackageParser.ProviderIntentInfo[size]; 8235 } 8236 8237 @Override 8238 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8239 if (!sUserManager.exists(userId)) 8240 return true; 8241 PackageParser.Package p = filter.provider.owner; 8242 if (p != null) { 8243 PackageSetting ps = (PackageSetting) p.mExtras; 8244 if (ps != null) { 8245 // System apps are never considered stopped for purposes of 8246 // filtering, because there may be no way for the user to 8247 // actually re-launch them. 8248 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8249 && ps.getStopped(userId); 8250 } 8251 } 8252 return false; 8253 } 8254 8255 @Override 8256 protected boolean isPackageForFilter(String packageName, 8257 PackageParser.ProviderIntentInfo info) { 8258 return packageName.equals(info.provider.owner.packageName); 8259 } 8260 8261 @Override 8262 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8263 int match, int userId) { 8264 if (!sUserManager.exists(userId)) 8265 return null; 8266 final PackageParser.ProviderIntentInfo info = filter; 8267 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8268 return null; 8269 } 8270 final PackageParser.Provider provider = info.provider; 8271 if (mSafeMode && (provider.info.applicationInfo.flags 8272 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8273 return null; 8274 } 8275 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8276 if (ps == null) { 8277 return null; 8278 } 8279 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8280 ps.readUserState(userId), userId); 8281 if (pi == null) { 8282 return null; 8283 } 8284 final ResolveInfo res = new ResolveInfo(); 8285 res.providerInfo = pi; 8286 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8287 res.filter = filter; 8288 } 8289 res.priority = info.getPriority(); 8290 res.preferredOrder = provider.owner.mPreferredOrder; 8291 res.match = match; 8292 res.isDefault = info.hasDefault; 8293 res.labelRes = info.labelRes; 8294 res.nonLocalizedLabel = info.nonLocalizedLabel; 8295 res.icon = info.icon; 8296 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8297 return res; 8298 } 8299 8300 @Override 8301 protected void sortResults(List<ResolveInfo> results) { 8302 Collections.sort(results, mResolvePrioritySorter); 8303 } 8304 8305 @Override 8306 protected void dumpFilter(PrintWriter out, String prefix, 8307 PackageParser.ProviderIntentInfo filter) { 8308 out.print(prefix); 8309 out.print( 8310 Integer.toHexString(System.identityHashCode(filter.provider))); 8311 out.print(' '); 8312 filter.provider.printComponentShortName(out); 8313 out.print(" filter "); 8314 out.println(Integer.toHexString(System.identityHashCode(filter))); 8315 } 8316 8317 @Override 8318 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8319 return filter.provider; 8320 } 8321 8322 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8323 PackageParser.Provider provider = (PackageParser.Provider)label; 8324 out.print(prefix); out.print( 8325 Integer.toHexString(System.identityHashCode(provider))); 8326 out.print(' '); 8327 provider.printComponentShortName(out); 8328 if (count > 1) { 8329 out.print(" ("); out.print(count); out.print(" filters)"); 8330 } 8331 out.println(); 8332 } 8333 8334 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8335 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8336 private int mFlags; 8337 }; 8338 8339 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8340 new Comparator<ResolveInfo>() { 8341 public int compare(ResolveInfo r1, ResolveInfo r2) { 8342 int v1 = r1.priority; 8343 int v2 = r2.priority; 8344 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8345 if (v1 != v2) { 8346 return (v1 > v2) ? -1 : 1; 8347 } 8348 v1 = r1.preferredOrder; 8349 v2 = r2.preferredOrder; 8350 if (v1 != v2) { 8351 return (v1 > v2) ? -1 : 1; 8352 } 8353 if (r1.isDefault != r2.isDefault) { 8354 return r1.isDefault ? -1 : 1; 8355 } 8356 v1 = r1.match; 8357 v2 = r2.match; 8358 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8359 if (v1 != v2) { 8360 return (v1 > v2) ? -1 : 1; 8361 } 8362 if (r1.system != r2.system) { 8363 return r1.system ? -1 : 1; 8364 } 8365 return 0; 8366 } 8367 }; 8368 8369 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8370 new Comparator<ProviderInfo>() { 8371 public int compare(ProviderInfo p1, ProviderInfo p2) { 8372 final int v1 = p1.initOrder; 8373 final int v2 = p2.initOrder; 8374 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8375 } 8376 }; 8377 8378 static final void sendPackageBroadcast(String action, String pkg, 8379 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8380 int[] userIds) { 8381 IActivityManager am = ActivityManagerNative.getDefault(); 8382 if (am != null) { 8383 try { 8384 if (userIds == null) { 8385 userIds = am.getRunningUserIds(); 8386 } 8387 for (int id : userIds) { 8388 final Intent intent = new Intent(action, 8389 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8390 if (extras != null) { 8391 intent.putExtras(extras); 8392 } 8393 if (targetPkg != null) { 8394 intent.setPackage(targetPkg); 8395 } 8396 // Modify the UID when posting to other users 8397 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8398 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8399 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8400 intent.putExtra(Intent.EXTRA_UID, uid); 8401 } 8402 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8403 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8404 if (DEBUG_BROADCASTS) { 8405 RuntimeException here = new RuntimeException("here"); 8406 here.fillInStackTrace(); 8407 Slog.d(TAG, "Sending to user " + id + ": " 8408 + intent.toShortString(false, true, false, false) 8409 + " " + intent.getExtras(), here); 8410 } 8411 am.broadcastIntent(null, intent, null, finishedReceiver, 8412 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8413 finishedReceiver != null, false, id); 8414 } 8415 } catch (RemoteException ex) { 8416 } 8417 } 8418 } 8419 8420 /** 8421 * Check if the external storage media is available. This is true if there 8422 * is a mounted external storage medium or if the external storage is 8423 * emulated. 8424 */ 8425 private boolean isExternalMediaAvailable() { 8426 return mMediaMounted || Environment.isExternalStorageEmulated(); 8427 } 8428 8429 @Override 8430 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8431 // writer 8432 synchronized (mPackages) { 8433 if (!isExternalMediaAvailable()) { 8434 // If the external storage is no longer mounted at this point, 8435 // the caller may not have been able to delete all of this 8436 // packages files and can not delete any more. Bail. 8437 return null; 8438 } 8439 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8440 if (lastPackage != null) { 8441 pkgs.remove(lastPackage); 8442 } 8443 if (pkgs.size() > 0) { 8444 return pkgs.get(0); 8445 } 8446 } 8447 return null; 8448 } 8449 8450 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8451 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8452 userId, andCode ? 1 : 0, packageName); 8453 if (mSystemReady) { 8454 msg.sendToTarget(); 8455 } else { 8456 if (mPostSystemReadyMessages == null) { 8457 mPostSystemReadyMessages = new ArrayList<>(); 8458 } 8459 mPostSystemReadyMessages.add(msg); 8460 } 8461 } 8462 8463 void startCleaningPackages() { 8464 // reader 8465 synchronized (mPackages) { 8466 if (!isExternalMediaAvailable()) { 8467 return; 8468 } 8469 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8470 return; 8471 } 8472 } 8473 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8474 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8475 IActivityManager am = ActivityManagerNative.getDefault(); 8476 if (am != null) { 8477 try { 8478 am.startService(null, intent, null, UserHandle.USER_OWNER); 8479 } catch (RemoteException e) { 8480 } 8481 } 8482 } 8483 8484 @Override 8485 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8486 int installFlags, String installerPackageName, VerificationParams verificationParams, 8487 String packageAbiOverride) { 8488 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8489 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8490 } 8491 8492 @Override 8493 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8494 int installFlags, String installerPackageName, VerificationParams verificationParams, 8495 String packageAbiOverride, int userId) { 8496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8497 8498 final int callingUid = Binder.getCallingUid(); 8499 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8500 8501 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8502 try { 8503 if (observer != null) { 8504 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8505 } 8506 } catch (RemoteException re) { 8507 } 8508 return; 8509 } 8510 8511 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8512 installFlags |= PackageManager.INSTALL_FROM_ADB; 8513 8514 } else { 8515 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8516 // about installerPackageName. 8517 8518 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8519 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8520 } 8521 8522 UserHandle user; 8523 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8524 user = UserHandle.ALL; 8525 } else { 8526 user = new UserHandle(userId); 8527 } 8528 8529 verificationParams.setInstallerUid(callingUid); 8530 8531 final File originFile = new File(originPath); 8532 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8533 8534 final Message msg = mHandler.obtainMessage(INIT_COPY); 8535 msg.obj = new InstallParams(origin, observer, installFlags, 8536 installerPackageName, null, verificationParams, user, packageAbiOverride); 8537 mHandler.sendMessage(msg); 8538 } 8539 8540 void installStage(String packageName, File stagedDir, String stagedCid, 8541 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8542 String installerPackageName, int installerUid, UserHandle user) { 8543 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8544 params.referrerUri, installerUid, null); 8545 8546 final OriginInfo origin; 8547 if (stagedDir != null) { 8548 origin = OriginInfo.fromStagedFile(stagedDir); 8549 } else { 8550 origin = OriginInfo.fromStagedContainer(stagedCid); 8551 } 8552 8553 final Message msg = mHandler.obtainMessage(INIT_COPY); 8554 msg.obj = new InstallParams(origin, observer, params.installFlags, 8555 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8556 mHandler.sendMessage(msg); 8557 } 8558 8559 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8560 Bundle extras = new Bundle(1); 8561 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8562 8563 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8564 packageName, extras, null, null, new int[] {userId}); 8565 try { 8566 IActivityManager am = ActivityManagerNative.getDefault(); 8567 final boolean isSystem = 8568 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8569 if (isSystem && am.isUserRunning(userId, false)) { 8570 // The just-installed/enabled app is bundled on the system, so presumed 8571 // to be able to run automatically without needing an explicit launch. 8572 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8573 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8574 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8575 .setPackage(packageName); 8576 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8577 android.app.AppOpsManager.OP_NONE, false, false, userId); 8578 } 8579 } catch (RemoteException e) { 8580 // shouldn't happen 8581 Slog.w(TAG, "Unable to bootstrap installed package", e); 8582 } 8583 } 8584 8585 @Override 8586 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8587 int userId) { 8588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8589 PackageSetting pkgSetting; 8590 final int uid = Binder.getCallingUid(); 8591 enforceCrossUserPermission(uid, userId, true, true, 8592 "setApplicationHiddenSetting for user " + userId); 8593 8594 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8595 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8596 return false; 8597 } 8598 8599 long callingId = Binder.clearCallingIdentity(); 8600 try { 8601 boolean sendAdded = false; 8602 boolean sendRemoved = false; 8603 // writer 8604 synchronized (mPackages) { 8605 pkgSetting = mSettings.mPackages.get(packageName); 8606 if (pkgSetting == null) { 8607 return false; 8608 } 8609 if (pkgSetting.getHidden(userId) != hidden) { 8610 pkgSetting.setHidden(hidden, userId); 8611 mSettings.writePackageRestrictionsLPr(userId); 8612 if (hidden) { 8613 sendRemoved = true; 8614 } else { 8615 sendAdded = true; 8616 } 8617 } 8618 } 8619 if (sendAdded) { 8620 sendPackageAddedForUser(packageName, pkgSetting, userId); 8621 return true; 8622 } 8623 if (sendRemoved) { 8624 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8625 "hiding pkg"); 8626 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8627 } 8628 } finally { 8629 Binder.restoreCallingIdentity(callingId); 8630 } 8631 return false; 8632 } 8633 8634 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8635 int userId) { 8636 final PackageRemovedInfo info = new PackageRemovedInfo(); 8637 info.removedPackage = packageName; 8638 info.removedUsers = new int[] {userId}; 8639 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8640 info.sendBroadcast(false, false, false); 8641 } 8642 8643 /** 8644 * Returns true if application is not found or there was an error. Otherwise it returns 8645 * the hidden state of the package for the given user. 8646 */ 8647 @Override 8648 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8649 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8650 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8651 false, "getApplicationHidden for user " + userId); 8652 PackageSetting pkgSetting; 8653 long callingId = Binder.clearCallingIdentity(); 8654 try { 8655 // writer 8656 synchronized (mPackages) { 8657 pkgSetting = mSettings.mPackages.get(packageName); 8658 if (pkgSetting == null) { 8659 return true; 8660 } 8661 return pkgSetting.getHidden(userId); 8662 } 8663 } finally { 8664 Binder.restoreCallingIdentity(callingId); 8665 } 8666 } 8667 8668 /** 8669 * @hide 8670 */ 8671 @Override 8672 public int installExistingPackageAsUser(String packageName, int userId) { 8673 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8674 null); 8675 PackageSetting pkgSetting; 8676 final int uid = Binder.getCallingUid(); 8677 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8678 + userId); 8679 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8680 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8681 } 8682 8683 long callingId = Binder.clearCallingIdentity(); 8684 try { 8685 boolean sendAdded = false; 8686 Bundle extras = new Bundle(1); 8687 8688 // writer 8689 synchronized (mPackages) { 8690 pkgSetting = mSettings.mPackages.get(packageName); 8691 if (pkgSetting == null) { 8692 return PackageManager.INSTALL_FAILED_INVALID_URI; 8693 } 8694 if (!pkgSetting.getInstalled(userId)) { 8695 pkgSetting.setInstalled(true, userId); 8696 pkgSetting.setHidden(false, userId); 8697 mSettings.writePackageRestrictionsLPr(userId); 8698 sendAdded = true; 8699 } 8700 } 8701 8702 if (sendAdded) { 8703 sendPackageAddedForUser(packageName, pkgSetting, userId); 8704 } 8705 } finally { 8706 Binder.restoreCallingIdentity(callingId); 8707 } 8708 8709 return PackageManager.INSTALL_SUCCEEDED; 8710 } 8711 8712 boolean isUserRestricted(int userId, String restrictionKey) { 8713 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8714 if (restrictions.getBoolean(restrictionKey, false)) { 8715 Log.w(TAG, "User is restricted: " + restrictionKey); 8716 return true; 8717 } 8718 return false; 8719 } 8720 8721 @Override 8722 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8723 mContext.enforceCallingOrSelfPermission( 8724 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8725 "Only package verification agents can verify applications"); 8726 8727 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8728 final PackageVerificationResponse response = new PackageVerificationResponse( 8729 verificationCode, Binder.getCallingUid()); 8730 msg.arg1 = id; 8731 msg.obj = response; 8732 mHandler.sendMessage(msg); 8733 } 8734 8735 @Override 8736 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8737 long millisecondsToDelay) { 8738 mContext.enforceCallingOrSelfPermission( 8739 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8740 "Only package verification agents can extend verification timeouts"); 8741 8742 final PackageVerificationState state = mPendingVerification.get(id); 8743 final PackageVerificationResponse response = new PackageVerificationResponse( 8744 verificationCodeAtTimeout, Binder.getCallingUid()); 8745 8746 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8747 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8748 } 8749 if (millisecondsToDelay < 0) { 8750 millisecondsToDelay = 0; 8751 } 8752 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8753 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8754 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8755 } 8756 8757 if ((state != null) && !state.timeoutExtended()) { 8758 state.extendTimeout(); 8759 8760 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8761 msg.arg1 = id; 8762 msg.obj = response; 8763 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8764 } 8765 } 8766 8767 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8768 int verificationCode, UserHandle user) { 8769 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8770 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8771 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8772 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8773 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8774 8775 mContext.sendBroadcastAsUser(intent, user, 8776 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8777 } 8778 8779 private ComponentName matchComponentForVerifier(String packageName, 8780 List<ResolveInfo> receivers) { 8781 ActivityInfo targetReceiver = null; 8782 8783 final int NR = receivers.size(); 8784 for (int i = 0; i < NR; i++) { 8785 final ResolveInfo info = receivers.get(i); 8786 if (info.activityInfo == null) { 8787 continue; 8788 } 8789 8790 if (packageName.equals(info.activityInfo.packageName)) { 8791 targetReceiver = info.activityInfo; 8792 break; 8793 } 8794 } 8795 8796 if (targetReceiver == null) { 8797 return null; 8798 } 8799 8800 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8801 } 8802 8803 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8804 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8805 if (pkgInfo.verifiers.length == 0) { 8806 return null; 8807 } 8808 8809 final int N = pkgInfo.verifiers.length; 8810 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8811 for (int i = 0; i < N; i++) { 8812 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8813 8814 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8815 receivers); 8816 if (comp == null) { 8817 continue; 8818 } 8819 8820 final int verifierUid = getUidForVerifier(verifierInfo); 8821 if (verifierUid == -1) { 8822 continue; 8823 } 8824 8825 if (DEBUG_VERIFY) { 8826 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8827 + " with the correct signature"); 8828 } 8829 sufficientVerifiers.add(comp); 8830 verificationState.addSufficientVerifier(verifierUid); 8831 } 8832 8833 return sufficientVerifiers; 8834 } 8835 8836 private int getUidForVerifier(VerifierInfo verifierInfo) { 8837 synchronized (mPackages) { 8838 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8839 if (pkg == null) { 8840 return -1; 8841 } else if (pkg.mSignatures.length != 1) { 8842 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8843 + " has more than one signature; ignoring"); 8844 return -1; 8845 } 8846 8847 /* 8848 * If the public key of the package's signature does not match 8849 * our expected public key, then this is a different package and 8850 * we should skip. 8851 */ 8852 8853 final byte[] expectedPublicKey; 8854 try { 8855 final Signature verifierSig = pkg.mSignatures[0]; 8856 final PublicKey publicKey = verifierSig.getPublicKey(); 8857 expectedPublicKey = publicKey.getEncoded(); 8858 } catch (CertificateException e) { 8859 return -1; 8860 } 8861 8862 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8863 8864 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8865 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8866 + " does not have the expected public key; ignoring"); 8867 return -1; 8868 } 8869 8870 return pkg.applicationInfo.uid; 8871 } 8872 } 8873 8874 @Override 8875 public void finishPackageInstall(int token) { 8876 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8877 8878 if (DEBUG_INSTALL) { 8879 Slog.v(TAG, "BM finishing package install for " + token); 8880 } 8881 8882 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8883 mHandler.sendMessage(msg); 8884 } 8885 8886 /** 8887 * Get the verification agent timeout. 8888 * 8889 * @return verification timeout in milliseconds 8890 */ 8891 private long getVerificationTimeout() { 8892 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8893 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8894 DEFAULT_VERIFICATION_TIMEOUT); 8895 } 8896 8897 /** 8898 * Get the default verification agent response code. 8899 * 8900 * @return default verification response code 8901 */ 8902 private int getDefaultVerificationResponse() { 8903 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8904 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8905 DEFAULT_VERIFICATION_RESPONSE); 8906 } 8907 8908 /** 8909 * Check whether or not package verification has been enabled. 8910 * 8911 * @return true if verification should be performed 8912 */ 8913 private boolean isVerificationEnabled(int userId, int installFlags) { 8914 if (!DEFAULT_VERIFY_ENABLE) { 8915 return false; 8916 } 8917 8918 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8919 8920 // Check if installing from ADB 8921 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8922 // Do not run verification in a test harness environment 8923 if (ActivityManager.isRunningInTestHarness()) { 8924 return false; 8925 } 8926 if (ensureVerifyAppsEnabled) { 8927 return true; 8928 } 8929 // Check if the developer does not want package verification for ADB installs 8930 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8931 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8932 return false; 8933 } 8934 } 8935 8936 if (ensureVerifyAppsEnabled) { 8937 return true; 8938 } 8939 8940 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8941 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8942 } 8943 8944 @Override 8945 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 8946 throws RemoteException { 8947 mContext.enforceCallingOrSelfPermission( 8948 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8949 "Only intentfilter verification agents can verify applications"); 8950 8951 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8952 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8953 Binder.getCallingUid(), verificationCode, failedDomains); 8954 msg.arg1 = id; 8955 msg.obj = response; 8956 mHandler.sendMessage(msg); 8957 } 8958 8959 @Override 8960 public int getIntentVerificationStatus(String packageName, int userId) { 8961 synchronized (mPackages) { 8962 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8963 } 8964 } 8965 8966 @Override 8967 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8968 boolean result = false; 8969 synchronized (mPackages) { 8970 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8971 } 8972 scheduleWritePackageRestrictionsLocked(userId); 8973 return result; 8974 } 8975 8976 @Override 8977 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8978 synchronized (mPackages) { 8979 return mSettings.getIntentFilterVerificationsLPr(packageName); 8980 } 8981 } 8982 8983 /** 8984 * Get the "allow unknown sources" setting. 8985 * 8986 * @return the current "allow unknown sources" setting 8987 */ 8988 private int getUnknownSourcesSettings() { 8989 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8990 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8991 -1); 8992 } 8993 8994 @Override 8995 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8996 final int uid = Binder.getCallingUid(); 8997 // writer 8998 synchronized (mPackages) { 8999 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9000 if (targetPackageSetting == null) { 9001 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9002 } 9003 9004 PackageSetting installerPackageSetting; 9005 if (installerPackageName != null) { 9006 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9007 if (installerPackageSetting == null) { 9008 throw new IllegalArgumentException("Unknown installer package: " 9009 + installerPackageName); 9010 } 9011 } else { 9012 installerPackageSetting = null; 9013 } 9014 9015 Signature[] callerSignature; 9016 Object obj = mSettings.getUserIdLPr(uid); 9017 if (obj != null) { 9018 if (obj instanceof SharedUserSetting) { 9019 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9020 } else if (obj instanceof PackageSetting) { 9021 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9022 } else { 9023 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9024 } 9025 } else { 9026 throw new SecurityException("Unknown calling uid " + uid); 9027 } 9028 9029 // Verify: can't set installerPackageName to a package that is 9030 // not signed with the same cert as the caller. 9031 if (installerPackageSetting != null) { 9032 if (compareSignatures(callerSignature, 9033 installerPackageSetting.signatures.mSignatures) 9034 != PackageManager.SIGNATURE_MATCH) { 9035 throw new SecurityException( 9036 "Caller does not have same cert as new installer package " 9037 + installerPackageName); 9038 } 9039 } 9040 9041 // Verify: if target already has an installer package, it must 9042 // be signed with the same cert as the caller. 9043 if (targetPackageSetting.installerPackageName != null) { 9044 PackageSetting setting = mSettings.mPackages.get( 9045 targetPackageSetting.installerPackageName); 9046 // If the currently set package isn't valid, then it's always 9047 // okay to change it. 9048 if (setting != null) { 9049 if (compareSignatures(callerSignature, 9050 setting.signatures.mSignatures) 9051 != PackageManager.SIGNATURE_MATCH) { 9052 throw new SecurityException( 9053 "Caller does not have same cert as old installer package " 9054 + targetPackageSetting.installerPackageName); 9055 } 9056 } 9057 } 9058 9059 // Okay! 9060 targetPackageSetting.installerPackageName = installerPackageName; 9061 scheduleWriteSettingsLocked(); 9062 } 9063 } 9064 9065 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9066 // Queue up an async operation since the package installation may take a little while. 9067 mHandler.post(new Runnable() { 9068 public void run() { 9069 mHandler.removeCallbacks(this); 9070 // Result object to be returned 9071 PackageInstalledInfo res = new PackageInstalledInfo(); 9072 res.returnCode = currentStatus; 9073 res.uid = -1; 9074 res.pkg = null; 9075 res.removedInfo = new PackageRemovedInfo(); 9076 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9077 args.doPreInstall(res.returnCode); 9078 synchronized (mInstallLock) { 9079 installPackageLI(args, res); 9080 } 9081 args.doPostInstall(res.returnCode, res.uid); 9082 } 9083 9084 // A restore should be performed at this point if (a) the install 9085 // succeeded, (b) the operation is not an update, and (c) the new 9086 // package has not opted out of backup participation. 9087 final boolean update = res.removedInfo.removedPackage != null; 9088 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9089 boolean doRestore = !update 9090 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9091 9092 // Set up the post-install work request bookkeeping. This will be used 9093 // and cleaned up by the post-install event handling regardless of whether 9094 // there's a restore pass performed. Token values are >= 1. 9095 int token; 9096 if (mNextInstallToken < 0) mNextInstallToken = 1; 9097 token = mNextInstallToken++; 9098 9099 PostInstallData data = new PostInstallData(args, res); 9100 mRunningInstalls.put(token, data); 9101 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9102 9103 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9104 // Pass responsibility to the Backup Manager. It will perform a 9105 // restore if appropriate, then pass responsibility back to the 9106 // Package Manager to run the post-install observer callbacks 9107 // and broadcasts. 9108 IBackupManager bm = IBackupManager.Stub.asInterface( 9109 ServiceManager.getService(Context.BACKUP_SERVICE)); 9110 if (bm != null) { 9111 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9112 + " to BM for possible restore"); 9113 try { 9114 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9115 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9116 } else { 9117 doRestore = false; 9118 } 9119 } catch (RemoteException e) { 9120 // can't happen; the backup manager is local 9121 } catch (Exception e) { 9122 Slog.e(TAG, "Exception trying to enqueue restore", e); 9123 doRestore = false; 9124 } 9125 } else { 9126 Slog.e(TAG, "Backup Manager not found!"); 9127 doRestore = false; 9128 } 9129 } 9130 9131 if (!doRestore) { 9132 // No restore possible, or the Backup Manager was mysteriously not 9133 // available -- just fire the post-install work request directly. 9134 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9135 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9136 mHandler.sendMessage(msg); 9137 } 9138 } 9139 }); 9140 } 9141 9142 private abstract class HandlerParams { 9143 private static final int MAX_RETRIES = 4; 9144 9145 /** 9146 * Number of times startCopy() has been attempted and had a non-fatal 9147 * error. 9148 */ 9149 private int mRetries = 0; 9150 9151 /** User handle for the user requesting the information or installation. */ 9152 private final UserHandle mUser; 9153 9154 HandlerParams(UserHandle user) { 9155 mUser = user; 9156 } 9157 9158 UserHandle getUser() { 9159 return mUser; 9160 } 9161 9162 final boolean startCopy() { 9163 boolean res; 9164 try { 9165 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9166 9167 if (++mRetries > MAX_RETRIES) { 9168 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9169 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9170 handleServiceError(); 9171 return false; 9172 } else { 9173 handleStartCopy(); 9174 res = true; 9175 } 9176 } catch (RemoteException e) { 9177 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9178 mHandler.sendEmptyMessage(MCS_RECONNECT); 9179 res = false; 9180 } 9181 handleReturnCode(); 9182 return res; 9183 } 9184 9185 final void serviceError() { 9186 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9187 handleServiceError(); 9188 handleReturnCode(); 9189 } 9190 9191 abstract void handleStartCopy() throws RemoteException; 9192 abstract void handleServiceError(); 9193 abstract void handleReturnCode(); 9194 } 9195 9196 class MeasureParams extends HandlerParams { 9197 private final PackageStats mStats; 9198 private boolean mSuccess; 9199 9200 private final IPackageStatsObserver mObserver; 9201 9202 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9203 super(new UserHandle(stats.userHandle)); 9204 mObserver = observer; 9205 mStats = stats; 9206 } 9207 9208 @Override 9209 public String toString() { 9210 return "MeasureParams{" 9211 + Integer.toHexString(System.identityHashCode(this)) 9212 + " " + mStats.packageName + "}"; 9213 } 9214 9215 @Override 9216 void handleStartCopy() throws RemoteException { 9217 synchronized (mInstallLock) { 9218 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9219 } 9220 9221 if (mSuccess) { 9222 final boolean mounted; 9223 if (Environment.isExternalStorageEmulated()) { 9224 mounted = true; 9225 } else { 9226 final String status = Environment.getExternalStorageState(); 9227 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9228 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9229 } 9230 9231 if (mounted) { 9232 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9233 9234 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9235 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9236 9237 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9238 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9239 9240 // Always subtract cache size, since it's a subdirectory 9241 mStats.externalDataSize -= mStats.externalCacheSize; 9242 9243 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9244 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9245 9246 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9247 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9248 } 9249 } 9250 } 9251 9252 @Override 9253 void handleReturnCode() { 9254 if (mObserver != null) { 9255 try { 9256 mObserver.onGetStatsCompleted(mStats, mSuccess); 9257 } catch (RemoteException e) { 9258 Slog.i(TAG, "Observer no longer exists."); 9259 } 9260 } 9261 } 9262 9263 @Override 9264 void handleServiceError() { 9265 Slog.e(TAG, "Could not measure application " + mStats.packageName 9266 + " external storage"); 9267 } 9268 } 9269 9270 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9271 throws RemoteException { 9272 long result = 0; 9273 for (File path : paths) { 9274 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9275 } 9276 return result; 9277 } 9278 9279 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9280 for (File path : paths) { 9281 try { 9282 mcs.clearDirectory(path.getAbsolutePath()); 9283 } catch (RemoteException e) { 9284 } 9285 } 9286 } 9287 9288 static class OriginInfo { 9289 /** 9290 * Location where install is coming from, before it has been 9291 * copied/renamed into place. This could be a single monolithic APK 9292 * file, or a cluster directory. This location may be untrusted. 9293 */ 9294 final File file; 9295 final String cid; 9296 9297 /** 9298 * Flag indicating that {@link #file} or {@link #cid} has already been 9299 * staged, meaning downstream users don't need to defensively copy the 9300 * contents. 9301 */ 9302 final boolean staged; 9303 9304 /** 9305 * Flag indicating that {@link #file} or {@link #cid} is an already 9306 * installed app that is being moved. 9307 */ 9308 final boolean existing; 9309 9310 final String resolvedPath; 9311 final File resolvedFile; 9312 9313 static OriginInfo fromNothing() { 9314 return new OriginInfo(null, null, false, false); 9315 } 9316 9317 static OriginInfo fromUntrustedFile(File file) { 9318 return new OriginInfo(file, null, false, false); 9319 } 9320 9321 static OriginInfo fromExistingFile(File file) { 9322 return new OriginInfo(file, null, false, true); 9323 } 9324 9325 static OriginInfo fromStagedFile(File file) { 9326 return new OriginInfo(file, null, true, false); 9327 } 9328 9329 static OriginInfo fromStagedContainer(String cid) { 9330 return new OriginInfo(null, cid, true, false); 9331 } 9332 9333 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9334 this.file = file; 9335 this.cid = cid; 9336 this.staged = staged; 9337 this.existing = existing; 9338 9339 if (cid != null) { 9340 resolvedPath = PackageHelper.getSdDir(cid); 9341 resolvedFile = new File(resolvedPath); 9342 } else if (file != null) { 9343 resolvedPath = file.getAbsolutePath(); 9344 resolvedFile = file; 9345 } else { 9346 resolvedPath = null; 9347 resolvedFile = null; 9348 } 9349 } 9350 } 9351 9352 class InstallParams extends HandlerParams { 9353 final OriginInfo origin; 9354 final IPackageInstallObserver2 observer; 9355 int installFlags; 9356 final String installerPackageName; 9357 final String volumeUuid; 9358 final VerificationParams verificationParams; 9359 private InstallArgs mArgs; 9360 private int mRet; 9361 final String packageAbiOverride; 9362 9363 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9364 String installerPackageName, String volumeUuid, 9365 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9366 super(user); 9367 this.origin = origin; 9368 this.observer = observer; 9369 this.installFlags = installFlags; 9370 this.installerPackageName = installerPackageName; 9371 this.volumeUuid = volumeUuid; 9372 this.verificationParams = verificationParams; 9373 this.packageAbiOverride = packageAbiOverride; 9374 } 9375 9376 @Override 9377 public String toString() { 9378 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9379 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9380 } 9381 9382 public ManifestDigest getManifestDigest() { 9383 if (verificationParams == null) { 9384 return null; 9385 } 9386 return verificationParams.getManifestDigest(); 9387 } 9388 9389 private int installLocationPolicy(PackageInfoLite pkgLite) { 9390 String packageName = pkgLite.packageName; 9391 int installLocation = pkgLite.installLocation; 9392 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9393 // reader 9394 synchronized (mPackages) { 9395 PackageParser.Package pkg = mPackages.get(packageName); 9396 if (pkg != null) { 9397 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9398 // Check for downgrading. 9399 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9400 try { 9401 checkDowngrade(pkg, pkgLite); 9402 } catch (PackageManagerException e) { 9403 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9404 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9405 } 9406 } 9407 // Check for updated system application. 9408 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9409 if (onSd) { 9410 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9411 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9412 } 9413 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9414 } else { 9415 if (onSd) { 9416 // Install flag overrides everything. 9417 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9418 } 9419 // If current upgrade specifies particular preference 9420 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9421 // Application explicitly specified internal. 9422 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9423 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9424 // App explictly prefers external. Let policy decide 9425 } else { 9426 // Prefer previous location 9427 if (isExternal(pkg)) { 9428 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9429 } 9430 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9431 } 9432 } 9433 } else { 9434 // Invalid install. Return error code 9435 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9436 } 9437 } 9438 } 9439 // All the special cases have been taken care of. 9440 // Return result based on recommended install location. 9441 if (onSd) { 9442 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9443 } 9444 return pkgLite.recommendedInstallLocation; 9445 } 9446 9447 /* 9448 * Invoke remote method to get package information and install 9449 * location values. Override install location based on default 9450 * policy if needed and then create install arguments based 9451 * on the install location. 9452 */ 9453 public void handleStartCopy() throws RemoteException { 9454 int ret = PackageManager.INSTALL_SUCCEEDED; 9455 9456 // If we're already staged, we've firmly committed to an install location 9457 if (origin.staged) { 9458 if (origin.file != null) { 9459 installFlags |= PackageManager.INSTALL_INTERNAL; 9460 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9461 } else if (origin.cid != null) { 9462 installFlags |= PackageManager.INSTALL_EXTERNAL; 9463 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9464 } else { 9465 throw new IllegalStateException("Invalid stage location"); 9466 } 9467 } 9468 9469 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9470 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9471 9472 PackageInfoLite pkgLite = null; 9473 9474 if (onInt && onSd) { 9475 // Check if both bits are set. 9476 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9477 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9478 } else { 9479 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9480 packageAbiOverride); 9481 9482 /* 9483 * If we have too little free space, try to free cache 9484 * before giving up. 9485 */ 9486 if (!origin.staged && pkgLite.recommendedInstallLocation 9487 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9488 // TODO: focus freeing disk space on the target device 9489 final StorageManager storage = StorageManager.from(mContext); 9490 final long lowThreshold = storage.getStorageLowBytes( 9491 Environment.getDataDirectory()); 9492 9493 final long sizeBytes = mContainerService.calculateInstalledSize( 9494 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9495 9496 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9497 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9498 installFlags, packageAbiOverride); 9499 } 9500 9501 /* 9502 * The cache free must have deleted the file we 9503 * downloaded to install. 9504 * 9505 * TODO: fix the "freeCache" call to not delete 9506 * the file we care about. 9507 */ 9508 if (pkgLite.recommendedInstallLocation 9509 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9510 pkgLite.recommendedInstallLocation 9511 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9512 } 9513 } 9514 } 9515 9516 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9517 int loc = pkgLite.recommendedInstallLocation; 9518 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9519 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9520 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9521 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9522 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9523 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9524 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9525 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9526 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9527 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9528 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9529 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9530 } else { 9531 // Override with defaults if needed. 9532 loc = installLocationPolicy(pkgLite); 9533 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9534 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9535 } else if (!onSd && !onInt) { 9536 // Override install location with flags 9537 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9538 // Set the flag to install on external media. 9539 installFlags |= PackageManager.INSTALL_EXTERNAL; 9540 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9541 } else { 9542 // Make sure the flag for installing on external 9543 // media is unset 9544 installFlags |= PackageManager.INSTALL_INTERNAL; 9545 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9546 } 9547 } 9548 } 9549 } 9550 9551 final InstallArgs args = createInstallArgs(this); 9552 mArgs = args; 9553 9554 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9555 /* 9556 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9557 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9558 */ 9559 int userIdentifier = getUser().getIdentifier(); 9560 if (userIdentifier == UserHandle.USER_ALL 9561 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9562 userIdentifier = UserHandle.USER_OWNER; 9563 } 9564 9565 /* 9566 * Determine if we have any installed package verifiers. If we 9567 * do, then we'll defer to them to verify the packages. 9568 */ 9569 final int requiredUid = mRequiredVerifierPackage == null ? -1 9570 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9571 if (!origin.existing && requiredUid != -1 9572 && isVerificationEnabled(userIdentifier, installFlags)) { 9573 final Intent verification = new Intent( 9574 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9575 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9576 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9577 PACKAGE_MIME_TYPE); 9578 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9579 9580 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9581 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9582 0 /* TODO: Which userId? */); 9583 9584 if (DEBUG_VERIFY) { 9585 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9586 + verification.toString() + " with " + pkgLite.verifiers.length 9587 + " optional verifiers"); 9588 } 9589 9590 final int verificationId = mPendingVerificationToken++; 9591 9592 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9593 9594 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9595 installerPackageName); 9596 9597 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9598 installFlags); 9599 9600 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9601 pkgLite.packageName); 9602 9603 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9604 pkgLite.versionCode); 9605 9606 if (verificationParams != null) { 9607 if (verificationParams.getVerificationURI() != null) { 9608 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9609 verificationParams.getVerificationURI()); 9610 } 9611 if (verificationParams.getOriginatingURI() != null) { 9612 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9613 verificationParams.getOriginatingURI()); 9614 } 9615 if (verificationParams.getReferrer() != null) { 9616 verification.putExtra(Intent.EXTRA_REFERRER, 9617 verificationParams.getReferrer()); 9618 } 9619 if (verificationParams.getOriginatingUid() >= 0) { 9620 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9621 verificationParams.getOriginatingUid()); 9622 } 9623 if (verificationParams.getInstallerUid() >= 0) { 9624 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9625 verificationParams.getInstallerUid()); 9626 } 9627 } 9628 9629 final PackageVerificationState verificationState = new PackageVerificationState( 9630 requiredUid, args); 9631 9632 mPendingVerification.append(verificationId, verificationState); 9633 9634 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9635 receivers, verificationState); 9636 9637 /* 9638 * If any sufficient verifiers were listed in the package 9639 * manifest, attempt to ask them. 9640 */ 9641 if (sufficientVerifiers != null) { 9642 final int N = sufficientVerifiers.size(); 9643 if (N == 0) { 9644 Slog.i(TAG, "Additional verifiers required, but none installed."); 9645 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9646 } else { 9647 for (int i = 0; i < N; i++) { 9648 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9649 9650 final Intent sufficientIntent = new Intent(verification); 9651 sufficientIntent.setComponent(verifierComponent); 9652 9653 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9654 } 9655 } 9656 } 9657 9658 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9659 mRequiredVerifierPackage, receivers); 9660 if (ret == PackageManager.INSTALL_SUCCEEDED 9661 && mRequiredVerifierPackage != null) { 9662 /* 9663 * Send the intent to the required verification agent, 9664 * but only start the verification timeout after the 9665 * target BroadcastReceivers have run. 9666 */ 9667 verification.setComponent(requiredVerifierComponent); 9668 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9669 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9670 new BroadcastReceiver() { 9671 @Override 9672 public void onReceive(Context context, Intent intent) { 9673 final Message msg = mHandler 9674 .obtainMessage(CHECK_PENDING_VERIFICATION); 9675 msg.arg1 = verificationId; 9676 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9677 } 9678 }, null, 0, null, null); 9679 9680 /* 9681 * We don't want the copy to proceed until verification 9682 * succeeds, so null out this field. 9683 */ 9684 mArgs = null; 9685 } 9686 } else { 9687 /* 9688 * No package verification is enabled, so immediately start 9689 * the remote call to initiate copy using temporary file. 9690 */ 9691 ret = args.copyApk(mContainerService, true); 9692 } 9693 } 9694 9695 mRet = ret; 9696 } 9697 9698 @Override 9699 void handleReturnCode() { 9700 // If mArgs is null, then MCS couldn't be reached. When it 9701 // reconnects, it will try again to install. At that point, this 9702 // will succeed. 9703 if (mArgs != null) { 9704 processPendingInstall(mArgs, mRet); 9705 } 9706 } 9707 9708 @Override 9709 void handleServiceError() { 9710 mArgs = createInstallArgs(this); 9711 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9712 } 9713 9714 public boolean isForwardLocked() { 9715 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9716 } 9717 } 9718 9719 /** 9720 * Used during creation of InstallArgs 9721 * 9722 * @param installFlags package installation flags 9723 * @return true if should be installed on external storage 9724 */ 9725 private static boolean installOnExternalAsec(int installFlags) { 9726 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9727 return false; 9728 } 9729 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9730 return true; 9731 } 9732 return false; 9733 } 9734 9735 /** 9736 * Used during creation of InstallArgs 9737 * 9738 * @param installFlags package installation flags 9739 * @return true if should be installed as forward locked 9740 */ 9741 private static boolean installForwardLocked(int installFlags) { 9742 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9743 } 9744 9745 private InstallArgs createInstallArgs(InstallParams params) { 9746 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9747 return new AsecInstallArgs(params); 9748 } else { 9749 return new FileInstallArgs(params); 9750 } 9751 } 9752 9753 /** 9754 * Create args that describe an existing installed package. Typically used 9755 * when cleaning up old installs, or used as a move source. 9756 */ 9757 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9758 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9759 final boolean isInAsec; 9760 if (installOnExternalAsec(installFlags)) { 9761 /* Apps on SD card are always in ASEC containers. */ 9762 isInAsec = true; 9763 } else if (installForwardLocked(installFlags) 9764 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9765 /* 9766 * Forward-locked apps are only in ASEC containers if they're the 9767 * new style 9768 */ 9769 isInAsec = true; 9770 } else { 9771 isInAsec = false; 9772 } 9773 9774 if (isInAsec) { 9775 return new AsecInstallArgs(codePath, instructionSets, 9776 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9777 } else { 9778 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9779 instructionSets); 9780 } 9781 } 9782 9783 static abstract class InstallArgs { 9784 /** @see InstallParams#origin */ 9785 final OriginInfo origin; 9786 9787 final IPackageInstallObserver2 observer; 9788 // Always refers to PackageManager flags only 9789 final int installFlags; 9790 final String installerPackageName; 9791 final String volumeUuid; 9792 final ManifestDigest manifestDigest; 9793 final UserHandle user; 9794 final String abiOverride; 9795 9796 // The list of instruction sets supported by this app. This is currently 9797 // only used during the rmdex() phase to clean up resources. We can get rid of this 9798 // if we move dex files under the common app path. 9799 /* nullable */ String[] instructionSets; 9800 9801 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9802 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9803 UserHandle user, String[] instructionSets, String abiOverride) { 9804 this.origin = origin; 9805 this.installFlags = installFlags; 9806 this.observer = observer; 9807 this.installerPackageName = installerPackageName; 9808 this.volumeUuid = volumeUuid; 9809 this.manifestDigest = manifestDigest; 9810 this.user = user; 9811 this.instructionSets = instructionSets; 9812 this.abiOverride = abiOverride; 9813 } 9814 9815 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9816 abstract int doPreInstall(int status); 9817 9818 /** 9819 * Rename package into final resting place. All paths on the given 9820 * scanned package should be updated to reflect the rename. 9821 */ 9822 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9823 abstract int doPostInstall(int status, int uid); 9824 9825 /** @see PackageSettingBase#codePathString */ 9826 abstract String getCodePath(); 9827 /** @see PackageSettingBase#resourcePathString */ 9828 abstract String getResourcePath(); 9829 abstract String getLegacyNativeLibraryPath(); 9830 9831 // Need installer lock especially for dex file removal. 9832 abstract void cleanUpResourcesLI(); 9833 abstract boolean doPostDeleteLI(boolean delete); 9834 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9835 9836 /** 9837 * Called before the source arguments are copied. This is used mostly 9838 * for MoveParams when it needs to read the source file to put it in the 9839 * destination. 9840 */ 9841 int doPreCopy() { 9842 return PackageManager.INSTALL_SUCCEEDED; 9843 } 9844 9845 /** 9846 * Called after the source arguments are copied. This is used mostly for 9847 * MoveParams when it needs to read the source file to put it in the 9848 * destination. 9849 * 9850 * @return 9851 */ 9852 int doPostCopy(int uid) { 9853 return PackageManager.INSTALL_SUCCEEDED; 9854 } 9855 9856 protected boolean isFwdLocked() { 9857 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9858 } 9859 9860 protected boolean isExternalAsec() { 9861 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9862 } 9863 9864 UserHandle getUser() { 9865 return user; 9866 } 9867 } 9868 9869 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9870 if (!allCodePaths.isEmpty()) { 9871 if (instructionSets == null) { 9872 throw new IllegalStateException("instructionSet == null"); 9873 } 9874 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9875 for (String codePath : allCodePaths) { 9876 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9877 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9878 if (retCode < 0) { 9879 Slog.w(TAG, "Couldn't remove dex file for package: " 9880 + " at location " + codePath + ", retcode=" + retCode); 9881 // we don't consider this to be a failure of the core package deletion 9882 } 9883 } 9884 } 9885 } 9886 } 9887 9888 /** 9889 * Logic to handle installation of non-ASEC applications, including copying 9890 * and renaming logic. 9891 */ 9892 class FileInstallArgs extends InstallArgs { 9893 private File codeFile; 9894 private File resourceFile; 9895 private File legacyNativeLibraryPath; 9896 9897 // Example topology: 9898 // /data/app/com.example/base.apk 9899 // /data/app/com.example/split_foo.apk 9900 // /data/app/com.example/lib/arm/libfoo.so 9901 // /data/app/com.example/lib/arm64/libfoo.so 9902 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9903 9904 /** New install */ 9905 FileInstallArgs(InstallParams params) { 9906 super(params.origin, params.observer, params.installFlags, 9907 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 9908 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 9909 if (isFwdLocked()) { 9910 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9911 } 9912 } 9913 9914 /** Existing install */ 9915 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9916 String[] instructionSets) { 9917 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 9918 this.codeFile = (codePath != null) ? new File(codePath) : null; 9919 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9920 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9921 new File(legacyNativeLibraryPath) : null; 9922 } 9923 9924 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9925 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9926 isFwdLocked(), abiOverride); 9927 9928 final StorageManager storage = StorageManager.from(mContext); 9929 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9930 } 9931 9932 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9933 if (origin.staged) { 9934 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9935 codeFile = origin.file; 9936 resourceFile = origin.file; 9937 return PackageManager.INSTALL_SUCCEEDED; 9938 } 9939 9940 try { 9941 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 9942 codeFile = tempDir; 9943 resourceFile = tempDir; 9944 } catch (IOException e) { 9945 Slog.w(TAG, "Failed to create copy file: " + e); 9946 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9947 } 9948 9949 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9950 @Override 9951 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9952 if (!FileUtils.isValidExtFilename(name)) { 9953 throw new IllegalArgumentException("Invalid filename: " + name); 9954 } 9955 try { 9956 final File file = new File(codeFile, name); 9957 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9958 O_RDWR | O_CREAT, 0644); 9959 Os.chmod(file.getAbsolutePath(), 0644); 9960 return new ParcelFileDescriptor(fd); 9961 } catch (ErrnoException e) { 9962 throw new RemoteException("Failed to open: " + e.getMessage()); 9963 } 9964 } 9965 }; 9966 9967 int ret = PackageManager.INSTALL_SUCCEEDED; 9968 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9969 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9970 Slog.e(TAG, "Failed to copy package"); 9971 return ret; 9972 } 9973 9974 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9975 NativeLibraryHelper.Handle handle = null; 9976 try { 9977 handle = NativeLibraryHelper.Handle.create(codeFile); 9978 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9979 abiOverride); 9980 } catch (IOException e) { 9981 Slog.e(TAG, "Copying native libraries failed", e); 9982 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9983 } finally { 9984 IoUtils.closeQuietly(handle); 9985 } 9986 9987 return ret; 9988 } 9989 9990 int doPreInstall(int status) { 9991 if (status != PackageManager.INSTALL_SUCCEEDED) { 9992 cleanUp(); 9993 } 9994 return status; 9995 } 9996 9997 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9998 if (status != PackageManager.INSTALL_SUCCEEDED) { 9999 cleanUp(); 10000 return false; 10001 } else { 10002 final File targetDir = codeFile.getParentFile(); 10003 final File beforeCodeFile = codeFile; 10004 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10005 10006 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10007 try { 10008 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10009 } catch (ErrnoException e) { 10010 Slog.d(TAG, "Failed to rename", e); 10011 return false; 10012 } 10013 10014 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10015 Slog.d(TAG, "Failed to restorecon"); 10016 return false; 10017 } 10018 10019 // Reflect the rename internally 10020 codeFile = afterCodeFile; 10021 resourceFile = afterCodeFile; 10022 10023 // Reflect the rename in scanned details 10024 pkg.codePath = afterCodeFile.getAbsolutePath(); 10025 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10026 pkg.baseCodePath); 10027 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10028 pkg.splitCodePaths); 10029 10030 // Reflect the rename in app info 10031 pkg.applicationInfo.setCodePath(pkg.codePath); 10032 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10033 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10034 pkg.applicationInfo.setResourcePath(pkg.codePath); 10035 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10036 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10037 10038 return true; 10039 } 10040 } 10041 10042 int doPostInstall(int status, int uid) { 10043 if (status != PackageManager.INSTALL_SUCCEEDED) { 10044 cleanUp(); 10045 } 10046 return status; 10047 } 10048 10049 @Override 10050 String getCodePath() { 10051 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10052 } 10053 10054 @Override 10055 String getResourcePath() { 10056 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10057 } 10058 10059 @Override 10060 String getLegacyNativeLibraryPath() { 10061 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10062 } 10063 10064 private boolean cleanUp() { 10065 if (codeFile == null || !codeFile.exists()) { 10066 return false; 10067 } 10068 10069 if (codeFile.isDirectory()) { 10070 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10071 } else { 10072 codeFile.delete(); 10073 } 10074 10075 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10076 resourceFile.delete(); 10077 } 10078 10079 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10080 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10081 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10082 } 10083 legacyNativeLibraryPath.delete(); 10084 } 10085 10086 return true; 10087 } 10088 10089 void cleanUpResourcesLI() { 10090 // Try enumerating all code paths before deleting 10091 List<String> allCodePaths = Collections.EMPTY_LIST; 10092 if (codeFile != null && codeFile.exists()) { 10093 try { 10094 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10095 allCodePaths = pkg.getAllCodePaths(); 10096 } catch (PackageParserException e) { 10097 // Ignored; we tried our best 10098 } 10099 } 10100 10101 cleanUp(); 10102 removeDexFiles(allCodePaths, instructionSets); 10103 } 10104 10105 boolean doPostDeleteLI(boolean delete) { 10106 // XXX err, shouldn't we respect the delete flag? 10107 cleanUpResourcesLI(); 10108 return true; 10109 } 10110 } 10111 10112 private boolean isAsecExternal(String cid) { 10113 final String asecPath = PackageHelper.getSdFilesystem(cid); 10114 return !asecPath.startsWith(mAsecInternalPath); 10115 } 10116 10117 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10118 PackageManagerException { 10119 if (copyRet < 0) { 10120 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10121 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10122 throw new PackageManagerException(copyRet, message); 10123 } 10124 } 10125 } 10126 10127 /** 10128 * Extract the MountService "container ID" from the full code path of an 10129 * .apk. 10130 */ 10131 static String cidFromCodePath(String fullCodePath) { 10132 int eidx = fullCodePath.lastIndexOf("/"); 10133 String subStr1 = fullCodePath.substring(0, eidx); 10134 int sidx = subStr1.lastIndexOf("/"); 10135 return subStr1.substring(sidx+1, eidx); 10136 } 10137 10138 /** 10139 * Logic to handle installation of ASEC applications, including copying and 10140 * renaming logic. 10141 */ 10142 class AsecInstallArgs extends InstallArgs { 10143 static final String RES_FILE_NAME = "pkg.apk"; 10144 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10145 10146 String cid; 10147 String packagePath; 10148 String resourcePath; 10149 String legacyNativeLibraryDir; 10150 10151 /** New install */ 10152 AsecInstallArgs(InstallParams params) { 10153 super(params.origin, params.observer, params.installFlags, 10154 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10155 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10156 } 10157 10158 /** Existing install */ 10159 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10160 boolean isExternal, boolean isForwardLocked) { 10161 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10162 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10163 instructionSets, null); 10164 // Hackily pretend we're still looking at a full code path 10165 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10166 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10167 } 10168 10169 // Extract cid from fullCodePath 10170 int eidx = fullCodePath.lastIndexOf("/"); 10171 String subStr1 = fullCodePath.substring(0, eidx); 10172 int sidx = subStr1.lastIndexOf("/"); 10173 cid = subStr1.substring(sidx+1, eidx); 10174 setMountPath(subStr1); 10175 } 10176 10177 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10178 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10179 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10180 instructionSets, null); 10181 this.cid = cid; 10182 setMountPath(PackageHelper.getSdDir(cid)); 10183 } 10184 10185 void createCopyFile() { 10186 cid = mInstallerService.allocateExternalStageCidLegacy(); 10187 } 10188 10189 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10190 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10191 abiOverride); 10192 10193 final File target; 10194 if (isExternalAsec()) { 10195 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10196 } else { 10197 target = Environment.getDataDirectory(); 10198 } 10199 10200 final StorageManager storage = StorageManager.from(mContext); 10201 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10202 } 10203 10204 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10205 if (origin.staged) { 10206 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10207 cid = origin.cid; 10208 setMountPath(PackageHelper.getSdDir(cid)); 10209 return PackageManager.INSTALL_SUCCEEDED; 10210 } 10211 10212 if (temp) { 10213 createCopyFile(); 10214 } else { 10215 /* 10216 * Pre-emptively destroy the container since it's destroyed if 10217 * copying fails due to it existing anyway. 10218 */ 10219 PackageHelper.destroySdDir(cid); 10220 } 10221 10222 final String newMountPath = imcs.copyPackageToContainer( 10223 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10224 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10225 10226 if (newMountPath != null) { 10227 setMountPath(newMountPath); 10228 return PackageManager.INSTALL_SUCCEEDED; 10229 } else { 10230 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10231 } 10232 } 10233 10234 @Override 10235 String getCodePath() { 10236 return packagePath; 10237 } 10238 10239 @Override 10240 String getResourcePath() { 10241 return resourcePath; 10242 } 10243 10244 @Override 10245 String getLegacyNativeLibraryPath() { 10246 return legacyNativeLibraryDir; 10247 } 10248 10249 int doPreInstall(int status) { 10250 if (status != PackageManager.INSTALL_SUCCEEDED) { 10251 // Destroy container 10252 PackageHelper.destroySdDir(cid); 10253 } else { 10254 boolean mounted = PackageHelper.isContainerMounted(cid); 10255 if (!mounted) { 10256 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10257 Process.SYSTEM_UID); 10258 if (newMountPath != null) { 10259 setMountPath(newMountPath); 10260 } else { 10261 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10262 } 10263 } 10264 } 10265 return status; 10266 } 10267 10268 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10269 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10270 String newMountPath = null; 10271 if (PackageHelper.isContainerMounted(cid)) { 10272 // Unmount the container 10273 if (!PackageHelper.unMountSdDir(cid)) { 10274 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10275 return false; 10276 } 10277 } 10278 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10279 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10280 " which might be stale. Will try to clean up."); 10281 // Clean up the stale container and proceed to recreate. 10282 if (!PackageHelper.destroySdDir(newCacheId)) { 10283 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10284 return false; 10285 } 10286 // Successfully cleaned up stale container. Try to rename again. 10287 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10288 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10289 + " inspite of cleaning it up."); 10290 return false; 10291 } 10292 } 10293 if (!PackageHelper.isContainerMounted(newCacheId)) { 10294 Slog.w(TAG, "Mounting container " + newCacheId); 10295 newMountPath = PackageHelper.mountSdDir(newCacheId, 10296 getEncryptKey(), Process.SYSTEM_UID); 10297 } else { 10298 newMountPath = PackageHelper.getSdDir(newCacheId); 10299 } 10300 if (newMountPath == null) { 10301 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10302 return false; 10303 } 10304 Log.i(TAG, "Succesfully renamed " + cid + 10305 " to " + newCacheId + 10306 " at new path: " + newMountPath); 10307 cid = newCacheId; 10308 10309 final File beforeCodeFile = new File(packagePath); 10310 setMountPath(newMountPath); 10311 final File afterCodeFile = new File(packagePath); 10312 10313 // Reflect the rename in scanned details 10314 pkg.codePath = afterCodeFile.getAbsolutePath(); 10315 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10316 pkg.baseCodePath); 10317 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10318 pkg.splitCodePaths); 10319 10320 // Reflect the rename in app info 10321 pkg.applicationInfo.setCodePath(pkg.codePath); 10322 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10323 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10324 pkg.applicationInfo.setResourcePath(pkg.codePath); 10325 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10326 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10327 10328 return true; 10329 } 10330 10331 private void setMountPath(String mountPath) { 10332 final File mountFile = new File(mountPath); 10333 10334 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10335 if (monolithicFile.exists()) { 10336 packagePath = monolithicFile.getAbsolutePath(); 10337 if (isFwdLocked()) { 10338 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10339 } else { 10340 resourcePath = packagePath; 10341 } 10342 } else { 10343 packagePath = mountFile.getAbsolutePath(); 10344 resourcePath = packagePath; 10345 } 10346 10347 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10348 } 10349 10350 int doPostInstall(int status, int uid) { 10351 if (status != PackageManager.INSTALL_SUCCEEDED) { 10352 cleanUp(); 10353 } else { 10354 final int groupOwner; 10355 final String protectedFile; 10356 if (isFwdLocked()) { 10357 groupOwner = UserHandle.getSharedAppGid(uid); 10358 protectedFile = RES_FILE_NAME; 10359 } else { 10360 groupOwner = -1; 10361 protectedFile = null; 10362 } 10363 10364 if (uid < Process.FIRST_APPLICATION_UID 10365 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10366 Slog.e(TAG, "Failed to finalize " + cid); 10367 PackageHelper.destroySdDir(cid); 10368 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10369 } 10370 10371 boolean mounted = PackageHelper.isContainerMounted(cid); 10372 if (!mounted) { 10373 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10374 } 10375 } 10376 return status; 10377 } 10378 10379 private void cleanUp() { 10380 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10381 10382 // Destroy secure container 10383 PackageHelper.destroySdDir(cid); 10384 } 10385 10386 private List<String> getAllCodePaths() { 10387 final File codeFile = new File(getCodePath()); 10388 if (codeFile != null && codeFile.exists()) { 10389 try { 10390 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10391 return pkg.getAllCodePaths(); 10392 } catch (PackageParserException e) { 10393 // Ignored; we tried our best 10394 } 10395 } 10396 return Collections.EMPTY_LIST; 10397 } 10398 10399 void cleanUpResourcesLI() { 10400 // Enumerate all code paths before deleting 10401 cleanUpResourcesLI(getAllCodePaths()); 10402 } 10403 10404 private void cleanUpResourcesLI(List<String> allCodePaths) { 10405 cleanUp(); 10406 removeDexFiles(allCodePaths, instructionSets); 10407 } 10408 10409 10410 10411 String getPackageName() { 10412 return getAsecPackageName(cid); 10413 } 10414 10415 boolean doPostDeleteLI(boolean delete) { 10416 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10417 final List<String> allCodePaths = getAllCodePaths(); 10418 boolean mounted = PackageHelper.isContainerMounted(cid); 10419 if (mounted) { 10420 // Unmount first 10421 if (PackageHelper.unMountSdDir(cid)) { 10422 mounted = false; 10423 } 10424 } 10425 if (!mounted && delete) { 10426 cleanUpResourcesLI(allCodePaths); 10427 } 10428 return !mounted; 10429 } 10430 10431 @Override 10432 int doPreCopy() { 10433 if (isFwdLocked()) { 10434 if (!PackageHelper.fixSdPermissions(cid, 10435 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10436 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10437 } 10438 } 10439 10440 return PackageManager.INSTALL_SUCCEEDED; 10441 } 10442 10443 @Override 10444 int doPostCopy(int uid) { 10445 if (isFwdLocked()) { 10446 if (uid < Process.FIRST_APPLICATION_UID 10447 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10448 RES_FILE_NAME)) { 10449 Slog.e(TAG, "Failed to finalize " + cid); 10450 PackageHelper.destroySdDir(cid); 10451 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10452 } 10453 } 10454 10455 return PackageManager.INSTALL_SUCCEEDED; 10456 } 10457 } 10458 10459 static String getAsecPackageName(String packageCid) { 10460 int idx = packageCid.lastIndexOf("-"); 10461 if (idx == -1) { 10462 return packageCid; 10463 } 10464 return packageCid.substring(0, idx); 10465 } 10466 10467 // Utility method used to create code paths based on package name and available index. 10468 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10469 String idxStr = ""; 10470 int idx = 1; 10471 // Fall back to default value of idx=1 if prefix is not 10472 // part of oldCodePath 10473 if (oldCodePath != null) { 10474 String subStr = oldCodePath; 10475 // Drop the suffix right away 10476 if (suffix != null && subStr.endsWith(suffix)) { 10477 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10478 } 10479 // If oldCodePath already contains prefix find out the 10480 // ending index to either increment or decrement. 10481 int sidx = subStr.lastIndexOf(prefix); 10482 if (sidx != -1) { 10483 subStr = subStr.substring(sidx + prefix.length()); 10484 if (subStr != null) { 10485 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10486 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10487 } 10488 try { 10489 idx = Integer.parseInt(subStr); 10490 if (idx <= 1) { 10491 idx++; 10492 } else { 10493 idx--; 10494 } 10495 } catch(NumberFormatException e) { 10496 } 10497 } 10498 } 10499 } 10500 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10501 return prefix + idxStr; 10502 } 10503 10504 private File getNextCodePath(File targetDir, String packageName) { 10505 int suffix = 1; 10506 File result; 10507 do { 10508 result = new File(targetDir, packageName + "-" + suffix); 10509 suffix++; 10510 } while (result.exists()); 10511 return result; 10512 } 10513 10514 // Utility method that returns the relative package path with respect 10515 // to the installation directory. Like say for /data/data/com.test-1.apk 10516 // string com.test-1 is returned. 10517 static String deriveCodePathName(String codePath) { 10518 if (codePath == null) { 10519 return null; 10520 } 10521 final File codeFile = new File(codePath); 10522 final String name = codeFile.getName(); 10523 if (codeFile.isDirectory()) { 10524 return name; 10525 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10526 final int lastDot = name.lastIndexOf('.'); 10527 return name.substring(0, lastDot); 10528 } else { 10529 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10530 return null; 10531 } 10532 } 10533 10534 class PackageInstalledInfo { 10535 String name; 10536 int uid; 10537 // The set of users that originally had this package installed. 10538 int[] origUsers; 10539 // The set of users that now have this package installed. 10540 int[] newUsers; 10541 PackageParser.Package pkg; 10542 int returnCode; 10543 String returnMsg; 10544 PackageRemovedInfo removedInfo; 10545 10546 public void setError(int code, String msg) { 10547 returnCode = code; 10548 returnMsg = msg; 10549 Slog.w(TAG, msg); 10550 } 10551 10552 public void setError(String msg, PackageParserException e) { 10553 returnCode = e.error; 10554 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10555 Slog.w(TAG, msg, e); 10556 } 10557 10558 public void setError(String msg, PackageManagerException e) { 10559 returnCode = e.error; 10560 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10561 Slog.w(TAG, msg, e); 10562 } 10563 10564 // In some error cases we want to convey more info back to the observer 10565 String origPackage; 10566 String origPermission; 10567 } 10568 10569 /* 10570 * Install a non-existing package. 10571 */ 10572 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10573 UserHandle user, String installerPackageName, String volumeUuid, 10574 PackageInstalledInfo res) { 10575 // Remember this for later, in case we need to rollback this install 10576 String pkgName = pkg.packageName; 10577 10578 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10579 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10580 synchronized(mPackages) { 10581 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10582 // A package with the same name is already installed, though 10583 // it has been renamed to an older name. The package we 10584 // are trying to install should be installed as an update to 10585 // the existing one, but that has not been requested, so bail. 10586 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10587 + " without first uninstalling package running as " 10588 + mSettings.mRenamedPackages.get(pkgName)); 10589 return; 10590 } 10591 if (mPackages.containsKey(pkgName)) { 10592 // Don't allow installation over an existing package with the same name. 10593 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10594 + " without first uninstalling."); 10595 return; 10596 } 10597 } 10598 10599 try { 10600 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10601 System.currentTimeMillis(), user); 10602 10603 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10604 // delete the partially installed application. the data directory will have to be 10605 // restored if it was already existing 10606 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10607 // remove package from internal structures. Note that we want deletePackageX to 10608 // delete the package data and cache directories that it created in 10609 // scanPackageLocked, unless those directories existed before we even tried to 10610 // install. 10611 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10612 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10613 res.removedInfo, true); 10614 } 10615 10616 } catch (PackageManagerException e) { 10617 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10618 } 10619 } 10620 10621 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10622 // Upgrade keysets are being used. Determine if new package has a superset of the 10623 // required keys. 10624 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10625 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10626 for (int i = 0; i < upgradeKeySets.length; i++) { 10627 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10628 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10629 return true; 10630 } 10631 } 10632 return false; 10633 } 10634 10635 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10636 UserHandle user, String installerPackageName, String volumeUuid, 10637 PackageInstalledInfo res) { 10638 PackageParser.Package oldPackage; 10639 String pkgName = pkg.packageName; 10640 int[] allUsers; 10641 boolean[] perUserInstalled; 10642 10643 // First find the old package info and check signatures 10644 synchronized(mPackages) { 10645 oldPackage = mPackages.get(pkgName); 10646 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10647 PackageSetting ps = mSettings.mPackages.get(pkgName); 10648 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10649 // default to original signature matching 10650 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10651 != PackageManager.SIGNATURE_MATCH) { 10652 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10653 "New package has a different signature: " + pkgName); 10654 return; 10655 } 10656 } else { 10657 if(!checkUpgradeKeySetLP(ps, pkg)) { 10658 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10659 "New package not signed by keys specified by upgrade-keysets: " 10660 + pkgName); 10661 return; 10662 } 10663 } 10664 10665 // In case of rollback, remember per-user/profile install state 10666 allUsers = sUserManager.getUserIds(); 10667 perUserInstalled = new boolean[allUsers.length]; 10668 for (int i = 0; i < allUsers.length; i++) { 10669 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10670 } 10671 } 10672 10673 boolean sysPkg = (isSystemApp(oldPackage)); 10674 if (sysPkg) { 10675 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10676 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10677 } else { 10678 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10679 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10680 } 10681 } 10682 10683 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10684 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10685 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10686 String volumeUuid, PackageInstalledInfo res) { 10687 String pkgName = deletedPackage.packageName; 10688 boolean deletedPkg = true; 10689 boolean updatedSettings = false; 10690 10691 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10692 + deletedPackage); 10693 long origUpdateTime; 10694 if (pkg.mExtras != null) { 10695 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10696 } else { 10697 origUpdateTime = 0; 10698 } 10699 10700 // First delete the existing package while retaining the data directory 10701 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10702 res.removedInfo, true)) { 10703 // If the existing package wasn't successfully deleted 10704 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10705 deletedPkg = false; 10706 } else { 10707 // Successfully deleted the old package; proceed with replace. 10708 10709 // If deleted package lived in a container, give users a chance to 10710 // relinquish resources before killing. 10711 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10712 if (DEBUG_INSTALL) { 10713 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10714 } 10715 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10716 final ArrayList<String> pkgList = new ArrayList<String>(1); 10717 pkgList.add(deletedPackage.applicationInfo.packageName); 10718 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10719 } 10720 10721 deleteCodeCacheDirsLI(pkgName); 10722 try { 10723 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10724 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10725 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10726 perUserInstalled, res, user); 10727 updatedSettings = true; 10728 } catch (PackageManagerException e) { 10729 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10730 } 10731 } 10732 10733 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10734 // remove package from internal structures. Note that we want deletePackageX to 10735 // delete the package data and cache directories that it created in 10736 // scanPackageLocked, unless those directories existed before we even tried to 10737 // install. 10738 if(updatedSettings) { 10739 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10740 deletePackageLI( 10741 pkgName, null, true, allUsers, perUserInstalled, 10742 PackageManager.DELETE_KEEP_DATA, 10743 res.removedInfo, true); 10744 } 10745 // Since we failed to install the new package we need to restore the old 10746 // package that we deleted. 10747 if (deletedPkg) { 10748 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10749 File restoreFile = new File(deletedPackage.codePath); 10750 // Parse old package 10751 boolean oldExternal = isExternal(deletedPackage); 10752 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10753 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10754 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10755 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10756 try { 10757 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10758 } catch (PackageManagerException e) { 10759 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10760 + e.getMessage()); 10761 return; 10762 } 10763 // Restore of old package succeeded. Update permissions. 10764 // writer 10765 synchronized (mPackages) { 10766 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10767 UPDATE_PERMISSIONS_ALL); 10768 // can downgrade to reader 10769 mSettings.writeLPr(); 10770 } 10771 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10772 } 10773 } 10774 } 10775 10776 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10777 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10778 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10779 String volumeUuid, PackageInstalledInfo res) { 10780 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10781 + ", old=" + deletedPackage); 10782 boolean disabledSystem = false; 10783 boolean updatedSettings = false; 10784 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10785 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10786 != 0) { 10787 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10788 } 10789 String packageName = deletedPackage.packageName; 10790 if (packageName == null) { 10791 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10792 "Attempt to delete null packageName."); 10793 return; 10794 } 10795 PackageParser.Package oldPkg; 10796 PackageSetting oldPkgSetting; 10797 // reader 10798 synchronized (mPackages) { 10799 oldPkg = mPackages.get(packageName); 10800 oldPkgSetting = mSettings.mPackages.get(packageName); 10801 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10802 (oldPkgSetting == null)) { 10803 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10804 "Couldn't find package:" + packageName + " information"); 10805 return; 10806 } 10807 } 10808 10809 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10810 10811 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10812 res.removedInfo.removedPackage = packageName; 10813 // Remove existing system package 10814 removePackageLI(oldPkgSetting, true); 10815 // writer 10816 synchronized (mPackages) { 10817 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10818 if (!disabledSystem && deletedPackage != null) { 10819 // We didn't need to disable the .apk as a current system package, 10820 // which means we are replacing another update that is already 10821 // installed. We need to make sure to delete the older one's .apk. 10822 res.removedInfo.args = createInstallArgsForExisting(0, 10823 deletedPackage.applicationInfo.getCodePath(), 10824 deletedPackage.applicationInfo.getResourcePath(), 10825 deletedPackage.applicationInfo.nativeLibraryRootDir, 10826 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10827 } else { 10828 res.removedInfo.args = null; 10829 } 10830 } 10831 10832 // Successfully disabled the old package. Now proceed with re-installation 10833 deleteCodeCacheDirsLI(packageName); 10834 10835 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10836 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10837 10838 PackageParser.Package newPackage = null; 10839 try { 10840 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10841 if (newPackage.mExtras != null) { 10842 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10843 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10844 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10845 10846 // is the update attempting to change shared user? that isn't going to work... 10847 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10848 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10849 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10850 + " to " + newPkgSetting.sharedUser); 10851 updatedSettings = true; 10852 } 10853 } 10854 10855 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10856 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10857 perUserInstalled, res, user); 10858 updatedSettings = true; 10859 } 10860 10861 } catch (PackageManagerException e) { 10862 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10863 } 10864 10865 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10866 // Re installation failed. Restore old information 10867 // Remove new pkg information 10868 if (newPackage != null) { 10869 removeInstalledPackageLI(newPackage, true); 10870 } 10871 // Add back the old system package 10872 try { 10873 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10874 } catch (PackageManagerException e) { 10875 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10876 } 10877 // Restore the old system information in Settings 10878 synchronized (mPackages) { 10879 if (disabledSystem) { 10880 mSettings.enableSystemPackageLPw(packageName); 10881 } 10882 if (updatedSettings) { 10883 mSettings.setInstallerPackageName(packageName, 10884 oldPkgSetting.installerPackageName); 10885 } 10886 mSettings.writeLPr(); 10887 } 10888 } 10889 } 10890 10891 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10892 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10893 UserHandle user) { 10894 String pkgName = newPackage.packageName; 10895 synchronized (mPackages) { 10896 //write settings. the installStatus will be incomplete at this stage. 10897 //note that the new package setting would have already been 10898 //added to mPackages. It hasn't been persisted yet. 10899 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10900 mSettings.writeLPr(); 10901 } 10902 10903 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10904 10905 synchronized (mPackages) { 10906 updatePermissionsLPw(newPackage.packageName, newPackage, 10907 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10908 ? UPDATE_PERMISSIONS_ALL : 0)); 10909 // For system-bundled packages, we assume that installing an upgraded version 10910 // of the package implies that the user actually wants to run that new code, 10911 // so we enable the package. 10912 PackageSetting ps = mSettings.mPackages.get(pkgName); 10913 if (ps != null) { 10914 if (isSystemApp(newPackage)) { 10915 // NB: implicit assumption that system package upgrades apply to all users 10916 if (DEBUG_INSTALL) { 10917 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10918 } 10919 if (res.origUsers != null) { 10920 for (int userHandle : res.origUsers) { 10921 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10922 userHandle, installerPackageName); 10923 } 10924 } 10925 // Also convey the prior install/uninstall state 10926 if (allUsers != null && perUserInstalled != null) { 10927 for (int i = 0; i < allUsers.length; i++) { 10928 if (DEBUG_INSTALL) { 10929 Slog.d(TAG, " user " + allUsers[i] 10930 + " => " + perUserInstalled[i]); 10931 } 10932 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10933 } 10934 // these install state changes will be persisted in the 10935 // upcoming call to mSettings.writeLPr(). 10936 } 10937 } 10938 // It's implied that when a user requests installation, they want the app to be 10939 // installed and enabled. 10940 int userId = user.getIdentifier(); 10941 if (userId != UserHandle.USER_ALL) { 10942 ps.setInstalled(true, userId); 10943 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10944 } 10945 } 10946 res.name = pkgName; 10947 res.uid = newPackage.applicationInfo.uid; 10948 res.pkg = newPackage; 10949 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10950 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10951 mSettings.setVolumeUuid(pkgName, volumeUuid); 10952 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10953 //to update install status 10954 mSettings.writeLPr(); 10955 } 10956 } 10957 10958 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10959 final int installFlags = args.installFlags; 10960 final String installerPackageName = args.installerPackageName; 10961 final String volumeUuid = args.volumeUuid; 10962 final File tmpPackageFile = new File(args.getCodePath()); 10963 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10964 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 10965 || (args.volumeUuid != null)); 10966 boolean replace = false; 10967 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10968 // Result object to be returned 10969 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10970 10971 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10972 // Retrieve PackageSettings and parse package 10973 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10974 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10975 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10976 PackageParser pp = new PackageParser(); 10977 pp.setSeparateProcesses(mSeparateProcesses); 10978 pp.setDisplayMetrics(mMetrics); 10979 10980 final PackageParser.Package pkg; 10981 try { 10982 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10983 } catch (PackageParserException e) { 10984 res.setError("Failed parse during installPackageLI", e); 10985 return; 10986 } 10987 10988 // Mark that we have an install time CPU ABI override. 10989 pkg.cpuAbiOverride = args.abiOverride; 10990 10991 String pkgName = res.name = pkg.packageName; 10992 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10993 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10994 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10995 return; 10996 } 10997 } 10998 10999 try { 11000 pp.collectCertificates(pkg, parseFlags); 11001 pp.collectManifestDigest(pkg); 11002 } catch (PackageParserException e) { 11003 res.setError("Failed collect during installPackageLI", e); 11004 return; 11005 } 11006 11007 /* If the installer passed in a manifest digest, compare it now. */ 11008 if (args.manifestDigest != null) { 11009 if (DEBUG_INSTALL) { 11010 final String parsedManifest = pkg.manifestDigest == null ? "null" 11011 : pkg.manifestDigest.toString(); 11012 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11013 + parsedManifest); 11014 } 11015 11016 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11017 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11018 return; 11019 } 11020 } else if (DEBUG_INSTALL) { 11021 final String parsedManifest = pkg.manifestDigest == null 11022 ? "null" : pkg.manifestDigest.toString(); 11023 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11024 } 11025 11026 // Get rid of all references to package scan path via parser. 11027 pp = null; 11028 String oldCodePath = null; 11029 boolean systemApp = false; 11030 synchronized (mPackages) { 11031 // Check if installing already existing package 11032 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11033 String oldName = mSettings.mRenamedPackages.get(pkgName); 11034 if (pkg.mOriginalPackages != null 11035 && pkg.mOriginalPackages.contains(oldName) 11036 && mPackages.containsKey(oldName)) { 11037 // This package is derived from an original package, 11038 // and this device has been updating from that original 11039 // name. We must continue using the original name, so 11040 // rename the new package here. 11041 pkg.setPackageName(oldName); 11042 pkgName = pkg.packageName; 11043 replace = true; 11044 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11045 + oldName + " pkgName=" + pkgName); 11046 } else if (mPackages.containsKey(pkgName)) { 11047 // This package, under its official name, already exists 11048 // on the device; we should replace it. 11049 replace = true; 11050 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11051 } 11052 } 11053 11054 PackageSetting ps = mSettings.mPackages.get(pkgName); 11055 if (ps != null) { 11056 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11057 11058 // Quick sanity check that we're signed correctly if updating; 11059 // we'll check this again later when scanning, but we want to 11060 // bail early here before tripping over redefined permissions. 11061 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11062 try { 11063 verifySignaturesLP(ps, pkg); 11064 } catch (PackageManagerException e) { 11065 res.setError(e.error, e.getMessage()); 11066 return; 11067 } 11068 } else { 11069 if (!checkUpgradeKeySetLP(ps, pkg)) { 11070 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11071 + pkg.packageName + " upgrade keys do not match the " 11072 + "previously installed version"); 11073 return; 11074 } 11075 } 11076 11077 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11078 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11079 systemApp = (ps.pkg.applicationInfo.flags & 11080 ApplicationInfo.FLAG_SYSTEM) != 0; 11081 } 11082 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11083 } 11084 11085 // Check whether the newly-scanned package wants to define an already-defined perm 11086 int N = pkg.permissions.size(); 11087 for (int i = N-1; i >= 0; i--) { 11088 PackageParser.Permission perm = pkg.permissions.get(i); 11089 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11090 if (bp != null) { 11091 // If the defining package is signed with our cert, it's okay. This 11092 // also includes the "updating the same package" case, of course. 11093 // "updating same package" could also involve key-rotation. 11094 final boolean sigsOk; 11095 if (!bp.sourcePackage.equals(pkg.packageName) 11096 || !(bp.packageSetting instanceof PackageSetting) 11097 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11098 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11099 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11100 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11101 } else { 11102 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11103 } 11104 if (!sigsOk) { 11105 // If the owning package is the system itself, we log but allow 11106 // install to proceed; we fail the install on all other permission 11107 // redefinitions. 11108 if (!bp.sourcePackage.equals("android")) { 11109 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11110 + pkg.packageName + " attempting to redeclare permission " 11111 + perm.info.name + " already owned by " + bp.sourcePackage); 11112 res.origPermission = perm.info.name; 11113 res.origPackage = bp.sourcePackage; 11114 return; 11115 } else { 11116 Slog.w(TAG, "Package " + pkg.packageName 11117 + " attempting to redeclare system permission " 11118 + perm.info.name + "; ignoring new declaration"); 11119 pkg.permissions.remove(i); 11120 } 11121 } 11122 } 11123 } 11124 11125 } 11126 11127 if (systemApp && onExternal) { 11128 // Disable updates to system apps on sdcard 11129 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11130 "Cannot install updates to system apps on sdcard"); 11131 return; 11132 } 11133 11134 // Run dexopt before old package gets removed, to minimize time when app is not available 11135 int result = mPackageDexOptimizer 11136 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11137 false /* defer */, false /* inclDependencies */); 11138 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11139 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11140 return; 11141 } 11142 11143 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11144 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11145 return; 11146 } 11147 11148 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11149 11150 if (replace) { 11151 // Call replacePackageLI with SCAN_NO_DEX, since we already made dexopt 11152 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11153 installerPackageName, volumeUuid, res); 11154 } else { 11155 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11156 args.user, installerPackageName, volumeUuid, res); 11157 } 11158 synchronized (mPackages) { 11159 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11160 if (ps != null) { 11161 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11162 } 11163 } 11164 } 11165 11166 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11167 if (mIntentFilterVerifierComponent == null) { 11168 Slog.d(TAG, "No IntentFilter verification will not be done as " 11169 + "there is no IntentFilterVerifier available!"); 11170 return; 11171 } 11172 11173 final int verifierUid = getPackageUid( 11174 mIntentFilterVerifierComponent.getPackageName(), 11175 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11176 11177 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11178 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11179 msg.obj = pkg; 11180 msg.arg1 = userId; 11181 msg.arg2 = verifierUid; 11182 11183 mHandler.sendMessage(msg); 11184 } 11185 11186 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11187 PackageParser.Package pkg) { 11188 int size = pkg.activities.size(); 11189 if (size == 0) { 11190 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11191 return; 11192 } 11193 11194 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11195 + " Activities needs verification ..."); 11196 11197 final int verificationId = mIntentFilterVerificationToken++; 11198 int count = 0; 11199 synchronized (mPackages) { 11200 for (PackageParser.Activity a : pkg.activities) { 11201 for (ActivityIntentInfo filter : a.intents) { 11202 boolean needFilterVerification = filter.needsVerification() && 11203 !filter.isVerified(); 11204 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11205 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11206 mIntentFilterVerifier.addOneIntentFilterVerification( 11207 verifierUid, userId, verificationId, filter, pkg.packageName); 11208 count++; 11209 } else { 11210 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11211 } 11212 } 11213 } 11214 } 11215 11216 if (count > 0) { 11217 mIntentFilterVerifier.startVerifications(userId); 11218 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11219 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11220 } else { 11221 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11222 } 11223 } 11224 11225 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11226 final ComponentName cn = filter.activity.getComponentName(); 11227 final String packageName = cn.getPackageName(); 11228 11229 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11230 packageName); 11231 if (ivi == null) { 11232 return true; 11233 } 11234 int status = ivi.getStatus(); 11235 switch (status) { 11236 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11237 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11238 return true; 11239 11240 default: 11241 // Nothing to do 11242 return false; 11243 } 11244 } 11245 11246 private static boolean isMultiArch(PackageSetting ps) { 11247 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11248 } 11249 11250 private static boolean isMultiArch(ApplicationInfo info) { 11251 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11252 } 11253 11254 private static boolean isExternal(PackageParser.Package pkg) { 11255 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11256 } 11257 11258 private static boolean isExternal(PackageSetting ps) { 11259 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11260 } 11261 11262 private static boolean isExternal(ApplicationInfo info) { 11263 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11264 } 11265 11266 private static boolean isSystemApp(PackageParser.Package pkg) { 11267 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11268 } 11269 11270 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11271 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11272 } 11273 11274 private static boolean isSystemApp(PackageSetting ps) { 11275 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11276 } 11277 11278 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11279 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11280 } 11281 11282 private int packageFlagsToInstallFlags(PackageSetting ps) { 11283 int installFlags = 0; 11284 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11285 // This existing package was an external ASEC install when we have 11286 // the external flag without a UUID 11287 installFlags |= PackageManager.INSTALL_EXTERNAL; 11288 } 11289 if (ps.isForwardLocked()) { 11290 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11291 } 11292 return installFlags; 11293 } 11294 11295 private void deleteTempPackageFiles() { 11296 final FilenameFilter filter = new FilenameFilter() { 11297 public boolean accept(File dir, String name) { 11298 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11299 } 11300 }; 11301 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11302 file.delete(); 11303 } 11304 } 11305 11306 @Override 11307 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11308 int flags) { 11309 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11310 flags); 11311 } 11312 11313 @Override 11314 public void deletePackage(final String packageName, 11315 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11316 mContext.enforceCallingOrSelfPermission( 11317 android.Manifest.permission.DELETE_PACKAGES, null); 11318 final int uid = Binder.getCallingUid(); 11319 if (UserHandle.getUserId(uid) != userId) { 11320 mContext.enforceCallingPermission( 11321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11322 "deletePackage for user " + userId); 11323 } 11324 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11325 try { 11326 observer.onPackageDeleted(packageName, 11327 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11328 } catch (RemoteException re) { 11329 } 11330 return; 11331 } 11332 11333 boolean uninstallBlocked = false; 11334 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11335 int[] users = sUserManager.getUserIds(); 11336 for (int i = 0; i < users.length; ++i) { 11337 if (getBlockUninstallForUser(packageName, users[i])) { 11338 uninstallBlocked = true; 11339 break; 11340 } 11341 } 11342 } else { 11343 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11344 } 11345 if (uninstallBlocked) { 11346 try { 11347 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11348 null); 11349 } catch (RemoteException re) { 11350 } 11351 return; 11352 } 11353 11354 if (DEBUG_REMOVE) { 11355 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11356 } 11357 // Queue up an async operation since the package deletion may take a little while. 11358 mHandler.post(new Runnable() { 11359 public void run() { 11360 mHandler.removeCallbacks(this); 11361 final int returnCode = deletePackageX(packageName, userId, flags); 11362 if (observer != null) { 11363 try { 11364 observer.onPackageDeleted(packageName, returnCode, null); 11365 } catch (RemoteException e) { 11366 Log.i(TAG, "Observer no longer exists."); 11367 } //end catch 11368 } //end if 11369 } //end run 11370 }); 11371 } 11372 11373 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11374 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11375 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11376 try { 11377 if (dpm != null) { 11378 if (dpm.isDeviceOwner(packageName)) { 11379 return true; 11380 } 11381 int[] users; 11382 if (userId == UserHandle.USER_ALL) { 11383 users = sUserManager.getUserIds(); 11384 } else { 11385 users = new int[]{userId}; 11386 } 11387 for (int i = 0; i < users.length; ++i) { 11388 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11389 return true; 11390 } 11391 } 11392 } 11393 } catch (RemoteException e) { 11394 } 11395 return false; 11396 } 11397 11398 /** 11399 * This method is an internal method that could be get invoked either 11400 * to delete an installed package or to clean up a failed installation. 11401 * After deleting an installed package, a broadcast is sent to notify any 11402 * listeners that the package has been installed. For cleaning up a failed 11403 * installation, the broadcast is not necessary since the package's 11404 * installation wouldn't have sent the initial broadcast either 11405 * The key steps in deleting a package are 11406 * deleting the package information in internal structures like mPackages, 11407 * deleting the packages base directories through installd 11408 * updating mSettings to reflect current status 11409 * persisting settings for later use 11410 * sending a broadcast if necessary 11411 */ 11412 private int deletePackageX(String packageName, int userId, int flags) { 11413 final PackageRemovedInfo info = new PackageRemovedInfo(); 11414 final boolean res; 11415 11416 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11417 ? UserHandle.ALL : new UserHandle(userId); 11418 11419 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11420 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11421 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11422 } 11423 11424 boolean removedForAllUsers = false; 11425 boolean systemUpdate = false; 11426 11427 // for the uninstall-updates case and restricted profiles, remember the per- 11428 // userhandle installed state 11429 int[] allUsers; 11430 boolean[] perUserInstalled; 11431 synchronized (mPackages) { 11432 PackageSetting ps = mSettings.mPackages.get(packageName); 11433 allUsers = sUserManager.getUserIds(); 11434 perUserInstalled = new boolean[allUsers.length]; 11435 for (int i = 0; i < allUsers.length; i++) { 11436 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11437 } 11438 } 11439 11440 synchronized (mInstallLock) { 11441 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11442 res = deletePackageLI(packageName, removeForUser, 11443 true, allUsers, perUserInstalled, 11444 flags | REMOVE_CHATTY, info, true); 11445 systemUpdate = info.isRemovedPackageSystemUpdate; 11446 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11447 removedForAllUsers = true; 11448 } 11449 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11450 + " removedForAllUsers=" + removedForAllUsers); 11451 } 11452 11453 if (res) { 11454 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11455 11456 // If the removed package was a system update, the old system package 11457 // was re-enabled; we need to broadcast this information 11458 if (systemUpdate) { 11459 Bundle extras = new Bundle(1); 11460 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11461 ? info.removedAppId : info.uid); 11462 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11463 11464 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11465 extras, null, null, null); 11466 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11467 extras, null, null, null); 11468 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11469 null, packageName, null, null); 11470 } 11471 } 11472 // Force a gc here. 11473 Runtime.getRuntime().gc(); 11474 // Delete the resources here after sending the broadcast to let 11475 // other processes clean up before deleting resources. 11476 if (info.args != null) { 11477 synchronized (mInstallLock) { 11478 info.args.doPostDeleteLI(true); 11479 } 11480 } 11481 11482 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11483 } 11484 11485 static class PackageRemovedInfo { 11486 String removedPackage; 11487 int uid = -1; 11488 int removedAppId = -1; 11489 int[] removedUsers = null; 11490 boolean isRemovedPackageSystemUpdate = false; 11491 // Clean up resources deleted packages. 11492 InstallArgs args = null; 11493 11494 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11495 Bundle extras = new Bundle(1); 11496 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11497 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11498 if (replacing) { 11499 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11500 } 11501 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11502 if (removedPackage != null) { 11503 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11504 extras, null, null, removedUsers); 11505 if (fullRemove && !replacing) { 11506 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11507 extras, null, null, removedUsers); 11508 } 11509 } 11510 if (removedAppId >= 0) { 11511 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11512 removedUsers); 11513 } 11514 } 11515 } 11516 11517 /* 11518 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11519 * flag is not set, the data directory is removed as well. 11520 * make sure this flag is set for partially installed apps. If not its meaningless to 11521 * delete a partially installed application. 11522 */ 11523 private void removePackageDataLI(PackageSetting ps, 11524 int[] allUserHandles, boolean[] perUserInstalled, 11525 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11526 String packageName = ps.name; 11527 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11528 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11529 // Retrieve object to delete permissions for shared user later on 11530 final PackageSetting deletedPs; 11531 // reader 11532 synchronized (mPackages) { 11533 deletedPs = mSettings.mPackages.get(packageName); 11534 if (outInfo != null) { 11535 outInfo.removedPackage = packageName; 11536 outInfo.removedUsers = deletedPs != null 11537 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11538 : null; 11539 } 11540 } 11541 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11542 removeDataDirsLI(packageName); 11543 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11544 } 11545 // writer 11546 synchronized (mPackages) { 11547 if (deletedPs != null) { 11548 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11549 if (outInfo != null) { 11550 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11551 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11552 } 11553 updatePermissionsLPw(deletedPs.name, null, 0); 11554 if (deletedPs.sharedUser != null) { 11555 // Remove permissions associated with package. Since runtime 11556 // permissions are per user we have to kill the removed package 11557 // or packages running under the shared user of the removed 11558 // package if revoking the permissions requested only by the removed 11559 // package is successful and this causes a change in gids. 11560 for (int userId : UserManagerService.getInstance().getUserIds()) { 11561 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11562 userId); 11563 if (userIdToKill == UserHandle.USER_ALL 11564 || userIdToKill >= UserHandle.USER_OWNER) { 11565 // If gids changed for this user, kill all affected packages. 11566 mHandler.post(new Runnable() { 11567 @Override 11568 public void run() { 11569 // This has to happen with no lock held. 11570 killSettingPackagesForUser(deletedPs, userIdToKill, 11571 KILL_APP_REASON_GIDS_CHANGED); 11572 } 11573 }); 11574 break; 11575 } 11576 } 11577 } 11578 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11579 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11580 } 11581 // make sure to preserve per-user disabled state if this removal was just 11582 // a downgrade of a system app to the factory package 11583 if (allUserHandles != null && perUserInstalled != null) { 11584 if (DEBUG_REMOVE) { 11585 Slog.d(TAG, "Propagating install state across downgrade"); 11586 } 11587 for (int i = 0; i < allUserHandles.length; i++) { 11588 if (DEBUG_REMOVE) { 11589 Slog.d(TAG, " user " + allUserHandles[i] 11590 + " => " + perUserInstalled[i]); 11591 } 11592 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11593 } 11594 } 11595 } 11596 // can downgrade to reader 11597 if (writeSettings) { 11598 // Save settings now 11599 mSettings.writeLPr(); 11600 } 11601 } 11602 if (outInfo != null) { 11603 // A user ID was deleted here. Go through all users and remove it 11604 // from KeyStore. 11605 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11606 } 11607 } 11608 11609 static boolean locationIsPrivileged(File path) { 11610 try { 11611 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11612 .getCanonicalPath(); 11613 return path.getCanonicalPath().startsWith(privilegedAppDir); 11614 } catch (IOException e) { 11615 Slog.e(TAG, "Unable to access code path " + path); 11616 } 11617 return false; 11618 } 11619 11620 /* 11621 * Tries to delete system package. 11622 */ 11623 private boolean deleteSystemPackageLI(PackageSetting newPs, 11624 int[] allUserHandles, boolean[] perUserInstalled, 11625 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11626 final boolean applyUserRestrictions 11627 = (allUserHandles != null) && (perUserInstalled != null); 11628 PackageSetting disabledPs = null; 11629 // Confirm if the system package has been updated 11630 // An updated system app can be deleted. This will also have to restore 11631 // the system pkg from system partition 11632 // reader 11633 synchronized (mPackages) { 11634 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11635 } 11636 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11637 + " disabledPs=" + disabledPs); 11638 if (disabledPs == null) { 11639 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11640 return false; 11641 } else if (DEBUG_REMOVE) { 11642 Slog.d(TAG, "Deleting system pkg from data partition"); 11643 } 11644 if (DEBUG_REMOVE) { 11645 if (applyUserRestrictions) { 11646 Slog.d(TAG, "Remembering install states:"); 11647 for (int i = 0; i < allUserHandles.length; i++) { 11648 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11649 } 11650 } 11651 } 11652 // Delete the updated package 11653 outInfo.isRemovedPackageSystemUpdate = true; 11654 if (disabledPs.versionCode < newPs.versionCode) { 11655 // Delete data for downgrades 11656 flags &= ~PackageManager.DELETE_KEEP_DATA; 11657 } else { 11658 // Preserve data by setting flag 11659 flags |= PackageManager.DELETE_KEEP_DATA; 11660 } 11661 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11662 allUserHandles, perUserInstalled, outInfo, writeSettings); 11663 if (!ret) { 11664 return false; 11665 } 11666 // writer 11667 synchronized (mPackages) { 11668 // Reinstate the old system package 11669 mSettings.enableSystemPackageLPw(newPs.name); 11670 // Remove any native libraries from the upgraded package. 11671 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11672 } 11673 // Install the system package 11674 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11675 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11676 if (locationIsPrivileged(disabledPs.codePath)) { 11677 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11678 } 11679 11680 final PackageParser.Package newPkg; 11681 try { 11682 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11683 } catch (PackageManagerException e) { 11684 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11685 return false; 11686 } 11687 11688 // writer 11689 synchronized (mPackages) { 11690 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11691 updatePermissionsLPw(newPkg.packageName, newPkg, 11692 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11693 if (applyUserRestrictions) { 11694 if (DEBUG_REMOVE) { 11695 Slog.d(TAG, "Propagating install state across reinstall"); 11696 } 11697 for (int i = 0; i < allUserHandles.length; i++) { 11698 if (DEBUG_REMOVE) { 11699 Slog.d(TAG, " user " + allUserHandles[i] 11700 + " => " + perUserInstalled[i]); 11701 } 11702 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11703 } 11704 // Regardless of writeSettings we need to ensure that this restriction 11705 // state propagation is persisted 11706 mSettings.writeAllUsersPackageRestrictionsLPr(); 11707 } 11708 // can downgrade to reader here 11709 if (writeSettings) { 11710 mSettings.writeLPr(); 11711 } 11712 } 11713 return true; 11714 } 11715 11716 private boolean deleteInstalledPackageLI(PackageSetting ps, 11717 boolean deleteCodeAndResources, int flags, 11718 int[] allUserHandles, boolean[] perUserInstalled, 11719 PackageRemovedInfo outInfo, boolean writeSettings) { 11720 if (outInfo != null) { 11721 outInfo.uid = ps.appId; 11722 } 11723 11724 // Delete package data from internal structures and also remove data if flag is set 11725 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11726 11727 // Delete application code and resources 11728 if (deleteCodeAndResources && (outInfo != null)) { 11729 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11730 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11731 getAppDexInstructionSets(ps)); 11732 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11733 } 11734 return true; 11735 } 11736 11737 @Override 11738 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11739 int userId) { 11740 mContext.enforceCallingOrSelfPermission( 11741 android.Manifest.permission.DELETE_PACKAGES, null); 11742 synchronized (mPackages) { 11743 PackageSetting ps = mSettings.mPackages.get(packageName); 11744 if (ps == null) { 11745 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11746 return false; 11747 } 11748 if (!ps.getInstalled(userId)) { 11749 // Can't block uninstall for an app that is not installed or enabled. 11750 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11751 return false; 11752 } 11753 ps.setBlockUninstall(blockUninstall, userId); 11754 mSettings.writePackageRestrictionsLPr(userId); 11755 } 11756 return true; 11757 } 11758 11759 @Override 11760 public boolean getBlockUninstallForUser(String packageName, int userId) { 11761 synchronized (mPackages) { 11762 PackageSetting ps = mSettings.mPackages.get(packageName); 11763 if (ps == null) { 11764 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11765 return false; 11766 } 11767 return ps.getBlockUninstall(userId); 11768 } 11769 } 11770 11771 /* 11772 * This method handles package deletion in general 11773 */ 11774 private boolean deletePackageLI(String packageName, UserHandle user, 11775 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11776 int flags, PackageRemovedInfo outInfo, 11777 boolean writeSettings) { 11778 if (packageName == null) { 11779 Slog.w(TAG, "Attempt to delete null packageName."); 11780 return false; 11781 } 11782 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11783 PackageSetting ps; 11784 boolean dataOnly = false; 11785 int removeUser = -1; 11786 int appId = -1; 11787 synchronized (mPackages) { 11788 ps = mSettings.mPackages.get(packageName); 11789 if (ps == null) { 11790 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11791 return false; 11792 } 11793 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11794 && user.getIdentifier() != UserHandle.USER_ALL) { 11795 // The caller is asking that the package only be deleted for a single 11796 // user. To do this, we just mark its uninstalled state and delete 11797 // its data. If this is a system app, we only allow this to happen if 11798 // they have set the special DELETE_SYSTEM_APP which requests different 11799 // semantics than normal for uninstalling system apps. 11800 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11801 ps.setUserState(user.getIdentifier(), 11802 COMPONENT_ENABLED_STATE_DEFAULT, 11803 false, //installed 11804 true, //stopped 11805 true, //notLaunched 11806 false, //hidden 11807 null, null, null, 11808 false, // blockUninstall 11809 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11810 if (!isSystemApp(ps)) { 11811 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11812 // Other user still have this package installed, so all 11813 // we need to do is clear this user's data and save that 11814 // it is uninstalled. 11815 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11816 removeUser = user.getIdentifier(); 11817 appId = ps.appId; 11818 mSettings.writePackageRestrictionsLPr(removeUser); 11819 } else { 11820 // We need to set it back to 'installed' so the uninstall 11821 // broadcasts will be sent correctly. 11822 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11823 ps.setInstalled(true, user.getIdentifier()); 11824 } 11825 } else { 11826 // This is a system app, so we assume that the 11827 // other users still have this package installed, so all 11828 // we need to do is clear this user's data and save that 11829 // it is uninstalled. 11830 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11831 removeUser = user.getIdentifier(); 11832 appId = ps.appId; 11833 mSettings.writePackageRestrictionsLPr(removeUser); 11834 } 11835 } 11836 } 11837 11838 if (removeUser >= 0) { 11839 // From above, we determined that we are deleting this only 11840 // for a single user. Continue the work here. 11841 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11842 if (outInfo != null) { 11843 outInfo.removedPackage = packageName; 11844 outInfo.removedAppId = appId; 11845 outInfo.removedUsers = new int[] {removeUser}; 11846 } 11847 mInstaller.clearUserData(packageName, removeUser); 11848 removeKeystoreDataIfNeeded(removeUser, appId); 11849 schedulePackageCleaning(packageName, removeUser, false); 11850 return true; 11851 } 11852 11853 if (dataOnly) { 11854 // Delete application data first 11855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11856 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11857 return true; 11858 } 11859 11860 boolean ret = false; 11861 if (isSystemApp(ps)) { 11862 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11863 // When an updated system application is deleted we delete the existing resources as well and 11864 // fall back to existing code in system partition 11865 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11866 flags, outInfo, writeSettings); 11867 } else { 11868 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11869 // Kill application pre-emptively especially for apps on sd. 11870 killApplication(packageName, ps.appId, "uninstall pkg"); 11871 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11872 allUserHandles, perUserInstalled, 11873 outInfo, writeSettings); 11874 } 11875 11876 return ret; 11877 } 11878 11879 private final class ClearStorageConnection implements ServiceConnection { 11880 IMediaContainerService mContainerService; 11881 11882 @Override 11883 public void onServiceConnected(ComponentName name, IBinder service) { 11884 synchronized (this) { 11885 mContainerService = IMediaContainerService.Stub.asInterface(service); 11886 notifyAll(); 11887 } 11888 } 11889 11890 @Override 11891 public void onServiceDisconnected(ComponentName name) { 11892 } 11893 } 11894 11895 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11896 final boolean mounted; 11897 if (Environment.isExternalStorageEmulated()) { 11898 mounted = true; 11899 } else { 11900 final String status = Environment.getExternalStorageState(); 11901 11902 mounted = status.equals(Environment.MEDIA_MOUNTED) 11903 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11904 } 11905 11906 if (!mounted) { 11907 return; 11908 } 11909 11910 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11911 int[] users; 11912 if (userId == UserHandle.USER_ALL) { 11913 users = sUserManager.getUserIds(); 11914 } else { 11915 users = new int[] { userId }; 11916 } 11917 final ClearStorageConnection conn = new ClearStorageConnection(); 11918 if (mContext.bindServiceAsUser( 11919 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11920 try { 11921 for (int curUser : users) { 11922 long timeout = SystemClock.uptimeMillis() + 5000; 11923 synchronized (conn) { 11924 long now = SystemClock.uptimeMillis(); 11925 while (conn.mContainerService == null && now < timeout) { 11926 try { 11927 conn.wait(timeout - now); 11928 } catch (InterruptedException e) { 11929 } 11930 } 11931 } 11932 if (conn.mContainerService == null) { 11933 return; 11934 } 11935 11936 final UserEnvironment userEnv = new UserEnvironment(curUser); 11937 clearDirectory(conn.mContainerService, 11938 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11939 if (allData) { 11940 clearDirectory(conn.mContainerService, 11941 userEnv.buildExternalStorageAppDataDirs(packageName)); 11942 clearDirectory(conn.mContainerService, 11943 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11944 } 11945 } 11946 } finally { 11947 mContext.unbindService(conn); 11948 } 11949 } 11950 } 11951 11952 @Override 11953 public void clearApplicationUserData(final String packageName, 11954 final IPackageDataObserver observer, final int userId) { 11955 mContext.enforceCallingOrSelfPermission( 11956 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11957 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11958 // Queue up an async operation since the package deletion may take a little while. 11959 mHandler.post(new Runnable() { 11960 public void run() { 11961 mHandler.removeCallbacks(this); 11962 final boolean succeeded; 11963 synchronized (mInstallLock) { 11964 succeeded = clearApplicationUserDataLI(packageName, userId); 11965 } 11966 clearExternalStorageDataSync(packageName, userId, true); 11967 if (succeeded) { 11968 // invoke DeviceStorageMonitor's update method to clear any notifications 11969 DeviceStorageMonitorInternal 11970 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11971 if (dsm != null) { 11972 dsm.checkMemory(); 11973 } 11974 } 11975 if(observer != null) { 11976 try { 11977 observer.onRemoveCompleted(packageName, succeeded); 11978 } catch (RemoteException e) { 11979 Log.i(TAG, "Observer no longer exists."); 11980 } 11981 } //end if observer 11982 } //end run 11983 }); 11984 } 11985 11986 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11987 if (packageName == null) { 11988 Slog.w(TAG, "Attempt to delete null packageName."); 11989 return false; 11990 } 11991 11992 // Try finding details about the requested package 11993 PackageParser.Package pkg; 11994 synchronized (mPackages) { 11995 pkg = mPackages.get(packageName); 11996 if (pkg == null) { 11997 final PackageSetting ps = mSettings.mPackages.get(packageName); 11998 if (ps != null) { 11999 pkg = ps.pkg; 12000 } 12001 } 12002 } 12003 12004 if (pkg == null) { 12005 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12006 } 12007 12008 // Always delete data directories for package, even if we found no other 12009 // record of app. This helps users recover from UID mismatches without 12010 // resorting to a full data wipe. 12011 int retCode = mInstaller.clearUserData(packageName, userId); 12012 if (retCode < 0) { 12013 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12014 return false; 12015 } 12016 12017 if (pkg == null) { 12018 return false; 12019 } 12020 12021 if (pkg != null && pkg.applicationInfo != null) { 12022 final int appId = pkg.applicationInfo.uid; 12023 removeKeystoreDataIfNeeded(userId, appId); 12024 } 12025 12026 // Create a native library symlink only if we have native libraries 12027 // and if the native libraries are 32 bit libraries. We do not provide 12028 // this symlink for 64 bit libraries. 12029 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12030 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12031 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12032 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12033 Slog.w(TAG, "Failed linking native library dir"); 12034 return false; 12035 } 12036 } 12037 12038 return true; 12039 } 12040 12041 /** 12042 * Remove entries from the keystore daemon. Will only remove it if the 12043 * {@code appId} is valid. 12044 */ 12045 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12046 if (appId < 0) { 12047 return; 12048 } 12049 12050 final KeyStore keyStore = KeyStore.getInstance(); 12051 if (keyStore != null) { 12052 if (userId == UserHandle.USER_ALL) { 12053 for (final int individual : sUserManager.getUserIds()) { 12054 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12055 } 12056 } else { 12057 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12058 } 12059 } else { 12060 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12061 } 12062 } 12063 12064 @Override 12065 public void deleteApplicationCacheFiles(final String packageName, 12066 final IPackageDataObserver observer) { 12067 mContext.enforceCallingOrSelfPermission( 12068 android.Manifest.permission.DELETE_CACHE_FILES, null); 12069 // Queue up an async operation since the package deletion may take a little while. 12070 final int userId = UserHandle.getCallingUserId(); 12071 mHandler.post(new Runnable() { 12072 public void run() { 12073 mHandler.removeCallbacks(this); 12074 final boolean succeded; 12075 synchronized (mInstallLock) { 12076 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12077 } 12078 clearExternalStorageDataSync(packageName, userId, false); 12079 if(observer != null) { 12080 try { 12081 observer.onRemoveCompleted(packageName, succeded); 12082 } catch (RemoteException e) { 12083 Log.i(TAG, "Observer no longer exists."); 12084 } 12085 } //end if observer 12086 } //end run 12087 }); 12088 } 12089 12090 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12091 if (packageName == null) { 12092 Slog.w(TAG, "Attempt to delete null packageName."); 12093 return false; 12094 } 12095 PackageParser.Package p; 12096 synchronized (mPackages) { 12097 p = mPackages.get(packageName); 12098 } 12099 if (p == null) { 12100 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12101 return false; 12102 } 12103 final ApplicationInfo applicationInfo = p.applicationInfo; 12104 if (applicationInfo == null) { 12105 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12106 return false; 12107 } 12108 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12109 if (retCode < 0) { 12110 Slog.w(TAG, "Couldn't remove cache files for package: " 12111 + packageName + " u" + userId); 12112 return false; 12113 } 12114 return true; 12115 } 12116 12117 @Override 12118 public void getPackageSizeInfo(final String packageName, int userHandle, 12119 final IPackageStatsObserver observer) { 12120 mContext.enforceCallingOrSelfPermission( 12121 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12122 if (packageName == null) { 12123 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12124 } 12125 12126 PackageStats stats = new PackageStats(packageName, userHandle); 12127 12128 /* 12129 * Queue up an async operation since the package measurement may take a 12130 * little while. 12131 */ 12132 Message msg = mHandler.obtainMessage(INIT_COPY); 12133 msg.obj = new MeasureParams(stats, observer); 12134 mHandler.sendMessage(msg); 12135 } 12136 12137 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12138 PackageStats pStats) { 12139 if (packageName == null) { 12140 Slog.w(TAG, "Attempt to get size of null packageName."); 12141 return false; 12142 } 12143 PackageParser.Package p; 12144 boolean dataOnly = false; 12145 String libDirRoot = null; 12146 String asecPath = null; 12147 PackageSetting ps = null; 12148 synchronized (mPackages) { 12149 p = mPackages.get(packageName); 12150 ps = mSettings.mPackages.get(packageName); 12151 if(p == null) { 12152 dataOnly = true; 12153 if((ps == null) || (ps.pkg == null)) { 12154 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12155 return false; 12156 } 12157 p = ps.pkg; 12158 } 12159 if (ps != null) { 12160 libDirRoot = ps.legacyNativeLibraryPathString; 12161 } 12162 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12163 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12164 if (secureContainerId != null) { 12165 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12166 } 12167 } 12168 } 12169 String publicSrcDir = null; 12170 if(!dataOnly) { 12171 final ApplicationInfo applicationInfo = p.applicationInfo; 12172 if (applicationInfo == null) { 12173 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12174 return false; 12175 } 12176 if (p.isForwardLocked()) { 12177 publicSrcDir = applicationInfo.getBaseResourcePath(); 12178 } 12179 } 12180 // TODO: extend to measure size of split APKs 12181 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12182 // not just the first level. 12183 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12184 // just the primary. 12185 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12186 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12187 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12188 if (res < 0) { 12189 return false; 12190 } 12191 12192 // Fix-up for forward-locked applications in ASEC containers. 12193 if (!isExternal(p)) { 12194 pStats.codeSize += pStats.externalCodeSize; 12195 pStats.externalCodeSize = 0L; 12196 } 12197 12198 return true; 12199 } 12200 12201 12202 @Override 12203 public void addPackageToPreferred(String packageName) { 12204 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12205 } 12206 12207 @Override 12208 public void removePackageFromPreferred(String packageName) { 12209 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12210 } 12211 12212 @Override 12213 public List<PackageInfo> getPreferredPackages(int flags) { 12214 return new ArrayList<PackageInfo>(); 12215 } 12216 12217 private int getUidTargetSdkVersionLockedLPr(int uid) { 12218 Object obj = mSettings.getUserIdLPr(uid); 12219 if (obj instanceof SharedUserSetting) { 12220 final SharedUserSetting sus = (SharedUserSetting) obj; 12221 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12222 final Iterator<PackageSetting> it = sus.packages.iterator(); 12223 while (it.hasNext()) { 12224 final PackageSetting ps = it.next(); 12225 if (ps.pkg != null) { 12226 int v = ps.pkg.applicationInfo.targetSdkVersion; 12227 if (v < vers) vers = v; 12228 } 12229 } 12230 return vers; 12231 } else if (obj instanceof PackageSetting) { 12232 final PackageSetting ps = (PackageSetting) obj; 12233 if (ps.pkg != null) { 12234 return ps.pkg.applicationInfo.targetSdkVersion; 12235 } 12236 } 12237 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12238 } 12239 12240 @Override 12241 public void addPreferredActivity(IntentFilter filter, int match, 12242 ComponentName[] set, ComponentName activity, int userId) { 12243 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12244 "Adding preferred"); 12245 } 12246 12247 private void addPreferredActivityInternal(IntentFilter filter, int match, 12248 ComponentName[] set, ComponentName activity, boolean always, int userId, 12249 String opname) { 12250 // writer 12251 int callingUid = Binder.getCallingUid(); 12252 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12253 if (filter.countActions() == 0) { 12254 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12255 return; 12256 } 12257 synchronized (mPackages) { 12258 if (mContext.checkCallingOrSelfPermission( 12259 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12260 != PackageManager.PERMISSION_GRANTED) { 12261 if (getUidTargetSdkVersionLockedLPr(callingUid) 12262 < Build.VERSION_CODES.FROYO) { 12263 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12264 + callingUid); 12265 return; 12266 } 12267 mContext.enforceCallingOrSelfPermission( 12268 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12269 } 12270 12271 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12272 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12273 + userId + ":"); 12274 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12275 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12276 scheduleWritePackageRestrictionsLocked(userId); 12277 } 12278 } 12279 12280 @Override 12281 public void replacePreferredActivity(IntentFilter filter, int match, 12282 ComponentName[] set, ComponentName activity, int userId) { 12283 if (filter.countActions() != 1) { 12284 throw new IllegalArgumentException( 12285 "replacePreferredActivity expects filter to have only 1 action."); 12286 } 12287 if (filter.countDataAuthorities() != 0 12288 || filter.countDataPaths() != 0 12289 || filter.countDataSchemes() > 1 12290 || filter.countDataTypes() != 0) { 12291 throw new IllegalArgumentException( 12292 "replacePreferredActivity expects filter to have no data authorities, " + 12293 "paths, or types; and at most one scheme."); 12294 } 12295 12296 final int callingUid = Binder.getCallingUid(); 12297 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12298 synchronized (mPackages) { 12299 if (mContext.checkCallingOrSelfPermission( 12300 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12301 != PackageManager.PERMISSION_GRANTED) { 12302 if (getUidTargetSdkVersionLockedLPr(callingUid) 12303 < Build.VERSION_CODES.FROYO) { 12304 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12305 + Binder.getCallingUid()); 12306 return; 12307 } 12308 mContext.enforceCallingOrSelfPermission( 12309 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12310 } 12311 12312 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12313 if (pir != null) { 12314 // Get all of the existing entries that exactly match this filter. 12315 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12316 if (existing != null && existing.size() == 1) { 12317 PreferredActivity cur = existing.get(0); 12318 if (DEBUG_PREFERRED) { 12319 Slog.i(TAG, "Checking replace of preferred:"); 12320 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12321 if (!cur.mPref.mAlways) { 12322 Slog.i(TAG, " -- CUR; not mAlways!"); 12323 } else { 12324 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12325 Slog.i(TAG, " -- CUR: mSet=" 12326 + Arrays.toString(cur.mPref.mSetComponents)); 12327 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12328 Slog.i(TAG, " -- NEW: mMatch=" 12329 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12330 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12331 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12332 } 12333 } 12334 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12335 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12336 && cur.mPref.sameSet(set)) { 12337 // Setting the preferred activity to what it happens to be already 12338 if (DEBUG_PREFERRED) { 12339 Slog.i(TAG, "Replacing with same preferred activity " 12340 + cur.mPref.mShortComponent + " for user " 12341 + userId + ":"); 12342 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12343 } 12344 return; 12345 } 12346 } 12347 12348 if (existing != null) { 12349 if (DEBUG_PREFERRED) { 12350 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12351 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12352 } 12353 for (int i = 0; i < existing.size(); i++) { 12354 PreferredActivity pa = existing.get(i); 12355 if (DEBUG_PREFERRED) { 12356 Slog.i(TAG, "Removing existing preferred activity " 12357 + pa.mPref.mComponent + ":"); 12358 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12359 } 12360 pir.removeFilter(pa); 12361 } 12362 } 12363 } 12364 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12365 "Replacing preferred"); 12366 } 12367 } 12368 12369 @Override 12370 public void clearPackagePreferredActivities(String packageName) { 12371 final int uid = Binder.getCallingUid(); 12372 // writer 12373 synchronized (mPackages) { 12374 PackageParser.Package pkg = mPackages.get(packageName); 12375 if (pkg == null || pkg.applicationInfo.uid != uid) { 12376 if (mContext.checkCallingOrSelfPermission( 12377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12378 != PackageManager.PERMISSION_GRANTED) { 12379 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12380 < Build.VERSION_CODES.FROYO) { 12381 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12382 + Binder.getCallingUid()); 12383 return; 12384 } 12385 mContext.enforceCallingOrSelfPermission( 12386 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12387 } 12388 } 12389 12390 int user = UserHandle.getCallingUserId(); 12391 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12392 scheduleWritePackageRestrictionsLocked(user); 12393 } 12394 } 12395 } 12396 12397 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12398 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12399 ArrayList<PreferredActivity> removed = null; 12400 boolean changed = false; 12401 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12402 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12403 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12404 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12405 continue; 12406 } 12407 Iterator<PreferredActivity> it = pir.filterIterator(); 12408 while (it.hasNext()) { 12409 PreferredActivity pa = it.next(); 12410 // Mark entry for removal only if it matches the package name 12411 // and the entry is of type "always". 12412 if (packageName == null || 12413 (pa.mPref.mComponent.getPackageName().equals(packageName) 12414 && pa.mPref.mAlways)) { 12415 if (removed == null) { 12416 removed = new ArrayList<PreferredActivity>(); 12417 } 12418 removed.add(pa); 12419 } 12420 } 12421 if (removed != null) { 12422 for (int j=0; j<removed.size(); j++) { 12423 PreferredActivity pa = removed.get(j); 12424 pir.removeFilter(pa); 12425 } 12426 changed = true; 12427 } 12428 } 12429 return changed; 12430 } 12431 12432 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12433 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12434 if (userId == UserHandle.USER_ALL) { 12435 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12436 for (int oneUserId : sUserManager.getUserIds()) { 12437 scheduleWritePackageRestrictionsLocked(oneUserId); 12438 } 12439 } else { 12440 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12441 scheduleWritePackageRestrictionsLocked(userId); 12442 } 12443 } 12444 12445 @Override 12446 public void resetPreferredActivities(int userId) { 12447 /* TODO: Actually use userId. Why is it being passed in? */ 12448 mContext.enforceCallingOrSelfPermission( 12449 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12450 // writer 12451 synchronized (mPackages) { 12452 int user = UserHandle.getCallingUserId(); 12453 clearPackagePreferredActivitiesLPw(null, user); 12454 mSettings.readDefaultPreferredAppsLPw(this, user); 12455 scheduleWritePackageRestrictionsLocked(user); 12456 } 12457 } 12458 12459 @Override 12460 public int getPreferredActivities(List<IntentFilter> outFilters, 12461 List<ComponentName> outActivities, String packageName) { 12462 12463 int num = 0; 12464 final int userId = UserHandle.getCallingUserId(); 12465 // reader 12466 synchronized (mPackages) { 12467 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12468 if (pir != null) { 12469 final Iterator<PreferredActivity> it = pir.filterIterator(); 12470 while (it.hasNext()) { 12471 final PreferredActivity pa = it.next(); 12472 if (packageName == null 12473 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12474 && pa.mPref.mAlways)) { 12475 if (outFilters != null) { 12476 outFilters.add(new IntentFilter(pa)); 12477 } 12478 if (outActivities != null) { 12479 outActivities.add(pa.mPref.mComponent); 12480 } 12481 } 12482 } 12483 } 12484 } 12485 12486 return num; 12487 } 12488 12489 @Override 12490 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12491 int userId) { 12492 int callingUid = Binder.getCallingUid(); 12493 if (callingUid != Process.SYSTEM_UID) { 12494 throw new SecurityException( 12495 "addPersistentPreferredActivity can only be run by the system"); 12496 } 12497 if (filter.countActions() == 0) { 12498 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12499 return; 12500 } 12501 synchronized (mPackages) { 12502 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12503 " :"); 12504 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12505 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12506 new PersistentPreferredActivity(filter, activity)); 12507 scheduleWritePackageRestrictionsLocked(userId); 12508 } 12509 } 12510 12511 @Override 12512 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12513 int callingUid = Binder.getCallingUid(); 12514 if (callingUid != Process.SYSTEM_UID) { 12515 throw new SecurityException( 12516 "clearPackagePersistentPreferredActivities can only be run by the system"); 12517 } 12518 ArrayList<PersistentPreferredActivity> removed = null; 12519 boolean changed = false; 12520 synchronized (mPackages) { 12521 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12522 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12523 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12524 .valueAt(i); 12525 if (userId != thisUserId) { 12526 continue; 12527 } 12528 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12529 while (it.hasNext()) { 12530 PersistentPreferredActivity ppa = it.next(); 12531 // Mark entry for removal only if it matches the package name. 12532 if (ppa.mComponent.getPackageName().equals(packageName)) { 12533 if (removed == null) { 12534 removed = new ArrayList<PersistentPreferredActivity>(); 12535 } 12536 removed.add(ppa); 12537 } 12538 } 12539 if (removed != null) { 12540 for (int j=0; j<removed.size(); j++) { 12541 PersistentPreferredActivity ppa = removed.get(j); 12542 ppir.removeFilter(ppa); 12543 } 12544 changed = true; 12545 } 12546 } 12547 12548 if (changed) { 12549 scheduleWritePackageRestrictionsLocked(userId); 12550 } 12551 } 12552 } 12553 12554 /** 12555 * Non-Binder method, support for the backup/restore mechanism: write the 12556 * full set of preferred activities in its canonical XML format. Returns true 12557 * on success; false otherwise. 12558 */ 12559 @Override 12560 public byte[] getPreferredActivityBackup(int userId) { 12561 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12562 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12563 } 12564 12565 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12566 try { 12567 final XmlSerializer serializer = new FastXmlSerializer(); 12568 serializer.setOutput(dataStream, "utf-8"); 12569 serializer.startDocument(null, true); 12570 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12571 12572 synchronized (mPackages) { 12573 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12574 } 12575 12576 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12577 serializer.endDocument(); 12578 serializer.flush(); 12579 } catch (Exception e) { 12580 if (DEBUG_BACKUP) { 12581 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12582 } 12583 return null; 12584 } 12585 12586 return dataStream.toByteArray(); 12587 } 12588 12589 @Override 12590 public void restorePreferredActivities(byte[] backup, int userId) { 12591 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12592 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12593 } 12594 12595 try { 12596 final XmlPullParser parser = Xml.newPullParser(); 12597 parser.setInput(new ByteArrayInputStream(backup), null); 12598 12599 int type; 12600 while ((type = parser.next()) != XmlPullParser.START_TAG 12601 && type != XmlPullParser.END_DOCUMENT) { 12602 } 12603 if (type != XmlPullParser.START_TAG) { 12604 // oops didn't find a start tag?! 12605 if (DEBUG_BACKUP) { 12606 Slog.e(TAG, "Didn't find start tag during restore"); 12607 } 12608 return; 12609 } 12610 12611 // this is supposed to be TAG_PREFERRED_BACKUP 12612 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12613 if (DEBUG_BACKUP) { 12614 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12615 } 12616 return; 12617 } 12618 12619 // skip interfering stuff, then we're aligned with the backing implementation 12620 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12621 synchronized (mPackages) { 12622 mSettings.readPreferredActivitiesLPw(parser, userId); 12623 } 12624 } catch (Exception e) { 12625 if (DEBUG_BACKUP) { 12626 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12627 } 12628 } 12629 } 12630 12631 @Override 12632 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12633 int sourceUserId, int targetUserId, int flags) { 12634 mContext.enforceCallingOrSelfPermission( 12635 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12636 int callingUid = Binder.getCallingUid(); 12637 enforceOwnerRights(ownerPackage, callingUid); 12638 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12639 if (intentFilter.countActions() == 0) { 12640 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12641 return; 12642 } 12643 synchronized (mPackages) { 12644 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12645 ownerPackage, targetUserId, flags); 12646 CrossProfileIntentResolver resolver = 12647 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12648 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12649 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12650 if (existing != null) { 12651 int size = existing.size(); 12652 for (int i = 0; i < size; i++) { 12653 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12654 return; 12655 } 12656 } 12657 } 12658 resolver.addFilter(newFilter); 12659 scheduleWritePackageRestrictionsLocked(sourceUserId); 12660 } 12661 } 12662 12663 @Override 12664 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12665 mContext.enforceCallingOrSelfPermission( 12666 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12667 int callingUid = Binder.getCallingUid(); 12668 enforceOwnerRights(ownerPackage, callingUid); 12669 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12670 synchronized (mPackages) { 12671 CrossProfileIntentResolver resolver = 12672 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12673 ArraySet<CrossProfileIntentFilter> set = 12674 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12675 for (CrossProfileIntentFilter filter : set) { 12676 if (filter.getOwnerPackage().equals(ownerPackage)) { 12677 resolver.removeFilter(filter); 12678 } 12679 } 12680 scheduleWritePackageRestrictionsLocked(sourceUserId); 12681 } 12682 } 12683 12684 // Enforcing that callingUid is owning pkg on userId 12685 private void enforceOwnerRights(String pkg, int callingUid) { 12686 // The system owns everything. 12687 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12688 return; 12689 } 12690 int callingUserId = UserHandle.getUserId(callingUid); 12691 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12692 if (pi == null) { 12693 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12694 + callingUserId); 12695 } 12696 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12697 throw new SecurityException("Calling uid " + callingUid 12698 + " does not own package " + pkg); 12699 } 12700 } 12701 12702 @Override 12703 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12704 Intent intent = new Intent(Intent.ACTION_MAIN); 12705 intent.addCategory(Intent.CATEGORY_HOME); 12706 12707 final int callingUserId = UserHandle.getCallingUserId(); 12708 List<ResolveInfo> list = queryIntentActivities(intent, null, 12709 PackageManager.GET_META_DATA, callingUserId); 12710 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12711 true, false, false, callingUserId); 12712 12713 allHomeCandidates.clear(); 12714 if (list != null) { 12715 for (ResolveInfo ri : list) { 12716 allHomeCandidates.add(ri); 12717 } 12718 } 12719 return (preferred == null || preferred.activityInfo == null) 12720 ? null 12721 : new ComponentName(preferred.activityInfo.packageName, 12722 preferred.activityInfo.name); 12723 } 12724 12725 @Override 12726 public void setApplicationEnabledSetting(String appPackageName, 12727 int newState, int flags, int userId, String callingPackage) { 12728 if (!sUserManager.exists(userId)) return; 12729 if (callingPackage == null) { 12730 callingPackage = Integer.toString(Binder.getCallingUid()); 12731 } 12732 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12733 } 12734 12735 @Override 12736 public void setComponentEnabledSetting(ComponentName componentName, 12737 int newState, int flags, int userId) { 12738 if (!sUserManager.exists(userId)) return; 12739 setEnabledSetting(componentName.getPackageName(), 12740 componentName.getClassName(), newState, flags, userId, null); 12741 } 12742 12743 private void setEnabledSetting(final String packageName, String className, int newState, 12744 final int flags, int userId, String callingPackage) { 12745 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12746 || newState == COMPONENT_ENABLED_STATE_ENABLED 12747 || newState == COMPONENT_ENABLED_STATE_DISABLED 12748 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12749 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12750 throw new IllegalArgumentException("Invalid new component state: " 12751 + newState); 12752 } 12753 PackageSetting pkgSetting; 12754 final int uid = Binder.getCallingUid(); 12755 final int permission = mContext.checkCallingOrSelfPermission( 12756 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12757 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12758 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12759 boolean sendNow = false; 12760 boolean isApp = (className == null); 12761 String componentName = isApp ? packageName : className; 12762 int packageUid = -1; 12763 ArrayList<String> components; 12764 12765 // writer 12766 synchronized (mPackages) { 12767 pkgSetting = mSettings.mPackages.get(packageName); 12768 if (pkgSetting == null) { 12769 if (className == null) { 12770 throw new IllegalArgumentException( 12771 "Unknown package: " + packageName); 12772 } 12773 throw new IllegalArgumentException( 12774 "Unknown component: " + packageName 12775 + "/" + className); 12776 } 12777 // Allow root and verify that userId is not being specified by a different user 12778 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12779 throw new SecurityException( 12780 "Permission Denial: attempt to change component state from pid=" 12781 + Binder.getCallingPid() 12782 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12783 } 12784 if (className == null) { 12785 // We're dealing with an application/package level state change 12786 if (pkgSetting.getEnabled(userId) == newState) { 12787 // Nothing to do 12788 return; 12789 } 12790 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12791 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12792 // Don't care about who enables an app. 12793 callingPackage = null; 12794 } 12795 pkgSetting.setEnabled(newState, userId, callingPackage); 12796 // pkgSetting.pkg.mSetEnabled = newState; 12797 } else { 12798 // We're dealing with a component level state change 12799 // First, verify that this is a valid class name. 12800 PackageParser.Package pkg = pkgSetting.pkg; 12801 if (pkg == null || !pkg.hasComponentClassName(className)) { 12802 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12803 throw new IllegalArgumentException("Component class " + className 12804 + " does not exist in " + packageName); 12805 } else { 12806 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12807 + className + " does not exist in " + packageName); 12808 } 12809 } 12810 switch (newState) { 12811 case COMPONENT_ENABLED_STATE_ENABLED: 12812 if (!pkgSetting.enableComponentLPw(className, userId)) { 12813 return; 12814 } 12815 break; 12816 case COMPONENT_ENABLED_STATE_DISABLED: 12817 if (!pkgSetting.disableComponentLPw(className, userId)) { 12818 return; 12819 } 12820 break; 12821 case COMPONENT_ENABLED_STATE_DEFAULT: 12822 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12823 return; 12824 } 12825 break; 12826 default: 12827 Slog.e(TAG, "Invalid new component state: " + newState); 12828 return; 12829 } 12830 } 12831 scheduleWritePackageRestrictionsLocked(userId); 12832 components = mPendingBroadcasts.get(userId, packageName); 12833 final boolean newPackage = components == null; 12834 if (newPackage) { 12835 components = new ArrayList<String>(); 12836 } 12837 if (!components.contains(componentName)) { 12838 components.add(componentName); 12839 } 12840 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12841 sendNow = true; 12842 // Purge entry from pending broadcast list if another one exists already 12843 // since we are sending one right away. 12844 mPendingBroadcasts.remove(userId, packageName); 12845 } else { 12846 if (newPackage) { 12847 mPendingBroadcasts.put(userId, packageName, components); 12848 } 12849 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12850 // Schedule a message 12851 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12852 } 12853 } 12854 } 12855 12856 long callingId = Binder.clearCallingIdentity(); 12857 try { 12858 if (sendNow) { 12859 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12860 sendPackageChangedBroadcast(packageName, 12861 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12862 } 12863 } finally { 12864 Binder.restoreCallingIdentity(callingId); 12865 } 12866 } 12867 12868 private void sendPackageChangedBroadcast(String packageName, 12869 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12870 if (DEBUG_INSTALL) 12871 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12872 + componentNames); 12873 Bundle extras = new Bundle(4); 12874 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12875 String nameList[] = new String[componentNames.size()]; 12876 componentNames.toArray(nameList); 12877 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12878 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12879 extras.putInt(Intent.EXTRA_UID, packageUid); 12880 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12881 new int[] {UserHandle.getUserId(packageUid)}); 12882 } 12883 12884 @Override 12885 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12886 if (!sUserManager.exists(userId)) return; 12887 final int uid = Binder.getCallingUid(); 12888 final int permission = mContext.checkCallingOrSelfPermission( 12889 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12890 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12891 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12892 // writer 12893 synchronized (mPackages) { 12894 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12895 uid, userId)) { 12896 scheduleWritePackageRestrictionsLocked(userId); 12897 } 12898 } 12899 } 12900 12901 @Override 12902 public String getInstallerPackageName(String packageName) { 12903 // reader 12904 synchronized (mPackages) { 12905 return mSettings.getInstallerPackageNameLPr(packageName); 12906 } 12907 } 12908 12909 @Override 12910 public int getApplicationEnabledSetting(String packageName, int userId) { 12911 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12912 int uid = Binder.getCallingUid(); 12913 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12914 // reader 12915 synchronized (mPackages) { 12916 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12917 } 12918 } 12919 12920 @Override 12921 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12922 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12923 int uid = Binder.getCallingUid(); 12924 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12925 // reader 12926 synchronized (mPackages) { 12927 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12928 } 12929 } 12930 12931 @Override 12932 public void enterSafeMode() { 12933 enforceSystemOrRoot("Only the system can request entering safe mode"); 12934 12935 if (!mSystemReady) { 12936 mSafeMode = true; 12937 } 12938 } 12939 12940 @Override 12941 public void systemReady() { 12942 mSystemReady = true; 12943 12944 // Read the compatibilty setting when the system is ready. 12945 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12946 mContext.getContentResolver(), 12947 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12948 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12949 if (DEBUG_SETTINGS) { 12950 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12951 } 12952 12953 synchronized (mPackages) { 12954 // Verify that all of the preferred activity components actually 12955 // exist. It is possible for applications to be updated and at 12956 // that point remove a previously declared activity component that 12957 // had been set as a preferred activity. We try to clean this up 12958 // the next time we encounter that preferred activity, but it is 12959 // possible for the user flow to never be able to return to that 12960 // situation so here we do a sanity check to make sure we haven't 12961 // left any junk around. 12962 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12963 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12964 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12965 removed.clear(); 12966 for (PreferredActivity pa : pir.filterSet()) { 12967 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12968 removed.add(pa); 12969 } 12970 } 12971 if (removed.size() > 0) { 12972 for (int r=0; r<removed.size(); r++) { 12973 PreferredActivity pa = removed.get(r); 12974 Slog.w(TAG, "Removing dangling preferred activity: " 12975 + pa.mPref.mComponent); 12976 pir.removeFilter(pa); 12977 } 12978 mSettings.writePackageRestrictionsLPr( 12979 mSettings.mPreferredActivities.keyAt(i)); 12980 } 12981 } 12982 } 12983 sUserManager.systemReady(); 12984 12985 // Kick off any messages waiting for system ready 12986 if (mPostSystemReadyMessages != null) { 12987 for (Message msg : mPostSystemReadyMessages) { 12988 msg.sendToTarget(); 12989 } 12990 mPostSystemReadyMessages = null; 12991 } 12992 12993 // Watch for external volumes that come and go over time 12994 final StorageManager storage = mContext.getSystemService(StorageManager.class); 12995 storage.registerListener(mStorageListener); 12996 12997 mInstallerService.systemReady(); 12998 } 12999 13000 @Override 13001 public boolean isSafeMode() { 13002 return mSafeMode; 13003 } 13004 13005 @Override 13006 public boolean hasSystemUidErrors() { 13007 return mHasSystemUidErrors; 13008 } 13009 13010 static String arrayToString(int[] array) { 13011 StringBuffer buf = new StringBuffer(128); 13012 buf.append('['); 13013 if (array != null) { 13014 for (int i=0; i<array.length; i++) { 13015 if (i > 0) buf.append(", "); 13016 buf.append(array[i]); 13017 } 13018 } 13019 buf.append(']'); 13020 return buf.toString(); 13021 } 13022 13023 static class DumpState { 13024 public static final int DUMP_LIBS = 1 << 0; 13025 public static final int DUMP_FEATURES = 1 << 1; 13026 public static final int DUMP_RESOLVERS = 1 << 2; 13027 public static final int DUMP_PERMISSIONS = 1 << 3; 13028 public static final int DUMP_PACKAGES = 1 << 4; 13029 public static final int DUMP_SHARED_USERS = 1 << 5; 13030 public static final int DUMP_MESSAGES = 1 << 6; 13031 public static final int DUMP_PROVIDERS = 1 << 7; 13032 public static final int DUMP_VERIFIERS = 1 << 8; 13033 public static final int DUMP_PREFERRED = 1 << 9; 13034 public static final int DUMP_PREFERRED_XML = 1 << 10; 13035 public static final int DUMP_KEYSETS = 1 << 11; 13036 public static final int DUMP_VERSION = 1 << 12; 13037 public static final int DUMP_INSTALLS = 1 << 13; 13038 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13039 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13040 13041 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13042 13043 private int mTypes; 13044 13045 private int mOptions; 13046 13047 private boolean mTitlePrinted; 13048 13049 private SharedUserSetting mSharedUser; 13050 13051 public boolean isDumping(int type) { 13052 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13053 return true; 13054 } 13055 13056 return (mTypes & type) != 0; 13057 } 13058 13059 public void setDump(int type) { 13060 mTypes |= type; 13061 } 13062 13063 public boolean isOptionEnabled(int option) { 13064 return (mOptions & option) != 0; 13065 } 13066 13067 public void setOptionEnabled(int option) { 13068 mOptions |= option; 13069 } 13070 13071 public boolean onTitlePrinted() { 13072 final boolean printed = mTitlePrinted; 13073 mTitlePrinted = true; 13074 return printed; 13075 } 13076 13077 public boolean getTitlePrinted() { 13078 return mTitlePrinted; 13079 } 13080 13081 public void setTitlePrinted(boolean enabled) { 13082 mTitlePrinted = enabled; 13083 } 13084 13085 public SharedUserSetting getSharedUser() { 13086 return mSharedUser; 13087 } 13088 13089 public void setSharedUser(SharedUserSetting user) { 13090 mSharedUser = user; 13091 } 13092 } 13093 13094 @Override 13095 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13096 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13097 != PackageManager.PERMISSION_GRANTED) { 13098 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13099 + Binder.getCallingPid() 13100 + ", uid=" + Binder.getCallingUid() 13101 + " without permission " 13102 + android.Manifest.permission.DUMP); 13103 return; 13104 } 13105 13106 DumpState dumpState = new DumpState(); 13107 boolean fullPreferred = false; 13108 boolean checkin = false; 13109 13110 String packageName = null; 13111 13112 int opti = 0; 13113 while (opti < args.length) { 13114 String opt = args[opti]; 13115 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13116 break; 13117 } 13118 opti++; 13119 13120 if ("-a".equals(opt)) { 13121 // Right now we only know how to print all. 13122 } else if ("-h".equals(opt)) { 13123 pw.println("Package manager dump options:"); 13124 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13125 pw.println(" --checkin: dump for a checkin"); 13126 pw.println(" -f: print details of intent filters"); 13127 pw.println(" -h: print this help"); 13128 pw.println(" cmd may be one of:"); 13129 pw.println(" l[ibraries]: list known shared libraries"); 13130 pw.println(" f[ibraries]: list device features"); 13131 pw.println(" k[eysets]: print known keysets"); 13132 pw.println(" r[esolvers]: dump intent resolvers"); 13133 pw.println(" perm[issions]: dump permissions"); 13134 pw.println(" pref[erred]: print preferred package settings"); 13135 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13136 pw.println(" prov[iders]: dump content providers"); 13137 pw.println(" p[ackages]: dump installed packages"); 13138 pw.println(" s[hared-users]: dump shared user IDs"); 13139 pw.println(" m[essages]: print collected runtime messages"); 13140 pw.println(" v[erifiers]: print package verifier info"); 13141 pw.println(" version: print database version info"); 13142 pw.println(" write: write current settings now"); 13143 pw.println(" <package.name>: info about given package"); 13144 pw.println(" installs: details about install sessions"); 13145 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13146 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13147 return; 13148 } else if ("--checkin".equals(opt)) { 13149 checkin = true; 13150 } else if ("-f".equals(opt)) { 13151 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13152 } else { 13153 pw.println("Unknown argument: " + opt + "; use -h for help"); 13154 } 13155 } 13156 13157 // Is the caller requesting to dump a particular piece of data? 13158 if (opti < args.length) { 13159 String cmd = args[opti]; 13160 opti++; 13161 // Is this a package name? 13162 if ("android".equals(cmd) || cmd.contains(".")) { 13163 packageName = cmd; 13164 // When dumping a single package, we always dump all of its 13165 // filter information since the amount of data will be reasonable. 13166 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13167 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13168 dumpState.setDump(DumpState.DUMP_LIBS); 13169 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13170 dumpState.setDump(DumpState.DUMP_FEATURES); 13171 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13172 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13173 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13174 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13175 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13176 dumpState.setDump(DumpState.DUMP_PREFERRED); 13177 } else if ("preferred-xml".equals(cmd)) { 13178 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13179 if (opti < args.length && "--full".equals(args[opti])) { 13180 fullPreferred = true; 13181 opti++; 13182 } 13183 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13184 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13185 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13186 dumpState.setDump(DumpState.DUMP_PACKAGES); 13187 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13188 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13189 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13190 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13191 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13192 dumpState.setDump(DumpState.DUMP_MESSAGES); 13193 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13194 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13195 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13196 || "intent-filter-verifiers".equals(cmd)) { 13197 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13198 } else if ("version".equals(cmd)) { 13199 dumpState.setDump(DumpState.DUMP_VERSION); 13200 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13201 dumpState.setDump(DumpState.DUMP_KEYSETS); 13202 } else if ("installs".equals(cmd)) { 13203 dumpState.setDump(DumpState.DUMP_INSTALLS); 13204 } else if ("write".equals(cmd)) { 13205 synchronized (mPackages) { 13206 mSettings.writeLPr(); 13207 pw.println("Settings written."); 13208 return; 13209 } 13210 } 13211 } 13212 13213 if (checkin) { 13214 pw.println("vers,1"); 13215 } 13216 13217 // reader 13218 synchronized (mPackages) { 13219 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13220 if (!checkin) { 13221 if (dumpState.onTitlePrinted()) 13222 pw.println(); 13223 pw.println("Database versions:"); 13224 pw.print(" SDK Version:"); 13225 pw.print(" internal="); 13226 pw.print(mSettings.mInternalSdkPlatform); 13227 pw.print(" external="); 13228 pw.println(mSettings.mExternalSdkPlatform); 13229 pw.print(" DB Version:"); 13230 pw.print(" internal="); 13231 pw.print(mSettings.mInternalDatabaseVersion); 13232 pw.print(" external="); 13233 pw.println(mSettings.mExternalDatabaseVersion); 13234 } 13235 } 13236 13237 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13238 if (!checkin) { 13239 if (dumpState.onTitlePrinted()) 13240 pw.println(); 13241 pw.println("Verifiers:"); 13242 pw.print(" Required: "); 13243 pw.print(mRequiredVerifierPackage); 13244 pw.print(" (uid="); 13245 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13246 pw.println(")"); 13247 } else if (mRequiredVerifierPackage != null) { 13248 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13249 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13250 } 13251 } 13252 13253 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13254 packageName == null) { 13255 if (mIntentFilterVerifierComponent != null) { 13256 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13257 if (!checkin) { 13258 if (dumpState.onTitlePrinted()) 13259 pw.println(); 13260 pw.println("Intent Filter Verifier:"); 13261 pw.print(" Using: "); 13262 pw.print(verifierPackageName); 13263 pw.print(" (uid="); 13264 pw.print(getPackageUid(verifierPackageName, 0)); 13265 pw.println(")"); 13266 } else if (verifierPackageName != null) { 13267 pw.print("ifv,"); pw.print(verifierPackageName); 13268 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13269 } 13270 } else { 13271 pw.println(); 13272 pw.println("No Intent Filter Verifier available!"); 13273 } 13274 } 13275 13276 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13277 boolean printedHeader = false; 13278 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13279 while (it.hasNext()) { 13280 String name = it.next(); 13281 SharedLibraryEntry ent = mSharedLibraries.get(name); 13282 if (!checkin) { 13283 if (!printedHeader) { 13284 if (dumpState.onTitlePrinted()) 13285 pw.println(); 13286 pw.println("Libraries:"); 13287 printedHeader = true; 13288 } 13289 pw.print(" "); 13290 } else { 13291 pw.print("lib,"); 13292 } 13293 pw.print(name); 13294 if (!checkin) { 13295 pw.print(" -> "); 13296 } 13297 if (ent.path != null) { 13298 if (!checkin) { 13299 pw.print("(jar) "); 13300 pw.print(ent.path); 13301 } else { 13302 pw.print(",jar,"); 13303 pw.print(ent.path); 13304 } 13305 } else { 13306 if (!checkin) { 13307 pw.print("(apk) "); 13308 pw.print(ent.apk); 13309 } else { 13310 pw.print(",apk,"); 13311 pw.print(ent.apk); 13312 } 13313 } 13314 pw.println(); 13315 } 13316 } 13317 13318 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13319 if (dumpState.onTitlePrinted()) 13320 pw.println(); 13321 if (!checkin) { 13322 pw.println("Features:"); 13323 } 13324 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13325 while (it.hasNext()) { 13326 String name = it.next(); 13327 if (!checkin) { 13328 pw.print(" "); 13329 } else { 13330 pw.print("feat,"); 13331 } 13332 pw.println(name); 13333 } 13334 } 13335 13336 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13337 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13338 : "Activity Resolver Table:", " ", packageName, 13339 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13340 dumpState.setTitlePrinted(true); 13341 } 13342 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13343 : "Receiver Resolver Table:", " ", packageName, 13344 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13345 dumpState.setTitlePrinted(true); 13346 } 13347 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13348 : "Service Resolver Table:", " ", packageName, 13349 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13350 dumpState.setTitlePrinted(true); 13351 } 13352 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13353 : "Provider Resolver Table:", " ", packageName, 13354 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13355 dumpState.setTitlePrinted(true); 13356 } 13357 } 13358 13359 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13360 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13361 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13362 int user = mSettings.mPreferredActivities.keyAt(i); 13363 if (pir.dump(pw, 13364 dumpState.getTitlePrinted() 13365 ? "\nPreferred Activities User " + user + ":" 13366 : "Preferred Activities User " + user + ":", " ", 13367 packageName, true, false)) { 13368 dumpState.setTitlePrinted(true); 13369 } 13370 } 13371 } 13372 13373 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13374 pw.flush(); 13375 FileOutputStream fout = new FileOutputStream(fd); 13376 BufferedOutputStream str = new BufferedOutputStream(fout); 13377 XmlSerializer serializer = new FastXmlSerializer(); 13378 try { 13379 serializer.setOutput(str, "utf-8"); 13380 serializer.startDocument(null, true); 13381 serializer.setFeature( 13382 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13383 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13384 serializer.endDocument(); 13385 serializer.flush(); 13386 } catch (IllegalArgumentException e) { 13387 pw.println("Failed writing: " + e); 13388 } catch (IllegalStateException e) { 13389 pw.println("Failed writing: " + e); 13390 } catch (IOException e) { 13391 pw.println("Failed writing: " + e); 13392 } 13393 } 13394 13395 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13396 pw.println(); 13397 int count = mSettings.mPackages.size(); 13398 if (count == 0) { 13399 pw.println("No domain preferred apps!"); 13400 pw.println(); 13401 } else { 13402 final String prefix = " "; 13403 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13404 if (allPackageSettings.size() == 0) { 13405 pw.println("No domain preferred apps!"); 13406 pw.println(); 13407 } else { 13408 pw.println("Domain preferred apps status:"); 13409 pw.println(); 13410 count = 0; 13411 for (PackageSetting ps : allPackageSettings) { 13412 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13413 if (ivi == null || ivi.getPackageName() == null) continue; 13414 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13415 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13416 pw.println(prefix + "Status: " + ivi.getStatusString()); 13417 pw.println(); 13418 count++; 13419 } 13420 if (count == 0) { 13421 pw.println(prefix + "No domain preferred app status!"); 13422 pw.println(); 13423 } 13424 for (int userId : sUserManager.getUserIds()) { 13425 pw.println("Domain preferred apps for User " + userId + ":"); 13426 pw.println(); 13427 count = 0; 13428 for (PackageSetting ps : allPackageSettings) { 13429 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13430 if (ivi == null || ivi.getPackageName() == null) { 13431 continue; 13432 } 13433 final int status = ps.getDomainVerificationStatusForUser(userId); 13434 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13435 continue; 13436 } 13437 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13438 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13439 String statusStr = IntentFilterVerificationInfo. 13440 getStatusStringFromValue(status); 13441 pw.println(prefix + "Status: " + statusStr); 13442 pw.println(); 13443 count++; 13444 } 13445 if (count == 0) { 13446 pw.println(prefix + "No domain preferred apps!"); 13447 pw.println(); 13448 } 13449 } 13450 } 13451 } 13452 } 13453 13454 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13455 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13456 if (packageName == null) { 13457 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13458 if (iperm == 0) { 13459 if (dumpState.onTitlePrinted()) 13460 pw.println(); 13461 pw.println("AppOp Permissions:"); 13462 } 13463 pw.print(" AppOp Permission "); 13464 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13465 pw.println(":"); 13466 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13467 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13468 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13469 } 13470 } 13471 } 13472 } 13473 13474 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13475 boolean printedSomething = false; 13476 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13477 if (packageName != null && !packageName.equals(p.info.packageName)) { 13478 continue; 13479 } 13480 if (!printedSomething) { 13481 if (dumpState.onTitlePrinted()) 13482 pw.println(); 13483 pw.println("Registered ContentProviders:"); 13484 printedSomething = true; 13485 } 13486 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13487 pw.print(" "); pw.println(p.toString()); 13488 } 13489 printedSomething = false; 13490 for (Map.Entry<String, PackageParser.Provider> entry : 13491 mProvidersByAuthority.entrySet()) { 13492 PackageParser.Provider p = entry.getValue(); 13493 if (packageName != null && !packageName.equals(p.info.packageName)) { 13494 continue; 13495 } 13496 if (!printedSomething) { 13497 if (dumpState.onTitlePrinted()) 13498 pw.println(); 13499 pw.println("ContentProvider Authorities:"); 13500 printedSomething = true; 13501 } 13502 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13503 pw.print(" "); pw.println(p.toString()); 13504 if (p.info != null && p.info.applicationInfo != null) { 13505 final String appInfo = p.info.applicationInfo.toString(); 13506 pw.print(" applicationInfo="); pw.println(appInfo); 13507 } 13508 } 13509 } 13510 13511 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13512 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13513 } 13514 13515 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13516 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13517 } 13518 13519 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13520 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13521 } 13522 13523 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13524 // XXX should handle packageName != null by dumping only install data that 13525 // the given package is involved with. 13526 if (dumpState.onTitlePrinted()) pw.println(); 13527 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13528 } 13529 13530 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13531 if (dumpState.onTitlePrinted()) pw.println(); 13532 mSettings.dumpReadMessagesLPr(pw, dumpState); 13533 13534 pw.println(); 13535 pw.println("Package warning messages:"); 13536 BufferedReader in = null; 13537 String line = null; 13538 try { 13539 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13540 while ((line = in.readLine()) != null) { 13541 if (line.contains("ignored: updated version")) continue; 13542 pw.println(line); 13543 } 13544 } catch (IOException ignored) { 13545 } finally { 13546 IoUtils.closeQuietly(in); 13547 } 13548 } 13549 13550 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13551 BufferedReader in = null; 13552 String line = null; 13553 try { 13554 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13555 while ((line = in.readLine()) != null) { 13556 if (line.contains("ignored: updated version")) continue; 13557 pw.print("msg,"); 13558 pw.println(line); 13559 } 13560 } catch (IOException ignored) { 13561 } finally { 13562 IoUtils.closeQuietly(in); 13563 } 13564 } 13565 } 13566 } 13567 13568 // ------- apps on sdcard specific code ------- 13569 static final boolean DEBUG_SD_INSTALL = false; 13570 13571 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13572 13573 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13574 13575 private boolean mMediaMounted = false; 13576 13577 static String getEncryptKey() { 13578 try { 13579 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13580 SD_ENCRYPTION_KEYSTORE_NAME); 13581 if (sdEncKey == null) { 13582 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13583 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13584 if (sdEncKey == null) { 13585 Slog.e(TAG, "Failed to create encryption keys"); 13586 return null; 13587 } 13588 } 13589 return sdEncKey; 13590 } catch (NoSuchAlgorithmException nsae) { 13591 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13592 return null; 13593 } catch (IOException ioe) { 13594 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13595 return null; 13596 } 13597 } 13598 13599 /* 13600 * Update media status on PackageManager. 13601 */ 13602 @Override 13603 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13604 int callingUid = Binder.getCallingUid(); 13605 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13606 throw new SecurityException("Media status can only be updated by the system"); 13607 } 13608 // reader; this apparently protects mMediaMounted, but should probably 13609 // be a different lock in that case. 13610 synchronized (mPackages) { 13611 Log.i(TAG, "Updating external media status from " 13612 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13613 + (mediaStatus ? "mounted" : "unmounted")); 13614 if (DEBUG_SD_INSTALL) 13615 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13616 + ", mMediaMounted=" + mMediaMounted); 13617 if (mediaStatus == mMediaMounted) { 13618 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13619 : 0, -1); 13620 mHandler.sendMessage(msg); 13621 return; 13622 } 13623 mMediaMounted = mediaStatus; 13624 } 13625 // Queue up an async operation since the package installation may take a 13626 // little while. 13627 mHandler.post(new Runnable() { 13628 public void run() { 13629 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13630 } 13631 }); 13632 } 13633 13634 /** 13635 * Called by MountService when the initial ASECs to scan are available. 13636 * Should block until all the ASEC containers are finished being scanned. 13637 */ 13638 public void scanAvailableAsecs() { 13639 updateExternalMediaStatusInner(true, false, false); 13640 if (mShouldRestoreconData) { 13641 SELinuxMMAC.setRestoreconDone(); 13642 mShouldRestoreconData = false; 13643 } 13644 } 13645 13646 /* 13647 * Collect information of applications on external media, map them against 13648 * existing containers and update information based on current mount status. 13649 * Please note that we always have to report status if reportStatus has been 13650 * set to true especially when unloading packages. 13651 */ 13652 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13653 boolean externalStorage) { 13654 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13655 int[] uidArr = EmptyArray.INT; 13656 13657 final String[] list = PackageHelper.getSecureContainerList(); 13658 if (ArrayUtils.isEmpty(list)) { 13659 Log.i(TAG, "No secure containers found"); 13660 } else { 13661 // Process list of secure containers and categorize them 13662 // as active or stale based on their package internal state. 13663 13664 // reader 13665 synchronized (mPackages) { 13666 for (String cid : list) { 13667 // Leave stages untouched for now; installer service owns them 13668 if (PackageInstallerService.isStageName(cid)) continue; 13669 13670 if (DEBUG_SD_INSTALL) 13671 Log.i(TAG, "Processing container " + cid); 13672 String pkgName = getAsecPackageName(cid); 13673 if (pkgName == null) { 13674 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13675 continue; 13676 } 13677 if (DEBUG_SD_INSTALL) 13678 Log.i(TAG, "Looking for pkg : " + pkgName); 13679 13680 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13681 if (ps == null) { 13682 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13683 continue; 13684 } 13685 13686 /* 13687 * Skip packages that are not external if we're unmounting 13688 * external storage. 13689 */ 13690 if (externalStorage && !isMounted && !isExternal(ps)) { 13691 continue; 13692 } 13693 13694 final AsecInstallArgs args = new AsecInstallArgs(cid, 13695 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13696 // The package status is changed only if the code path 13697 // matches between settings and the container id. 13698 if (ps.codePathString != null 13699 && ps.codePathString.startsWith(args.getCodePath())) { 13700 if (DEBUG_SD_INSTALL) { 13701 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13702 + " at code path: " + ps.codePathString); 13703 } 13704 13705 // We do have a valid package installed on sdcard 13706 processCids.put(args, ps.codePathString); 13707 final int uid = ps.appId; 13708 if (uid != -1) { 13709 uidArr = ArrayUtils.appendInt(uidArr, uid); 13710 } 13711 } else { 13712 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13713 + ps.codePathString); 13714 } 13715 } 13716 } 13717 13718 Arrays.sort(uidArr); 13719 } 13720 13721 // Process packages with valid entries. 13722 if (isMounted) { 13723 if (DEBUG_SD_INSTALL) 13724 Log.i(TAG, "Loading packages"); 13725 loadMediaPackages(processCids, uidArr); 13726 startCleaningPackages(); 13727 mInstallerService.onSecureContainersAvailable(); 13728 } else { 13729 if (DEBUG_SD_INSTALL) 13730 Log.i(TAG, "Unloading packages"); 13731 unloadMediaPackages(processCids, uidArr, reportStatus); 13732 } 13733 } 13734 13735 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13736 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13737 final int size = infos.size(); 13738 final String[] packageNames = new String[size]; 13739 final int[] packageUids = new int[size]; 13740 for (int i = 0; i < size; i++) { 13741 final ApplicationInfo info = infos.get(i); 13742 packageNames[i] = info.packageName; 13743 packageUids[i] = info.uid; 13744 } 13745 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13746 finishedReceiver); 13747 } 13748 13749 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13750 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13751 sendResourcesChangedBroadcast(mediaStatus, replacing, 13752 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13753 } 13754 13755 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13756 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13757 int size = pkgList.length; 13758 if (size > 0) { 13759 // Send broadcasts here 13760 Bundle extras = new Bundle(); 13761 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13762 if (uidArr != null) { 13763 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13764 } 13765 if (replacing) { 13766 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13767 } 13768 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13769 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13770 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13771 } 13772 } 13773 13774 /* 13775 * Look at potentially valid container ids from processCids If package 13776 * information doesn't match the one on record or package scanning fails, 13777 * the cid is added to list of removeCids. We currently don't delete stale 13778 * containers. 13779 */ 13780 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13781 ArrayList<String> pkgList = new ArrayList<String>(); 13782 Set<AsecInstallArgs> keys = processCids.keySet(); 13783 13784 for (AsecInstallArgs args : keys) { 13785 String codePath = processCids.get(args); 13786 if (DEBUG_SD_INSTALL) 13787 Log.i(TAG, "Loading container : " + args.cid); 13788 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13789 try { 13790 // Make sure there are no container errors first. 13791 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13792 Slog.e(TAG, "Failed to mount cid : " + args.cid 13793 + " when installing from sdcard"); 13794 continue; 13795 } 13796 // Check code path here. 13797 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13798 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13799 + " does not match one in settings " + codePath); 13800 continue; 13801 } 13802 // Parse package 13803 int parseFlags = mDefParseFlags; 13804 if (args.isExternalAsec()) { 13805 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13806 } 13807 if (args.isFwdLocked()) { 13808 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13809 } 13810 13811 synchronized (mInstallLock) { 13812 PackageParser.Package pkg = null; 13813 try { 13814 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13815 } catch (PackageManagerException e) { 13816 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13817 } 13818 // Scan the package 13819 if (pkg != null) { 13820 /* 13821 * TODO why is the lock being held? doPostInstall is 13822 * called in other places without the lock. This needs 13823 * to be straightened out. 13824 */ 13825 // writer 13826 synchronized (mPackages) { 13827 retCode = PackageManager.INSTALL_SUCCEEDED; 13828 pkgList.add(pkg.packageName); 13829 // Post process args 13830 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13831 pkg.applicationInfo.uid); 13832 } 13833 } else { 13834 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13835 } 13836 } 13837 13838 } finally { 13839 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13840 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13841 } 13842 } 13843 } 13844 // writer 13845 synchronized (mPackages) { 13846 // If the platform SDK has changed since the last time we booted, 13847 // we need to re-grant app permission to catch any new ones that 13848 // appear. This is really a hack, and means that apps can in some 13849 // cases get permissions that the user didn't initially explicitly 13850 // allow... it would be nice to have some better way to handle 13851 // this situation. 13852 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13853 if (regrantPermissions) 13854 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13855 + mSdkVersion + "; regranting permissions for external storage"); 13856 mSettings.mExternalSdkPlatform = mSdkVersion; 13857 13858 // Make sure group IDs have been assigned, and any permission 13859 // changes in other apps are accounted for 13860 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13861 | (regrantPermissions 13862 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13863 : 0)); 13864 13865 mSettings.updateExternalDatabaseVersion(); 13866 13867 // can downgrade to reader 13868 // Persist settings 13869 mSettings.writeLPr(); 13870 } 13871 // Send a broadcast to let everyone know we are done processing 13872 if (pkgList.size() > 0) { 13873 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13874 } 13875 } 13876 13877 /* 13878 * Utility method to unload a list of specified containers 13879 */ 13880 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13881 // Just unmount all valid containers. 13882 for (AsecInstallArgs arg : cidArgs) { 13883 synchronized (mInstallLock) { 13884 arg.doPostDeleteLI(false); 13885 } 13886 } 13887 } 13888 13889 /* 13890 * Unload packages mounted on external media. This involves deleting package 13891 * data from internal structures, sending broadcasts about diabled packages, 13892 * gc'ing to free up references, unmounting all secure containers 13893 * corresponding to packages on external media, and posting a 13894 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13895 * that we always have to post this message if status has been requested no 13896 * matter what. 13897 */ 13898 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13899 final boolean reportStatus) { 13900 if (DEBUG_SD_INSTALL) 13901 Log.i(TAG, "unloading media packages"); 13902 ArrayList<String> pkgList = new ArrayList<String>(); 13903 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13904 final Set<AsecInstallArgs> keys = processCids.keySet(); 13905 for (AsecInstallArgs args : keys) { 13906 String pkgName = args.getPackageName(); 13907 if (DEBUG_SD_INSTALL) 13908 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13909 // Delete package internally 13910 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13911 synchronized (mInstallLock) { 13912 boolean res = deletePackageLI(pkgName, null, false, null, null, 13913 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13914 if (res) { 13915 pkgList.add(pkgName); 13916 } else { 13917 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13918 failedList.add(args); 13919 } 13920 } 13921 } 13922 13923 // reader 13924 synchronized (mPackages) { 13925 // We didn't update the settings after removing each package; 13926 // write them now for all packages. 13927 mSettings.writeLPr(); 13928 } 13929 13930 // We have to absolutely send UPDATED_MEDIA_STATUS only 13931 // after confirming that all the receivers processed the ordered 13932 // broadcast when packages get disabled, force a gc to clean things up. 13933 // and unload all the containers. 13934 if (pkgList.size() > 0) { 13935 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13936 new IIntentReceiver.Stub() { 13937 public void performReceive(Intent intent, int resultCode, String data, 13938 Bundle extras, boolean ordered, boolean sticky, 13939 int sendingUser) throws RemoteException { 13940 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13941 reportStatus ? 1 : 0, 1, keys); 13942 mHandler.sendMessage(msg); 13943 } 13944 }); 13945 } else { 13946 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13947 keys); 13948 mHandler.sendMessage(msg); 13949 } 13950 } 13951 13952 private void loadPrivatePackages(VolumeInfo vol) { 13953 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 13954 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 13955 synchronized (mPackages) { 13956 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 13957 for (PackageSetting ps : packages) { 13958 synchronized (mInstallLock) { 13959 final PackageParser.Package pkg; 13960 try { 13961 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 13962 loaded.add(pkg.applicationInfo); 13963 } catch (PackageManagerException e) { 13964 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 13965 } 13966 } 13967 } 13968 13969 // TODO: regrant any permissions that changed based since original install 13970 13971 mSettings.writeLPr(); 13972 } 13973 13974 Slog.d(TAG, "Loaded packages " + loaded); 13975 sendResourcesChangedBroadcast(true, false, loaded, null); 13976 } 13977 13978 private void unloadPrivatePackages(VolumeInfo vol) { 13979 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 13980 synchronized (mPackages) { 13981 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 13982 for (PackageSetting ps : packages) { 13983 if (ps.pkg == null) continue; 13984 synchronized (mInstallLock) { 13985 final ApplicationInfo info = ps.pkg.applicationInfo; 13986 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13987 if (deletePackageLI(ps.name, null, false, null, null, 13988 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 13989 unloaded.add(info); 13990 } else { 13991 Slog.w(TAG, "Failed to unload " + ps.codePath); 13992 } 13993 } 13994 } 13995 13996 mSettings.writeLPr(); 13997 } 13998 13999 Slog.d(TAG, "Unloaded packages " + unloaded); 14000 sendResourcesChangedBroadcast(false, false, unloaded, null); 14001 } 14002 14003 @Override 14004 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14005 final int flags) { 14006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14007 14008 final int installFlags; 14009 if ((flags & MOVE_INTERNAL) != 0) { 14010 installFlags = INSTALL_INTERNAL; 14011 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14012 installFlags = INSTALL_EXTERNAL; 14013 } else { 14014 throw new IllegalArgumentException("Unsupported move flags " + flags); 14015 } 14016 14017 try { 14018 movePackageInternal(packageName, null, installFlags, false, observer); 14019 } catch (PackageManagerException e) { 14020 Slog.d(TAG, "Failed to move " + packageName, e); 14021 try { 14022 observer.packageMoved(packageName, e.error); 14023 } catch (RemoteException ignored) { 14024 } 14025 } 14026 } 14027 14028 @Override 14029 public void movePackageAndData(final String packageName, final String volumeUuid, 14030 final IPackageMoveObserver observer) { 14031 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14032 try { 14033 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14034 } catch (PackageManagerException e) { 14035 Slog.d(TAG, "Failed to move " + packageName, e); 14036 try { 14037 observer.packageMoved(packageName, e.error); 14038 } catch (RemoteException ignored) { 14039 } 14040 } 14041 } 14042 14043 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14044 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14045 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14046 14047 File codeFile = null; 14048 String installerPackageName = null; 14049 String packageAbiOverride = null; 14050 14051 // TOOD: move app private data before installing 14052 14053 // reader 14054 synchronized (mPackages) { 14055 final PackageParser.Package pkg = mPackages.get(packageName); 14056 final PackageSetting ps = mSettings.mPackages.get(packageName); 14057 if (pkg == null || ps == null) { 14058 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14059 } 14060 14061 if (pkg.applicationInfo.isSystemApp()) { 14062 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14063 "Cannot move system application"); 14064 } else if (pkg.mOperationPending) { 14065 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14066 "Attempt to move package which has pending operations"); 14067 } 14068 14069 // TODO: yell if already in desired location 14070 14071 pkg.mOperationPending = true; 14072 14073 codeFile = new File(pkg.codePath); 14074 installerPackageName = ps.installerPackageName; 14075 packageAbiOverride = ps.cpuAbiOverrideString; 14076 } 14077 14078 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14079 @Override 14080 public void onUserActionRequired(Intent intent) throws RemoteException { 14081 throw new IllegalStateException(); 14082 } 14083 14084 @Override 14085 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14086 Bundle extras) throws RemoteException { 14087 Slog.d(TAG, "Install result for move: " 14088 + PackageManager.installStatusToString(returnCode, msg)); 14089 14090 // We usually have a new package now after the install, but if 14091 // we failed we need to clear the pending flag on the original 14092 // package object. 14093 synchronized (mPackages) { 14094 final PackageParser.Package pkg = mPackages.get(packageName); 14095 if (pkg != null) { 14096 pkg.mOperationPending = false; 14097 } 14098 } 14099 14100 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14101 switch (status) { 14102 case PackageInstaller.STATUS_SUCCESS: 14103 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14104 break; 14105 case PackageInstaller.STATUS_FAILURE_STORAGE: 14106 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14107 break; 14108 default: 14109 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14110 break; 14111 } 14112 } 14113 }; 14114 14115 // Treat a move like reinstalling an existing app, which ensures that we 14116 // process everythign uniformly, like unpacking native libraries. 14117 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14118 14119 final Message msg = mHandler.obtainMessage(INIT_COPY); 14120 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14121 msg.obj = new InstallParams(origin, installObserver, installFlags, 14122 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14123 mHandler.sendMessage(msg); 14124 } 14125 14126 @Override 14127 public boolean setInstallLocation(int loc) { 14128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14129 null); 14130 if (getInstallLocation() == loc) { 14131 return true; 14132 } 14133 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14134 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14135 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14136 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14137 return true; 14138 } 14139 return false; 14140 } 14141 14142 @Override 14143 public int getInstallLocation() { 14144 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14145 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14146 PackageHelper.APP_INSTALL_AUTO); 14147 } 14148 14149 /** Called by UserManagerService */ 14150 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14151 mDirtyUsers.remove(userHandle); 14152 mSettings.removeUserLPw(userHandle); 14153 mPendingBroadcasts.remove(userHandle); 14154 if (mInstaller != null) { 14155 // Technically, we shouldn't be doing this with the package lock 14156 // held. However, this is very rare, and there is already so much 14157 // other disk I/O going on, that we'll let it slide for now. 14158 mInstaller.removeUserDataDirs(userHandle); 14159 } 14160 mUserNeedsBadging.delete(userHandle); 14161 removeUnusedPackagesLILPw(userManager, userHandle); 14162 } 14163 14164 /** 14165 * We're removing userHandle and would like to remove any downloaded packages 14166 * that are no longer in use by any other user. 14167 * @param userHandle the user being removed 14168 */ 14169 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14170 final boolean DEBUG_CLEAN_APKS = false; 14171 int [] users = userManager.getUserIdsLPr(); 14172 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14173 while (psit.hasNext()) { 14174 PackageSetting ps = psit.next(); 14175 if (ps.pkg == null) { 14176 continue; 14177 } 14178 final String packageName = ps.pkg.packageName; 14179 // Skip over if system app 14180 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14181 continue; 14182 } 14183 if (DEBUG_CLEAN_APKS) { 14184 Slog.i(TAG, "Checking package " + packageName); 14185 } 14186 boolean keep = false; 14187 for (int i = 0; i < users.length; i++) { 14188 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14189 keep = true; 14190 if (DEBUG_CLEAN_APKS) { 14191 Slog.i(TAG, " Keeping package " + packageName + " for user " 14192 + users[i]); 14193 } 14194 break; 14195 } 14196 } 14197 if (!keep) { 14198 if (DEBUG_CLEAN_APKS) { 14199 Slog.i(TAG, " Removing package " + packageName); 14200 } 14201 mHandler.post(new Runnable() { 14202 public void run() { 14203 deletePackageX(packageName, userHandle, 0); 14204 } //end run 14205 }); 14206 } 14207 } 14208 } 14209 14210 /** Called by UserManagerService */ 14211 void createNewUserLILPw(int userHandle, File path) { 14212 if (mInstaller != null) { 14213 mInstaller.createUserConfig(userHandle); 14214 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14215 } 14216 } 14217 14218 void newUserCreatedLILPw(int userHandle) { 14219 // Adding a user requires updating runtime permissions for system apps. 14220 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14221 } 14222 14223 @Override 14224 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14225 mContext.enforceCallingOrSelfPermission( 14226 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14227 "Only package verification agents can read the verifier device identity"); 14228 14229 synchronized (mPackages) { 14230 return mSettings.getVerifierDeviceIdentityLPw(); 14231 } 14232 } 14233 14234 @Override 14235 public void setPermissionEnforced(String permission, boolean enforced) { 14236 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14237 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14238 synchronized (mPackages) { 14239 if (mSettings.mReadExternalStorageEnforced == null 14240 || mSettings.mReadExternalStorageEnforced != enforced) { 14241 mSettings.mReadExternalStorageEnforced = enforced; 14242 mSettings.writeLPr(); 14243 } 14244 } 14245 // kill any non-foreground processes so we restart them and 14246 // grant/revoke the GID. 14247 final IActivityManager am = ActivityManagerNative.getDefault(); 14248 if (am != null) { 14249 final long token = Binder.clearCallingIdentity(); 14250 try { 14251 am.killProcessesBelowForeground("setPermissionEnforcement"); 14252 } catch (RemoteException e) { 14253 } finally { 14254 Binder.restoreCallingIdentity(token); 14255 } 14256 } 14257 } else { 14258 throw new IllegalArgumentException("No selective enforcement for " + permission); 14259 } 14260 } 14261 14262 @Override 14263 @Deprecated 14264 public boolean isPermissionEnforced(String permission) { 14265 return true; 14266 } 14267 14268 @Override 14269 public boolean isStorageLow() { 14270 final long token = Binder.clearCallingIdentity(); 14271 try { 14272 final DeviceStorageMonitorInternal 14273 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14274 if (dsm != null) { 14275 return dsm.isMemoryLow(); 14276 } else { 14277 return false; 14278 } 14279 } finally { 14280 Binder.restoreCallingIdentity(token); 14281 } 14282 } 14283 14284 @Override 14285 public IPackageInstaller getPackageInstaller() { 14286 return mInstallerService; 14287 } 14288 14289 private boolean userNeedsBadging(int userId) { 14290 int index = mUserNeedsBadging.indexOfKey(userId); 14291 if (index < 0) { 14292 final UserInfo userInfo; 14293 final long token = Binder.clearCallingIdentity(); 14294 try { 14295 userInfo = sUserManager.getUserInfo(userId); 14296 } finally { 14297 Binder.restoreCallingIdentity(token); 14298 } 14299 final boolean b; 14300 if (userInfo != null && userInfo.isManagedProfile()) { 14301 b = true; 14302 } else { 14303 b = false; 14304 } 14305 mUserNeedsBadging.put(userId, b); 14306 return b; 14307 } 14308 return mUserNeedsBadging.valueAt(index); 14309 } 14310 14311 @Override 14312 public KeySet getKeySetByAlias(String packageName, String alias) { 14313 if (packageName == null || alias == null) { 14314 return null; 14315 } 14316 synchronized(mPackages) { 14317 final PackageParser.Package pkg = mPackages.get(packageName); 14318 if (pkg == null) { 14319 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14320 throw new IllegalArgumentException("Unknown package: " + packageName); 14321 } 14322 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14323 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14324 } 14325 } 14326 14327 @Override 14328 public KeySet getSigningKeySet(String packageName) { 14329 if (packageName == null) { 14330 return null; 14331 } 14332 synchronized(mPackages) { 14333 final PackageParser.Package pkg = mPackages.get(packageName); 14334 if (pkg == null) { 14335 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14336 throw new IllegalArgumentException("Unknown package: " + packageName); 14337 } 14338 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14339 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14340 throw new SecurityException("May not access signing KeySet of other apps."); 14341 } 14342 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14343 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14344 } 14345 } 14346 14347 @Override 14348 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14349 if (packageName == null || ks == null) { 14350 return false; 14351 } 14352 synchronized(mPackages) { 14353 final PackageParser.Package pkg = mPackages.get(packageName); 14354 if (pkg == null) { 14355 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14356 throw new IllegalArgumentException("Unknown package: " + packageName); 14357 } 14358 IBinder ksh = ks.getToken(); 14359 if (ksh instanceof KeySetHandle) { 14360 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14361 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14362 } 14363 return false; 14364 } 14365 } 14366 14367 @Override 14368 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14369 if (packageName == null || ks == null) { 14370 return false; 14371 } 14372 synchronized(mPackages) { 14373 final PackageParser.Package pkg = mPackages.get(packageName); 14374 if (pkg == null) { 14375 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14376 throw new IllegalArgumentException("Unknown package: " + packageName); 14377 } 14378 IBinder ksh = ks.getToken(); 14379 if (ksh instanceof KeySetHandle) { 14380 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14381 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14382 } 14383 return false; 14384 } 14385 } 14386 14387 public void getUsageStatsIfNoPackageUsageInfo() { 14388 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14389 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14390 if (usm == null) { 14391 throw new IllegalStateException("UsageStatsManager must be initialized"); 14392 } 14393 long now = System.currentTimeMillis(); 14394 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14395 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14396 String packageName = entry.getKey(); 14397 PackageParser.Package pkg = mPackages.get(packageName); 14398 if (pkg == null) { 14399 continue; 14400 } 14401 UsageStats usage = entry.getValue(); 14402 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14403 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14404 } 14405 } 14406 } 14407 14408 /** 14409 * Check and throw if the given before/after packages would be considered a 14410 * downgrade. 14411 */ 14412 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14413 throws PackageManagerException { 14414 if (after.versionCode < before.mVersionCode) { 14415 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14416 "Update version code " + after.versionCode + " is older than current " 14417 + before.mVersionCode); 14418 } else if (after.versionCode == before.mVersionCode) { 14419 if (after.baseRevisionCode < before.baseRevisionCode) { 14420 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14421 "Update base revision code " + after.baseRevisionCode 14422 + " is older than current " + before.baseRevisionCode); 14423 } 14424 14425 if (!ArrayUtils.isEmpty(after.splitNames)) { 14426 for (int i = 0; i < after.splitNames.length; i++) { 14427 final String splitName = after.splitNames[i]; 14428 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14429 if (j != -1) { 14430 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14431 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14432 "Update split " + splitName + " revision code " 14433 + after.splitRevisionCodes[i] + " is older than current " 14434 + before.splitRevisionCodes[j]); 14435 } 14436 } 14437 } 14438 } 14439 } 14440 } 14441} 14442