PackageManagerService.java revision 805b63e253c139625f5a86d72ef7b31d6ec9f8e9
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 ArraySet<String> domainsSet = new ArraySet<>(); 568 for (int m=0; m<filterCount; m++) { 569 PackageParser.ActivityIntentInfo filter = filters.get(m); 570 domainsSet.addAll(filter.getHostsList()); 571 } 572 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 573 synchronized (mPackages) { 574 modified = mSettings.createIntentFilterVerificationIfNeededLPw( 575 packageName, domainsList); 576 if (modified) { 577 scheduleWriteSettingsLocked(); 578 } 579 } 580 sendVerificationRequest(userId, verificationId, ivs); 581 } 582 mCurrentIntentFilterVerifications.clear(); 583 } 584 585 private void sendVerificationRequest(int userId, int verificationId, 586 IntentFilterVerificationState ivs) { 587 588 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 589 verificationIntent.putExtra( 590 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 591 verificationId); 592 verificationIntent.putExtra( 593 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 594 getDefaultScheme()); 595 verificationIntent.putExtra( 596 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 597 ivs.getHostsString()); 598 verificationIntent.putExtra( 599 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 600 ivs.getPackageName()); 601 verificationIntent.setComponent(mIntentFilterVerifierComponent); 602 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 603 604 UserHandle user = new UserHandle(userId); 605 mContext.sendBroadcastAsUser(verificationIntent, user); 606 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 607 } 608 609 public void receiveVerificationResponse(int verificationId) { 610 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 611 612 final boolean verified = ivs.isVerified(); 613 614 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 615 final int count = filters.size(); 616 for (int n=0; n<count; n++) { 617 PackageParser.ActivityIntentInfo filter = filters.get(n); 618 filter.setVerified(verified); 619 620 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 621 + verified + " and hosts:" + ivs.getHostsString()); 622 } 623 624 mIntentFilterVerificationStates.remove(verificationId); 625 626 final String packageName = ivs.getPackageName(); 627 IntentFilterVerificationInfo ivi = null; 628 629 synchronized (mPackages) { 630 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 631 } 632 if (ivi == null) { 633 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 634 + verificationId + " packageName:" + packageName); 635 return; 636 } 637 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 638 + verificationId); 639 640 synchronized (mPackages) { 641 if (verified) { 642 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 643 } else { 644 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 645 } 646 scheduleWriteSettingsLocked(); 647 648 final int userId = ivs.getUserId(); 649 if (userId != UserHandle.USER_ALL) { 650 final int userStatus = 651 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 652 653 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 654 boolean needUpdate = false; 655 656 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 657 // already been set by the User thru the Disambiguation dialog 658 switch (userStatus) { 659 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 660 if (verified) { 661 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 662 } else { 663 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 664 } 665 needUpdate = true; 666 break; 667 668 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 669 if (verified) { 670 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 671 needUpdate = true; 672 } 673 break; 674 675 default: 676 // Nothing to do 677 } 678 679 if (needUpdate) { 680 mSettings.updateIntentFilterVerificationStatusLPw( 681 packageName, updatedStatus, userId); 682 scheduleWritePackageRestrictionsLocked(userId); 683 } 684 } 685 } 686 } 687 688 @Override 689 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 690 ActivityIntentInfo filter, String packageName) { 691 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 692 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 693 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 694 return false; 695 } 696 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 697 if (ivs == null) { 698 ivs = createDomainVerificationState(verifierId, userId, verificationId, 699 packageName); 700 } 701 ArrayList<String> hosts = filter.getHostsList(); 702 if (!hasValidHosts(hosts)) { 703 return false; 704 } 705 ivs.addFilter(filter); 706 return true; 707 } 708 709 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 710 int userId, int verificationId, String packageName) { 711 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 712 verifierId, userId, packageName); 713 ivs.setPendingState(); 714 synchronized (mPackages) { 715 mIntentFilterVerificationStates.append(verificationId, ivs); 716 mCurrentIntentFilterVerifications.add(verificationId); 717 } 718 return ivs; 719 } 720 } 721 722 private static boolean hasValidHosts(ArrayList<String> hosts) { 723 if (hosts.size() == 0) { 724 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 725 return false; 726 } 727 String hostEndBase = null; 728 for (String host : hosts) { 729 String[] hostParts = host.split("\\."); 730 // Should be at minimum a host like "example.com" 731 if (hostParts.length < 2) { 732 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 733 return false; 734 } 735 // Verify that we have the same ending domain 736 int length = hostParts.length; 737 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 738 if (hostEndBase == null) { 739 hostEndBase = hostEnd; 740 } 741 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 742 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 743 return false; 744 } 745 } 746 return true; 747 } 748 749 private IntentFilterVerifier mIntentFilterVerifier; 750 751 // Set of pending broadcasts for aggregating enable/disable of components. 752 static class PendingPackageBroadcasts { 753 // for each user id, a map of <package name -> components within that package> 754 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 755 756 public PendingPackageBroadcasts() { 757 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 758 } 759 760 public ArrayList<String> get(int userId, String packageName) { 761 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 762 return packages.get(packageName); 763 } 764 765 public void put(int userId, String packageName, ArrayList<String> components) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 packages.put(packageName, components); 768 } 769 770 public void remove(int userId, String packageName) { 771 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 772 if (packages != null) { 773 packages.remove(packageName); 774 } 775 } 776 777 public void remove(int userId) { 778 mUidMap.remove(userId); 779 } 780 781 public int userIdCount() { 782 return mUidMap.size(); 783 } 784 785 public int userIdAt(int n) { 786 return mUidMap.keyAt(n); 787 } 788 789 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 790 return mUidMap.get(userId); 791 } 792 793 public int size() { 794 // total number of pending broadcast entries across all userIds 795 int num = 0; 796 for (int i = 0; i< mUidMap.size(); i++) { 797 num += mUidMap.valueAt(i).size(); 798 } 799 return num; 800 } 801 802 public void clear() { 803 mUidMap.clear(); 804 } 805 806 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 807 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 808 if (map == null) { 809 map = new ArrayMap<String, ArrayList<String>>(); 810 mUidMap.put(userId, map); 811 } 812 return map; 813 } 814 } 815 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 816 817 // Service Connection to remote media container service to copy 818 // package uri's from external media onto secure containers 819 // or internal storage. 820 private IMediaContainerService mContainerService = null; 821 822 static final int SEND_PENDING_BROADCAST = 1; 823 static final int MCS_BOUND = 3; 824 static final int END_COPY = 4; 825 static final int INIT_COPY = 5; 826 static final int MCS_UNBIND = 6; 827 static final int START_CLEANING_PACKAGE = 7; 828 static final int FIND_INSTALL_LOC = 8; 829 static final int POST_INSTALL = 9; 830 static final int MCS_RECONNECT = 10; 831 static final int MCS_GIVE_UP = 11; 832 static final int UPDATED_MEDIA_STATUS = 12; 833 static final int WRITE_SETTINGS = 13; 834 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 835 static final int PACKAGE_VERIFIED = 15; 836 static final int CHECK_PENDING_VERIFICATION = 16; 837 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 838 static final int INTENT_FILTER_VERIFIED = 18; 839 840 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 841 842 // Delay time in millisecs 843 static final int BROADCAST_DELAY = 10 * 1000; 844 845 static UserManagerService sUserManager; 846 847 // Stores a list of users whose package restrictions file needs to be updated 848 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 849 850 final private DefaultContainerConnection mDefContainerConn = 851 new DefaultContainerConnection(); 852 class DefaultContainerConnection implements ServiceConnection { 853 public void onServiceConnected(ComponentName name, IBinder service) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 855 IMediaContainerService imcs = 856 IMediaContainerService.Stub.asInterface(service); 857 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 858 } 859 860 public void onServiceDisconnected(ComponentName name) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 862 } 863 }; 864 865 // Recordkeeping of restore-after-install operations that are currently in flight 866 // between the Package Manager and the Backup Manager 867 class PostInstallData { 868 public InstallArgs args; 869 public PackageInstalledInfo res; 870 871 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 872 args = _a; 873 res = _r; 874 } 875 }; 876 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 877 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 878 879 // backup/restore of preferred activity state 880 private static final String TAG_PREFERRED_BACKUP = "pa"; 881 882 private final String mRequiredVerifierPackage; 883 884 private final PackageUsage mPackageUsage = new PackageUsage(); 885 886 private class PackageUsage { 887 private static final int WRITE_INTERVAL 888 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 889 890 private final Object mFileLock = new Object(); 891 private final AtomicLong mLastWritten = new AtomicLong(0); 892 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 893 894 private boolean mIsHistoricalPackageUsageAvailable = true; 895 896 boolean isHistoricalPackageUsageAvailable() { 897 return mIsHistoricalPackageUsageAvailable; 898 } 899 900 void write(boolean force) { 901 if (force) { 902 writeInternal(); 903 return; 904 } 905 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 906 && !DEBUG_DEXOPT) { 907 return; 908 } 909 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 910 new Thread("PackageUsage_DiskWriter") { 911 @Override 912 public void run() { 913 try { 914 writeInternal(); 915 } finally { 916 mBackgroundWriteRunning.set(false); 917 } 918 } 919 }.start(); 920 } 921 } 922 923 private void writeInternal() { 924 synchronized (mPackages) { 925 synchronized (mFileLock) { 926 AtomicFile file = getFile(); 927 FileOutputStream f = null; 928 try { 929 f = file.startWrite(); 930 BufferedOutputStream out = new BufferedOutputStream(f); 931 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 932 StringBuilder sb = new StringBuilder(); 933 for (PackageParser.Package pkg : mPackages.values()) { 934 if (pkg.mLastPackageUsageTimeInMills == 0) { 935 continue; 936 } 937 sb.setLength(0); 938 sb.append(pkg.packageName); 939 sb.append(' '); 940 sb.append((long)pkg.mLastPackageUsageTimeInMills); 941 sb.append('\n'); 942 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 943 } 944 out.flush(); 945 file.finishWrite(f); 946 } catch (IOException e) { 947 if (f != null) { 948 file.failWrite(f); 949 } 950 Log.e(TAG, "Failed to write package usage times", e); 951 } 952 } 953 } 954 mLastWritten.set(SystemClock.elapsedRealtime()); 955 } 956 957 void readLP() { 958 synchronized (mFileLock) { 959 AtomicFile file = getFile(); 960 BufferedInputStream in = null; 961 try { 962 in = new BufferedInputStream(file.openRead()); 963 StringBuffer sb = new StringBuffer(); 964 while (true) { 965 String packageName = readToken(in, sb, ' '); 966 if (packageName == null) { 967 break; 968 } 969 String timeInMillisString = readToken(in, sb, '\n'); 970 if (timeInMillisString == null) { 971 throw new IOException("Failed to find last usage time for package " 972 + packageName); 973 } 974 PackageParser.Package pkg = mPackages.get(packageName); 975 if (pkg == null) { 976 continue; 977 } 978 long timeInMillis; 979 try { 980 timeInMillis = Long.parseLong(timeInMillisString.toString()); 981 } catch (NumberFormatException e) { 982 throw new IOException("Failed to parse " + timeInMillisString 983 + " as a long.", e); 984 } 985 pkg.mLastPackageUsageTimeInMills = timeInMillis; 986 } 987 } catch (FileNotFoundException expected) { 988 mIsHistoricalPackageUsageAvailable = false; 989 } catch (IOException e) { 990 Log.w(TAG, "Failed to read package usage times", e); 991 } finally { 992 IoUtils.closeQuietly(in); 993 } 994 } 995 mLastWritten.set(SystemClock.elapsedRealtime()); 996 } 997 998 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 999 throws IOException { 1000 sb.setLength(0); 1001 while (true) { 1002 int ch = in.read(); 1003 if (ch == -1) { 1004 if (sb.length() == 0) { 1005 return null; 1006 } 1007 throw new IOException("Unexpected EOF"); 1008 } 1009 if (ch == endOfToken) { 1010 return sb.toString(); 1011 } 1012 sb.append((char)ch); 1013 } 1014 } 1015 1016 private AtomicFile getFile() { 1017 File dataDir = Environment.getDataDirectory(); 1018 File systemDir = new File(dataDir, "system"); 1019 File fname = new File(systemDir, "package-usage.list"); 1020 return new AtomicFile(fname); 1021 } 1022 } 1023 1024 class PackageHandler extends Handler { 1025 private boolean mBound = false; 1026 final ArrayList<HandlerParams> mPendingInstalls = 1027 new ArrayList<HandlerParams>(); 1028 1029 private boolean connectToService() { 1030 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1031 " DefaultContainerService"); 1032 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1034 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1035 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 mBound = true; 1038 return true; 1039 } 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 return false; 1042 } 1043 1044 private void disconnectService() { 1045 mContainerService = null; 1046 mBound = false; 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1048 mContext.unbindService(mDefContainerConn); 1049 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1050 } 1051 1052 PackageHandler(Looper looper) { 1053 super(looper); 1054 } 1055 1056 public void handleMessage(Message msg) { 1057 try { 1058 doHandleMessage(msg); 1059 } finally { 1060 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1061 } 1062 } 1063 1064 void doHandleMessage(Message msg) { 1065 switch (msg.what) { 1066 case INIT_COPY: { 1067 HandlerParams params = (HandlerParams) msg.obj; 1068 int idx = mPendingInstalls.size(); 1069 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1070 // If a bind was already initiated we dont really 1071 // need to do anything. The pending install 1072 // will be processed later on. 1073 if (!mBound) { 1074 // If this is the only one pending we might 1075 // have to bind to the service again. 1076 if (!connectToService()) { 1077 Slog.e(TAG, "Failed to bind to media container service"); 1078 params.serviceError(); 1079 return; 1080 } else { 1081 // Once we bind to the service, the first 1082 // pending request will be processed. 1083 mPendingInstalls.add(idx, params); 1084 } 1085 } else { 1086 mPendingInstalls.add(idx, params); 1087 // Already bound to the service. Just make 1088 // sure we trigger off processing the first request. 1089 if (idx == 0) { 1090 mHandler.sendEmptyMessage(MCS_BOUND); 1091 } 1092 } 1093 break; 1094 } 1095 case MCS_BOUND: { 1096 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1097 if (msg.obj != null) { 1098 mContainerService = (IMediaContainerService) msg.obj; 1099 } 1100 if (mContainerService == null) { 1101 // Something seriously wrong. Bail out 1102 Slog.e(TAG, "Cannot bind to media container service"); 1103 for (HandlerParams params : mPendingInstalls) { 1104 // Indicate service bind error 1105 params.serviceError(); 1106 } 1107 mPendingInstalls.clear(); 1108 } else if (mPendingInstalls.size() > 0) { 1109 HandlerParams params = mPendingInstalls.get(0); 1110 if (params != null) { 1111 if (params.startCopy()) { 1112 // We are done... look for more work or to 1113 // go idle. 1114 if (DEBUG_SD_INSTALL) Log.i(TAG, 1115 "Checking for more work or unbind..."); 1116 // Delete pending install 1117 if (mPendingInstalls.size() > 0) { 1118 mPendingInstalls.remove(0); 1119 } 1120 if (mPendingInstalls.size() == 0) { 1121 if (mBound) { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, 1123 "Posting delayed MCS_UNBIND"); 1124 removeMessages(MCS_UNBIND); 1125 Message ubmsg = obtainMessage(MCS_UNBIND); 1126 // Unbind after a little delay, to avoid 1127 // continual thrashing. 1128 sendMessageDelayed(ubmsg, 10000); 1129 } 1130 } else { 1131 // There are more pending requests in queue. 1132 // Just post MCS_BOUND message to trigger processing 1133 // of next pending install. 1134 if (DEBUG_SD_INSTALL) Log.i(TAG, 1135 "Posting MCS_BOUND for next work"); 1136 mHandler.sendEmptyMessage(MCS_BOUND); 1137 } 1138 } 1139 } 1140 } else { 1141 // Should never happen ideally. 1142 Slog.w(TAG, "Empty queue"); 1143 } 1144 break; 1145 } 1146 case MCS_RECONNECT: { 1147 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1148 if (mPendingInstalls.size() > 0) { 1149 if (mBound) { 1150 disconnectService(); 1151 } 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 for (HandlerParams params : mPendingInstalls) { 1155 // Indicate service bind error 1156 params.serviceError(); 1157 } 1158 mPendingInstalls.clear(); 1159 } 1160 } 1161 break; 1162 } 1163 case MCS_UNBIND: { 1164 // If there is no actual work left, then time to unbind. 1165 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1166 1167 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1168 if (mBound) { 1169 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1170 1171 disconnectService(); 1172 } 1173 } else if (mPendingInstalls.size() > 0) { 1174 // There are more pending requests in queue. 1175 // Just post MCS_BOUND message to trigger processing 1176 // of next pending install. 1177 mHandler.sendEmptyMessage(MCS_BOUND); 1178 } 1179 1180 break; 1181 } 1182 case MCS_GIVE_UP: { 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1184 mPendingInstalls.remove(0); 1185 break; 1186 } 1187 case SEND_PENDING_BROADCAST: { 1188 String packages[]; 1189 ArrayList<String> components[]; 1190 int size = 0; 1191 int uids[]; 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1193 synchronized (mPackages) { 1194 if (mPendingBroadcasts == null) { 1195 return; 1196 } 1197 size = mPendingBroadcasts.size(); 1198 if (size <= 0) { 1199 // Nothing to be done. Just return 1200 return; 1201 } 1202 packages = new String[size]; 1203 components = new ArrayList[size]; 1204 uids = new int[size]; 1205 int i = 0; // filling out the above arrays 1206 1207 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1208 int packageUserId = mPendingBroadcasts.userIdAt(n); 1209 Iterator<Map.Entry<String, ArrayList<String>>> it 1210 = mPendingBroadcasts.packagesForUserId(packageUserId) 1211 .entrySet().iterator(); 1212 while (it.hasNext() && i < size) { 1213 Map.Entry<String, ArrayList<String>> ent = it.next(); 1214 packages[i] = ent.getKey(); 1215 components[i] = ent.getValue(); 1216 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1217 uids[i] = (ps != null) 1218 ? UserHandle.getUid(packageUserId, ps.appId) 1219 : -1; 1220 i++; 1221 } 1222 } 1223 size = i; 1224 mPendingBroadcasts.clear(); 1225 } 1226 // Send broadcasts 1227 for (int i = 0; i < size; i++) { 1228 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1229 } 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1231 break; 1232 } 1233 case START_CLEANING_PACKAGE: { 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1235 final String packageName = (String)msg.obj; 1236 final int userId = msg.arg1; 1237 final boolean andCode = msg.arg2 != 0; 1238 synchronized (mPackages) { 1239 if (userId == UserHandle.USER_ALL) { 1240 int[] users = sUserManager.getUserIds(); 1241 for (int user : users) { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(user, packageName, andCode)); 1244 } 1245 } else { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(userId, packageName, andCode)); 1248 } 1249 } 1250 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1251 startCleaningPackages(); 1252 } break; 1253 case POST_INSTALL: { 1254 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1255 PostInstallData data = mRunningInstalls.get(msg.arg1); 1256 mRunningInstalls.delete(msg.arg1); 1257 boolean deleteOld = false; 1258 1259 if (data != null) { 1260 InstallArgs args = data.args; 1261 PackageInstalledInfo res = data.res; 1262 1263 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1264 res.removedInfo.sendBroadcast(false, true, false); 1265 Bundle extras = new Bundle(1); 1266 extras.putInt(Intent.EXTRA_UID, res.uid); 1267 1268 // Now that we successfully installed the package, grant runtime 1269 // permissions if requested before broadcasting the install. 1270 if ((args.installFlags 1271 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1272 grantRequestedRuntimePermissions(res.pkg, 1273 args.user.getIdentifier()); 1274 } 1275 1276 // Determine the set of users who are adding this 1277 // package for the first time vs. those who are seeing 1278 // an update. 1279 int[] firstUsers; 1280 int[] updateUsers = new int[0]; 1281 if (res.origUsers == null || res.origUsers.length == 0) { 1282 firstUsers = res.newUsers; 1283 } else { 1284 firstUsers = new int[0]; 1285 for (int i=0; i<res.newUsers.length; i++) { 1286 int user = res.newUsers[i]; 1287 boolean isNew = true; 1288 for (int j=0; j<res.origUsers.length; j++) { 1289 if (res.origUsers[j] == user) { 1290 isNew = false; 1291 break; 1292 } 1293 } 1294 if (isNew) { 1295 int[] newFirst = new int[firstUsers.length+1]; 1296 System.arraycopy(firstUsers, 0, newFirst, 0, 1297 firstUsers.length); 1298 newFirst[firstUsers.length] = user; 1299 firstUsers = newFirst; 1300 } else { 1301 int[] newUpdate = new int[updateUsers.length+1]; 1302 System.arraycopy(updateUsers, 0, newUpdate, 0, 1303 updateUsers.length); 1304 newUpdate[updateUsers.length] = user; 1305 updateUsers = newUpdate; 1306 } 1307 } 1308 } 1309 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1310 res.pkg.applicationInfo.packageName, 1311 extras, null, null, firstUsers); 1312 final boolean update = res.removedInfo.removedPackage != null; 1313 if (update) { 1314 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 if (update) { 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1324 null, null, 1325 res.pkg.applicationInfo.packageName, null, updateUsers); 1326 1327 // treat asec-hosted packages like removable media on upgrade 1328 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1329 if (DEBUG_INSTALL) { 1330 Slog.i(TAG, "upgrading pkg " + res.pkg 1331 + " is ASEC-hosted -> AVAILABLE"); 1332 } 1333 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1334 ArrayList<String> pkgList = new ArrayList<String>(1); 1335 pkgList.add(res.pkg.applicationInfo.packageName); 1336 sendResourcesChangedBroadcast(true, true, 1337 pkgList,uidArray, null); 1338 } 1339 } 1340 if (res.removedInfo.args != null) { 1341 // Remove the replaced package's older resources safely now 1342 deleteOld = true; 1343 } 1344 1345 // Log current value of "unknown sources" setting 1346 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1347 getUnknownSourcesSettings()); 1348 } 1349 // Force a gc to clear up things 1350 Runtime.getRuntime().gc(); 1351 // We delete after a gc for applications on sdcard. 1352 if (deleteOld) { 1353 synchronized (mInstallLock) { 1354 res.removedInfo.args.doPostDeleteLI(true); 1355 } 1356 } 1357 if (args.observer != null) { 1358 try { 1359 Bundle extras = extrasForInstallResult(res); 1360 args.observer.onPackageInstalled(res.name, res.returnCode, 1361 res.returnMsg, extras); 1362 } catch (RemoteException e) { 1363 Slog.i(TAG, "Observer no longer exists."); 1364 } 1365 } 1366 } else { 1367 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1368 } 1369 } break; 1370 case UPDATED_MEDIA_STATUS: { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1372 boolean reportStatus = msg.arg1 == 1; 1373 boolean doGc = msg.arg2 == 1; 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1375 if (doGc) { 1376 // Force a gc to clear up stale containers. 1377 Runtime.getRuntime().gc(); 1378 } 1379 if (msg.obj != null) { 1380 @SuppressWarnings("unchecked") 1381 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1383 // Unload containers 1384 unloadAllContainers(args); 1385 } 1386 if (reportStatus) { 1387 try { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1389 PackageHelper.getMountService().finishMediaUpdate(); 1390 } catch (RemoteException e) { 1391 Log.e(TAG, "MountService not running?"); 1392 } 1393 } 1394 } break; 1395 case WRITE_SETTINGS: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 synchronized (mPackages) { 1398 removeMessages(WRITE_SETTINGS); 1399 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1400 mSettings.writeLPr(); 1401 mDirtyUsers.clear(); 1402 } 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1404 } break; 1405 case WRITE_PACKAGE_RESTRICTIONS: { 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 synchronized (mPackages) { 1408 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1409 for (int userId : mDirtyUsers) { 1410 mSettings.writePackageRestrictionsLPr(userId); 1411 } 1412 mDirtyUsers.clear(); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 } break; 1416 case CHECK_PENDING_VERIFICATION: { 1417 final int verificationId = msg.arg1; 1418 final PackageVerificationState state = mPendingVerification.get(verificationId); 1419 1420 if ((state != null) && !state.timeoutExtended()) { 1421 final InstallArgs args = state.getInstallArgs(); 1422 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1423 1424 Slog.i(TAG, "Verification timed out for " + originUri); 1425 mPendingVerification.remove(verificationId); 1426 1427 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1428 1429 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1430 Slog.i(TAG, "Continuing with installation of " + originUri); 1431 state.setVerifierResponse(Binder.getCallingUid(), 1432 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1433 broadcastPackageVerified(verificationId, originUri, 1434 PackageManager.VERIFICATION_ALLOW, 1435 state.getInstallArgs().getUser()); 1436 try { 1437 ret = args.copyApk(mContainerService, true); 1438 } catch (RemoteException e) { 1439 Slog.e(TAG, "Could not contact the ContainerService"); 1440 } 1441 } else { 1442 broadcastPackageVerified(verificationId, originUri, 1443 PackageManager.VERIFICATION_REJECT, 1444 state.getInstallArgs().getUser()); 1445 } 1446 1447 processPendingInstall(args, ret); 1448 mHandler.sendEmptyMessage(MCS_UNBIND); 1449 } 1450 break; 1451 } 1452 case PACKAGE_VERIFIED: { 1453 final int verificationId = msg.arg1; 1454 1455 final PackageVerificationState state = mPendingVerification.get(verificationId); 1456 if (state == null) { 1457 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1458 break; 1459 } 1460 1461 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1462 1463 state.setVerifierResponse(response.callerUid, response.code); 1464 1465 if (state.isVerificationComplete()) { 1466 mPendingVerification.remove(verificationId); 1467 1468 final InstallArgs args = state.getInstallArgs(); 1469 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1470 1471 int ret; 1472 if (state.isInstallAllowed()) { 1473 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1474 broadcastPackageVerified(verificationId, originUri, 1475 response.code, state.getInstallArgs().getUser()); 1476 try { 1477 ret = args.copyApk(mContainerService, true); 1478 } catch (RemoteException e) { 1479 Slog.e(TAG, "Could not contact the ContainerService"); 1480 } 1481 } else { 1482 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1483 } 1484 1485 processPendingInstall(args, ret); 1486 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 1490 break; 1491 } 1492 case START_INTENT_FILTER_VERIFICATIONS: { 1493 int userId = msg.arg1; 1494 int verifierUid = msg.arg2; 1495 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1496 1497 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1498 break; 1499 } 1500 case INTENT_FILTER_VERIFIED: { 1501 final int verificationId = msg.arg1; 1502 1503 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1504 verificationId); 1505 if (state == null) { 1506 Slog.w(TAG, "Invalid IntentFilter verification token " 1507 + verificationId + " received"); 1508 break; 1509 } 1510 1511 final int userId = state.getUserId(); 1512 1513 Slog.d(TAG, "Processing IntentFilter verification with token:" 1514 + verificationId + " and userId:" + userId); 1515 1516 final IntentFilterVerificationResponse response = 1517 (IntentFilterVerificationResponse) msg.obj; 1518 1519 state.setVerifierResponse(response.callerUid, response.code); 1520 1521 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1522 + " and userId:" + userId 1523 + " is settings verifier response with response code:" 1524 + response.code); 1525 1526 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1527 Slog.d(TAG, "Domains failing verification: " 1528 + response.getFailedDomainsString()); 1529 } 1530 1531 if (state.isVerificationComplete()) { 1532 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1533 } else { 1534 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1535 + " was not said to be complete"); 1536 } 1537 1538 break; 1539 } 1540 } 1541 } 1542 } 1543 1544 private StorageEventListener mStorageListener = new StorageEventListener() { 1545 @Override 1546 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1547 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1548 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1549 loadPrivatePackages(vol); 1550 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1551 unloadPrivatePackages(vol); 1552 } 1553 } 1554 1555 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1556 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1557 updateExternalMediaStatus(true, false); 1558 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1559 updateExternalMediaStatus(false, false); 1560 } 1561 } 1562 } 1563 }; 1564 1565 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1566 if (userId >= UserHandle.USER_OWNER) { 1567 grantRequestedRuntimePermissionsForUser(pkg, userId); 1568 } else if (userId == UserHandle.USER_ALL) { 1569 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1570 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1571 } 1572 } 1573 } 1574 1575 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1576 SettingBase sb = (SettingBase) pkg.mExtras; 1577 if (sb == null) { 1578 return; 1579 } 1580 1581 PermissionsState permissionsState = sb.getPermissionsState(); 1582 1583 for (String permission : pkg.requestedPermissions) { 1584 BasePermission bp = mSettings.mPermissions.get(permission); 1585 if (bp != null && bp.isRuntime()) { 1586 permissionsState.grantRuntimePermission(bp, userId); 1587 } 1588 } 1589 } 1590 1591 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1592 Bundle extras = null; 1593 switch (res.returnCode) { 1594 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1595 extras = new Bundle(); 1596 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1597 res.origPermission); 1598 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1599 res.origPackage); 1600 break; 1601 } 1602 } 1603 return extras; 1604 } 1605 1606 void scheduleWriteSettingsLocked() { 1607 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1608 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1609 } 1610 } 1611 1612 void scheduleWritePackageRestrictionsLocked(int userId) { 1613 if (!sUserManager.exists(userId)) return; 1614 mDirtyUsers.add(userId); 1615 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1616 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1617 } 1618 } 1619 1620 public static PackageManagerService main(Context context, Installer installer, 1621 boolean factoryTest, boolean onlyCore) { 1622 PackageManagerService m = new PackageManagerService(context, installer, 1623 factoryTest, onlyCore); 1624 ServiceManager.addService("package", m); 1625 return m; 1626 } 1627 1628 static String[] splitString(String str, char sep) { 1629 int count = 1; 1630 int i = 0; 1631 while ((i=str.indexOf(sep, i)) >= 0) { 1632 count++; 1633 i++; 1634 } 1635 1636 String[] res = new String[count]; 1637 i=0; 1638 count = 0; 1639 int lastI=0; 1640 while ((i=str.indexOf(sep, i)) >= 0) { 1641 res[count] = str.substring(lastI, i); 1642 count++; 1643 i++; 1644 lastI = i; 1645 } 1646 res[count] = str.substring(lastI, str.length()); 1647 return res; 1648 } 1649 1650 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1651 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1652 Context.DISPLAY_SERVICE); 1653 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1654 } 1655 1656 public PackageManagerService(Context context, Installer installer, 1657 boolean factoryTest, boolean onlyCore) { 1658 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1659 SystemClock.uptimeMillis()); 1660 1661 if (mSdkVersion <= 0) { 1662 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1663 } 1664 1665 mContext = context; 1666 mFactoryTest = factoryTest; 1667 mOnlyCore = onlyCore; 1668 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1669 mMetrics = new DisplayMetrics(); 1670 mSettings = new Settings(mPackages); 1671 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1674 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1675 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1676 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1677 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1682 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1683 1684 // TODO: add a property to control this? 1685 long dexOptLRUThresholdInMinutes; 1686 if (mLazyDexOpt) { 1687 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1688 } else { 1689 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1690 } 1691 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1692 1693 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1694 if (separateProcesses != null && separateProcesses.length() > 0) { 1695 if ("*".equals(separateProcesses)) { 1696 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1697 mSeparateProcesses = null; 1698 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1699 } else { 1700 mDefParseFlags = 0; 1701 mSeparateProcesses = separateProcesses.split(","); 1702 Slog.w(TAG, "Running with debug.separate_processes: " 1703 + separateProcesses); 1704 } 1705 } else { 1706 mDefParseFlags = 0; 1707 mSeparateProcesses = null; 1708 } 1709 1710 mInstaller = installer; 1711 mPackageDexOptimizer = new PackageDexOptimizer(this); 1712 1713 getDefaultDisplayMetrics(context, mMetrics); 1714 1715 SystemConfig systemConfig = SystemConfig.getInstance(); 1716 mGlobalGids = systemConfig.getGlobalGids(); 1717 mSystemPermissions = systemConfig.getSystemPermissions(); 1718 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1719 1720 synchronized (mInstallLock) { 1721 // writer 1722 synchronized (mPackages) { 1723 mHandlerThread = new ServiceThread(TAG, 1724 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1725 mHandlerThread.start(); 1726 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1727 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1728 1729 File dataDir = Environment.getDataDirectory(); 1730 mAppDataDir = new File(dataDir, "data"); 1731 mAppInstallDir = new File(dataDir, "app"); 1732 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1733 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1734 mUserAppDataDir = new File(dataDir, "user"); 1735 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1736 1737 sUserManager = new UserManagerService(context, this, 1738 mInstallLock, mPackages); 1739 1740 // Propagate permission configuration in to package manager. 1741 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1742 = systemConfig.getPermissions(); 1743 for (int i=0; i<permConfig.size(); i++) { 1744 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1745 BasePermission bp = mSettings.mPermissions.get(perm.name); 1746 if (bp == null) { 1747 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1748 mSettings.mPermissions.put(perm.name, bp); 1749 } 1750 if (perm.gids != null) { 1751 bp.setGids(perm.gids, perm.perUser); 1752 } 1753 } 1754 1755 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1756 for (int i=0; i<libConfig.size(); i++) { 1757 mSharedLibraries.put(libConfig.keyAt(i), 1758 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1759 } 1760 1761 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1762 1763 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1764 mSdkVersion, mOnlyCore); 1765 1766 String customResolverActivity = Resources.getSystem().getString( 1767 R.string.config_customResolverActivity); 1768 if (TextUtils.isEmpty(customResolverActivity)) { 1769 customResolverActivity = null; 1770 } else { 1771 mCustomResolverComponentName = ComponentName.unflattenFromString( 1772 customResolverActivity); 1773 } 1774 1775 long startTime = SystemClock.uptimeMillis(); 1776 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1778 startTime); 1779 1780 // Set flag to monitor and not change apk file paths when 1781 // scanning install directories. 1782 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1783 1784 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1785 1786 /** 1787 * Add everything in the in the boot class path to the 1788 * list of process files because dexopt will have been run 1789 * if necessary during zygote startup. 1790 */ 1791 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1792 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1793 1794 if (bootClassPath != null) { 1795 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1796 for (String element : bootClassPathElements) { 1797 alreadyDexOpted.add(element); 1798 } 1799 } else { 1800 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1801 } 1802 1803 if (systemServerClassPath != null) { 1804 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1805 for (String element : systemServerClassPathElements) { 1806 alreadyDexOpted.add(element); 1807 } 1808 } else { 1809 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1810 } 1811 1812 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1813 final String[] dexCodeInstructionSets = 1814 getDexCodeInstructionSets( 1815 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1816 1817 /** 1818 * Ensure all external libraries have had dexopt run on them. 1819 */ 1820 if (mSharedLibraries.size() > 0) { 1821 // NOTE: For now, we're compiling these system "shared libraries" 1822 // (and framework jars) into all available architectures. It's possible 1823 // to compile them only when we come across an app that uses them (there's 1824 // already logic for that in scanPackageLI) but that adds some complexity. 1825 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1826 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1827 final String lib = libEntry.path; 1828 if (lib == null) { 1829 continue; 1830 } 1831 1832 try { 1833 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1834 dexCodeInstructionSet, 1835 false); 1836 if (dexoptRequired != DexFile.UP_TO_DATE) { 1837 alreadyDexOpted.add(lib); 1838 1839 // The list of "shared libraries" we have at this point is 1840 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1841 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1842 } else { 1843 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1844 } 1845 } 1846 } catch (FileNotFoundException e) { 1847 Slog.w(TAG, "Library not found: " + lib); 1848 } catch (IOException e) { 1849 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1850 + e.getMessage()); 1851 } 1852 } 1853 } 1854 } 1855 1856 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1857 1858 // Gross hack for now: we know this file doesn't contain any 1859 // code, so don't dexopt it to avoid the resulting log spew. 1860 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1861 1862 // Gross hack for now: we know this file is only part of 1863 // the boot class path for art, so don't dexopt it to 1864 // avoid the resulting log spew. 1865 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1866 1867 /** 1868 * And there are a number of commands implemented in Java, which 1869 * we currently need to do the dexopt on so that they can be 1870 * run from a non-root shell. 1871 */ 1872 String[] frameworkFiles = frameworkDir.list(); 1873 if (frameworkFiles != null) { 1874 // TODO: We could compile these only for the most preferred ABI. We should 1875 // first double check that the dex files for these commands are not referenced 1876 // by other system apps. 1877 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1878 for (int i=0; i<frameworkFiles.length; i++) { 1879 File libPath = new File(frameworkDir, frameworkFiles[i]); 1880 String path = libPath.getPath(); 1881 // Skip the file if we already did it. 1882 if (alreadyDexOpted.contains(path)) { 1883 continue; 1884 } 1885 // Skip the file if it is not a type we want to dexopt. 1886 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1887 continue; 1888 } 1889 try { 1890 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1891 dexCodeInstructionSet, 1892 false); 1893 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1894 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1895 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1896 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1897 } 1898 } catch (FileNotFoundException e) { 1899 Slog.w(TAG, "Jar not found: " + path); 1900 } catch (IOException e) { 1901 Slog.w(TAG, "Exception reading jar: " + path, e); 1902 } 1903 } 1904 } 1905 } 1906 1907 // Collect vendor overlay packages. 1908 // (Do this before scanning any apps.) 1909 // For security and version matching reason, only consider 1910 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1911 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1912 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1913 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1914 1915 // Find base frameworks (resource packages without code). 1916 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR 1918 | PackageParser.PARSE_IS_PRIVILEGED, 1919 scanFlags | SCAN_NO_DEX, 0); 1920 1921 // Collected privileged system packages. 1922 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1923 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1924 | PackageParser.PARSE_IS_SYSTEM_DIR 1925 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1926 1927 // Collect ordinary system packages. 1928 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1929 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1931 1932 // Collect all vendor packages. 1933 File vendorAppDir = new File("/vendor/app"); 1934 try { 1935 vendorAppDir = vendorAppDir.getCanonicalFile(); 1936 } catch (IOException e) { 1937 // failed to look up canonical path, continue with original one 1938 } 1939 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1941 1942 // Collect all OEM packages. 1943 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1944 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1945 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1946 1947 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1948 mInstaller.moveFiles(); 1949 1950 // Prune any system packages that no longer exist. 1951 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1952 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1953 if (!mOnlyCore) { 1954 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1955 while (psit.hasNext()) { 1956 PackageSetting ps = psit.next(); 1957 1958 /* 1959 * If this is not a system app, it can't be a 1960 * disable system app. 1961 */ 1962 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1963 continue; 1964 } 1965 1966 /* 1967 * If the package is scanned, it's not erased. 1968 */ 1969 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1970 if (scannedPkg != null) { 1971 /* 1972 * If the system app is both scanned and in the 1973 * disabled packages list, then it must have been 1974 * added via OTA. Remove it from the currently 1975 * scanned package so the previously user-installed 1976 * application can be scanned. 1977 */ 1978 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1979 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1980 + ps.name + "; removing system app. Last known codePath=" 1981 + ps.codePathString + ", installStatus=" + ps.installStatus 1982 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1983 + scannedPkg.mVersionCode); 1984 removePackageLI(ps, true); 1985 expectingBetter.put(ps.name, ps.codePath); 1986 } 1987 1988 continue; 1989 } 1990 1991 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1992 psit.remove(); 1993 logCriticalInfo(Log.WARN, "System package " + ps.name 1994 + " no longer exists; wiping its data"); 1995 removeDataDirsLI(ps.name); 1996 } else { 1997 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1998 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1999 possiblyDeletedUpdatedSystemApps.add(ps.name); 2000 } 2001 } 2002 } 2003 } 2004 2005 //look for any incomplete package installations 2006 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2007 //clean up list 2008 for(int i = 0; i < deletePkgsList.size(); i++) { 2009 //clean up here 2010 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2011 } 2012 //delete tmp files 2013 deleteTempPackageFiles(); 2014 2015 // Remove any shared userIDs that have no associated packages 2016 mSettings.pruneSharedUsersLPw(); 2017 2018 if (!mOnlyCore) { 2019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2020 SystemClock.uptimeMillis()); 2021 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2022 2023 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2024 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2025 2026 /** 2027 * Remove disable package settings for any updated system 2028 * apps that were removed via an OTA. If they're not a 2029 * previously-updated app, remove them completely. 2030 * Otherwise, just revoke their system-level permissions. 2031 */ 2032 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2033 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2034 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2035 2036 String msg; 2037 if (deletedPkg == null) { 2038 msg = "Updated system package " + deletedAppName 2039 + " no longer exists; wiping its data"; 2040 removeDataDirsLI(deletedAppName); 2041 } else { 2042 msg = "Updated system app + " + deletedAppName 2043 + " no longer present; removing system privileges for " 2044 + deletedAppName; 2045 2046 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2047 2048 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2049 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2050 } 2051 logCriticalInfo(Log.WARN, msg); 2052 } 2053 2054 /** 2055 * Make sure all system apps that we expected to appear on 2056 * the userdata partition actually showed up. If they never 2057 * appeared, crawl back and revive the system version. 2058 */ 2059 for (int i = 0; i < expectingBetter.size(); i++) { 2060 final String packageName = expectingBetter.keyAt(i); 2061 if (!mPackages.containsKey(packageName)) { 2062 final File scanFile = expectingBetter.valueAt(i); 2063 2064 logCriticalInfo(Log.WARN, "Expected better " + packageName 2065 + " but never showed up; reverting to system"); 2066 2067 final int reparseFlags; 2068 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2069 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2070 | PackageParser.PARSE_IS_SYSTEM_DIR 2071 | PackageParser.PARSE_IS_PRIVILEGED; 2072 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2073 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2074 | PackageParser.PARSE_IS_SYSTEM_DIR; 2075 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2076 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2077 | PackageParser.PARSE_IS_SYSTEM_DIR; 2078 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2079 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR; 2081 } else { 2082 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2083 continue; 2084 } 2085 2086 mSettings.enableSystemPackageLPw(packageName); 2087 2088 try { 2089 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2090 } catch (PackageManagerException e) { 2091 Slog.e(TAG, "Failed to parse original system package: " 2092 + e.getMessage()); 2093 } 2094 } 2095 } 2096 } 2097 2098 // Now that we know all of the shared libraries, update all clients to have 2099 // the correct library paths. 2100 updateAllSharedLibrariesLPw(); 2101 2102 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2103 // NOTE: We ignore potential failures here during a system scan (like 2104 // the rest of the commands above) because there's precious little we 2105 // can do about it. A settings error is reported, though. 2106 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2107 false /* force dexopt */, false /* defer dexopt */); 2108 } 2109 2110 // Now that we know all the packages we are keeping, 2111 // read and update their last usage times. 2112 mPackageUsage.readLP(); 2113 2114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2115 SystemClock.uptimeMillis()); 2116 Slog.i(TAG, "Time to scan packages: " 2117 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2118 + " seconds"); 2119 2120 // If the platform SDK has changed since the last time we booted, 2121 // we need to re-grant app permission to catch any new ones that 2122 // appear. This is really a hack, and means that apps can in some 2123 // cases get permissions that the user didn't initially explicitly 2124 // allow... it would be nice to have some better way to handle 2125 // this situation. 2126 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2127 != mSdkVersion; 2128 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2129 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2130 + "; regranting permissions for internal storage"); 2131 mSettings.mInternalSdkPlatform = mSdkVersion; 2132 2133 // For now runtime permissions are toggled via a system property. 2134 if (!RUNTIME_PERMISSIONS_ENABLED) { 2135 // Remove the runtime permissions state if the feature 2136 // was disabled by flipping the system property. 2137 mSettings.deleteRuntimePermissionsFiles(); 2138 } 2139 2140 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2141 | (regrantPermissions 2142 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2143 : 0)); 2144 2145 // If this is the first boot, and it is a normal boot, then 2146 // we need to initialize the default preferred apps. 2147 if (!mRestoredSettings && !onlyCore) { 2148 mSettings.readDefaultPreferredAppsLPw(this, 0); 2149 } 2150 2151 // If this is first boot after an OTA, and a normal boot, then 2152 // we need to clear code cache directories. 2153 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2154 if (mIsUpgrade && !onlyCore) { 2155 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2156 for (String pkgName : mSettings.mPackages.keySet()) { 2157 deleteCodeCacheDirsLI(pkgName); 2158 } 2159 mSettings.mFingerprint = Build.FINGERPRINT; 2160 } 2161 2162 // All the changes are done during package scanning. 2163 mSettings.updateInternalDatabaseVersion(); 2164 2165 // can downgrade to reader 2166 mSettings.writeLPr(); 2167 2168 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2169 SystemClock.uptimeMillis()); 2170 2171 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2172 2173 mInstallerService = new PackageInstallerService(context, this); 2174 2175 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2176 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2177 mIntentFilterVerifierComponent); 2178 2179 } // synchronized (mPackages) 2180 } // synchronized (mInstallLock) 2181 2182 // Now after opening every single application zip, make sure they 2183 // are all flushed. Not really needed, but keeps things nice and 2184 // tidy. 2185 Runtime.getRuntime().gc(); 2186 } 2187 2188 @Override 2189 public boolean isFirstBoot() { 2190 return !mRestoredSettings; 2191 } 2192 2193 @Override 2194 public boolean isOnlyCoreApps() { 2195 return mOnlyCore; 2196 } 2197 2198 @Override 2199 public boolean isUpgrade() { 2200 return mIsUpgrade; 2201 } 2202 2203 private String getRequiredVerifierLPr() { 2204 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2205 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2206 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2207 2208 String requiredVerifier = null; 2209 2210 final int N = receivers.size(); 2211 for (int i = 0; i < N; i++) { 2212 final ResolveInfo info = receivers.get(i); 2213 2214 if (info.activityInfo == null) { 2215 continue; 2216 } 2217 2218 final String packageName = info.activityInfo.packageName; 2219 2220 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2221 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2222 continue; 2223 } 2224 2225 if (requiredVerifier != null) { 2226 throw new RuntimeException("There can be only one required verifier"); 2227 } 2228 2229 requiredVerifier = packageName; 2230 } 2231 2232 return requiredVerifier; 2233 } 2234 2235 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2236 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2237 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2238 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2239 2240 ComponentName verifierComponentName = null; 2241 2242 int priority = -1000; 2243 final int N = receivers.size(); 2244 for (int i = 0; i < N; i++) { 2245 final ResolveInfo info = receivers.get(i); 2246 2247 if (info.activityInfo == null) { 2248 continue; 2249 } 2250 2251 final String packageName = info.activityInfo.packageName; 2252 2253 final PackageSetting ps = mSettings.mPackages.get(packageName); 2254 if (ps == null) { 2255 continue; 2256 } 2257 2258 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2259 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2260 continue; 2261 } 2262 2263 // Select the IntentFilterVerifier with the highest priority 2264 if (priority < info.priority) { 2265 priority = info.priority; 2266 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2267 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2268 " with priority: " + info.priority); 2269 } 2270 } 2271 2272 return verifierComponentName; 2273 } 2274 2275 @Override 2276 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2277 throws RemoteException { 2278 try { 2279 return super.onTransact(code, data, reply, flags); 2280 } catch (RuntimeException e) { 2281 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2282 Slog.wtf(TAG, "Package Manager Crash", e); 2283 } 2284 throw e; 2285 } 2286 } 2287 2288 void cleanupInstallFailedPackage(PackageSetting ps) { 2289 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2290 2291 removeDataDirsLI(ps.name); 2292 if (ps.codePath != null) { 2293 if (ps.codePath.isDirectory()) { 2294 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2295 } else { 2296 ps.codePath.delete(); 2297 } 2298 } 2299 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2300 if (ps.resourcePath.isDirectory()) { 2301 FileUtils.deleteContents(ps.resourcePath); 2302 } 2303 ps.resourcePath.delete(); 2304 } 2305 mSettings.removePackageLPw(ps.name); 2306 } 2307 2308 static int[] appendInts(int[] cur, int[] add) { 2309 if (add == null) return cur; 2310 if (cur == null) return add; 2311 final int N = add.length; 2312 for (int i=0; i<N; i++) { 2313 cur = appendInt(cur, add[i]); 2314 } 2315 return cur; 2316 } 2317 2318 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2319 if (!sUserManager.exists(userId)) return null; 2320 final PackageSetting ps = (PackageSetting) p.mExtras; 2321 if (ps == null) { 2322 return null; 2323 } 2324 2325 final PermissionsState permissionsState = ps.getPermissionsState(); 2326 2327 final int[] gids = permissionsState.computeGids(userId); 2328 final Set<String> permissions = permissionsState.getPermissions(userId); 2329 final PackageUserState state = ps.readUserState(userId); 2330 2331 return PackageParser.generatePackageInfo(p, gids, flags, 2332 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2333 } 2334 2335 @Override 2336 public boolean isPackageAvailable(String packageName, int userId) { 2337 if (!sUserManager.exists(userId)) return false; 2338 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2339 synchronized (mPackages) { 2340 PackageParser.Package p = mPackages.get(packageName); 2341 if (p != null) { 2342 final PackageSetting ps = (PackageSetting) p.mExtras; 2343 if (ps != null) { 2344 final PackageUserState state = ps.readUserState(userId); 2345 if (state != null) { 2346 return PackageParser.isAvailable(state); 2347 } 2348 } 2349 } 2350 } 2351 return false; 2352 } 2353 2354 @Override 2355 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2356 if (!sUserManager.exists(userId)) return null; 2357 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2358 // reader 2359 synchronized (mPackages) { 2360 PackageParser.Package p = mPackages.get(packageName); 2361 if (DEBUG_PACKAGE_INFO) 2362 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2363 if (p != null) { 2364 return generatePackageInfo(p, flags, userId); 2365 } 2366 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2367 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2368 } 2369 } 2370 return null; 2371 } 2372 2373 @Override 2374 public String[] currentToCanonicalPackageNames(String[] names) { 2375 String[] out = new String[names.length]; 2376 // reader 2377 synchronized (mPackages) { 2378 for (int i=names.length-1; i>=0; i--) { 2379 PackageSetting ps = mSettings.mPackages.get(names[i]); 2380 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2381 } 2382 } 2383 return out; 2384 } 2385 2386 @Override 2387 public String[] canonicalToCurrentPackageNames(String[] names) { 2388 String[] out = new String[names.length]; 2389 // reader 2390 synchronized (mPackages) { 2391 for (int i=names.length-1; i>=0; i--) { 2392 String cur = mSettings.mRenamedPackages.get(names[i]); 2393 out[i] = cur != null ? cur : names[i]; 2394 } 2395 } 2396 return out; 2397 } 2398 2399 @Override 2400 public int getPackageUid(String packageName, int userId) { 2401 if (!sUserManager.exists(userId)) return -1; 2402 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2403 2404 // reader 2405 synchronized (mPackages) { 2406 PackageParser.Package p = mPackages.get(packageName); 2407 if(p != null) { 2408 return UserHandle.getUid(userId, p.applicationInfo.uid); 2409 } 2410 PackageSetting ps = mSettings.mPackages.get(packageName); 2411 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2412 return -1; 2413 } 2414 p = ps.pkg; 2415 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2416 } 2417 } 2418 2419 @Override 2420 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2421 if (!sUserManager.exists(userId)) { 2422 return null; 2423 } 2424 2425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2426 "getPackageGids"); 2427 2428 // reader 2429 synchronized (mPackages) { 2430 PackageParser.Package p = mPackages.get(packageName); 2431 if (DEBUG_PACKAGE_INFO) { 2432 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2433 } 2434 if (p != null) { 2435 PackageSetting ps = (PackageSetting) p.mExtras; 2436 return ps.getPermissionsState().computeGids(userId); 2437 } 2438 } 2439 2440 return null; 2441 } 2442 2443 static PermissionInfo generatePermissionInfo( 2444 BasePermission bp, int flags) { 2445 if (bp.perm != null) { 2446 return PackageParser.generatePermissionInfo(bp.perm, flags); 2447 } 2448 PermissionInfo pi = new PermissionInfo(); 2449 pi.name = bp.name; 2450 pi.packageName = bp.sourcePackage; 2451 pi.nonLocalizedLabel = bp.name; 2452 pi.protectionLevel = bp.protectionLevel; 2453 return pi; 2454 } 2455 2456 @Override 2457 public PermissionInfo getPermissionInfo(String name, int flags) { 2458 // reader 2459 synchronized (mPackages) { 2460 final BasePermission p = mSettings.mPermissions.get(name); 2461 if (p != null) { 2462 return generatePermissionInfo(p, flags); 2463 } 2464 return null; 2465 } 2466 } 2467 2468 @Override 2469 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2470 // reader 2471 synchronized (mPackages) { 2472 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2473 for (BasePermission p : mSettings.mPermissions.values()) { 2474 if (group == null) { 2475 if (p.perm == null || p.perm.info.group == null) { 2476 out.add(generatePermissionInfo(p, flags)); 2477 } 2478 } else { 2479 if (p.perm != null && group.equals(p.perm.info.group)) { 2480 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2481 } 2482 } 2483 } 2484 2485 if (out.size() > 0) { 2486 return out; 2487 } 2488 return mPermissionGroups.containsKey(group) ? out : null; 2489 } 2490 } 2491 2492 @Override 2493 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2494 // reader 2495 synchronized (mPackages) { 2496 return PackageParser.generatePermissionGroupInfo( 2497 mPermissionGroups.get(name), flags); 2498 } 2499 } 2500 2501 @Override 2502 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2503 // reader 2504 synchronized (mPackages) { 2505 final int N = mPermissionGroups.size(); 2506 ArrayList<PermissionGroupInfo> out 2507 = new ArrayList<PermissionGroupInfo>(N); 2508 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2509 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2510 } 2511 return out; 2512 } 2513 } 2514 2515 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2516 int userId) { 2517 if (!sUserManager.exists(userId)) return null; 2518 PackageSetting ps = mSettings.mPackages.get(packageName); 2519 if (ps != null) { 2520 if (ps.pkg == null) { 2521 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2522 flags, userId); 2523 if (pInfo != null) { 2524 return pInfo.applicationInfo; 2525 } 2526 return null; 2527 } 2528 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2529 ps.readUserState(userId), userId); 2530 } 2531 return null; 2532 } 2533 2534 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2535 int userId) { 2536 if (!sUserManager.exists(userId)) return null; 2537 PackageSetting ps = mSettings.mPackages.get(packageName); 2538 if (ps != null) { 2539 PackageParser.Package pkg = ps.pkg; 2540 if (pkg == null) { 2541 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2542 return null; 2543 } 2544 // Only data remains, so we aren't worried about code paths 2545 pkg = new PackageParser.Package(packageName); 2546 pkg.applicationInfo.packageName = packageName; 2547 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2548 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2549 pkg.applicationInfo.dataDir = 2550 getDataPathForPackage(packageName, 0).getPath(); 2551 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2552 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2553 } 2554 return generatePackageInfo(pkg, flags, userId); 2555 } 2556 return null; 2557 } 2558 2559 @Override 2560 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2561 if (!sUserManager.exists(userId)) return null; 2562 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2563 // writer 2564 synchronized (mPackages) { 2565 PackageParser.Package p = mPackages.get(packageName); 2566 if (DEBUG_PACKAGE_INFO) Log.v( 2567 TAG, "getApplicationInfo " + packageName 2568 + ": " + p); 2569 if (p != null) { 2570 PackageSetting ps = mSettings.mPackages.get(packageName); 2571 if (ps == null) return null; 2572 // Note: isEnabledLP() does not apply here - always return info 2573 return PackageParser.generateApplicationInfo( 2574 p, flags, ps.readUserState(userId), userId); 2575 } 2576 if ("android".equals(packageName)||"system".equals(packageName)) { 2577 return mAndroidApplication; 2578 } 2579 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2580 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2581 } 2582 } 2583 return null; 2584 } 2585 2586 2587 @Override 2588 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2589 mContext.enforceCallingOrSelfPermission( 2590 android.Manifest.permission.CLEAR_APP_CACHE, null); 2591 // Queue up an async operation since clearing cache may take a little while. 2592 mHandler.post(new Runnable() { 2593 public void run() { 2594 mHandler.removeCallbacks(this); 2595 int retCode = -1; 2596 synchronized (mInstallLock) { 2597 retCode = mInstaller.freeCache(freeStorageSize); 2598 if (retCode < 0) { 2599 Slog.w(TAG, "Couldn't clear application caches"); 2600 } 2601 } 2602 if (observer != null) { 2603 try { 2604 observer.onRemoveCompleted(null, (retCode >= 0)); 2605 } catch (RemoteException e) { 2606 Slog.w(TAG, "RemoveException when invoking call back"); 2607 } 2608 } 2609 } 2610 }); 2611 } 2612 2613 @Override 2614 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2615 mContext.enforceCallingOrSelfPermission( 2616 android.Manifest.permission.CLEAR_APP_CACHE, null); 2617 // Queue up an async operation since clearing cache may take a little while. 2618 mHandler.post(new Runnable() { 2619 public void run() { 2620 mHandler.removeCallbacks(this); 2621 int retCode = -1; 2622 synchronized (mInstallLock) { 2623 retCode = mInstaller.freeCache(freeStorageSize); 2624 if (retCode < 0) { 2625 Slog.w(TAG, "Couldn't clear application caches"); 2626 } 2627 } 2628 if(pi != null) { 2629 try { 2630 // Callback via pending intent 2631 int code = (retCode >= 0) ? 1 : 0; 2632 pi.sendIntent(null, code, null, 2633 null, null); 2634 } catch (SendIntentException e1) { 2635 Slog.i(TAG, "Failed to send pending intent"); 2636 } 2637 } 2638 } 2639 }); 2640 } 2641 2642 void freeStorage(long freeStorageSize) throws IOException { 2643 synchronized (mInstallLock) { 2644 if (mInstaller.freeCache(freeStorageSize) < 0) { 2645 throw new IOException("Failed to free enough space"); 2646 } 2647 } 2648 } 2649 2650 @Override 2651 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2652 if (!sUserManager.exists(userId)) return null; 2653 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2654 synchronized (mPackages) { 2655 PackageParser.Activity a = mActivities.mActivities.get(component); 2656 2657 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2658 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2659 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2660 if (ps == null) return null; 2661 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2662 userId); 2663 } 2664 if (mResolveComponentName.equals(component)) { 2665 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2666 new PackageUserState(), userId); 2667 } 2668 } 2669 return null; 2670 } 2671 2672 @Override 2673 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2674 String resolvedType) { 2675 synchronized (mPackages) { 2676 PackageParser.Activity a = mActivities.mActivities.get(component); 2677 if (a == null) { 2678 return false; 2679 } 2680 for (int i=0; i<a.intents.size(); i++) { 2681 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2682 intent.getData(), intent.getCategories(), TAG) >= 0) { 2683 return true; 2684 } 2685 } 2686 return false; 2687 } 2688 } 2689 2690 @Override 2691 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2692 if (!sUserManager.exists(userId)) return null; 2693 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2694 synchronized (mPackages) { 2695 PackageParser.Activity a = mReceivers.mActivities.get(component); 2696 if (DEBUG_PACKAGE_INFO) Log.v( 2697 TAG, "getReceiverInfo " + component + ": " + a); 2698 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2699 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2700 if (ps == null) return null; 2701 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2702 userId); 2703 } 2704 } 2705 return null; 2706 } 2707 2708 @Override 2709 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2710 if (!sUserManager.exists(userId)) return null; 2711 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2712 synchronized (mPackages) { 2713 PackageParser.Service s = mServices.mServices.get(component); 2714 if (DEBUG_PACKAGE_INFO) Log.v( 2715 TAG, "getServiceInfo " + component + ": " + s); 2716 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2717 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2718 if (ps == null) return null; 2719 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2720 userId); 2721 } 2722 } 2723 return null; 2724 } 2725 2726 @Override 2727 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2728 if (!sUserManager.exists(userId)) return null; 2729 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2730 synchronized (mPackages) { 2731 PackageParser.Provider p = mProviders.mProviders.get(component); 2732 if (DEBUG_PACKAGE_INFO) Log.v( 2733 TAG, "getProviderInfo " + component + ": " + p); 2734 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2735 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2736 if (ps == null) return null; 2737 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2738 userId); 2739 } 2740 } 2741 return null; 2742 } 2743 2744 @Override 2745 public String[] getSystemSharedLibraryNames() { 2746 Set<String> libSet; 2747 synchronized (mPackages) { 2748 libSet = mSharedLibraries.keySet(); 2749 int size = libSet.size(); 2750 if (size > 0) { 2751 String[] libs = new String[size]; 2752 libSet.toArray(libs); 2753 return libs; 2754 } 2755 } 2756 return null; 2757 } 2758 2759 /** 2760 * @hide 2761 */ 2762 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2763 synchronized (mPackages) { 2764 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2765 if (lib != null && lib.apk != null) { 2766 return mPackages.get(lib.apk); 2767 } 2768 } 2769 return null; 2770 } 2771 2772 @Override 2773 public FeatureInfo[] getSystemAvailableFeatures() { 2774 Collection<FeatureInfo> featSet; 2775 synchronized (mPackages) { 2776 featSet = mAvailableFeatures.values(); 2777 int size = featSet.size(); 2778 if (size > 0) { 2779 FeatureInfo[] features = new FeatureInfo[size+1]; 2780 featSet.toArray(features); 2781 FeatureInfo fi = new FeatureInfo(); 2782 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2783 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2784 features[size] = fi; 2785 return features; 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public boolean hasSystemFeature(String name) { 2793 synchronized (mPackages) { 2794 return mAvailableFeatures.containsKey(name); 2795 } 2796 } 2797 2798 private void checkValidCaller(int uid, int userId) { 2799 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2800 return; 2801 2802 throw new SecurityException("Caller uid=" + uid 2803 + " is not privileged to communicate with user=" + userId); 2804 } 2805 2806 @Override 2807 public int checkPermission(String permName, String pkgName, int userId) { 2808 if (!sUserManager.exists(userId)) { 2809 return PackageManager.PERMISSION_DENIED; 2810 } 2811 2812 synchronized (mPackages) { 2813 final PackageParser.Package p = mPackages.get(pkgName); 2814 if (p != null && p.mExtras != null) { 2815 final PackageSetting ps = (PackageSetting) p.mExtras; 2816 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2817 return PackageManager.PERMISSION_GRANTED; 2818 } 2819 } 2820 } 2821 2822 return PackageManager.PERMISSION_DENIED; 2823 } 2824 2825 @Override 2826 public int checkUidPermission(String permName, int uid) { 2827 final int userId = UserHandle.getUserId(uid); 2828 2829 if (!sUserManager.exists(userId)) { 2830 return PackageManager.PERMISSION_DENIED; 2831 } 2832 2833 synchronized (mPackages) { 2834 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2835 if (obj != null) { 2836 final SettingBase ps = (SettingBase) obj; 2837 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2838 return PackageManager.PERMISSION_GRANTED; 2839 } 2840 } else { 2841 ArraySet<String> perms = mSystemPermissions.get(uid); 2842 if (perms != null && perms.contains(permName)) { 2843 return PackageManager.PERMISSION_GRANTED; 2844 } 2845 } 2846 } 2847 2848 return PackageManager.PERMISSION_DENIED; 2849 } 2850 2851 /** 2852 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2853 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2854 * @param checkShell TODO(yamasani): 2855 * @param message the message to log on security exception 2856 */ 2857 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2858 boolean checkShell, String message) { 2859 if (userId < 0) { 2860 throw new IllegalArgumentException("Invalid userId " + userId); 2861 } 2862 if (checkShell) { 2863 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2864 } 2865 if (userId == UserHandle.getUserId(callingUid)) return; 2866 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2867 if (requireFullPermission) { 2868 mContext.enforceCallingOrSelfPermission( 2869 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2870 } else { 2871 try { 2872 mContext.enforceCallingOrSelfPermission( 2873 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2874 } catch (SecurityException se) { 2875 mContext.enforceCallingOrSelfPermission( 2876 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2877 } 2878 } 2879 } 2880 } 2881 2882 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2883 if (callingUid == Process.SHELL_UID) { 2884 if (userHandle >= 0 2885 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2886 throw new SecurityException("Shell does not have permission to access user " 2887 + userHandle); 2888 } else if (userHandle < 0) { 2889 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2890 + Debug.getCallers(3)); 2891 } 2892 } 2893 } 2894 2895 private BasePermission findPermissionTreeLP(String permName) { 2896 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2897 if (permName.startsWith(bp.name) && 2898 permName.length() > bp.name.length() && 2899 permName.charAt(bp.name.length()) == '.') { 2900 return bp; 2901 } 2902 } 2903 return null; 2904 } 2905 2906 private BasePermission checkPermissionTreeLP(String permName) { 2907 if (permName != null) { 2908 BasePermission bp = findPermissionTreeLP(permName); 2909 if (bp != null) { 2910 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2911 return bp; 2912 } 2913 throw new SecurityException("Calling uid " 2914 + Binder.getCallingUid() 2915 + " is not allowed to add to permission tree " 2916 + bp.name + " owned by uid " + bp.uid); 2917 } 2918 } 2919 throw new SecurityException("No permission tree found for " + permName); 2920 } 2921 2922 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2923 if (s1 == null) { 2924 return s2 == null; 2925 } 2926 if (s2 == null) { 2927 return false; 2928 } 2929 if (s1.getClass() != s2.getClass()) { 2930 return false; 2931 } 2932 return s1.equals(s2); 2933 } 2934 2935 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2936 if (pi1.icon != pi2.icon) return false; 2937 if (pi1.logo != pi2.logo) return false; 2938 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2939 if (!compareStrings(pi1.name, pi2.name)) return false; 2940 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2941 // We'll take care of setting this one. 2942 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2943 // These are not currently stored in settings. 2944 //if (!compareStrings(pi1.group, pi2.group)) return false; 2945 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2946 //if (pi1.labelRes != pi2.labelRes) return false; 2947 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2948 return true; 2949 } 2950 2951 int permissionInfoFootprint(PermissionInfo info) { 2952 int size = info.name.length(); 2953 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2954 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2955 return size; 2956 } 2957 2958 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2959 int size = 0; 2960 for (BasePermission perm : mSettings.mPermissions.values()) { 2961 if (perm.uid == tree.uid) { 2962 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2963 } 2964 } 2965 return size; 2966 } 2967 2968 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2969 // We calculate the max size of permissions defined by this uid and throw 2970 // if that plus the size of 'info' would exceed our stated maximum. 2971 if (tree.uid != Process.SYSTEM_UID) { 2972 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2973 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2974 throw new SecurityException("Permission tree size cap exceeded"); 2975 } 2976 } 2977 } 2978 2979 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2980 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2981 throw new SecurityException("Label must be specified in permission"); 2982 } 2983 BasePermission tree = checkPermissionTreeLP(info.name); 2984 BasePermission bp = mSettings.mPermissions.get(info.name); 2985 boolean added = bp == null; 2986 boolean changed = true; 2987 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2988 if (added) { 2989 enforcePermissionCapLocked(info, tree); 2990 bp = new BasePermission(info.name, tree.sourcePackage, 2991 BasePermission.TYPE_DYNAMIC); 2992 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2993 throw new SecurityException( 2994 "Not allowed to modify non-dynamic permission " 2995 + info.name); 2996 } else { 2997 if (bp.protectionLevel == fixedLevel 2998 && bp.perm.owner.equals(tree.perm.owner) 2999 && bp.uid == tree.uid 3000 && comparePermissionInfos(bp.perm.info, info)) { 3001 changed = false; 3002 } 3003 } 3004 bp.protectionLevel = fixedLevel; 3005 info = new PermissionInfo(info); 3006 info.protectionLevel = fixedLevel; 3007 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3008 bp.perm.info.packageName = tree.perm.info.packageName; 3009 bp.uid = tree.uid; 3010 if (added) { 3011 mSettings.mPermissions.put(info.name, bp); 3012 } 3013 if (changed) { 3014 if (!async) { 3015 mSettings.writeLPr(); 3016 } else { 3017 scheduleWriteSettingsLocked(); 3018 } 3019 } 3020 return added; 3021 } 3022 3023 @Override 3024 public boolean addPermission(PermissionInfo info) { 3025 synchronized (mPackages) { 3026 return addPermissionLocked(info, false); 3027 } 3028 } 3029 3030 @Override 3031 public boolean addPermissionAsync(PermissionInfo info) { 3032 synchronized (mPackages) { 3033 return addPermissionLocked(info, true); 3034 } 3035 } 3036 3037 @Override 3038 public void removePermission(String name) { 3039 synchronized (mPackages) { 3040 checkPermissionTreeLP(name); 3041 BasePermission bp = mSettings.mPermissions.get(name); 3042 if (bp != null) { 3043 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3044 throw new SecurityException( 3045 "Not allowed to modify non-dynamic permission " 3046 + name); 3047 } 3048 mSettings.mPermissions.remove(name); 3049 mSettings.writeLPr(); 3050 } 3051 } 3052 } 3053 3054 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3055 BasePermission bp) { 3056 int index = pkg.requestedPermissions.indexOf(bp.name); 3057 if (index == -1) { 3058 throw new SecurityException("Package " + pkg.packageName 3059 + " has not requested permission " + bp.name); 3060 } 3061 if (!bp.isRuntime()) { 3062 throw new SecurityException("Permission " + bp.name 3063 + " is not a changeable permission type"); 3064 } 3065 } 3066 3067 @Override 3068 public boolean grantPermission(String packageName, String name, int userId) { 3069 if (!RUNTIME_PERMISSIONS_ENABLED) { 3070 return false; 3071 } 3072 3073 if (!sUserManager.exists(userId)) { 3074 return false; 3075 } 3076 3077 mContext.enforceCallingOrSelfPermission( 3078 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3079 "grantPermission"); 3080 3081 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3082 "grantPermission"); 3083 3084 boolean gidsChanged = false; 3085 final SettingBase sb; 3086 3087 synchronized (mPackages) { 3088 final PackageParser.Package pkg = mPackages.get(packageName); 3089 if (pkg == null) { 3090 throw new IllegalArgumentException("Unknown package: " + packageName); 3091 } 3092 3093 final BasePermission bp = mSettings.mPermissions.get(name); 3094 if (bp == null) { 3095 throw new IllegalArgumentException("Unknown permission: " + name); 3096 } 3097 3098 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3099 3100 sb = (SettingBase) pkg.mExtras; 3101 if (sb == null) { 3102 throw new IllegalArgumentException("Unknown package: " + packageName); 3103 } 3104 3105 final PermissionsState permissionsState = sb.getPermissionsState(); 3106 3107 final int result = permissionsState.grantRuntimePermission(bp, userId); 3108 switch (result) { 3109 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3110 return false; 3111 } 3112 3113 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3114 gidsChanged = true; 3115 } break; 3116 } 3117 3118 // Not critical if that is lost - app has to request again. 3119 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3120 } 3121 3122 if (gidsChanged) { 3123 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3124 } 3125 3126 return true; 3127 } 3128 3129 @Override 3130 public boolean revokePermission(String packageName, String name, int userId) { 3131 if (!RUNTIME_PERMISSIONS_ENABLED) { 3132 return false; 3133 } 3134 3135 if (!sUserManager.exists(userId)) { 3136 return false; 3137 } 3138 3139 mContext.enforceCallingOrSelfPermission( 3140 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3141 "revokePermission"); 3142 3143 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3144 "revokePermission"); 3145 3146 final SettingBase sb; 3147 3148 synchronized (mPackages) { 3149 final PackageParser.Package pkg = mPackages.get(packageName); 3150 if (pkg == null) { 3151 throw new IllegalArgumentException("Unknown package: " + packageName); 3152 } 3153 3154 final BasePermission bp = mSettings.mPermissions.get(name); 3155 if (bp == null) { 3156 throw new IllegalArgumentException("Unknown permission: " + name); 3157 } 3158 3159 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3160 3161 sb = (SettingBase) pkg.mExtras; 3162 if (sb == null) { 3163 throw new IllegalArgumentException("Unknown package: " + packageName); 3164 } 3165 3166 final PermissionsState permissionsState = sb.getPermissionsState(); 3167 3168 if (permissionsState.revokeRuntimePermission(bp, userId) == 3169 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3170 return false; 3171 } 3172 3173 // Critical, after this call all should never have the permission. 3174 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3175 } 3176 3177 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3178 3179 return true; 3180 } 3181 3182 @Override 3183 public boolean isProtectedBroadcast(String actionName) { 3184 synchronized (mPackages) { 3185 return mProtectedBroadcasts.contains(actionName); 3186 } 3187 } 3188 3189 @Override 3190 public int checkSignatures(String pkg1, String pkg2) { 3191 synchronized (mPackages) { 3192 final PackageParser.Package p1 = mPackages.get(pkg1); 3193 final PackageParser.Package p2 = mPackages.get(pkg2); 3194 if (p1 == null || p1.mExtras == null 3195 || p2 == null || p2.mExtras == null) { 3196 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3197 } 3198 return compareSignatures(p1.mSignatures, p2.mSignatures); 3199 } 3200 } 3201 3202 @Override 3203 public int checkUidSignatures(int uid1, int uid2) { 3204 // Map to base uids. 3205 uid1 = UserHandle.getAppId(uid1); 3206 uid2 = UserHandle.getAppId(uid2); 3207 // reader 3208 synchronized (mPackages) { 3209 Signature[] s1; 3210 Signature[] s2; 3211 Object obj = mSettings.getUserIdLPr(uid1); 3212 if (obj != null) { 3213 if (obj instanceof SharedUserSetting) { 3214 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3215 } else if (obj instanceof PackageSetting) { 3216 s1 = ((PackageSetting)obj).signatures.mSignatures; 3217 } else { 3218 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3219 } 3220 } else { 3221 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3222 } 3223 obj = mSettings.getUserIdLPr(uid2); 3224 if (obj != null) { 3225 if (obj instanceof SharedUserSetting) { 3226 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3227 } else if (obj instanceof PackageSetting) { 3228 s2 = ((PackageSetting)obj).signatures.mSignatures; 3229 } else { 3230 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3231 } 3232 } else { 3233 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3234 } 3235 return compareSignatures(s1, s2); 3236 } 3237 } 3238 3239 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3240 final long identity = Binder.clearCallingIdentity(); 3241 try { 3242 if (sb instanceof SharedUserSetting) { 3243 SharedUserSetting sus = (SharedUserSetting) sb; 3244 final int packageCount = sus.packages.size(); 3245 for (int i = 0; i < packageCount; i++) { 3246 PackageSetting susPs = sus.packages.valueAt(i); 3247 if (userId == UserHandle.USER_ALL) { 3248 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3249 } else { 3250 final int uid = UserHandle.getUid(userId, susPs.appId); 3251 killUid(uid, reason); 3252 } 3253 } 3254 } else if (sb instanceof PackageSetting) { 3255 PackageSetting ps = (PackageSetting) sb; 3256 if (userId == UserHandle.USER_ALL) { 3257 killApplication(ps.pkg.packageName, ps.appId, reason); 3258 } else { 3259 final int uid = UserHandle.getUid(userId, ps.appId); 3260 killUid(uid, reason); 3261 } 3262 } 3263 } finally { 3264 Binder.restoreCallingIdentity(identity); 3265 } 3266 } 3267 3268 private static void killUid(int uid, String reason) { 3269 IActivityManager am = ActivityManagerNative.getDefault(); 3270 if (am != null) { 3271 try { 3272 am.killUid(uid, reason); 3273 } catch (RemoteException e) { 3274 /* ignore - same process */ 3275 } 3276 } 3277 } 3278 3279 /** 3280 * Compares two sets of signatures. Returns: 3281 * <br /> 3282 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3283 * <br /> 3284 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3285 * <br /> 3286 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3287 * <br /> 3288 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3289 * <br /> 3290 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3291 */ 3292 static int compareSignatures(Signature[] s1, Signature[] s2) { 3293 if (s1 == null) { 3294 return s2 == null 3295 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3296 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3297 } 3298 3299 if (s2 == null) { 3300 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3301 } 3302 3303 if (s1.length != s2.length) { 3304 return PackageManager.SIGNATURE_NO_MATCH; 3305 } 3306 3307 // Since both signature sets are of size 1, we can compare without HashSets. 3308 if (s1.length == 1) { 3309 return s1[0].equals(s2[0]) ? 3310 PackageManager.SIGNATURE_MATCH : 3311 PackageManager.SIGNATURE_NO_MATCH; 3312 } 3313 3314 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3315 for (Signature sig : s1) { 3316 set1.add(sig); 3317 } 3318 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3319 for (Signature sig : s2) { 3320 set2.add(sig); 3321 } 3322 // Make sure s2 contains all signatures in s1. 3323 if (set1.equals(set2)) { 3324 return PackageManager.SIGNATURE_MATCH; 3325 } 3326 return PackageManager.SIGNATURE_NO_MATCH; 3327 } 3328 3329 /** 3330 * If the database version for this type of package (internal storage or 3331 * external storage) is less than the version where package signatures 3332 * were updated, return true. 3333 */ 3334 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3335 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3336 DatabaseVersion.SIGNATURE_END_ENTITY)) 3337 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3338 DatabaseVersion.SIGNATURE_END_ENTITY)); 3339 } 3340 3341 /** 3342 * Used for backward compatibility to make sure any packages with 3343 * certificate chains get upgraded to the new style. {@code existingSigs} 3344 * will be in the old format (since they were stored on disk from before the 3345 * system upgrade) and {@code scannedSigs} will be in the newer format. 3346 */ 3347 private int compareSignaturesCompat(PackageSignatures existingSigs, 3348 PackageParser.Package scannedPkg) { 3349 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3350 return PackageManager.SIGNATURE_NO_MATCH; 3351 } 3352 3353 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3354 for (Signature sig : existingSigs.mSignatures) { 3355 existingSet.add(sig); 3356 } 3357 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3358 for (Signature sig : scannedPkg.mSignatures) { 3359 try { 3360 Signature[] chainSignatures = sig.getChainSignatures(); 3361 for (Signature chainSig : chainSignatures) { 3362 scannedCompatSet.add(chainSig); 3363 } 3364 } catch (CertificateEncodingException e) { 3365 scannedCompatSet.add(sig); 3366 } 3367 } 3368 /* 3369 * Make sure the expanded scanned set contains all signatures in the 3370 * existing one. 3371 */ 3372 if (scannedCompatSet.equals(existingSet)) { 3373 // Migrate the old signatures to the new scheme. 3374 existingSigs.assignSignatures(scannedPkg.mSignatures); 3375 // The new KeySets will be re-added later in the scanning process. 3376 synchronized (mPackages) { 3377 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3378 } 3379 return PackageManager.SIGNATURE_MATCH; 3380 } 3381 return PackageManager.SIGNATURE_NO_MATCH; 3382 } 3383 3384 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3385 if (isExternal(scannedPkg)) { 3386 return mSettings.isExternalDatabaseVersionOlderThan( 3387 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3388 } else { 3389 return mSettings.isInternalDatabaseVersionOlderThan( 3390 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3391 } 3392 } 3393 3394 private int compareSignaturesRecover(PackageSignatures existingSigs, 3395 PackageParser.Package scannedPkg) { 3396 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3397 return PackageManager.SIGNATURE_NO_MATCH; 3398 } 3399 3400 String msg = null; 3401 try { 3402 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3403 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3404 + scannedPkg.packageName); 3405 return PackageManager.SIGNATURE_MATCH; 3406 } 3407 } catch (CertificateException e) { 3408 msg = e.getMessage(); 3409 } 3410 3411 logCriticalInfo(Log.INFO, 3412 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3413 return PackageManager.SIGNATURE_NO_MATCH; 3414 } 3415 3416 @Override 3417 public String[] getPackagesForUid(int uid) { 3418 uid = UserHandle.getAppId(uid); 3419 // reader 3420 synchronized (mPackages) { 3421 Object obj = mSettings.getUserIdLPr(uid); 3422 if (obj instanceof SharedUserSetting) { 3423 final SharedUserSetting sus = (SharedUserSetting) obj; 3424 final int N = sus.packages.size(); 3425 final String[] res = new String[N]; 3426 final Iterator<PackageSetting> it = sus.packages.iterator(); 3427 int i = 0; 3428 while (it.hasNext()) { 3429 res[i++] = it.next().name; 3430 } 3431 return res; 3432 } else if (obj instanceof PackageSetting) { 3433 final PackageSetting ps = (PackageSetting) obj; 3434 return new String[] { ps.name }; 3435 } 3436 } 3437 return null; 3438 } 3439 3440 @Override 3441 public String getNameForUid(int uid) { 3442 // reader 3443 synchronized (mPackages) { 3444 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3445 if (obj instanceof SharedUserSetting) { 3446 final SharedUserSetting sus = (SharedUserSetting) obj; 3447 return sus.name + ":" + sus.userId; 3448 } else if (obj instanceof PackageSetting) { 3449 final PackageSetting ps = (PackageSetting) obj; 3450 return ps.name; 3451 } 3452 } 3453 return null; 3454 } 3455 3456 @Override 3457 public int getUidForSharedUser(String sharedUserName) { 3458 if(sharedUserName == null) { 3459 return -1; 3460 } 3461 // reader 3462 synchronized (mPackages) { 3463 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3464 if (suid == null) { 3465 return -1; 3466 } 3467 return suid.userId; 3468 } 3469 } 3470 3471 @Override 3472 public int getFlagsForUid(int uid) { 3473 synchronized (mPackages) { 3474 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3475 if (obj instanceof SharedUserSetting) { 3476 final SharedUserSetting sus = (SharedUserSetting) obj; 3477 return sus.pkgFlags; 3478 } else if (obj instanceof PackageSetting) { 3479 final PackageSetting ps = (PackageSetting) obj; 3480 return ps.pkgFlags; 3481 } 3482 } 3483 return 0; 3484 } 3485 3486 @Override 3487 public int getPrivateFlagsForUid(int uid) { 3488 synchronized (mPackages) { 3489 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3490 if (obj instanceof SharedUserSetting) { 3491 final SharedUserSetting sus = (SharedUserSetting) obj; 3492 return sus.pkgPrivateFlags; 3493 } else if (obj instanceof PackageSetting) { 3494 final PackageSetting ps = (PackageSetting) obj; 3495 return ps.pkgPrivateFlags; 3496 } 3497 } 3498 return 0; 3499 } 3500 3501 @Override 3502 public boolean isUidPrivileged(int uid) { 3503 uid = UserHandle.getAppId(uid); 3504 // reader 3505 synchronized (mPackages) { 3506 Object obj = mSettings.getUserIdLPr(uid); 3507 if (obj instanceof SharedUserSetting) { 3508 final SharedUserSetting sus = (SharedUserSetting) obj; 3509 final Iterator<PackageSetting> it = sus.packages.iterator(); 3510 while (it.hasNext()) { 3511 if (it.next().isPrivileged()) { 3512 return true; 3513 } 3514 } 3515 } else if (obj instanceof PackageSetting) { 3516 final PackageSetting ps = (PackageSetting) obj; 3517 return ps.isPrivileged(); 3518 } 3519 } 3520 return false; 3521 } 3522 3523 @Override 3524 public String[] getAppOpPermissionPackages(String permissionName) { 3525 synchronized (mPackages) { 3526 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3527 if (pkgs == null) { 3528 return null; 3529 } 3530 return pkgs.toArray(new String[pkgs.size()]); 3531 } 3532 } 3533 3534 @Override 3535 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3536 int flags, int userId) { 3537 if (!sUserManager.exists(userId)) return null; 3538 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3539 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3540 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3541 } 3542 3543 @Override 3544 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3545 IntentFilter filter, int match, ComponentName activity) { 3546 final int userId = UserHandle.getCallingUserId(); 3547 if (DEBUG_PREFERRED) { 3548 Log.v(TAG, "setLastChosenActivity intent=" + intent 3549 + " resolvedType=" + resolvedType 3550 + " flags=" + flags 3551 + " filter=" + filter 3552 + " match=" + match 3553 + " activity=" + activity); 3554 filter.dump(new PrintStreamPrinter(System.out), " "); 3555 } 3556 intent.setComponent(null); 3557 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3558 // Find any earlier preferred or last chosen entries and nuke them 3559 findPreferredActivity(intent, resolvedType, 3560 flags, query, 0, false, true, false, userId); 3561 // Add the new activity as the last chosen for this filter 3562 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3563 "Setting last chosen"); 3564 } 3565 3566 @Override 3567 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3568 final int userId = UserHandle.getCallingUserId(); 3569 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3570 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3571 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3572 false, false, false, userId); 3573 } 3574 3575 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3576 int flags, List<ResolveInfo> query, int userId) { 3577 if (query != null) { 3578 final int N = query.size(); 3579 if (N == 1) { 3580 return query.get(0); 3581 } else if (N > 1) { 3582 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3583 // If there is more than one activity with the same priority, 3584 // then let the user decide between them. 3585 ResolveInfo r0 = query.get(0); 3586 ResolveInfo r1 = query.get(1); 3587 if (DEBUG_INTENT_MATCHING || debug) { 3588 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3589 + r1.activityInfo.name + "=" + r1.priority); 3590 } 3591 // If the first activity has a higher priority, or a different 3592 // default, then it is always desireable to pick it. 3593 if (r0.priority != r1.priority 3594 || r0.preferredOrder != r1.preferredOrder 3595 || r0.isDefault != r1.isDefault) { 3596 return query.get(0); 3597 } 3598 // If we have saved a preference for a preferred activity for 3599 // this Intent, use that. 3600 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3601 flags, query, r0.priority, true, false, debug, userId); 3602 if (ri != null) { 3603 return ri; 3604 } 3605 if (userId != 0) { 3606 ri = new ResolveInfo(mResolveInfo); 3607 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3608 ri.activityInfo.applicationInfo = new ApplicationInfo( 3609 ri.activityInfo.applicationInfo); 3610 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3611 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3612 return ri; 3613 } 3614 return mResolveInfo; 3615 } 3616 } 3617 return null; 3618 } 3619 3620 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3621 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3622 final int N = query.size(); 3623 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3624 .get(userId); 3625 // Get the list of persistent preferred activities that handle the intent 3626 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3627 List<PersistentPreferredActivity> pprefs = ppir != null 3628 ? ppir.queryIntent(intent, resolvedType, 3629 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3630 : null; 3631 if (pprefs != null && pprefs.size() > 0) { 3632 final int M = pprefs.size(); 3633 for (int i=0; i<M; i++) { 3634 final PersistentPreferredActivity ppa = pprefs.get(i); 3635 if (DEBUG_PREFERRED || debug) { 3636 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3637 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3638 + "\n component=" + ppa.mComponent); 3639 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3640 } 3641 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3642 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3643 if (DEBUG_PREFERRED || debug) { 3644 Slog.v(TAG, "Found persistent preferred activity:"); 3645 if (ai != null) { 3646 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3647 } else { 3648 Slog.v(TAG, " null"); 3649 } 3650 } 3651 if (ai == null) { 3652 // This previously registered persistent preferred activity 3653 // component is no longer known. Ignore it and do NOT remove it. 3654 continue; 3655 } 3656 for (int j=0; j<N; j++) { 3657 final ResolveInfo ri = query.get(j); 3658 if (!ri.activityInfo.applicationInfo.packageName 3659 .equals(ai.applicationInfo.packageName)) { 3660 continue; 3661 } 3662 if (!ri.activityInfo.name.equals(ai.name)) { 3663 continue; 3664 } 3665 // Found a persistent preference that can handle the intent. 3666 if (DEBUG_PREFERRED || debug) { 3667 Slog.v(TAG, "Returning persistent preferred activity: " + 3668 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3669 } 3670 return ri; 3671 } 3672 } 3673 } 3674 return null; 3675 } 3676 3677 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3678 List<ResolveInfo> query, int priority, boolean always, 3679 boolean removeMatches, boolean debug, int userId) { 3680 if (!sUserManager.exists(userId)) return null; 3681 // writer 3682 synchronized (mPackages) { 3683 if (intent.getSelector() != null) { 3684 intent = intent.getSelector(); 3685 } 3686 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3687 3688 // Try to find a matching persistent preferred activity. 3689 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3690 debug, userId); 3691 3692 // If a persistent preferred activity matched, use it. 3693 if (pri != null) { 3694 return pri; 3695 } 3696 3697 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3698 // Get the list of preferred activities that handle the intent 3699 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3700 List<PreferredActivity> prefs = pir != null 3701 ? pir.queryIntent(intent, resolvedType, 3702 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3703 : null; 3704 if (prefs != null && prefs.size() > 0) { 3705 boolean changed = false; 3706 try { 3707 // First figure out how good the original match set is. 3708 // We will only allow preferred activities that came 3709 // from the same match quality. 3710 int match = 0; 3711 3712 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3713 3714 final int N = query.size(); 3715 for (int j=0; j<N; j++) { 3716 final ResolveInfo ri = query.get(j); 3717 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3718 + ": 0x" + Integer.toHexString(match)); 3719 if (ri.match > match) { 3720 match = ri.match; 3721 } 3722 } 3723 3724 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3725 + Integer.toHexString(match)); 3726 3727 match &= IntentFilter.MATCH_CATEGORY_MASK; 3728 final int M = prefs.size(); 3729 for (int i=0; i<M; i++) { 3730 final PreferredActivity pa = prefs.get(i); 3731 if (DEBUG_PREFERRED || debug) { 3732 Slog.v(TAG, "Checking PreferredActivity ds=" 3733 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3734 + "\n component=" + pa.mPref.mComponent); 3735 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3736 } 3737 if (pa.mPref.mMatch != match) { 3738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3739 + Integer.toHexString(pa.mPref.mMatch)); 3740 continue; 3741 } 3742 // If it's not an "always" type preferred activity and that's what we're 3743 // looking for, skip it. 3744 if (always && !pa.mPref.mAlways) { 3745 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3746 continue; 3747 } 3748 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3749 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3750 if (DEBUG_PREFERRED || debug) { 3751 Slog.v(TAG, "Found preferred activity:"); 3752 if (ai != null) { 3753 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3754 } else { 3755 Slog.v(TAG, " null"); 3756 } 3757 } 3758 if (ai == null) { 3759 // This previously registered preferred activity 3760 // component is no longer known. Most likely an update 3761 // to the app was installed and in the new version this 3762 // component no longer exists. Clean it up by removing 3763 // it from the preferred activities list, and skip it. 3764 Slog.w(TAG, "Removing dangling preferred activity: " 3765 + pa.mPref.mComponent); 3766 pir.removeFilter(pa); 3767 changed = true; 3768 continue; 3769 } 3770 for (int j=0; j<N; j++) { 3771 final ResolveInfo ri = query.get(j); 3772 if (!ri.activityInfo.applicationInfo.packageName 3773 .equals(ai.applicationInfo.packageName)) { 3774 continue; 3775 } 3776 if (!ri.activityInfo.name.equals(ai.name)) { 3777 continue; 3778 } 3779 3780 if (removeMatches) { 3781 pir.removeFilter(pa); 3782 changed = true; 3783 if (DEBUG_PREFERRED) { 3784 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3785 } 3786 break; 3787 } 3788 3789 // Okay we found a previously set preferred or last chosen app. 3790 // If the result set is different from when this 3791 // was created, we need to clear it and re-ask the 3792 // user their preference, if we're looking for an "always" type entry. 3793 if (always && !pa.mPref.sameSet(query)) { 3794 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3795 + intent + " type " + resolvedType); 3796 if (DEBUG_PREFERRED) { 3797 Slog.v(TAG, "Removing preferred activity since set changed " 3798 + pa.mPref.mComponent); 3799 } 3800 pir.removeFilter(pa); 3801 // Re-add the filter as a "last chosen" entry (!always) 3802 PreferredActivity lastChosen = new PreferredActivity( 3803 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3804 pir.addFilter(lastChosen); 3805 changed = true; 3806 return null; 3807 } 3808 3809 // Yay! Either the set matched or we're looking for the last chosen 3810 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3811 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3812 return ri; 3813 } 3814 } 3815 } finally { 3816 if (changed) { 3817 if (DEBUG_PREFERRED) { 3818 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3819 } 3820 scheduleWritePackageRestrictionsLocked(userId); 3821 } 3822 } 3823 } 3824 } 3825 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3826 return null; 3827 } 3828 3829 /* 3830 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3831 */ 3832 @Override 3833 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3834 int targetUserId) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3837 List<CrossProfileIntentFilter> matches = 3838 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3839 if (matches != null) { 3840 int size = matches.size(); 3841 for (int i = 0; i < size; i++) { 3842 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3843 } 3844 } 3845 return false; 3846 } 3847 3848 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3849 String resolvedType, int userId) { 3850 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3851 if (resolver != null) { 3852 return resolver.queryIntent(intent, resolvedType, false, userId); 3853 } 3854 return null; 3855 } 3856 3857 @Override 3858 public List<ResolveInfo> queryIntentActivities(Intent intent, 3859 String resolvedType, int flags, int userId) { 3860 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3862 ComponentName comp = intent.getComponent(); 3863 if (comp == null) { 3864 if (intent.getSelector() != null) { 3865 intent = intent.getSelector(); 3866 comp = intent.getComponent(); 3867 } 3868 } 3869 3870 if (comp != null) { 3871 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3872 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3873 if (ai != null) { 3874 final ResolveInfo ri = new ResolveInfo(); 3875 ri.activityInfo = ai; 3876 list.add(ri); 3877 } 3878 return list; 3879 } 3880 3881 // reader 3882 synchronized (mPackages) { 3883 final String pkgName = intent.getPackage(); 3884 if (pkgName == null) { 3885 List<CrossProfileIntentFilter> matchingFilters = 3886 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3887 // Check for results that need to skip the current profile. 3888 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3889 resolvedType, flags, userId); 3890 if (resolveInfo != null) { 3891 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3892 result.add(resolveInfo); 3893 return filterIfNotPrimaryUser(result, userId); 3894 } 3895 // Check for cross profile results. 3896 resolveInfo = queryCrossProfileIntents( 3897 matchingFilters, intent, resolvedType, flags, userId); 3898 3899 // Check for results in the current profile. 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 filterCandidatesWithDomainPreferedActivitiesLPr(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> filterCandidatesWithDomainPreferedActivitiesLPr( 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>(); 3950 synchronized (mPackages) { 3951 final int count = candidates.size(); 3952 // First, try to use the domain prefered App 3953 for (int n=0; n<count; n++) { 3954 ResolveInfo info = candidates.get(n); 3955 String packageName = info.activityInfo.packageName; 3956 PackageSetting ps = mSettings.mPackages.get(packageName); 3957 if (ps != null) { 3958 // Try to get the status from User settings first 3959 int status = getDomainVerificationStatusLPr(ps, userId); 3960 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 3961 result.add(info); 3962 } 3963 } 3964 } 3965 // There is not much we can do, add all candidates 3966 if (result.size() == 0) { 3967 result.addAll(candidates); 3968 } 3969 } 3970 if (DEBUG_PREFERRED) { 3971 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 3972 result.size()); 3973 } 3974 return result; 3975 } 3976 3977 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 3978 int status = ps.getDomainVerificationStatusForUser(userId); 3979 // if none available, get the master status 3980 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 3981 if (ps.getIntentFilterVerificationInfo() != null) { 3982 status = ps.getIntentFilterVerificationInfo().getStatus(); 3983 } 3984 } 3985 return status; 3986 } 3987 3988 private ResolveInfo querySkipCurrentProfileIntents( 3989 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3990 int flags, int sourceUserId) { 3991 if (matchingFilters != null) { 3992 int size = matchingFilters.size(); 3993 for (int i = 0; i < size; i ++) { 3994 CrossProfileIntentFilter filter = matchingFilters.get(i); 3995 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3996 // Checking if there are activities in the target user that can handle the 3997 // intent. 3998 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3999 flags, sourceUserId); 4000 if (resolveInfo != null) { 4001 return resolveInfo; 4002 } 4003 } 4004 } 4005 } 4006 return null; 4007 } 4008 4009 // Return matching ResolveInfo if any for skip current profile intent filters. 4010 private ResolveInfo queryCrossProfileIntents( 4011 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4012 int flags, int sourceUserId) { 4013 if (matchingFilters != null) { 4014 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4015 // match the same intent. For performance reasons, it is better not to 4016 // run queryIntent twice for the same userId 4017 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4018 int size = matchingFilters.size(); 4019 for (int i = 0; i < size; i++) { 4020 CrossProfileIntentFilter filter = matchingFilters.get(i); 4021 int targetUserId = filter.getTargetUserId(); 4022 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4023 && !alreadyTriedUserIds.get(targetUserId)) { 4024 // Checking if there are activities in the target user that can handle the 4025 // intent. 4026 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4027 flags, sourceUserId); 4028 if (resolveInfo != null) return resolveInfo; 4029 alreadyTriedUserIds.put(targetUserId, true); 4030 } 4031 } 4032 } 4033 return null; 4034 } 4035 4036 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4037 String resolvedType, int flags, int sourceUserId) { 4038 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4039 resolvedType, flags, filter.getTargetUserId()); 4040 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4041 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4042 } 4043 return null; 4044 } 4045 4046 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4047 int sourceUserId, int targetUserId) { 4048 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4049 String className; 4050 if (targetUserId == UserHandle.USER_OWNER) { 4051 className = FORWARD_INTENT_TO_USER_OWNER; 4052 } else { 4053 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4054 } 4055 ComponentName forwardingActivityComponentName = new ComponentName( 4056 mAndroidApplication.packageName, className); 4057 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4058 sourceUserId); 4059 if (targetUserId == UserHandle.USER_OWNER) { 4060 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4061 forwardingResolveInfo.noResourceId = true; 4062 } 4063 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4064 forwardingResolveInfo.priority = 0; 4065 forwardingResolveInfo.preferredOrder = 0; 4066 forwardingResolveInfo.match = 0; 4067 forwardingResolveInfo.isDefault = true; 4068 forwardingResolveInfo.filter = filter; 4069 forwardingResolveInfo.targetUserId = targetUserId; 4070 return forwardingResolveInfo; 4071 } 4072 4073 @Override 4074 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4075 Intent[] specifics, String[] specificTypes, Intent intent, 4076 String resolvedType, int flags, int userId) { 4077 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4079 false, "query intent activity options"); 4080 final String resultsAction = intent.getAction(); 4081 4082 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4083 | PackageManager.GET_RESOLVED_FILTER, userId); 4084 4085 if (DEBUG_INTENT_MATCHING) { 4086 Log.v(TAG, "Query " + intent + ": " + results); 4087 } 4088 4089 int specificsPos = 0; 4090 int N; 4091 4092 // todo: note that the algorithm used here is O(N^2). This 4093 // isn't a problem in our current environment, but if we start running 4094 // into situations where we have more than 5 or 10 matches then this 4095 // should probably be changed to something smarter... 4096 4097 // First we go through and resolve each of the specific items 4098 // that were supplied, taking care of removing any corresponding 4099 // duplicate items in the generic resolve list. 4100 if (specifics != null) { 4101 for (int i=0; i<specifics.length; i++) { 4102 final Intent sintent = specifics[i]; 4103 if (sintent == null) { 4104 continue; 4105 } 4106 4107 if (DEBUG_INTENT_MATCHING) { 4108 Log.v(TAG, "Specific #" + i + ": " + sintent); 4109 } 4110 4111 String action = sintent.getAction(); 4112 if (resultsAction != null && resultsAction.equals(action)) { 4113 // If this action was explicitly requested, then don't 4114 // remove things that have it. 4115 action = null; 4116 } 4117 4118 ResolveInfo ri = null; 4119 ActivityInfo ai = null; 4120 4121 ComponentName comp = sintent.getComponent(); 4122 if (comp == null) { 4123 ri = resolveIntent( 4124 sintent, 4125 specificTypes != null ? specificTypes[i] : null, 4126 flags, userId); 4127 if (ri == null) { 4128 continue; 4129 } 4130 if (ri == mResolveInfo) { 4131 // ACK! Must do something better with this. 4132 } 4133 ai = ri.activityInfo; 4134 comp = new ComponentName(ai.applicationInfo.packageName, 4135 ai.name); 4136 } else { 4137 ai = getActivityInfo(comp, flags, userId); 4138 if (ai == null) { 4139 continue; 4140 } 4141 } 4142 4143 // Look for any generic query activities that are duplicates 4144 // of this specific one, and remove them from the results. 4145 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4146 N = results.size(); 4147 int j; 4148 for (j=specificsPos; j<N; j++) { 4149 ResolveInfo sri = results.get(j); 4150 if ((sri.activityInfo.name.equals(comp.getClassName()) 4151 && sri.activityInfo.applicationInfo.packageName.equals( 4152 comp.getPackageName())) 4153 || (action != null && sri.filter.matchAction(action))) { 4154 results.remove(j); 4155 if (DEBUG_INTENT_MATCHING) Log.v( 4156 TAG, "Removing duplicate item from " + j 4157 + " due to specific " + specificsPos); 4158 if (ri == null) { 4159 ri = sri; 4160 } 4161 j--; 4162 N--; 4163 } 4164 } 4165 4166 // Add this specific item to its proper place. 4167 if (ri == null) { 4168 ri = new ResolveInfo(); 4169 ri.activityInfo = ai; 4170 } 4171 results.add(specificsPos, ri); 4172 ri.specificIndex = i; 4173 specificsPos++; 4174 } 4175 } 4176 4177 // Now we go through the remaining generic results and remove any 4178 // duplicate actions that are found here. 4179 N = results.size(); 4180 for (int i=specificsPos; i<N-1; i++) { 4181 final ResolveInfo rii = results.get(i); 4182 if (rii.filter == null) { 4183 continue; 4184 } 4185 4186 // Iterate over all of the actions of this result's intent 4187 // filter... typically this should be just one. 4188 final Iterator<String> it = rii.filter.actionsIterator(); 4189 if (it == null) { 4190 continue; 4191 } 4192 while (it.hasNext()) { 4193 final String action = it.next(); 4194 if (resultsAction != null && resultsAction.equals(action)) { 4195 // If this action was explicitly requested, then don't 4196 // remove things that have it. 4197 continue; 4198 } 4199 for (int j=i+1; j<N; j++) { 4200 final ResolveInfo rij = results.get(j); 4201 if (rij.filter != null && rij.filter.hasAction(action)) { 4202 results.remove(j); 4203 if (DEBUG_INTENT_MATCHING) Log.v( 4204 TAG, "Removing duplicate item from " + j 4205 + " due to action " + action + " at " + i); 4206 j--; 4207 N--; 4208 } 4209 } 4210 } 4211 4212 // If the caller didn't request filter information, drop it now 4213 // so we don't have to marshall/unmarshall it. 4214 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4215 rii.filter = null; 4216 } 4217 } 4218 4219 // Filter out the caller activity if so requested. 4220 if (caller != null) { 4221 N = results.size(); 4222 for (int i=0; i<N; i++) { 4223 ActivityInfo ainfo = results.get(i).activityInfo; 4224 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4225 && caller.getClassName().equals(ainfo.name)) { 4226 results.remove(i); 4227 break; 4228 } 4229 } 4230 } 4231 4232 // If the caller didn't request filter information, 4233 // drop them now so we don't have to 4234 // marshall/unmarshall it. 4235 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4236 N = results.size(); 4237 for (int i=0; i<N; i++) { 4238 results.get(i).filter = null; 4239 } 4240 } 4241 4242 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4243 return results; 4244 } 4245 4246 @Override 4247 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4248 int userId) { 4249 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4250 ComponentName comp = intent.getComponent(); 4251 if (comp == null) { 4252 if (intent.getSelector() != null) { 4253 intent = intent.getSelector(); 4254 comp = intent.getComponent(); 4255 } 4256 } 4257 if (comp != null) { 4258 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4259 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4260 if (ai != null) { 4261 ResolveInfo ri = new ResolveInfo(); 4262 ri.activityInfo = ai; 4263 list.add(ri); 4264 } 4265 return list; 4266 } 4267 4268 // reader 4269 synchronized (mPackages) { 4270 String pkgName = intent.getPackage(); 4271 if (pkgName == null) { 4272 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4273 } 4274 final PackageParser.Package pkg = mPackages.get(pkgName); 4275 if (pkg != null) { 4276 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4277 userId); 4278 } 4279 return null; 4280 } 4281 } 4282 4283 @Override 4284 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4285 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4286 if (!sUserManager.exists(userId)) return null; 4287 if (query != null) { 4288 if (query.size() >= 1) { 4289 // If there is more than one service with the same priority, 4290 // just arbitrarily pick the first one. 4291 return query.get(0); 4292 } 4293 } 4294 return null; 4295 } 4296 4297 @Override 4298 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4299 int userId) { 4300 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4301 ComponentName comp = intent.getComponent(); 4302 if (comp == null) { 4303 if (intent.getSelector() != null) { 4304 intent = intent.getSelector(); 4305 comp = intent.getComponent(); 4306 } 4307 } 4308 if (comp != null) { 4309 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4310 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4311 if (si != null) { 4312 final ResolveInfo ri = new ResolveInfo(); 4313 ri.serviceInfo = si; 4314 list.add(ri); 4315 } 4316 return list; 4317 } 4318 4319 // reader 4320 synchronized (mPackages) { 4321 String pkgName = intent.getPackage(); 4322 if (pkgName == null) { 4323 return mServices.queryIntent(intent, resolvedType, flags, userId); 4324 } 4325 final PackageParser.Package pkg = mPackages.get(pkgName); 4326 if (pkg != null) { 4327 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4328 userId); 4329 } 4330 return null; 4331 } 4332 } 4333 4334 @Override 4335 public List<ResolveInfo> queryIntentContentProviders( 4336 Intent intent, String resolvedType, int flags, int userId) { 4337 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4338 ComponentName comp = intent.getComponent(); 4339 if (comp == null) { 4340 if (intent.getSelector() != null) { 4341 intent = intent.getSelector(); 4342 comp = intent.getComponent(); 4343 } 4344 } 4345 if (comp != null) { 4346 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4347 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4348 if (pi != null) { 4349 final ResolveInfo ri = new ResolveInfo(); 4350 ri.providerInfo = pi; 4351 list.add(ri); 4352 } 4353 return list; 4354 } 4355 4356 // reader 4357 synchronized (mPackages) { 4358 String pkgName = intent.getPackage(); 4359 if (pkgName == null) { 4360 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4361 } 4362 final PackageParser.Package pkg = mPackages.get(pkgName); 4363 if (pkg != null) { 4364 return mProviders.queryIntentForPackage( 4365 intent, resolvedType, flags, pkg.providers, userId); 4366 } 4367 return null; 4368 } 4369 } 4370 4371 @Override 4372 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4373 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4374 4375 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4376 4377 // writer 4378 synchronized (mPackages) { 4379 ArrayList<PackageInfo> list; 4380 if (listUninstalled) { 4381 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4382 for (PackageSetting ps : mSettings.mPackages.values()) { 4383 PackageInfo pi; 4384 if (ps.pkg != null) { 4385 pi = generatePackageInfo(ps.pkg, flags, userId); 4386 } else { 4387 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4388 } 4389 if (pi != null) { 4390 list.add(pi); 4391 } 4392 } 4393 } else { 4394 list = new ArrayList<PackageInfo>(mPackages.size()); 4395 for (PackageParser.Package p : mPackages.values()) { 4396 PackageInfo pi = generatePackageInfo(p, flags, userId); 4397 if (pi != null) { 4398 list.add(pi); 4399 } 4400 } 4401 } 4402 4403 return new ParceledListSlice<PackageInfo>(list); 4404 } 4405 } 4406 4407 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4408 String[] permissions, boolean[] tmp, int flags, int userId) { 4409 int numMatch = 0; 4410 final PermissionsState permissionsState = ps.getPermissionsState(); 4411 for (int i=0; i<permissions.length; i++) { 4412 final String permission = permissions[i]; 4413 if (permissionsState.hasPermission(permission, userId)) { 4414 tmp[i] = true; 4415 numMatch++; 4416 } else { 4417 tmp[i] = false; 4418 } 4419 } 4420 if (numMatch == 0) { 4421 return; 4422 } 4423 PackageInfo pi; 4424 if (ps.pkg != null) { 4425 pi = generatePackageInfo(ps.pkg, flags, userId); 4426 } else { 4427 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4428 } 4429 // The above might return null in cases of uninstalled apps or install-state 4430 // skew across users/profiles. 4431 if (pi != null) { 4432 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4433 if (numMatch == permissions.length) { 4434 pi.requestedPermissions = permissions; 4435 } else { 4436 pi.requestedPermissions = new String[numMatch]; 4437 numMatch = 0; 4438 for (int i=0; i<permissions.length; i++) { 4439 if (tmp[i]) { 4440 pi.requestedPermissions[numMatch] = permissions[i]; 4441 numMatch++; 4442 } 4443 } 4444 } 4445 } 4446 list.add(pi); 4447 } 4448 } 4449 4450 @Override 4451 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4452 String[] permissions, int flags, int userId) { 4453 if (!sUserManager.exists(userId)) return null; 4454 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4455 4456 // writer 4457 synchronized (mPackages) { 4458 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4459 boolean[] tmpBools = new boolean[permissions.length]; 4460 if (listUninstalled) { 4461 for (PackageSetting ps : mSettings.mPackages.values()) { 4462 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4463 } 4464 } else { 4465 for (PackageParser.Package pkg : mPackages.values()) { 4466 PackageSetting ps = (PackageSetting)pkg.mExtras; 4467 if (ps != null) { 4468 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4469 userId); 4470 } 4471 } 4472 } 4473 4474 return new ParceledListSlice<PackageInfo>(list); 4475 } 4476 } 4477 4478 @Override 4479 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4480 if (!sUserManager.exists(userId)) return null; 4481 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4482 4483 // writer 4484 synchronized (mPackages) { 4485 ArrayList<ApplicationInfo> list; 4486 if (listUninstalled) { 4487 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4488 for (PackageSetting ps : mSettings.mPackages.values()) { 4489 ApplicationInfo ai; 4490 if (ps.pkg != null) { 4491 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4492 ps.readUserState(userId), userId); 4493 } else { 4494 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4495 } 4496 if (ai != null) { 4497 list.add(ai); 4498 } 4499 } 4500 } else { 4501 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4502 for (PackageParser.Package p : mPackages.values()) { 4503 if (p.mExtras != null) { 4504 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4505 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4506 if (ai != null) { 4507 list.add(ai); 4508 } 4509 } 4510 } 4511 } 4512 4513 return new ParceledListSlice<ApplicationInfo>(list); 4514 } 4515 } 4516 4517 public List<ApplicationInfo> getPersistentApplications(int flags) { 4518 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4519 4520 // reader 4521 synchronized (mPackages) { 4522 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4523 final int userId = UserHandle.getCallingUserId(); 4524 while (i.hasNext()) { 4525 final PackageParser.Package p = i.next(); 4526 if (p.applicationInfo != null 4527 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4528 && (!mSafeMode || isSystemApp(p))) { 4529 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4530 if (ps != null) { 4531 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4532 ps.readUserState(userId), userId); 4533 if (ai != null) { 4534 finalList.add(ai); 4535 } 4536 } 4537 } 4538 } 4539 } 4540 4541 return finalList; 4542 } 4543 4544 @Override 4545 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4546 if (!sUserManager.exists(userId)) return null; 4547 // reader 4548 synchronized (mPackages) { 4549 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4550 PackageSetting ps = provider != null 4551 ? mSettings.mPackages.get(provider.owner.packageName) 4552 : null; 4553 return ps != null 4554 && mSettings.isEnabledLPr(provider.info, flags, userId) 4555 && (!mSafeMode || (provider.info.applicationInfo.flags 4556 &ApplicationInfo.FLAG_SYSTEM) != 0) 4557 ? PackageParser.generateProviderInfo(provider, flags, 4558 ps.readUserState(userId), userId) 4559 : null; 4560 } 4561 } 4562 4563 /** 4564 * @deprecated 4565 */ 4566 @Deprecated 4567 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4568 // reader 4569 synchronized (mPackages) { 4570 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4571 .entrySet().iterator(); 4572 final int userId = UserHandle.getCallingUserId(); 4573 while (i.hasNext()) { 4574 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4575 PackageParser.Provider p = entry.getValue(); 4576 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4577 4578 if (ps != null && p.syncable 4579 && (!mSafeMode || (p.info.applicationInfo.flags 4580 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4581 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4582 ps.readUserState(userId), userId); 4583 if (info != null) { 4584 outNames.add(entry.getKey()); 4585 outInfo.add(info); 4586 } 4587 } 4588 } 4589 } 4590 } 4591 4592 @Override 4593 public List<ProviderInfo> queryContentProviders(String processName, 4594 int uid, int flags) { 4595 ArrayList<ProviderInfo> finalList = null; 4596 // reader 4597 synchronized (mPackages) { 4598 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4599 final int userId = processName != null ? 4600 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4601 while (i.hasNext()) { 4602 final PackageParser.Provider p = i.next(); 4603 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4604 if (ps != null && p.info.authority != null 4605 && (processName == null 4606 || (p.info.processName.equals(processName) 4607 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4608 && mSettings.isEnabledLPr(p.info, flags, userId) 4609 && (!mSafeMode 4610 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4611 if (finalList == null) { 4612 finalList = new ArrayList<ProviderInfo>(3); 4613 } 4614 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4615 ps.readUserState(userId), userId); 4616 if (info != null) { 4617 finalList.add(info); 4618 } 4619 } 4620 } 4621 } 4622 4623 if (finalList != null) { 4624 Collections.sort(finalList, mProviderInitOrderSorter); 4625 } 4626 4627 return finalList; 4628 } 4629 4630 @Override 4631 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4632 int flags) { 4633 // reader 4634 synchronized (mPackages) { 4635 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4636 return PackageParser.generateInstrumentationInfo(i, flags); 4637 } 4638 } 4639 4640 @Override 4641 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4642 int flags) { 4643 ArrayList<InstrumentationInfo> finalList = 4644 new ArrayList<InstrumentationInfo>(); 4645 4646 // reader 4647 synchronized (mPackages) { 4648 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4649 while (i.hasNext()) { 4650 final PackageParser.Instrumentation p = i.next(); 4651 if (targetPackage == null 4652 || targetPackage.equals(p.info.targetPackage)) { 4653 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4654 flags); 4655 if (ii != null) { 4656 finalList.add(ii); 4657 } 4658 } 4659 } 4660 } 4661 4662 return finalList; 4663 } 4664 4665 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4666 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4667 if (overlays == null) { 4668 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4669 return; 4670 } 4671 for (PackageParser.Package opkg : overlays.values()) { 4672 // Not much to do if idmap fails: we already logged the error 4673 // and we certainly don't want to abort installation of pkg simply 4674 // because an overlay didn't fit properly. For these reasons, 4675 // ignore the return value of createIdmapForPackagePairLI. 4676 createIdmapForPackagePairLI(pkg, opkg); 4677 } 4678 } 4679 4680 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4681 PackageParser.Package opkg) { 4682 if (!opkg.mTrustedOverlay) { 4683 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4684 opkg.baseCodePath + ": overlay not trusted"); 4685 return false; 4686 } 4687 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4688 if (overlaySet == null) { 4689 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4690 opkg.baseCodePath + " but target package has no known overlays"); 4691 return false; 4692 } 4693 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4694 // TODO: generate idmap for split APKs 4695 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4696 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4697 + opkg.baseCodePath); 4698 return false; 4699 } 4700 PackageParser.Package[] overlayArray = 4701 overlaySet.values().toArray(new PackageParser.Package[0]); 4702 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4703 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4704 return p1.mOverlayPriority - p2.mOverlayPriority; 4705 } 4706 }; 4707 Arrays.sort(overlayArray, cmp); 4708 4709 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4710 int i = 0; 4711 for (PackageParser.Package p : overlayArray) { 4712 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4713 } 4714 return true; 4715 } 4716 4717 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4718 final File[] files = dir.listFiles(); 4719 if (ArrayUtils.isEmpty(files)) { 4720 Log.d(TAG, "No files in app dir " + dir); 4721 return; 4722 } 4723 4724 if (DEBUG_PACKAGE_SCANNING) { 4725 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4726 + " flags=0x" + Integer.toHexString(parseFlags)); 4727 } 4728 4729 for (File file : files) { 4730 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4731 && !PackageInstallerService.isStageName(file.getName()); 4732 if (!isPackage) { 4733 // Ignore entries which are not packages 4734 continue; 4735 } 4736 try { 4737 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4738 scanFlags, currentTime, null); 4739 } catch (PackageManagerException e) { 4740 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4741 4742 // Delete invalid userdata apps 4743 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4744 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4745 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4746 if (file.isDirectory()) { 4747 mInstaller.rmPackageDir(file.getAbsolutePath()); 4748 } else { 4749 file.delete(); 4750 } 4751 } 4752 } 4753 } 4754 } 4755 4756 private static File getSettingsProblemFile() { 4757 File dataDir = Environment.getDataDirectory(); 4758 File systemDir = new File(dataDir, "system"); 4759 File fname = new File(systemDir, "uiderrors.txt"); 4760 return fname; 4761 } 4762 4763 static void reportSettingsProblem(int priority, String msg) { 4764 logCriticalInfo(priority, msg); 4765 } 4766 4767 static void logCriticalInfo(int priority, String msg) { 4768 Slog.println(priority, TAG, msg); 4769 EventLogTags.writePmCriticalInfo(msg); 4770 try { 4771 File fname = getSettingsProblemFile(); 4772 FileOutputStream out = new FileOutputStream(fname, true); 4773 PrintWriter pw = new FastPrintWriter(out); 4774 SimpleDateFormat formatter = new SimpleDateFormat(); 4775 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4776 pw.println(dateString + ": " + msg); 4777 pw.close(); 4778 FileUtils.setPermissions( 4779 fname.toString(), 4780 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4781 -1, -1); 4782 } catch (java.io.IOException e) { 4783 } 4784 } 4785 4786 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4787 PackageParser.Package pkg, File srcFile, int parseFlags) 4788 throws PackageManagerException { 4789 if (ps != null 4790 && ps.codePath.equals(srcFile) 4791 && ps.timeStamp == srcFile.lastModified() 4792 && !isCompatSignatureUpdateNeeded(pkg) 4793 && !isRecoverSignatureUpdateNeeded(pkg)) { 4794 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4795 if (ps.signatures.mSignatures != null 4796 && ps.signatures.mSignatures.length != 0 4797 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4798 // Optimization: reuse the existing cached certificates 4799 // if the package appears to be unchanged. 4800 pkg.mSignatures = ps.signatures.mSignatures; 4801 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4802 synchronized (mPackages) { 4803 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4804 } 4805 return; 4806 } 4807 4808 Slog.w(TAG, "PackageSetting for " + ps.name 4809 + " is missing signatures. Collecting certs again to recover them."); 4810 } else { 4811 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4812 } 4813 4814 try { 4815 pp.collectCertificates(pkg, parseFlags); 4816 pp.collectManifestDigest(pkg); 4817 } catch (PackageParserException e) { 4818 throw PackageManagerException.from(e); 4819 } 4820 } 4821 4822 /* 4823 * Scan a package and return the newly parsed package. 4824 * Returns null in case of errors and the error code is stored in mLastScanError 4825 */ 4826 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4827 long currentTime, UserHandle user) throws PackageManagerException { 4828 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4829 parseFlags |= mDefParseFlags; 4830 PackageParser pp = new PackageParser(); 4831 pp.setSeparateProcesses(mSeparateProcesses); 4832 pp.setOnlyCoreApps(mOnlyCore); 4833 pp.setDisplayMetrics(mMetrics); 4834 4835 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4836 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4837 } 4838 4839 final PackageParser.Package pkg; 4840 try { 4841 pkg = pp.parsePackage(scanFile, parseFlags); 4842 } catch (PackageParserException e) { 4843 throw PackageManagerException.from(e); 4844 } 4845 4846 PackageSetting ps = null; 4847 PackageSetting updatedPkg; 4848 // reader 4849 synchronized (mPackages) { 4850 // Look to see if we already know about this package. 4851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4853 // This package has been renamed to its original name. Let's 4854 // use that. 4855 ps = mSettings.peekPackageLPr(oldName); 4856 } 4857 // If there was no original package, see one for the real package name. 4858 if (ps == null) { 4859 ps = mSettings.peekPackageLPr(pkg.packageName); 4860 } 4861 // Check to see if this package could be hiding/updating a system 4862 // package. Must look for it either under the original or real 4863 // package name depending on our state. 4864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4866 } 4867 boolean updatedPkgBetter = false; 4868 // First check if this is a system package that may involve an update 4869 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4870 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4871 // it needs to drop FLAG_PRIVILEGED. 4872 if (locationIsPrivileged(scanFile)) { 4873 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4874 } else { 4875 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4876 } 4877 4878 if (ps != null && !ps.codePath.equals(scanFile)) { 4879 // The path has changed from what was last scanned... check the 4880 // version of the new path against what we have stored to determine 4881 // what to do. 4882 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4883 if (pkg.mVersionCode <= ps.versionCode) { 4884 // The system package has been updated and the code path does not match 4885 // Ignore entry. Skip it. 4886 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4887 + " ignored: updated version " + ps.versionCode 4888 + " better than this " + pkg.mVersionCode); 4889 if (!updatedPkg.codePath.equals(scanFile)) { 4890 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4891 + ps.name + " changing from " + updatedPkg.codePathString 4892 + " to " + scanFile); 4893 updatedPkg.codePath = scanFile; 4894 updatedPkg.codePathString = scanFile.toString(); 4895 updatedPkg.resourcePath = scanFile; 4896 updatedPkg.resourcePathString = scanFile.toString(); 4897 } 4898 updatedPkg.pkg = pkg; 4899 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4900 } else { 4901 // The current app on the system partition is better than 4902 // what we have updated to on the data partition; switch 4903 // back to the system partition version. 4904 // At this point, its safely assumed that package installation for 4905 // apps in system partition will go through. If not there won't be a working 4906 // version of the app 4907 // writer 4908 synchronized (mPackages) { 4909 // Just remove the loaded entries from package lists. 4910 mPackages.remove(ps.name); 4911 } 4912 4913 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4914 + " reverting from " + ps.codePathString 4915 + ": new version " + pkg.mVersionCode 4916 + " better than installed " + ps.versionCode); 4917 4918 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4919 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4920 getAppDexInstructionSets(ps)); 4921 synchronized (mInstallLock) { 4922 args.cleanUpResourcesLI(); 4923 } 4924 synchronized (mPackages) { 4925 mSettings.enableSystemPackageLPw(ps.name); 4926 } 4927 updatedPkgBetter = true; 4928 } 4929 } 4930 } 4931 4932 if (updatedPkg != null) { 4933 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4934 // initially 4935 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4936 4937 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4938 // flag set initially 4939 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4940 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4941 } 4942 } 4943 4944 // Verify certificates against what was last scanned 4945 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4946 4947 /* 4948 * A new system app appeared, but we already had a non-system one of the 4949 * same name installed earlier. 4950 */ 4951 boolean shouldHideSystemApp = false; 4952 if (updatedPkg == null && ps != null 4953 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4954 /* 4955 * Check to make sure the signatures match first. If they don't, 4956 * wipe the installed application and its data. 4957 */ 4958 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4959 != PackageManager.SIGNATURE_MATCH) { 4960 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4961 + " signatures don't match existing userdata copy; removing"); 4962 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4963 ps = null; 4964 } else { 4965 /* 4966 * If the newly-added system app is an older version than the 4967 * already installed version, hide it. It will be scanned later 4968 * and re-added like an update. 4969 */ 4970 if (pkg.mVersionCode <= ps.versionCode) { 4971 shouldHideSystemApp = true; 4972 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4973 + " but new version " + pkg.mVersionCode + " better than installed " 4974 + ps.versionCode + "; hiding system"); 4975 } else { 4976 /* 4977 * The newly found system app is a newer version that the 4978 * one previously installed. Simply remove the 4979 * already-installed application and replace it with our own 4980 * while keeping the application data. 4981 */ 4982 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4983 + " reverting from " + ps.codePathString + ": new version " 4984 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4985 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4986 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4987 getAppDexInstructionSets(ps)); 4988 synchronized (mInstallLock) { 4989 args.cleanUpResourcesLI(); 4990 } 4991 } 4992 } 4993 } 4994 4995 // The apk is forward locked (not public) if its code and resources 4996 // are kept in different files. (except for app in either system or 4997 // vendor path). 4998 // TODO grab this value from PackageSettings 4999 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5000 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5001 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5002 } 5003 } 5004 5005 // TODO: extend to support forward-locked splits 5006 String resourcePath = null; 5007 String baseResourcePath = null; 5008 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5009 if (ps != null && ps.resourcePathString != null) { 5010 resourcePath = ps.resourcePathString; 5011 baseResourcePath = ps.resourcePathString; 5012 } else { 5013 // Should not happen at all. Just log an error. 5014 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5015 } 5016 } else { 5017 resourcePath = pkg.codePath; 5018 baseResourcePath = pkg.baseCodePath; 5019 } 5020 5021 // Set application objects path explicitly. 5022 pkg.applicationInfo.setCodePath(pkg.codePath); 5023 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5024 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5025 pkg.applicationInfo.setResourcePath(resourcePath); 5026 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5027 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5028 5029 // Note that we invoke the following method only if we are about to unpack an application 5030 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5031 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5032 5033 /* 5034 * If the system app should be overridden by a previously installed 5035 * data, hide the system app now and let the /data/app scan pick it up 5036 * again. 5037 */ 5038 if (shouldHideSystemApp) { 5039 synchronized (mPackages) { 5040 /* 5041 * We have to grant systems permissions before we hide, because 5042 * grantPermissions will assume the package update is trying to 5043 * expand its permissions. 5044 */ 5045 grantPermissionsLPw(pkg, true, pkg.packageName); 5046 mSettings.disableSystemPackageLPw(pkg.packageName); 5047 } 5048 } 5049 5050 return scannedPkg; 5051 } 5052 5053 private static String fixProcessName(String defProcessName, 5054 String processName, int uid) { 5055 if (processName == null) { 5056 return defProcessName; 5057 } 5058 return processName; 5059 } 5060 5061 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5062 throws PackageManagerException { 5063 if (pkgSetting.signatures.mSignatures != null) { 5064 // Already existing package. Make sure signatures match 5065 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5066 == PackageManager.SIGNATURE_MATCH; 5067 if (!match) { 5068 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5069 == PackageManager.SIGNATURE_MATCH; 5070 } 5071 if (!match) { 5072 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5073 == PackageManager.SIGNATURE_MATCH; 5074 } 5075 if (!match) { 5076 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5077 + pkg.packageName + " signatures do not match the " 5078 + "previously installed version; ignoring!"); 5079 } 5080 } 5081 5082 // Check for shared user signatures 5083 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5084 // Already existing package. Make sure signatures match 5085 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5086 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5087 if (!match) { 5088 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5089 == PackageManager.SIGNATURE_MATCH; 5090 } 5091 if (!match) { 5092 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5093 == PackageManager.SIGNATURE_MATCH; 5094 } 5095 if (!match) { 5096 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5097 "Package " + pkg.packageName 5098 + " has no signatures that match those in shared user " 5099 + pkgSetting.sharedUser.name + "; ignoring!"); 5100 } 5101 } 5102 } 5103 5104 /** 5105 * Enforces that only the system UID or root's UID can call a method exposed 5106 * via Binder. 5107 * 5108 * @param message used as message if SecurityException is thrown 5109 * @throws SecurityException if the caller is not system or root 5110 */ 5111 private static final void enforceSystemOrRoot(String message) { 5112 final int uid = Binder.getCallingUid(); 5113 if (uid != Process.SYSTEM_UID && uid != 0) { 5114 throw new SecurityException(message); 5115 } 5116 } 5117 5118 @Override 5119 public void performBootDexOpt() { 5120 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5121 5122 // Before everything else, see whether we need to fstrim. 5123 try { 5124 IMountService ms = PackageHelper.getMountService(); 5125 if (ms != null) { 5126 final boolean isUpgrade = isUpgrade(); 5127 boolean doTrim = isUpgrade; 5128 if (doTrim) { 5129 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5130 } else { 5131 final long interval = android.provider.Settings.Global.getLong( 5132 mContext.getContentResolver(), 5133 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5134 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5135 if (interval > 0) { 5136 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5137 if (timeSinceLast > interval) { 5138 doTrim = true; 5139 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5140 + "; running immediately"); 5141 } 5142 } 5143 } 5144 if (doTrim) { 5145 if (!isFirstBoot()) { 5146 try { 5147 ActivityManagerNative.getDefault().showBootMessage( 5148 mContext.getResources().getString( 5149 R.string.android_upgrading_fstrim), true); 5150 } catch (RemoteException e) { 5151 } 5152 } 5153 ms.runMaintenance(); 5154 } 5155 } else { 5156 Slog.e(TAG, "Mount service unavailable!"); 5157 } 5158 } catch (RemoteException e) { 5159 // Can't happen; MountService is local 5160 } 5161 5162 final ArraySet<PackageParser.Package> pkgs; 5163 synchronized (mPackages) { 5164 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5165 } 5166 5167 if (pkgs != null) { 5168 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5169 // in case the device runs out of space. 5170 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5171 // Give priority to core apps. 5172 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5173 PackageParser.Package pkg = it.next(); 5174 if (pkg.coreApp) { 5175 if (DEBUG_DEXOPT) { 5176 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5177 } 5178 sortedPkgs.add(pkg); 5179 it.remove(); 5180 } 5181 } 5182 // Give priority to system apps that listen for pre boot complete. 5183 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5184 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5185 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5186 PackageParser.Package pkg = it.next(); 5187 if (pkgNames.contains(pkg.packageName)) { 5188 if (DEBUG_DEXOPT) { 5189 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5190 } 5191 sortedPkgs.add(pkg); 5192 it.remove(); 5193 } 5194 } 5195 // Give priority to system apps. 5196 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5197 PackageParser.Package pkg = it.next(); 5198 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5199 if (DEBUG_DEXOPT) { 5200 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5201 } 5202 sortedPkgs.add(pkg); 5203 it.remove(); 5204 } 5205 } 5206 // Give priority to updated system apps. 5207 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5208 PackageParser.Package pkg = it.next(); 5209 if (pkg.isUpdatedSystemApp()) { 5210 if (DEBUG_DEXOPT) { 5211 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5212 } 5213 sortedPkgs.add(pkg); 5214 it.remove(); 5215 } 5216 } 5217 // Give priority to apps that listen for boot complete. 5218 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5219 pkgNames = getPackageNamesForIntent(intent); 5220 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5221 PackageParser.Package pkg = it.next(); 5222 if (pkgNames.contains(pkg.packageName)) { 5223 if (DEBUG_DEXOPT) { 5224 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5225 } 5226 sortedPkgs.add(pkg); 5227 it.remove(); 5228 } 5229 } 5230 // Filter out packages that aren't recently used. 5231 filterRecentlyUsedApps(pkgs); 5232 // Add all remaining apps. 5233 for (PackageParser.Package pkg : pkgs) { 5234 if (DEBUG_DEXOPT) { 5235 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5236 } 5237 sortedPkgs.add(pkg); 5238 } 5239 5240 // If we want to be lazy, filter everything that wasn't recently used. 5241 if (mLazyDexOpt) { 5242 filterRecentlyUsedApps(sortedPkgs); 5243 } 5244 5245 int i = 0; 5246 int total = sortedPkgs.size(); 5247 File dataDir = Environment.getDataDirectory(); 5248 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5249 if (lowThreshold == 0) { 5250 throw new IllegalStateException("Invalid low memory threshold"); 5251 } 5252 for (PackageParser.Package pkg : sortedPkgs) { 5253 long usableSpace = dataDir.getUsableSpace(); 5254 if (usableSpace < lowThreshold) { 5255 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5256 break; 5257 } 5258 performBootDexOpt(pkg, ++i, total); 5259 } 5260 } 5261 } 5262 5263 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5264 // Filter out packages that aren't recently used. 5265 // 5266 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5267 // should do a full dexopt. 5268 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5269 int total = pkgs.size(); 5270 int skipped = 0; 5271 long now = System.currentTimeMillis(); 5272 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5273 PackageParser.Package pkg = i.next(); 5274 long then = pkg.mLastPackageUsageTimeInMills; 5275 if (then + mDexOptLRUThresholdInMills < now) { 5276 if (DEBUG_DEXOPT) { 5277 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5278 ((then == 0) ? "never" : new Date(then))); 5279 } 5280 i.remove(); 5281 skipped++; 5282 } 5283 } 5284 if (DEBUG_DEXOPT) { 5285 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5286 } 5287 } 5288 } 5289 5290 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5291 List<ResolveInfo> ris = null; 5292 try { 5293 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5294 intent, null, 0, UserHandle.USER_OWNER); 5295 } catch (RemoteException e) { 5296 } 5297 ArraySet<String> pkgNames = new ArraySet<String>(); 5298 if (ris != null) { 5299 for (ResolveInfo ri : ris) { 5300 pkgNames.add(ri.activityInfo.packageName); 5301 } 5302 } 5303 return pkgNames; 5304 } 5305 5306 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5307 if (DEBUG_DEXOPT) { 5308 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5309 } 5310 if (!isFirstBoot()) { 5311 try { 5312 ActivityManagerNative.getDefault().showBootMessage( 5313 mContext.getResources().getString(R.string.android_upgrading_apk, 5314 curr, total), true); 5315 } catch (RemoteException e) { 5316 } 5317 } 5318 PackageParser.Package p = pkg; 5319 synchronized (mInstallLock) { 5320 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5321 false /* force dex */, false /* defer */, true /* include dependencies */); 5322 } 5323 } 5324 5325 @Override 5326 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5327 return performDexOpt(packageName, instructionSet, false); 5328 } 5329 5330 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5331 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5332 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5333 if (!dexopt && !updateUsage) { 5334 // We aren't going to dexopt or update usage, so bail early. 5335 return false; 5336 } 5337 PackageParser.Package p; 5338 final String targetInstructionSet; 5339 synchronized (mPackages) { 5340 p = mPackages.get(packageName); 5341 if (p == null) { 5342 return false; 5343 } 5344 if (updateUsage) { 5345 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5346 } 5347 mPackageUsage.write(false); 5348 if (!dexopt) { 5349 // We aren't going to dexopt, so bail early. 5350 return false; 5351 } 5352 5353 targetInstructionSet = instructionSet != null ? instructionSet : 5354 getPrimaryInstructionSet(p.applicationInfo); 5355 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5356 return false; 5357 } 5358 } 5359 5360 synchronized (mInstallLock) { 5361 final String[] instructionSets = new String[] { targetInstructionSet }; 5362 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5363 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5364 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5365 } 5366 } 5367 5368 public ArraySet<String> getPackagesThatNeedDexOpt() { 5369 ArraySet<String> pkgs = null; 5370 synchronized (mPackages) { 5371 for (PackageParser.Package p : mPackages.values()) { 5372 if (DEBUG_DEXOPT) { 5373 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5374 } 5375 if (!p.mDexOptPerformed.isEmpty()) { 5376 continue; 5377 } 5378 if (pkgs == null) { 5379 pkgs = new ArraySet<String>(); 5380 } 5381 pkgs.add(p.packageName); 5382 } 5383 } 5384 return pkgs; 5385 } 5386 5387 public void shutdown() { 5388 mPackageUsage.write(true); 5389 } 5390 5391 @Override 5392 public void forceDexOpt(String packageName) { 5393 enforceSystemOrRoot("forceDexOpt"); 5394 5395 PackageParser.Package pkg; 5396 synchronized (mPackages) { 5397 pkg = mPackages.get(packageName); 5398 if (pkg == null) { 5399 throw new IllegalArgumentException("Missing package: " + packageName); 5400 } 5401 } 5402 5403 synchronized (mInstallLock) { 5404 final String[] instructionSets = new String[] { 5405 getPrimaryInstructionSet(pkg.applicationInfo) }; 5406 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5407 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5408 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5409 throw new IllegalStateException("Failed to dexopt: " + res); 5410 } 5411 } 5412 } 5413 5414 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5415 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5416 Slog.w(TAG, "Unable to update from " + oldPkg.name 5417 + " to " + newPkg.packageName 5418 + ": old package not in system partition"); 5419 return false; 5420 } else if (mPackages.get(oldPkg.name) != null) { 5421 Slog.w(TAG, "Unable to update from " + oldPkg.name 5422 + " to " + newPkg.packageName 5423 + ": old package still exists"); 5424 return false; 5425 } 5426 return true; 5427 } 5428 5429 private File getDataPathForPackage(String packageName, int userId) { 5430 /* 5431 * Until we fully support multiple users, return the directory we 5432 * previously would have. The PackageManagerTests will need to be 5433 * revised when this is changed back.. 5434 */ 5435 if (userId == 0) { 5436 return new File(mAppDataDir, packageName); 5437 } else { 5438 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5439 + File.separator + packageName); 5440 } 5441 } 5442 5443 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5444 int[] users = sUserManager.getUserIds(); 5445 int res = mInstaller.install(packageName, uid, uid, seinfo); 5446 if (res < 0) { 5447 return res; 5448 } 5449 for (int user : users) { 5450 if (user != 0) { 5451 res = mInstaller.createUserData(packageName, 5452 UserHandle.getUid(user, uid), user, seinfo); 5453 if (res < 0) { 5454 return res; 5455 } 5456 } 5457 } 5458 return res; 5459 } 5460 5461 private int removeDataDirsLI(String packageName) { 5462 int[] users = sUserManager.getUserIds(); 5463 int res = 0; 5464 for (int user : users) { 5465 int resInner = mInstaller.remove(packageName, user); 5466 if (resInner < 0) { 5467 res = resInner; 5468 } 5469 } 5470 5471 return res; 5472 } 5473 5474 private int deleteCodeCacheDirsLI(String packageName) { 5475 int[] users = sUserManager.getUserIds(); 5476 int res = 0; 5477 for (int user : users) { 5478 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5479 if (resInner < 0) { 5480 res = resInner; 5481 } 5482 } 5483 return res; 5484 } 5485 5486 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5487 PackageParser.Package changingLib) { 5488 if (file.path != null) { 5489 usesLibraryFiles.add(file.path); 5490 return; 5491 } 5492 PackageParser.Package p = mPackages.get(file.apk); 5493 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5494 // If we are doing this while in the middle of updating a library apk, 5495 // then we need to make sure to use that new apk for determining the 5496 // dependencies here. (We haven't yet finished committing the new apk 5497 // to the package manager state.) 5498 if (p == null || p.packageName.equals(changingLib.packageName)) { 5499 p = changingLib; 5500 } 5501 } 5502 if (p != null) { 5503 usesLibraryFiles.addAll(p.getAllCodePaths()); 5504 } 5505 } 5506 5507 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5508 PackageParser.Package changingLib) throws PackageManagerException { 5509 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5510 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5511 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5512 for (int i=0; i<N; i++) { 5513 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5514 if (file == null) { 5515 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5516 "Package " + pkg.packageName + " requires unavailable shared library " 5517 + pkg.usesLibraries.get(i) + "; failing!"); 5518 } 5519 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5520 } 5521 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5522 for (int i=0; i<N; i++) { 5523 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5524 if (file == null) { 5525 Slog.w(TAG, "Package " + pkg.packageName 5526 + " desires unavailable shared library " 5527 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5528 } else { 5529 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5530 } 5531 } 5532 N = usesLibraryFiles.size(); 5533 if (N > 0) { 5534 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5535 } else { 5536 pkg.usesLibraryFiles = null; 5537 } 5538 } 5539 } 5540 5541 private static boolean hasString(List<String> list, List<String> which) { 5542 if (list == null) { 5543 return false; 5544 } 5545 for (int i=list.size()-1; i>=0; i--) { 5546 for (int j=which.size()-1; j>=0; j--) { 5547 if (which.get(j).equals(list.get(i))) { 5548 return true; 5549 } 5550 } 5551 } 5552 return false; 5553 } 5554 5555 private void updateAllSharedLibrariesLPw() { 5556 for (PackageParser.Package pkg : mPackages.values()) { 5557 try { 5558 updateSharedLibrariesLPw(pkg, null); 5559 } catch (PackageManagerException e) { 5560 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5561 } 5562 } 5563 } 5564 5565 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5566 PackageParser.Package changingPkg) { 5567 ArrayList<PackageParser.Package> res = null; 5568 for (PackageParser.Package pkg : mPackages.values()) { 5569 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5570 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5571 if (res == null) { 5572 res = new ArrayList<PackageParser.Package>(); 5573 } 5574 res.add(pkg); 5575 try { 5576 updateSharedLibrariesLPw(pkg, changingPkg); 5577 } catch (PackageManagerException e) { 5578 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5579 } 5580 } 5581 } 5582 return res; 5583 } 5584 5585 /** 5586 * Derive the value of the {@code cpuAbiOverride} based on the provided 5587 * value and an optional stored value from the package settings. 5588 */ 5589 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5590 String cpuAbiOverride = null; 5591 5592 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5593 cpuAbiOverride = null; 5594 } else if (abiOverride != null) { 5595 cpuAbiOverride = abiOverride; 5596 } else if (settings != null) { 5597 cpuAbiOverride = settings.cpuAbiOverrideString; 5598 } 5599 5600 return cpuAbiOverride; 5601 } 5602 5603 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5604 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5605 boolean success = false; 5606 try { 5607 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5608 currentTime, user); 5609 success = true; 5610 return res; 5611 } finally { 5612 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5613 removeDataDirsLI(pkg.packageName); 5614 } 5615 } 5616 } 5617 5618 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5619 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5620 final File scanFile = new File(pkg.codePath); 5621 if (pkg.applicationInfo.getCodePath() == null || 5622 pkg.applicationInfo.getResourcePath() == null) { 5623 // Bail out. The resource and code paths haven't been set. 5624 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5625 "Code and resource paths haven't been set correctly"); 5626 } 5627 5628 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5629 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5630 } else { 5631 // Only allow system apps to be flagged as core apps. 5632 pkg.coreApp = false; 5633 } 5634 5635 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5636 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5637 } 5638 5639 if (mCustomResolverComponentName != null && 5640 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5641 setUpCustomResolverActivity(pkg); 5642 } 5643 5644 if (pkg.packageName.equals("android")) { 5645 synchronized (mPackages) { 5646 if (mAndroidApplication != null) { 5647 Slog.w(TAG, "*************************************************"); 5648 Slog.w(TAG, "Core android package being redefined. Skipping."); 5649 Slog.w(TAG, " file=" + scanFile); 5650 Slog.w(TAG, "*************************************************"); 5651 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5652 "Core android package being redefined. Skipping."); 5653 } 5654 5655 // Set up information for our fall-back user intent resolution activity. 5656 mPlatformPackage = pkg; 5657 pkg.mVersionCode = mSdkVersion; 5658 mAndroidApplication = pkg.applicationInfo; 5659 5660 if (!mResolverReplaced) { 5661 mResolveActivity.applicationInfo = mAndroidApplication; 5662 mResolveActivity.name = ResolverActivity.class.getName(); 5663 mResolveActivity.packageName = mAndroidApplication.packageName; 5664 mResolveActivity.processName = "system:ui"; 5665 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5666 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5667 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5668 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5669 mResolveActivity.exported = true; 5670 mResolveActivity.enabled = true; 5671 mResolveInfo.activityInfo = mResolveActivity; 5672 mResolveInfo.priority = 0; 5673 mResolveInfo.preferredOrder = 0; 5674 mResolveInfo.match = 0; 5675 mResolveComponentName = new ComponentName( 5676 mAndroidApplication.packageName, mResolveActivity.name); 5677 } 5678 } 5679 } 5680 5681 if (DEBUG_PACKAGE_SCANNING) { 5682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5683 Log.d(TAG, "Scanning package " + pkg.packageName); 5684 } 5685 5686 if (mPackages.containsKey(pkg.packageName) 5687 || mSharedLibraries.containsKey(pkg.packageName)) { 5688 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5689 "Application package " + pkg.packageName 5690 + " already installed. Skipping duplicate."); 5691 } 5692 5693 // If we're only installing presumed-existing packages, require that the 5694 // scanned APK is both already known and at the path previously established 5695 // for it. Previously unknown packages we pick up normally, but if we have an 5696 // a priori expectation about this package's install presence, enforce it. 5697 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5698 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5699 if (known != null) { 5700 if (DEBUG_PACKAGE_SCANNING) { 5701 Log.d(TAG, "Examining " + pkg.codePath 5702 + " and requiring known paths " + known.codePathString 5703 + " & " + known.resourcePathString); 5704 } 5705 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5706 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5707 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5708 "Application package " + pkg.packageName 5709 + " found at " + pkg.applicationInfo.getCodePath() 5710 + " but expected at " + known.codePathString + "; ignoring."); 5711 } 5712 } 5713 } 5714 5715 // Initialize package source and resource directories 5716 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5717 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5718 5719 SharedUserSetting suid = null; 5720 PackageSetting pkgSetting = null; 5721 5722 if (!isSystemApp(pkg)) { 5723 // Only system apps can use these features. 5724 pkg.mOriginalPackages = null; 5725 pkg.mRealPackage = null; 5726 pkg.mAdoptPermissions = null; 5727 } 5728 5729 // writer 5730 synchronized (mPackages) { 5731 if (pkg.mSharedUserId != null) { 5732 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5733 if (suid == null) { 5734 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5735 "Creating application package " + pkg.packageName 5736 + " for shared user failed"); 5737 } 5738 if (DEBUG_PACKAGE_SCANNING) { 5739 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5740 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5741 + "): packages=" + suid.packages); 5742 } 5743 } 5744 5745 // Check if we are renaming from an original package name. 5746 PackageSetting origPackage = null; 5747 String realName = null; 5748 if (pkg.mOriginalPackages != null) { 5749 // This package may need to be renamed to a previously 5750 // installed name. Let's check on that... 5751 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5752 if (pkg.mOriginalPackages.contains(renamed)) { 5753 // This package had originally been installed as the 5754 // original name, and we have already taken care of 5755 // transitioning to the new one. Just update the new 5756 // one to continue using the old name. 5757 realName = pkg.mRealPackage; 5758 if (!pkg.packageName.equals(renamed)) { 5759 // Callers into this function may have already taken 5760 // care of renaming the package; only do it here if 5761 // it is not already done. 5762 pkg.setPackageName(renamed); 5763 } 5764 5765 } else { 5766 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5767 if ((origPackage = mSettings.peekPackageLPr( 5768 pkg.mOriginalPackages.get(i))) != null) { 5769 // We do have the package already installed under its 5770 // original name... should we use it? 5771 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5772 // New package is not compatible with original. 5773 origPackage = null; 5774 continue; 5775 } else if (origPackage.sharedUser != null) { 5776 // Make sure uid is compatible between packages. 5777 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5778 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5779 + " to " + pkg.packageName + ": old uid " 5780 + origPackage.sharedUser.name 5781 + " differs from " + pkg.mSharedUserId); 5782 origPackage = null; 5783 continue; 5784 } 5785 } else { 5786 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5787 + pkg.packageName + " to old name " + origPackage.name); 5788 } 5789 break; 5790 } 5791 } 5792 } 5793 } 5794 5795 if (mTransferedPackages.contains(pkg.packageName)) { 5796 Slog.w(TAG, "Package " + pkg.packageName 5797 + " was transferred to another, but its .apk remains"); 5798 } 5799 5800 // Just create the setting, don't add it yet. For already existing packages 5801 // the PkgSetting exists already and doesn't have to be created. 5802 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5803 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5804 pkg.applicationInfo.primaryCpuAbi, 5805 pkg.applicationInfo.secondaryCpuAbi, 5806 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5807 user, false); 5808 if (pkgSetting == null) { 5809 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5810 "Creating application package " + pkg.packageName + " failed"); 5811 } 5812 5813 if (pkgSetting.origPackage != null) { 5814 // If we are first transitioning from an original package, 5815 // fix up the new package's name now. We need to do this after 5816 // looking up the package under its new name, so getPackageLP 5817 // can take care of fiddling things correctly. 5818 pkg.setPackageName(origPackage.name); 5819 5820 // File a report about this. 5821 String msg = "New package " + pkgSetting.realName 5822 + " renamed to replace old package " + pkgSetting.name; 5823 reportSettingsProblem(Log.WARN, msg); 5824 5825 // Make a note of it. 5826 mTransferedPackages.add(origPackage.name); 5827 5828 // No longer need to retain this. 5829 pkgSetting.origPackage = null; 5830 } 5831 5832 if (realName != null) { 5833 // Make a note of it. 5834 mTransferedPackages.add(pkg.packageName); 5835 } 5836 5837 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5839 } 5840 5841 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5842 // Check all shared libraries and map to their actual file path. 5843 // We only do this here for apps not on a system dir, because those 5844 // are the only ones that can fail an install due to this. We 5845 // will take care of the system apps by updating all of their 5846 // library paths after the scan is done. 5847 updateSharedLibrariesLPw(pkg, null); 5848 } 5849 5850 if (mFoundPolicyFile) { 5851 SELinuxMMAC.assignSeinfoValue(pkg); 5852 } 5853 5854 pkg.applicationInfo.uid = pkgSetting.appId; 5855 pkg.mExtras = pkgSetting; 5856 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5857 try { 5858 verifySignaturesLP(pkgSetting, pkg); 5859 // We just determined the app is signed correctly, so bring 5860 // over the latest parsed certs. 5861 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5862 } catch (PackageManagerException e) { 5863 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5864 throw e; 5865 } 5866 // The signature has changed, but this package is in the system 5867 // image... let's recover! 5868 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5869 // However... if this package is part of a shared user, but it 5870 // doesn't match the signature of the shared user, let's fail. 5871 // What this means is that you can't change the signatures 5872 // associated with an overall shared user, which doesn't seem all 5873 // that unreasonable. 5874 if (pkgSetting.sharedUser != null) { 5875 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5876 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5877 throw new PackageManagerException( 5878 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5879 "Signature mismatch for shared user : " 5880 + pkgSetting.sharedUser); 5881 } 5882 } 5883 // File a report about this. 5884 String msg = "System package " + pkg.packageName 5885 + " signature changed; retaining data."; 5886 reportSettingsProblem(Log.WARN, msg); 5887 } 5888 } else { 5889 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5890 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5891 + pkg.packageName + " upgrade keys do not match the " 5892 + "previously installed version"); 5893 } else { 5894 // We just determined the app is signed correctly, so bring 5895 // over the latest parsed certs. 5896 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5897 } 5898 } 5899 // Verify that this new package doesn't have any content providers 5900 // that conflict with existing packages. Only do this if the 5901 // package isn't already installed, since we don't want to break 5902 // things that are installed. 5903 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5904 final int N = pkg.providers.size(); 5905 int i; 5906 for (i=0; i<N; i++) { 5907 PackageParser.Provider p = pkg.providers.get(i); 5908 if (p.info.authority != null) { 5909 String names[] = p.info.authority.split(";"); 5910 for (int j = 0; j < names.length; j++) { 5911 if (mProvidersByAuthority.containsKey(names[j])) { 5912 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5913 final String otherPackageName = 5914 ((other != null && other.getComponentName() != null) ? 5915 other.getComponentName().getPackageName() : "?"); 5916 throw new PackageManagerException( 5917 INSTALL_FAILED_CONFLICTING_PROVIDER, 5918 "Can't install because provider name " + names[j] 5919 + " (in package " + pkg.applicationInfo.packageName 5920 + ") is already used by " + otherPackageName); 5921 } 5922 } 5923 } 5924 } 5925 } 5926 5927 if (pkg.mAdoptPermissions != null) { 5928 // This package wants to adopt ownership of permissions from 5929 // another package. 5930 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5931 final String origName = pkg.mAdoptPermissions.get(i); 5932 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5933 if (orig != null) { 5934 if (verifyPackageUpdateLPr(orig, pkg)) { 5935 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5936 + pkg.packageName); 5937 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5938 } 5939 } 5940 } 5941 } 5942 } 5943 5944 final String pkgName = pkg.packageName; 5945 5946 final long scanFileTime = scanFile.lastModified(); 5947 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5948 pkg.applicationInfo.processName = fixProcessName( 5949 pkg.applicationInfo.packageName, 5950 pkg.applicationInfo.processName, 5951 pkg.applicationInfo.uid); 5952 5953 File dataPath; 5954 if (mPlatformPackage == pkg) { 5955 // The system package is special. 5956 dataPath = new File(Environment.getDataDirectory(), "system"); 5957 5958 pkg.applicationInfo.dataDir = dataPath.getPath(); 5959 5960 } else { 5961 // This is a normal package, need to make its data directory. 5962 dataPath = getDataPathForPackage(pkg.packageName, 0); 5963 5964 boolean uidError = false; 5965 if (dataPath.exists()) { 5966 int currentUid = 0; 5967 try { 5968 StructStat stat = Os.stat(dataPath.getPath()); 5969 currentUid = stat.st_uid; 5970 } catch (ErrnoException e) { 5971 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5972 } 5973 5974 // If we have mismatched owners for the data path, we have a problem. 5975 if (currentUid != pkg.applicationInfo.uid) { 5976 boolean recovered = false; 5977 if (currentUid == 0) { 5978 // The directory somehow became owned by root. Wow. 5979 // This is probably because the system was stopped while 5980 // installd was in the middle of messing with its libs 5981 // directory. Ask installd to fix that. 5982 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5983 pkg.applicationInfo.uid); 5984 if (ret >= 0) { 5985 recovered = true; 5986 String msg = "Package " + pkg.packageName 5987 + " unexpectedly changed to uid 0; recovered to " + 5988 + pkg.applicationInfo.uid; 5989 reportSettingsProblem(Log.WARN, msg); 5990 } 5991 } 5992 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5993 || (scanFlags&SCAN_BOOTING) != 0)) { 5994 // If this is a system app, we can at least delete its 5995 // current data so the application will still work. 5996 int ret = removeDataDirsLI(pkgName); 5997 if (ret >= 0) { 5998 // TODO: Kill the processes first 5999 // Old data gone! 6000 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6001 ? "System package " : "Third party package "; 6002 String msg = prefix + pkg.packageName 6003 + " has changed from uid: " 6004 + currentUid + " to " 6005 + pkg.applicationInfo.uid + "; old data erased"; 6006 reportSettingsProblem(Log.WARN, msg); 6007 recovered = true; 6008 6009 // And now re-install the app. 6010 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6011 pkg.applicationInfo.seinfo); 6012 if (ret == -1) { 6013 // Ack should not happen! 6014 msg = prefix + pkg.packageName 6015 + " could not have data directory re-created after delete."; 6016 reportSettingsProblem(Log.WARN, msg); 6017 throw new PackageManagerException( 6018 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6019 } 6020 } 6021 if (!recovered) { 6022 mHasSystemUidErrors = true; 6023 } 6024 } else if (!recovered) { 6025 // If we allow this install to proceed, we will be broken. 6026 // Abort, abort! 6027 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6028 "scanPackageLI"); 6029 } 6030 if (!recovered) { 6031 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6032 + pkg.applicationInfo.uid + "/fs_" 6033 + currentUid; 6034 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6035 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6036 String msg = "Package " + pkg.packageName 6037 + " has mismatched uid: " 6038 + currentUid + " on disk, " 6039 + pkg.applicationInfo.uid + " in settings"; 6040 // writer 6041 synchronized (mPackages) { 6042 mSettings.mReadMessages.append(msg); 6043 mSettings.mReadMessages.append('\n'); 6044 uidError = true; 6045 if (!pkgSetting.uidError) { 6046 reportSettingsProblem(Log.ERROR, msg); 6047 } 6048 } 6049 } 6050 } 6051 pkg.applicationInfo.dataDir = dataPath.getPath(); 6052 if (mShouldRestoreconData) { 6053 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6054 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6055 pkg.applicationInfo.uid); 6056 } 6057 } else { 6058 if (DEBUG_PACKAGE_SCANNING) { 6059 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6060 Log.v(TAG, "Want this data dir: " + dataPath); 6061 } 6062 //invoke installer to do the actual installation 6063 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6064 pkg.applicationInfo.seinfo); 6065 if (ret < 0) { 6066 // Error from installer 6067 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6068 "Unable to create data dirs [errorCode=" + ret + "]"); 6069 } 6070 6071 if (dataPath.exists()) { 6072 pkg.applicationInfo.dataDir = dataPath.getPath(); 6073 } else { 6074 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6075 pkg.applicationInfo.dataDir = null; 6076 } 6077 } 6078 6079 pkgSetting.uidError = uidError; 6080 } 6081 6082 final String path = scanFile.getPath(); 6083 final String codePath = pkg.applicationInfo.getCodePath(); 6084 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6085 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6086 setBundledAppAbisAndRoots(pkg, pkgSetting); 6087 6088 // If we haven't found any native libraries for the app, check if it has 6089 // renderscript code. We'll need to force the app to 32 bit if it has 6090 // renderscript bitcode. 6091 if (pkg.applicationInfo.primaryCpuAbi == null 6092 && pkg.applicationInfo.secondaryCpuAbi == null 6093 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6094 NativeLibraryHelper.Handle handle = null; 6095 try { 6096 handle = NativeLibraryHelper.Handle.create(scanFile); 6097 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6098 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6099 } 6100 } catch (IOException ioe) { 6101 Slog.w(TAG, "Error scanning system app : " + ioe); 6102 } finally { 6103 IoUtils.closeQuietly(handle); 6104 } 6105 } 6106 6107 setNativeLibraryPaths(pkg); 6108 } else { 6109 // TODO: We can probably be smarter about this stuff. For installed apps, 6110 // we can calculate this information at install time once and for all. For 6111 // system apps, we can probably assume that this information doesn't change 6112 // after the first boot scan. As things stand, we do lots of unnecessary work. 6113 6114 // Give ourselves some initial paths; we'll come back for another 6115 // pass once we've determined ABI below. 6116 setNativeLibraryPaths(pkg); 6117 6118 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6119 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6120 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6121 6122 NativeLibraryHelper.Handle handle = null; 6123 try { 6124 handle = NativeLibraryHelper.Handle.create(scanFile); 6125 // TODO(multiArch): This can be null for apps that didn't go through the 6126 // usual installation process. We can calculate it again, like we 6127 // do during install time. 6128 // 6129 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6130 // unnecessary. 6131 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6132 6133 // Null out the abis so that they can be recalculated. 6134 pkg.applicationInfo.primaryCpuAbi = null; 6135 pkg.applicationInfo.secondaryCpuAbi = null; 6136 if (isMultiArch(pkg.applicationInfo)) { 6137 // Warn if we've set an abiOverride for multi-lib packages.. 6138 // By definition, we need to copy both 32 and 64 bit libraries for 6139 // such packages. 6140 if (pkg.cpuAbiOverride != null 6141 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6142 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6143 } 6144 6145 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6146 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6147 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6148 if (isAsec) { 6149 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6150 } else { 6151 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6152 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6153 useIsaSpecificSubdirs); 6154 } 6155 } 6156 6157 maybeThrowExceptionForMultiArchCopy( 6158 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6159 6160 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6161 if (isAsec) { 6162 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6163 } else { 6164 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6165 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6166 useIsaSpecificSubdirs); 6167 } 6168 } 6169 6170 maybeThrowExceptionForMultiArchCopy( 6171 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6172 6173 if (abi64 >= 0) { 6174 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6175 } 6176 6177 if (abi32 >= 0) { 6178 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6179 if (abi64 >= 0) { 6180 pkg.applicationInfo.secondaryCpuAbi = abi; 6181 } else { 6182 pkg.applicationInfo.primaryCpuAbi = abi; 6183 } 6184 } 6185 } else { 6186 String[] abiList = (cpuAbiOverride != null) ? 6187 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6188 6189 // Enable gross and lame hacks for apps that are built with old 6190 // SDK tools. We must scan their APKs for renderscript bitcode and 6191 // not launch them if it's present. Don't bother checking on devices 6192 // that don't have 64 bit support. 6193 boolean needsRenderScriptOverride = false; 6194 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6195 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6196 abiList = Build.SUPPORTED_32_BIT_ABIS; 6197 needsRenderScriptOverride = true; 6198 } 6199 6200 final int copyRet; 6201 if (isAsec) { 6202 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6203 } else { 6204 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6205 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6206 } 6207 6208 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6209 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6210 "Error unpackaging native libs for app, errorCode=" + copyRet); 6211 } 6212 6213 if (copyRet >= 0) { 6214 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6215 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6216 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6217 } else if (needsRenderScriptOverride) { 6218 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6219 } 6220 } 6221 } catch (IOException ioe) { 6222 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6223 } finally { 6224 IoUtils.closeQuietly(handle); 6225 } 6226 6227 // Now that we've calculated the ABIs and determined if it's an internal app, 6228 // we will go ahead and populate the nativeLibraryPath. 6229 setNativeLibraryPaths(pkg); 6230 6231 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6232 final int[] userIds = sUserManager.getUserIds(); 6233 synchronized (mInstallLock) { 6234 // Create a native library symlink only if we have native libraries 6235 // and if the native libraries are 32 bit libraries. We do not provide 6236 // this symlink for 64 bit libraries. 6237 if (pkg.applicationInfo.primaryCpuAbi != null && 6238 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6239 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6240 for (int userId : userIds) { 6241 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6242 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6243 "Failed linking native library dir (user=" + userId + ")"); 6244 } 6245 } 6246 } 6247 } 6248 } 6249 6250 // This is a special case for the "system" package, where the ABI is 6251 // dictated by the zygote configuration (and init.rc). We should keep track 6252 // of this ABI so that we can deal with "normal" applications that run under 6253 // the same UID correctly. 6254 if (mPlatformPackage == pkg) { 6255 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6256 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6257 } 6258 6259 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6260 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6261 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6262 // Copy the derived override back to the parsed package, so that we can 6263 // update the package settings accordingly. 6264 pkg.cpuAbiOverride = cpuAbiOverride; 6265 6266 if (DEBUG_ABI_SELECTION) { 6267 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6268 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6269 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6270 } 6271 6272 // Push the derived path down into PackageSettings so we know what to 6273 // clean up at uninstall time. 6274 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6275 6276 if (DEBUG_ABI_SELECTION) { 6277 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6278 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6279 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6280 } 6281 6282 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6283 // We don't do this here during boot because we can do it all 6284 // at once after scanning all existing packages. 6285 // 6286 // We also do this *before* we perform dexopt on this package, so that 6287 // we can avoid redundant dexopts, and also to make sure we've got the 6288 // code and package path correct. 6289 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6290 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6291 } 6292 6293 if ((scanFlags & SCAN_NO_DEX) == 0) { 6294 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6295 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6296 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6297 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6298 } 6299 } 6300 if (mFactoryTest && pkg.requestedPermissions.contains( 6301 android.Manifest.permission.FACTORY_TEST)) { 6302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6303 } 6304 6305 ArrayList<PackageParser.Package> clientLibPkgs = null; 6306 6307 // writer 6308 synchronized (mPackages) { 6309 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6310 // Only system apps can add new shared libraries. 6311 if (pkg.libraryNames != null) { 6312 for (int i=0; i<pkg.libraryNames.size(); i++) { 6313 String name = pkg.libraryNames.get(i); 6314 boolean allowed = false; 6315 if (pkg.isUpdatedSystemApp()) { 6316 // New library entries can only be added through the 6317 // system image. This is important to get rid of a lot 6318 // of nasty edge cases: for example if we allowed a non- 6319 // system update of the app to add a library, then uninstalling 6320 // the update would make the library go away, and assumptions 6321 // we made such as through app install filtering would now 6322 // have allowed apps on the device which aren't compatible 6323 // with it. Better to just have the restriction here, be 6324 // conservative, and create many fewer cases that can negatively 6325 // impact the user experience. 6326 final PackageSetting sysPs = mSettings 6327 .getDisabledSystemPkgLPr(pkg.packageName); 6328 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6329 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6330 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6331 allowed = true; 6332 allowed = true; 6333 break; 6334 } 6335 } 6336 } 6337 } else { 6338 allowed = true; 6339 } 6340 if (allowed) { 6341 if (!mSharedLibraries.containsKey(name)) { 6342 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6343 } else if (!name.equals(pkg.packageName)) { 6344 Slog.w(TAG, "Package " + pkg.packageName + " library " 6345 + name + " already exists; skipping"); 6346 } 6347 } else { 6348 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6349 + name + " that is not declared on system image; skipping"); 6350 } 6351 } 6352 if ((scanFlags&SCAN_BOOTING) == 0) { 6353 // If we are not booting, we need to update any applications 6354 // that are clients of our shared library. If we are booting, 6355 // this will all be done once the scan is complete. 6356 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6357 } 6358 } 6359 } 6360 } 6361 6362 // We also need to dexopt any apps that are dependent on this library. Note that 6363 // if these fail, we should abort the install since installing the library will 6364 // result in some apps being broken. 6365 if (clientLibPkgs != null) { 6366 if ((scanFlags & SCAN_NO_DEX) == 0) { 6367 for (int i = 0; i < clientLibPkgs.size(); i++) { 6368 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6369 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6370 null /* instruction sets */, forceDex, 6371 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6372 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6373 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6374 "scanPackageLI failed to dexopt clientLibPkgs"); 6375 } 6376 } 6377 } 6378 } 6379 6380 // Request the ActivityManager to kill the process(only for existing packages) 6381 // so that we do not end up in a confused state while the user is still using the older 6382 // version of the application while the new one gets installed. 6383 if ((scanFlags & SCAN_REPLACING) != 0) { 6384 killApplication(pkg.applicationInfo.packageName, 6385 pkg.applicationInfo.uid, "update pkg"); 6386 } 6387 6388 // Also need to kill any apps that are dependent on the library. 6389 if (clientLibPkgs != null) { 6390 for (int i=0; i<clientLibPkgs.size(); i++) { 6391 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6392 killApplication(clientPkg.applicationInfo.packageName, 6393 clientPkg.applicationInfo.uid, "update lib"); 6394 } 6395 } 6396 6397 // writer 6398 synchronized (mPackages) { 6399 // We don't expect installation to fail beyond this point 6400 6401 // Add the new setting to mSettings 6402 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6403 // Add the new setting to mPackages 6404 mPackages.put(pkg.applicationInfo.packageName, pkg); 6405 // Make sure we don't accidentally delete its data. 6406 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6407 while (iter.hasNext()) { 6408 PackageCleanItem item = iter.next(); 6409 if (pkgName.equals(item.packageName)) { 6410 iter.remove(); 6411 } 6412 } 6413 6414 // Take care of first install / last update times. 6415 if (currentTime != 0) { 6416 if (pkgSetting.firstInstallTime == 0) { 6417 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6418 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6419 pkgSetting.lastUpdateTime = currentTime; 6420 } 6421 } else if (pkgSetting.firstInstallTime == 0) { 6422 // We need *something*. Take time time stamp of the file. 6423 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6424 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6425 if (scanFileTime != pkgSetting.timeStamp) { 6426 // A package on the system image has changed; consider this 6427 // to be an update. 6428 pkgSetting.lastUpdateTime = scanFileTime; 6429 } 6430 } 6431 6432 // Add the package's KeySets to the global KeySetManagerService 6433 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6434 try { 6435 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6436 if (pkg.mKeySetMapping != null) { 6437 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6438 if (pkg.mUpgradeKeySets != null) { 6439 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6440 } 6441 } 6442 } catch (NullPointerException e) { 6443 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6444 } catch (IllegalArgumentException e) { 6445 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6446 } 6447 6448 int N = pkg.providers.size(); 6449 StringBuilder r = null; 6450 int i; 6451 for (i=0; i<N; i++) { 6452 PackageParser.Provider p = pkg.providers.get(i); 6453 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6454 p.info.processName, pkg.applicationInfo.uid); 6455 mProviders.addProvider(p); 6456 p.syncable = p.info.isSyncable; 6457 if (p.info.authority != null) { 6458 String names[] = p.info.authority.split(";"); 6459 p.info.authority = null; 6460 for (int j = 0; j < names.length; j++) { 6461 if (j == 1 && p.syncable) { 6462 // We only want the first authority for a provider to possibly be 6463 // syncable, so if we already added this provider using a different 6464 // authority clear the syncable flag. We copy the provider before 6465 // changing it because the mProviders object contains a reference 6466 // to a provider that we don't want to change. 6467 // Only do this for the second authority since the resulting provider 6468 // object can be the same for all future authorities for this provider. 6469 p = new PackageParser.Provider(p); 6470 p.syncable = false; 6471 } 6472 if (!mProvidersByAuthority.containsKey(names[j])) { 6473 mProvidersByAuthority.put(names[j], p); 6474 if (p.info.authority == null) { 6475 p.info.authority = names[j]; 6476 } else { 6477 p.info.authority = p.info.authority + ";" + names[j]; 6478 } 6479 if (DEBUG_PACKAGE_SCANNING) { 6480 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6481 Log.d(TAG, "Registered content provider: " + names[j] 6482 + ", className = " + p.info.name + ", isSyncable = " 6483 + p.info.isSyncable); 6484 } 6485 } else { 6486 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6487 Slog.w(TAG, "Skipping provider name " + names[j] + 6488 " (in package " + pkg.applicationInfo.packageName + 6489 "): name already used by " 6490 + ((other != null && other.getComponentName() != null) 6491 ? other.getComponentName().getPackageName() : "?")); 6492 } 6493 } 6494 } 6495 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6496 if (r == null) { 6497 r = new StringBuilder(256); 6498 } else { 6499 r.append(' '); 6500 } 6501 r.append(p.info.name); 6502 } 6503 } 6504 if (r != null) { 6505 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6506 } 6507 6508 N = pkg.services.size(); 6509 r = null; 6510 for (i=0; i<N; i++) { 6511 PackageParser.Service s = pkg.services.get(i); 6512 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6513 s.info.processName, pkg.applicationInfo.uid); 6514 mServices.addService(s); 6515 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6516 if (r == null) { 6517 r = new StringBuilder(256); 6518 } else { 6519 r.append(' '); 6520 } 6521 r.append(s.info.name); 6522 } 6523 } 6524 if (r != null) { 6525 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6526 } 6527 6528 N = pkg.receivers.size(); 6529 r = null; 6530 for (i=0; i<N; i++) { 6531 PackageParser.Activity a = pkg.receivers.get(i); 6532 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6533 a.info.processName, pkg.applicationInfo.uid); 6534 mReceivers.addActivity(a, "receiver"); 6535 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6536 if (r == null) { 6537 r = new StringBuilder(256); 6538 } else { 6539 r.append(' '); 6540 } 6541 r.append(a.info.name); 6542 } 6543 } 6544 if (r != null) { 6545 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6546 } 6547 6548 N = pkg.activities.size(); 6549 r = null; 6550 for (i=0; i<N; i++) { 6551 PackageParser.Activity a = pkg.activities.get(i); 6552 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6553 a.info.processName, pkg.applicationInfo.uid); 6554 mActivities.addActivity(a, "activity"); 6555 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6556 if (r == null) { 6557 r = new StringBuilder(256); 6558 } else { 6559 r.append(' '); 6560 } 6561 r.append(a.info.name); 6562 } 6563 } 6564 if (r != null) { 6565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6566 } 6567 6568 N = pkg.permissionGroups.size(); 6569 r = null; 6570 for (i=0; i<N; i++) { 6571 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6572 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6573 if (cur == null) { 6574 mPermissionGroups.put(pg.info.name, pg); 6575 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6576 if (r == null) { 6577 r = new StringBuilder(256); 6578 } else { 6579 r.append(' '); 6580 } 6581 r.append(pg.info.name); 6582 } 6583 } else { 6584 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6585 + pg.info.packageName + " ignored: original from " 6586 + cur.info.packageName); 6587 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6588 if (r == null) { 6589 r = new StringBuilder(256); 6590 } else { 6591 r.append(' '); 6592 } 6593 r.append("DUP:"); 6594 r.append(pg.info.name); 6595 } 6596 } 6597 } 6598 if (r != null) { 6599 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6600 } 6601 6602 N = pkg.permissions.size(); 6603 r = null; 6604 for (i=0; i<N; i++) { 6605 PackageParser.Permission p = pkg.permissions.get(i); 6606 ArrayMap<String, BasePermission> permissionMap = 6607 p.tree ? mSettings.mPermissionTrees 6608 : mSettings.mPermissions; 6609 p.group = mPermissionGroups.get(p.info.group); 6610 if (p.info.group == null || p.group != null) { 6611 BasePermission bp = permissionMap.get(p.info.name); 6612 6613 // Allow system apps to redefine non-system permissions 6614 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6615 final boolean currentOwnerIsSystem = (bp.perm != null 6616 && isSystemApp(bp.perm.owner)); 6617 if (isSystemApp(p.owner)) { 6618 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6619 // It's a built-in permission and no owner, take ownership now 6620 bp.packageSetting = pkgSetting; 6621 bp.perm = p; 6622 bp.uid = pkg.applicationInfo.uid; 6623 bp.sourcePackage = p.info.packageName; 6624 } else if (!currentOwnerIsSystem) { 6625 String msg = "New decl " + p.owner + " of permission " 6626 + p.info.name + " is system; overriding " + bp.sourcePackage; 6627 reportSettingsProblem(Log.WARN, msg); 6628 bp = null; 6629 } 6630 } 6631 } 6632 6633 if (bp == null) { 6634 bp = new BasePermission(p.info.name, p.info.packageName, 6635 BasePermission.TYPE_NORMAL); 6636 permissionMap.put(p.info.name, bp); 6637 } 6638 6639 if (bp.perm == null) { 6640 if (bp.sourcePackage == null 6641 || bp.sourcePackage.equals(p.info.packageName)) { 6642 BasePermission tree = findPermissionTreeLP(p.info.name); 6643 if (tree == null 6644 || tree.sourcePackage.equals(p.info.packageName)) { 6645 bp.packageSetting = pkgSetting; 6646 bp.perm = p; 6647 bp.uid = pkg.applicationInfo.uid; 6648 bp.sourcePackage = p.info.packageName; 6649 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6650 if (r == null) { 6651 r = new StringBuilder(256); 6652 } else { 6653 r.append(' '); 6654 } 6655 r.append(p.info.name); 6656 } 6657 } else { 6658 Slog.w(TAG, "Permission " + p.info.name + " from package " 6659 + p.info.packageName + " ignored: base tree " 6660 + tree.name + " is from package " 6661 + tree.sourcePackage); 6662 } 6663 } else { 6664 Slog.w(TAG, "Permission " + p.info.name + " from package " 6665 + p.info.packageName + " ignored: original from " 6666 + bp.sourcePackage); 6667 } 6668 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6669 if (r == null) { 6670 r = new StringBuilder(256); 6671 } else { 6672 r.append(' '); 6673 } 6674 r.append("DUP:"); 6675 r.append(p.info.name); 6676 } 6677 if (bp.perm == p) { 6678 bp.protectionLevel = p.info.protectionLevel; 6679 } 6680 } else { 6681 Slog.w(TAG, "Permission " + p.info.name + " from package " 6682 + p.info.packageName + " ignored: no group " 6683 + p.group); 6684 } 6685 } 6686 if (r != null) { 6687 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6688 } 6689 6690 N = pkg.instrumentation.size(); 6691 r = null; 6692 for (i=0; i<N; i++) { 6693 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6694 a.info.packageName = pkg.applicationInfo.packageName; 6695 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6696 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6697 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6698 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6699 a.info.dataDir = pkg.applicationInfo.dataDir; 6700 6701 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6702 // need other information about the application, like the ABI and what not ? 6703 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6704 mInstrumentation.put(a.getComponentName(), a); 6705 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6706 if (r == null) { 6707 r = new StringBuilder(256); 6708 } else { 6709 r.append(' '); 6710 } 6711 r.append(a.info.name); 6712 } 6713 } 6714 if (r != null) { 6715 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6716 } 6717 6718 if (pkg.protectedBroadcasts != null) { 6719 N = pkg.protectedBroadcasts.size(); 6720 for (i=0; i<N; i++) { 6721 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6722 } 6723 } 6724 6725 pkgSetting.setTimeStamp(scanFileTime); 6726 6727 // Create idmap files for pairs of (packages, overlay packages). 6728 // Note: "android", ie framework-res.apk, is handled by native layers. 6729 if (pkg.mOverlayTarget != null) { 6730 // This is an overlay package. 6731 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6732 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6733 mOverlays.put(pkg.mOverlayTarget, 6734 new ArrayMap<String, PackageParser.Package>()); 6735 } 6736 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6737 map.put(pkg.packageName, pkg); 6738 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6739 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6740 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6741 "scanPackageLI failed to createIdmap"); 6742 } 6743 } 6744 } else if (mOverlays.containsKey(pkg.packageName) && 6745 !pkg.packageName.equals("android")) { 6746 // This is a regular package, with one or more known overlay packages. 6747 createIdmapsForPackageLI(pkg); 6748 } 6749 } 6750 6751 return pkg; 6752 } 6753 6754 /** 6755 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6756 * i.e, so that all packages can be run inside a single process if required. 6757 * 6758 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6759 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6760 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6761 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6762 * updating a package that belongs to a shared user. 6763 * 6764 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6765 * adds unnecessary complexity. 6766 */ 6767 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6768 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6769 String requiredInstructionSet = null; 6770 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6771 requiredInstructionSet = VMRuntime.getInstructionSet( 6772 scannedPackage.applicationInfo.primaryCpuAbi); 6773 } 6774 6775 PackageSetting requirer = null; 6776 for (PackageSetting ps : packagesForUser) { 6777 // If packagesForUser contains scannedPackage, we skip it. This will happen 6778 // when scannedPackage is an update of an existing package. Without this check, 6779 // we will never be able to change the ABI of any package belonging to a shared 6780 // user, even if it's compatible with other packages. 6781 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6782 if (ps.primaryCpuAbiString == null) { 6783 continue; 6784 } 6785 6786 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6787 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6788 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6789 // this but there's not much we can do. 6790 String errorMessage = "Instruction set mismatch, " 6791 + ((requirer == null) ? "[caller]" : requirer) 6792 + " requires " + requiredInstructionSet + " whereas " + ps 6793 + " requires " + instructionSet; 6794 Slog.w(TAG, errorMessage); 6795 } 6796 6797 if (requiredInstructionSet == null) { 6798 requiredInstructionSet = instructionSet; 6799 requirer = ps; 6800 } 6801 } 6802 } 6803 6804 if (requiredInstructionSet != null) { 6805 String adjustedAbi; 6806 if (requirer != null) { 6807 // requirer != null implies that either scannedPackage was null or that scannedPackage 6808 // did not require an ABI, in which case we have to adjust scannedPackage to match 6809 // the ABI of the set (which is the same as requirer's ABI) 6810 adjustedAbi = requirer.primaryCpuAbiString; 6811 if (scannedPackage != null) { 6812 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6813 } 6814 } else { 6815 // requirer == null implies that we're updating all ABIs in the set to 6816 // match scannedPackage. 6817 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6818 } 6819 6820 for (PackageSetting ps : packagesForUser) { 6821 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6822 if (ps.primaryCpuAbiString != null) { 6823 continue; 6824 } 6825 6826 ps.primaryCpuAbiString = adjustedAbi; 6827 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6828 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6829 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6830 6831 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6832 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6833 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6834 ps.primaryCpuAbiString = null; 6835 ps.pkg.applicationInfo.primaryCpuAbi = null; 6836 return; 6837 } else { 6838 mInstaller.rmdex(ps.codePathString, 6839 getDexCodeInstructionSet(getPreferredInstructionSet())); 6840 } 6841 } 6842 } 6843 } 6844 } 6845 } 6846 6847 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6848 synchronized (mPackages) { 6849 mResolverReplaced = true; 6850 // Set up information for custom user intent resolution activity. 6851 mResolveActivity.applicationInfo = pkg.applicationInfo; 6852 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6853 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6854 mResolveActivity.processName = pkg.applicationInfo.packageName; 6855 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6856 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6857 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6858 mResolveActivity.theme = 0; 6859 mResolveActivity.exported = true; 6860 mResolveActivity.enabled = true; 6861 mResolveInfo.activityInfo = mResolveActivity; 6862 mResolveInfo.priority = 0; 6863 mResolveInfo.preferredOrder = 0; 6864 mResolveInfo.match = 0; 6865 mResolveComponentName = mCustomResolverComponentName; 6866 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6867 mResolveComponentName); 6868 } 6869 } 6870 6871 private static String calculateBundledApkRoot(final String codePathString) { 6872 final File codePath = new File(codePathString); 6873 final File codeRoot; 6874 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6875 codeRoot = Environment.getRootDirectory(); 6876 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6877 codeRoot = Environment.getOemDirectory(); 6878 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6879 codeRoot = Environment.getVendorDirectory(); 6880 } else { 6881 // Unrecognized code path; take its top real segment as the apk root: 6882 // e.g. /something/app/blah.apk => /something 6883 try { 6884 File f = codePath.getCanonicalFile(); 6885 File parent = f.getParentFile(); // non-null because codePath is a file 6886 File tmp; 6887 while ((tmp = parent.getParentFile()) != null) { 6888 f = parent; 6889 parent = tmp; 6890 } 6891 codeRoot = f; 6892 Slog.w(TAG, "Unrecognized code path " 6893 + codePath + " - using " + codeRoot); 6894 } catch (IOException e) { 6895 // Can't canonicalize the code path -- shenanigans? 6896 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6897 return Environment.getRootDirectory().getPath(); 6898 } 6899 } 6900 return codeRoot.getPath(); 6901 } 6902 6903 /** 6904 * Derive and set the location of native libraries for the given package, 6905 * which varies depending on where and how the package was installed. 6906 */ 6907 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6908 final ApplicationInfo info = pkg.applicationInfo; 6909 final String codePath = pkg.codePath; 6910 final File codeFile = new File(codePath); 6911 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6912 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6913 6914 info.nativeLibraryRootDir = null; 6915 info.nativeLibraryRootRequiresIsa = false; 6916 info.nativeLibraryDir = null; 6917 info.secondaryNativeLibraryDir = null; 6918 6919 if (isApkFile(codeFile)) { 6920 // Monolithic install 6921 if (bundledApp) { 6922 // If "/system/lib64/apkname" exists, assume that is the per-package 6923 // native library directory to use; otherwise use "/system/lib/apkname". 6924 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6925 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6926 getPrimaryInstructionSet(info)); 6927 6928 // This is a bundled system app so choose the path based on the ABI. 6929 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6930 // is just the default path. 6931 final String apkName = deriveCodePathName(codePath); 6932 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6933 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6934 apkName).getAbsolutePath(); 6935 6936 if (info.secondaryCpuAbi != null) { 6937 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6938 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6939 secondaryLibDir, apkName).getAbsolutePath(); 6940 } 6941 } else if (asecApp) { 6942 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6943 .getAbsolutePath(); 6944 } else { 6945 final String apkName = deriveCodePathName(codePath); 6946 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6947 .getAbsolutePath(); 6948 } 6949 6950 info.nativeLibraryRootRequiresIsa = false; 6951 info.nativeLibraryDir = info.nativeLibraryRootDir; 6952 } else { 6953 // Cluster install 6954 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6955 info.nativeLibraryRootRequiresIsa = true; 6956 6957 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6958 getPrimaryInstructionSet(info)).getAbsolutePath(); 6959 6960 if (info.secondaryCpuAbi != null) { 6961 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6962 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6963 } 6964 } 6965 } 6966 6967 /** 6968 * Calculate the abis and roots for a bundled app. These can uniquely 6969 * be determined from the contents of the system partition, i.e whether 6970 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6971 * of this information, and instead assume that the system was built 6972 * sensibly. 6973 */ 6974 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6975 PackageSetting pkgSetting) { 6976 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6977 6978 // If "/system/lib64/apkname" exists, assume that is the per-package 6979 // native library directory to use; otherwise use "/system/lib/apkname". 6980 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6981 setBundledAppAbi(pkg, apkRoot, apkName); 6982 // pkgSetting might be null during rescan following uninstall of updates 6983 // to a bundled app, so accommodate that possibility. The settings in 6984 // that case will be established later from the parsed package. 6985 // 6986 // If the settings aren't null, sync them up with what we've just derived. 6987 // note that apkRoot isn't stored in the package settings. 6988 if (pkgSetting != null) { 6989 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6990 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6991 } 6992 } 6993 6994 /** 6995 * Deduces the ABI of a bundled app and sets the relevant fields on the 6996 * parsed pkg object. 6997 * 6998 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6999 * under which system libraries are installed. 7000 * @param apkName the name of the installed package. 7001 */ 7002 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7003 final File codeFile = new File(pkg.codePath); 7004 7005 final boolean has64BitLibs; 7006 final boolean has32BitLibs; 7007 if (isApkFile(codeFile)) { 7008 // Monolithic install 7009 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7010 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7011 } else { 7012 // Cluster install 7013 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7014 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7015 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7016 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7017 has64BitLibs = (new File(rootDir, isa)).exists(); 7018 } else { 7019 has64BitLibs = false; 7020 } 7021 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7022 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7023 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7024 has32BitLibs = (new File(rootDir, isa)).exists(); 7025 } else { 7026 has32BitLibs = false; 7027 } 7028 } 7029 7030 if (has64BitLibs && !has32BitLibs) { 7031 // The package has 64 bit libs, but not 32 bit libs. Its primary 7032 // ABI should be 64 bit. We can safely assume here that the bundled 7033 // native libraries correspond to the most preferred ABI in the list. 7034 7035 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7036 pkg.applicationInfo.secondaryCpuAbi = null; 7037 } else if (has32BitLibs && !has64BitLibs) { 7038 // The package has 32 bit libs but not 64 bit libs. Its primary 7039 // ABI should be 32 bit. 7040 7041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7042 pkg.applicationInfo.secondaryCpuAbi = null; 7043 } else if (has32BitLibs && has64BitLibs) { 7044 // The application has both 64 and 32 bit bundled libraries. We check 7045 // here that the app declares multiArch support, and warn if it doesn't. 7046 // 7047 // We will be lenient here and record both ABIs. The primary will be the 7048 // ABI that's higher on the list, i.e, a device that's configured to prefer 7049 // 64 bit apps will see a 64 bit primary ABI, 7050 7051 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7052 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7053 } 7054 7055 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7056 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7057 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7058 } else { 7059 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7060 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7061 } 7062 } else { 7063 pkg.applicationInfo.primaryCpuAbi = null; 7064 pkg.applicationInfo.secondaryCpuAbi = null; 7065 } 7066 } 7067 7068 private void killApplication(String pkgName, int appId, String reason) { 7069 // Request the ActivityManager to kill the process(only for existing packages) 7070 // so that we do not end up in a confused state while the user is still using the older 7071 // version of the application while the new one gets installed. 7072 IActivityManager am = ActivityManagerNative.getDefault(); 7073 if (am != null) { 7074 try { 7075 am.killApplicationWithAppId(pkgName, appId, reason); 7076 } catch (RemoteException e) { 7077 } 7078 } 7079 } 7080 7081 void removePackageLI(PackageSetting ps, boolean chatty) { 7082 if (DEBUG_INSTALL) { 7083 if (chatty) 7084 Log.d(TAG, "Removing package " + ps.name); 7085 } 7086 7087 // writer 7088 synchronized (mPackages) { 7089 mPackages.remove(ps.name); 7090 final PackageParser.Package pkg = ps.pkg; 7091 if (pkg != null) { 7092 cleanPackageDataStructuresLILPw(pkg, chatty); 7093 } 7094 } 7095 } 7096 7097 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7098 if (DEBUG_INSTALL) { 7099 if (chatty) 7100 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7101 } 7102 7103 // writer 7104 synchronized (mPackages) { 7105 mPackages.remove(pkg.applicationInfo.packageName); 7106 cleanPackageDataStructuresLILPw(pkg, chatty); 7107 } 7108 } 7109 7110 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7111 int N = pkg.providers.size(); 7112 StringBuilder r = null; 7113 int i; 7114 for (i=0; i<N; i++) { 7115 PackageParser.Provider p = pkg.providers.get(i); 7116 mProviders.removeProvider(p); 7117 if (p.info.authority == null) { 7118 7119 /* There was another ContentProvider with this authority when 7120 * this app was installed so this authority is null, 7121 * Ignore it as we don't have to unregister the provider. 7122 */ 7123 continue; 7124 } 7125 String names[] = p.info.authority.split(";"); 7126 for (int j = 0; j < names.length; j++) { 7127 if (mProvidersByAuthority.get(names[j]) == p) { 7128 mProvidersByAuthority.remove(names[j]); 7129 if (DEBUG_REMOVE) { 7130 if (chatty) 7131 Log.d(TAG, "Unregistered content provider: " + names[j] 7132 + ", className = " + p.info.name + ", isSyncable = " 7133 + p.info.isSyncable); 7134 } 7135 } 7136 } 7137 if (DEBUG_REMOVE && chatty) { 7138 if (r == null) { 7139 r = new StringBuilder(256); 7140 } else { 7141 r.append(' '); 7142 } 7143 r.append(p.info.name); 7144 } 7145 } 7146 if (r != null) { 7147 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7148 } 7149 7150 N = pkg.services.size(); 7151 r = null; 7152 for (i=0; i<N; i++) { 7153 PackageParser.Service s = pkg.services.get(i); 7154 mServices.removeService(s); 7155 if (chatty) { 7156 if (r == null) { 7157 r = new StringBuilder(256); 7158 } else { 7159 r.append(' '); 7160 } 7161 r.append(s.info.name); 7162 } 7163 } 7164 if (r != null) { 7165 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7166 } 7167 7168 N = pkg.receivers.size(); 7169 r = null; 7170 for (i=0; i<N; i++) { 7171 PackageParser.Activity a = pkg.receivers.get(i); 7172 mReceivers.removeActivity(a, "receiver"); 7173 if (DEBUG_REMOVE && chatty) { 7174 if (r == null) { 7175 r = new StringBuilder(256); 7176 } else { 7177 r.append(' '); 7178 } 7179 r.append(a.info.name); 7180 } 7181 } 7182 if (r != null) { 7183 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7184 } 7185 7186 N = pkg.activities.size(); 7187 r = null; 7188 for (i=0; i<N; i++) { 7189 PackageParser.Activity a = pkg.activities.get(i); 7190 mActivities.removeActivity(a, "activity"); 7191 if (DEBUG_REMOVE && chatty) { 7192 if (r == null) { 7193 r = new StringBuilder(256); 7194 } else { 7195 r.append(' '); 7196 } 7197 r.append(a.info.name); 7198 } 7199 } 7200 if (r != null) { 7201 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7202 } 7203 7204 N = pkg.permissions.size(); 7205 r = null; 7206 for (i=0; i<N; i++) { 7207 PackageParser.Permission p = pkg.permissions.get(i); 7208 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7209 if (bp == null) { 7210 bp = mSettings.mPermissionTrees.get(p.info.name); 7211 } 7212 if (bp != null && bp.perm == p) { 7213 bp.perm = null; 7214 if (DEBUG_REMOVE && chatty) { 7215 if (r == null) { 7216 r = new StringBuilder(256); 7217 } else { 7218 r.append(' '); 7219 } 7220 r.append(p.info.name); 7221 } 7222 } 7223 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7224 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7225 if (appOpPerms != null) { 7226 appOpPerms.remove(pkg.packageName); 7227 } 7228 } 7229 } 7230 if (r != null) { 7231 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7232 } 7233 7234 N = pkg.requestedPermissions.size(); 7235 r = null; 7236 for (i=0; i<N; i++) { 7237 String perm = pkg.requestedPermissions.get(i); 7238 BasePermission bp = mSettings.mPermissions.get(perm); 7239 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7240 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7241 if (appOpPerms != null) { 7242 appOpPerms.remove(pkg.packageName); 7243 if (appOpPerms.isEmpty()) { 7244 mAppOpPermissionPackages.remove(perm); 7245 } 7246 } 7247 } 7248 } 7249 if (r != null) { 7250 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7251 } 7252 7253 N = pkg.instrumentation.size(); 7254 r = null; 7255 for (i=0; i<N; i++) { 7256 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7257 mInstrumentation.remove(a.getComponentName()); 7258 if (DEBUG_REMOVE && chatty) { 7259 if (r == null) { 7260 r = new StringBuilder(256); 7261 } else { 7262 r.append(' '); 7263 } 7264 r.append(a.info.name); 7265 } 7266 } 7267 if (r != null) { 7268 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7269 } 7270 7271 r = null; 7272 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7273 // Only system apps can hold shared libraries. 7274 if (pkg.libraryNames != null) { 7275 for (i=0; i<pkg.libraryNames.size(); i++) { 7276 String name = pkg.libraryNames.get(i); 7277 SharedLibraryEntry cur = mSharedLibraries.get(name); 7278 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7279 mSharedLibraries.remove(name); 7280 if (DEBUG_REMOVE && chatty) { 7281 if (r == null) { 7282 r = new StringBuilder(256); 7283 } else { 7284 r.append(' '); 7285 } 7286 r.append(name); 7287 } 7288 } 7289 } 7290 } 7291 } 7292 if (r != null) { 7293 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7294 } 7295 } 7296 7297 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7298 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7299 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7300 return true; 7301 } 7302 } 7303 return false; 7304 } 7305 7306 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7307 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7308 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7309 7310 private void updatePermissionsLPw(String changingPkg, 7311 PackageParser.Package pkgInfo, int flags) { 7312 // Make sure there are no dangling permission trees. 7313 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7314 while (it.hasNext()) { 7315 final BasePermission bp = it.next(); 7316 if (bp.packageSetting == null) { 7317 // We may not yet have parsed the package, so just see if 7318 // we still know about its settings. 7319 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7320 } 7321 if (bp.packageSetting == null) { 7322 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7323 + " from package " + bp.sourcePackage); 7324 it.remove(); 7325 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7326 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7327 Slog.i(TAG, "Removing old permission tree: " + bp.name 7328 + " from package " + bp.sourcePackage); 7329 flags |= UPDATE_PERMISSIONS_ALL; 7330 it.remove(); 7331 } 7332 } 7333 } 7334 7335 // Make sure all dynamic permissions have been assigned to a package, 7336 // and make sure there are no dangling permissions. 7337 it = mSettings.mPermissions.values().iterator(); 7338 while (it.hasNext()) { 7339 final BasePermission bp = it.next(); 7340 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7341 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7342 + bp.name + " pkg=" + bp.sourcePackage 7343 + " info=" + bp.pendingInfo); 7344 if (bp.packageSetting == null && bp.pendingInfo != null) { 7345 final BasePermission tree = findPermissionTreeLP(bp.name); 7346 if (tree != null && tree.perm != null) { 7347 bp.packageSetting = tree.packageSetting; 7348 bp.perm = new PackageParser.Permission(tree.perm.owner, 7349 new PermissionInfo(bp.pendingInfo)); 7350 bp.perm.info.packageName = tree.perm.info.packageName; 7351 bp.perm.info.name = bp.name; 7352 bp.uid = tree.uid; 7353 } 7354 } 7355 } 7356 if (bp.packageSetting == null) { 7357 // We may not yet have parsed the package, so just see if 7358 // we still know about its settings. 7359 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7360 } 7361 if (bp.packageSetting == null) { 7362 Slog.w(TAG, "Removing dangling permission: " + bp.name 7363 + " from package " + bp.sourcePackage); 7364 it.remove(); 7365 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7366 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7367 Slog.i(TAG, "Removing old permission: " + bp.name 7368 + " from package " + bp.sourcePackage); 7369 flags |= UPDATE_PERMISSIONS_ALL; 7370 it.remove(); 7371 } 7372 } 7373 } 7374 7375 // Now update the permissions for all packages, in particular 7376 // replace the granted permissions of the system packages. 7377 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7378 for (PackageParser.Package pkg : mPackages.values()) { 7379 if (pkg != pkgInfo) { 7380 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7381 changingPkg); 7382 } 7383 } 7384 } 7385 7386 if (pkgInfo != null) { 7387 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7388 } 7389 } 7390 7391 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7392 String packageOfInterest) { 7393 // IMPORTANT: There are two types of permissions: install and runtime. 7394 // Install time permissions are granted when the app is installed to 7395 // all device users and users added in the future. Runtime permissions 7396 // are granted at runtime explicitly to specific users. Normal and signature 7397 // protected permissions are install time permissions. Dangerous permissions 7398 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7399 // otherwise they are runtime permissions. This function does not manage 7400 // runtime permissions except for the case an app targeting Lollipop MR1 7401 // being upgraded to target a newer SDK, in which case dangerous permissions 7402 // are transformed from install time to runtime ones. 7403 7404 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7405 if (ps == null) { 7406 return; 7407 } 7408 7409 PermissionsState permissionsState = ps.getPermissionsState(); 7410 PermissionsState origPermissions = permissionsState; 7411 7412 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7413 7414 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7415 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7416 7417 boolean changedInstallPermission = false; 7418 7419 if (replace) { 7420 ps.installPermissionsFixed = false; 7421 if (!ps.isSharedUser()) { 7422 origPermissions = new PermissionsState(permissionsState); 7423 permissionsState.reset(); 7424 } 7425 } 7426 7427 permissionsState.setGlobalGids(mGlobalGids); 7428 7429 final int N = pkg.requestedPermissions.size(); 7430 for (int i=0; i<N; i++) { 7431 final String name = pkg.requestedPermissions.get(i); 7432 final BasePermission bp = mSettings.mPermissions.get(name); 7433 7434 if (DEBUG_INSTALL) { 7435 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7436 } 7437 7438 if (bp == null || bp.packageSetting == null) { 7439 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7440 Slog.w(TAG, "Unknown permission " + name 7441 + " in package " + pkg.packageName); 7442 } 7443 continue; 7444 } 7445 7446 final String perm = bp.name; 7447 boolean allowedSig = false; 7448 int grant = GRANT_DENIED; 7449 7450 // Keep track of app op permissions. 7451 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7452 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7453 if (pkgs == null) { 7454 pkgs = new ArraySet<>(); 7455 mAppOpPermissionPackages.put(bp.name, pkgs); 7456 } 7457 pkgs.add(pkg.packageName); 7458 } 7459 7460 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7461 switch (level) { 7462 case PermissionInfo.PROTECTION_NORMAL: { 7463 // For all apps normal permissions are install time ones. 7464 grant = GRANT_INSTALL; 7465 } break; 7466 7467 case PermissionInfo.PROTECTION_DANGEROUS: { 7468 if (!RUNTIME_PERMISSIONS_ENABLED 7469 || pkg.applicationInfo.targetSdkVersion 7470 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7471 // For legacy apps dangerous permissions are install time ones. 7472 grant = GRANT_INSTALL; 7473 } else if (ps.isSystem()) { 7474 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7475 if (origPermissions.hasInstallPermission(bp.name)) { 7476 // If a system app had an install permission, then the app was 7477 // upgraded and we grant the permissions as runtime to all users. 7478 grant = GRANT_UPGRADE; 7479 upgradeUserIds = currentUserIds; 7480 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7481 // If users changed since the last permissions update for a 7482 // system app, we grant the permission as runtime to the new users. 7483 grant = GRANT_UPGRADE; 7484 upgradeUserIds = currentUserIds; 7485 for (int userId : updatedUserIds) { 7486 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7487 } 7488 } else { 7489 // Otherwise, we grant the permission as runtime if the app 7490 // already had it, i.e. we preserve runtime permissions. 7491 grant = GRANT_RUNTIME; 7492 } 7493 } else if (origPermissions.hasInstallPermission(bp.name)) { 7494 // For legacy apps that became modern, install becomes runtime. 7495 grant = GRANT_UPGRADE; 7496 upgradeUserIds = currentUserIds; 7497 } else if (replace) { 7498 // For upgraded modern apps keep runtime permissions unchanged. 7499 grant = GRANT_RUNTIME; 7500 } 7501 } break; 7502 7503 case PermissionInfo.PROTECTION_SIGNATURE: { 7504 // For all apps signature permissions are install time ones. 7505 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7506 if (allowedSig) { 7507 grant = GRANT_INSTALL; 7508 } 7509 } break; 7510 } 7511 7512 if (DEBUG_INSTALL) { 7513 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7514 } 7515 7516 if (grant != GRANT_DENIED) { 7517 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7518 // If this is an existing, non-system package, then 7519 // we can't add any new permissions to it. 7520 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7521 // Except... if this is a permission that was added 7522 // to the platform (note: need to only do this when 7523 // updating the platform). 7524 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7525 grant = GRANT_DENIED; 7526 } 7527 } 7528 } 7529 7530 switch (grant) { 7531 case GRANT_INSTALL: { 7532 // Grant an install permission. 7533 if (permissionsState.grantInstallPermission(bp) != 7534 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7535 changedInstallPermission = true; 7536 } 7537 } break; 7538 7539 case GRANT_RUNTIME: { 7540 // Grant previously granted runtime permissions. 7541 for (int userId : UserManagerService.getInstance().getUserIds()) { 7542 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7543 if (permissionsState.grantRuntimePermission(bp, userId) == 7544 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7545 // If we cannot put the permission as it was, we have to write. 7546 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7547 changedRuntimePermissionUserIds, userId); 7548 } 7549 } 7550 } 7551 } break; 7552 7553 case GRANT_UPGRADE: { 7554 // Grant runtime permissions for a previously held install permission. 7555 permissionsState.revokeInstallPermission(bp); 7556 for (int userId : upgradeUserIds) { 7557 if (permissionsState.grantRuntimePermission(bp, userId) != 7558 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7559 // If we granted the permission, we have to write. 7560 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7561 changedRuntimePermissionUserIds, userId); 7562 } 7563 } 7564 } break; 7565 7566 default: { 7567 if (packageOfInterest == null 7568 || packageOfInterest.equals(pkg.packageName)) { 7569 Slog.w(TAG, "Not granting permission " + perm 7570 + " to package " + pkg.packageName 7571 + " because it was previously installed without"); 7572 } 7573 } break; 7574 } 7575 } else { 7576 if (permissionsState.revokeInstallPermission(bp) != 7577 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7578 changedInstallPermission = true; 7579 Slog.i(TAG, "Un-granting permission " + perm 7580 + " from package " + pkg.packageName 7581 + " (protectionLevel=" + bp.protectionLevel 7582 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7583 + ")"); 7584 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7585 // Don't print warning for app op permissions, since it is fine for them 7586 // not to be granted, there is a UI for the user to decide. 7587 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7588 Slog.w(TAG, "Not granting permission " + perm 7589 + " to package " + pkg.packageName 7590 + " (protectionLevel=" + bp.protectionLevel 7591 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7592 + ")"); 7593 } 7594 } 7595 } 7596 } 7597 7598 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7599 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7600 // This is the first that we have heard about this package, so the 7601 // permissions we have now selected are fixed until explicitly 7602 // changed. 7603 ps.installPermissionsFixed = true; 7604 } 7605 7606 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7607 7608 // Persist the runtime permissions state for users with changes. 7609 if (RUNTIME_PERMISSIONS_ENABLED) { 7610 for (int userId : changedRuntimePermissionUserIds) { 7611 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7612 } 7613 } 7614 } 7615 7616 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7617 boolean allowed = false; 7618 final int NP = PackageParser.NEW_PERMISSIONS.length; 7619 for (int ip=0; ip<NP; ip++) { 7620 final PackageParser.NewPermissionInfo npi 7621 = PackageParser.NEW_PERMISSIONS[ip]; 7622 if (npi.name.equals(perm) 7623 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7624 allowed = true; 7625 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7626 + pkg.packageName); 7627 break; 7628 } 7629 } 7630 return allowed; 7631 } 7632 7633 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7634 BasePermission bp, PermissionsState origPermissions) { 7635 boolean allowed; 7636 allowed = (compareSignatures( 7637 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7638 == PackageManager.SIGNATURE_MATCH) 7639 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7640 == PackageManager.SIGNATURE_MATCH); 7641 if (!allowed && (bp.protectionLevel 7642 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7643 if (isSystemApp(pkg)) { 7644 // For updated system applications, a system permission 7645 // is granted only if it had been defined by the original application. 7646 if (pkg.isUpdatedSystemApp()) { 7647 final PackageSetting sysPs = mSettings 7648 .getDisabledSystemPkgLPr(pkg.packageName); 7649 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7650 // If the original was granted this permission, we take 7651 // that grant decision as read and propagate it to the 7652 // update. 7653 if (sysPs.isPrivileged()) { 7654 allowed = true; 7655 } 7656 } else { 7657 // The system apk may have been updated with an older 7658 // version of the one on the data partition, but which 7659 // granted a new system permission that it didn't have 7660 // before. In this case we do want to allow the app to 7661 // now get the new permission if the ancestral apk is 7662 // privileged to get it. 7663 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7664 for (int j=0; 7665 j<sysPs.pkg.requestedPermissions.size(); j++) { 7666 if (perm.equals( 7667 sysPs.pkg.requestedPermissions.get(j))) { 7668 allowed = true; 7669 break; 7670 } 7671 } 7672 } 7673 } 7674 } else { 7675 allowed = isPrivilegedApp(pkg); 7676 } 7677 } 7678 } 7679 if (!allowed && (bp.protectionLevel 7680 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7681 // For development permissions, a development permission 7682 // is granted only if it was already granted. 7683 allowed = origPermissions.hasInstallPermission(perm); 7684 } 7685 return allowed; 7686 } 7687 7688 final class ActivityIntentResolver 7689 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7690 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7691 boolean defaultOnly, int userId) { 7692 if (!sUserManager.exists(userId)) return null; 7693 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7694 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7695 } 7696 7697 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7698 int userId) { 7699 if (!sUserManager.exists(userId)) return null; 7700 mFlags = flags; 7701 return super.queryIntent(intent, resolvedType, 7702 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7703 } 7704 7705 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7706 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7707 if (!sUserManager.exists(userId)) return null; 7708 if (packageActivities == null) { 7709 return null; 7710 } 7711 mFlags = flags; 7712 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7713 final int N = packageActivities.size(); 7714 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7715 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7716 7717 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7718 for (int i = 0; i < N; ++i) { 7719 intentFilters = packageActivities.get(i).intents; 7720 if (intentFilters != null && intentFilters.size() > 0) { 7721 PackageParser.ActivityIntentInfo[] array = 7722 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7723 intentFilters.toArray(array); 7724 listCut.add(array); 7725 } 7726 } 7727 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7728 } 7729 7730 public final void addActivity(PackageParser.Activity a, String type) { 7731 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7732 mActivities.put(a.getComponentName(), a); 7733 if (DEBUG_SHOW_INFO) 7734 Log.v( 7735 TAG, " " + type + " " + 7736 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7737 if (DEBUG_SHOW_INFO) 7738 Log.v(TAG, " Class=" + a.info.name); 7739 final int NI = a.intents.size(); 7740 for (int j=0; j<NI; j++) { 7741 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7742 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7743 intent.setPriority(0); 7744 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7745 + a.className + " with priority > 0, forcing to 0"); 7746 } 7747 if (DEBUG_SHOW_INFO) { 7748 Log.v(TAG, " IntentFilter:"); 7749 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7750 } 7751 if (!intent.debugCheck()) { 7752 Log.w(TAG, "==> For Activity " + a.info.name); 7753 } 7754 addFilter(intent); 7755 } 7756 } 7757 7758 public final void removeActivity(PackageParser.Activity a, String type) { 7759 mActivities.remove(a.getComponentName()); 7760 if (DEBUG_SHOW_INFO) { 7761 Log.v(TAG, " " + type + " " 7762 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7763 : a.info.name) + ":"); 7764 Log.v(TAG, " Class=" + a.info.name); 7765 } 7766 final int NI = a.intents.size(); 7767 for (int j=0; j<NI; j++) { 7768 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7769 if (DEBUG_SHOW_INFO) { 7770 Log.v(TAG, " IntentFilter:"); 7771 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7772 } 7773 removeFilter(intent); 7774 } 7775 } 7776 7777 @Override 7778 protected boolean allowFilterResult( 7779 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7780 ActivityInfo filterAi = filter.activity.info; 7781 for (int i=dest.size()-1; i>=0; i--) { 7782 ActivityInfo destAi = dest.get(i).activityInfo; 7783 if (destAi.name == filterAi.name 7784 && destAi.packageName == filterAi.packageName) { 7785 return false; 7786 } 7787 } 7788 return true; 7789 } 7790 7791 @Override 7792 protected ActivityIntentInfo[] newArray(int size) { 7793 return new ActivityIntentInfo[size]; 7794 } 7795 7796 @Override 7797 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7798 if (!sUserManager.exists(userId)) return true; 7799 PackageParser.Package p = filter.activity.owner; 7800 if (p != null) { 7801 PackageSetting ps = (PackageSetting)p.mExtras; 7802 if (ps != null) { 7803 // System apps are never considered stopped for purposes of 7804 // filtering, because there may be no way for the user to 7805 // actually re-launch them. 7806 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7807 && ps.getStopped(userId); 7808 } 7809 } 7810 return false; 7811 } 7812 7813 @Override 7814 protected boolean isPackageForFilter(String packageName, 7815 PackageParser.ActivityIntentInfo info) { 7816 return packageName.equals(info.activity.owner.packageName); 7817 } 7818 7819 @Override 7820 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7821 int match, int userId) { 7822 if (!sUserManager.exists(userId)) return null; 7823 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7824 return null; 7825 } 7826 final PackageParser.Activity activity = info.activity; 7827 if (mSafeMode && (activity.info.applicationInfo.flags 7828 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7829 return null; 7830 } 7831 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7832 if (ps == null) { 7833 return null; 7834 } 7835 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7836 ps.readUserState(userId), userId); 7837 if (ai == null) { 7838 return null; 7839 } 7840 final ResolveInfo res = new ResolveInfo(); 7841 res.activityInfo = ai; 7842 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7843 res.filter = info; 7844 } 7845 if (info != null) { 7846 res.filterNeedsVerification = info.needsVerification(); 7847 } 7848 res.priority = info.getPriority(); 7849 res.preferredOrder = activity.owner.mPreferredOrder; 7850 //System.out.println("Result: " + res.activityInfo.className + 7851 // " = " + res.priority); 7852 res.match = match; 7853 res.isDefault = info.hasDefault; 7854 res.labelRes = info.labelRes; 7855 res.nonLocalizedLabel = info.nonLocalizedLabel; 7856 if (userNeedsBadging(userId)) { 7857 res.noResourceId = true; 7858 } else { 7859 res.icon = info.icon; 7860 } 7861 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7862 return res; 7863 } 7864 7865 @Override 7866 protected void sortResults(List<ResolveInfo> results) { 7867 Collections.sort(results, mResolvePrioritySorter); 7868 } 7869 7870 @Override 7871 protected void dumpFilter(PrintWriter out, String prefix, 7872 PackageParser.ActivityIntentInfo filter) { 7873 out.print(prefix); out.print( 7874 Integer.toHexString(System.identityHashCode(filter.activity))); 7875 out.print(' '); 7876 filter.activity.printComponentShortName(out); 7877 out.print(" filter "); 7878 out.println(Integer.toHexString(System.identityHashCode(filter))); 7879 } 7880 7881 @Override 7882 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7883 return filter.activity; 7884 } 7885 7886 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7887 PackageParser.Activity activity = (PackageParser.Activity)label; 7888 out.print(prefix); out.print( 7889 Integer.toHexString(System.identityHashCode(activity))); 7890 out.print(' '); 7891 activity.printComponentShortName(out); 7892 if (count > 1) { 7893 out.print(" ("); out.print(count); out.print(" filters)"); 7894 } 7895 out.println(); 7896 } 7897 7898// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7899// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7900// final List<ResolveInfo> retList = Lists.newArrayList(); 7901// while (i.hasNext()) { 7902// final ResolveInfo resolveInfo = i.next(); 7903// if (isEnabledLP(resolveInfo.activityInfo)) { 7904// retList.add(resolveInfo); 7905// } 7906// } 7907// return retList; 7908// } 7909 7910 // Keys are String (activity class name), values are Activity. 7911 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7912 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7913 private int mFlags; 7914 } 7915 7916 private final class ServiceIntentResolver 7917 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7918 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7919 boolean defaultOnly, int userId) { 7920 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7921 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7922 } 7923 7924 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7925 int userId) { 7926 if (!sUserManager.exists(userId)) return null; 7927 mFlags = flags; 7928 return super.queryIntent(intent, resolvedType, 7929 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7930 } 7931 7932 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7933 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7934 if (!sUserManager.exists(userId)) return null; 7935 if (packageServices == null) { 7936 return null; 7937 } 7938 mFlags = flags; 7939 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7940 final int N = packageServices.size(); 7941 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7942 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7943 7944 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7945 for (int i = 0; i < N; ++i) { 7946 intentFilters = packageServices.get(i).intents; 7947 if (intentFilters != null && intentFilters.size() > 0) { 7948 PackageParser.ServiceIntentInfo[] array = 7949 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7950 intentFilters.toArray(array); 7951 listCut.add(array); 7952 } 7953 } 7954 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7955 } 7956 7957 public final void addService(PackageParser.Service s) { 7958 mServices.put(s.getComponentName(), s); 7959 if (DEBUG_SHOW_INFO) { 7960 Log.v(TAG, " " 7961 + (s.info.nonLocalizedLabel != null 7962 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7963 Log.v(TAG, " Class=" + s.info.name); 7964 } 7965 final int NI = s.intents.size(); 7966 int j; 7967 for (j=0; j<NI; j++) { 7968 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7969 if (DEBUG_SHOW_INFO) { 7970 Log.v(TAG, " IntentFilter:"); 7971 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7972 } 7973 if (!intent.debugCheck()) { 7974 Log.w(TAG, "==> For Service " + s.info.name); 7975 } 7976 addFilter(intent); 7977 } 7978 } 7979 7980 public final void removeService(PackageParser.Service s) { 7981 mServices.remove(s.getComponentName()); 7982 if (DEBUG_SHOW_INFO) { 7983 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7984 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7985 Log.v(TAG, " Class=" + s.info.name); 7986 } 7987 final int NI = s.intents.size(); 7988 int j; 7989 for (j=0; j<NI; j++) { 7990 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7991 if (DEBUG_SHOW_INFO) { 7992 Log.v(TAG, " IntentFilter:"); 7993 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7994 } 7995 removeFilter(intent); 7996 } 7997 } 7998 7999 @Override 8000 protected boolean allowFilterResult( 8001 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8002 ServiceInfo filterSi = filter.service.info; 8003 for (int i=dest.size()-1; i>=0; i--) { 8004 ServiceInfo destAi = dest.get(i).serviceInfo; 8005 if (destAi.name == filterSi.name 8006 && destAi.packageName == filterSi.packageName) { 8007 return false; 8008 } 8009 } 8010 return true; 8011 } 8012 8013 @Override 8014 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8015 return new PackageParser.ServiceIntentInfo[size]; 8016 } 8017 8018 @Override 8019 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8020 if (!sUserManager.exists(userId)) return true; 8021 PackageParser.Package p = filter.service.owner; 8022 if (p != null) { 8023 PackageSetting ps = (PackageSetting)p.mExtras; 8024 if (ps != null) { 8025 // System apps are never considered stopped for purposes of 8026 // filtering, because there may be no way for the user to 8027 // actually re-launch them. 8028 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8029 && ps.getStopped(userId); 8030 } 8031 } 8032 return false; 8033 } 8034 8035 @Override 8036 protected boolean isPackageForFilter(String packageName, 8037 PackageParser.ServiceIntentInfo info) { 8038 return packageName.equals(info.service.owner.packageName); 8039 } 8040 8041 @Override 8042 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8043 int match, int userId) { 8044 if (!sUserManager.exists(userId)) return null; 8045 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8046 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8047 return null; 8048 } 8049 final PackageParser.Service service = info.service; 8050 if (mSafeMode && (service.info.applicationInfo.flags 8051 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8052 return null; 8053 } 8054 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8055 if (ps == null) { 8056 return null; 8057 } 8058 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8059 ps.readUserState(userId), userId); 8060 if (si == null) { 8061 return null; 8062 } 8063 final ResolveInfo res = new ResolveInfo(); 8064 res.serviceInfo = si; 8065 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8066 res.filter = filter; 8067 } 8068 res.priority = info.getPriority(); 8069 res.preferredOrder = service.owner.mPreferredOrder; 8070 res.match = match; 8071 res.isDefault = info.hasDefault; 8072 res.labelRes = info.labelRes; 8073 res.nonLocalizedLabel = info.nonLocalizedLabel; 8074 res.icon = info.icon; 8075 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8076 return res; 8077 } 8078 8079 @Override 8080 protected void sortResults(List<ResolveInfo> results) { 8081 Collections.sort(results, mResolvePrioritySorter); 8082 } 8083 8084 @Override 8085 protected void dumpFilter(PrintWriter out, String prefix, 8086 PackageParser.ServiceIntentInfo filter) { 8087 out.print(prefix); out.print( 8088 Integer.toHexString(System.identityHashCode(filter.service))); 8089 out.print(' '); 8090 filter.service.printComponentShortName(out); 8091 out.print(" filter "); 8092 out.println(Integer.toHexString(System.identityHashCode(filter))); 8093 } 8094 8095 @Override 8096 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8097 return filter.service; 8098 } 8099 8100 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8101 PackageParser.Service service = (PackageParser.Service)label; 8102 out.print(prefix); out.print( 8103 Integer.toHexString(System.identityHashCode(service))); 8104 out.print(' '); 8105 service.printComponentShortName(out); 8106 if (count > 1) { 8107 out.print(" ("); out.print(count); out.print(" filters)"); 8108 } 8109 out.println(); 8110 } 8111 8112// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8113// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8114// final List<ResolveInfo> retList = Lists.newArrayList(); 8115// while (i.hasNext()) { 8116// final ResolveInfo resolveInfo = (ResolveInfo) i; 8117// if (isEnabledLP(resolveInfo.serviceInfo)) { 8118// retList.add(resolveInfo); 8119// } 8120// } 8121// return retList; 8122// } 8123 8124 // Keys are String (activity class name), values are Activity. 8125 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8126 = new ArrayMap<ComponentName, PackageParser.Service>(); 8127 private int mFlags; 8128 }; 8129 8130 private final class ProviderIntentResolver 8131 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8133 boolean defaultOnly, int userId) { 8134 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8135 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8136 } 8137 8138 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8139 int userId) { 8140 if (!sUserManager.exists(userId)) 8141 return null; 8142 mFlags = flags; 8143 return super.queryIntent(intent, resolvedType, 8144 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8145 } 8146 8147 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8148 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8149 if (!sUserManager.exists(userId)) 8150 return null; 8151 if (packageProviders == null) { 8152 return null; 8153 } 8154 mFlags = flags; 8155 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8156 final int N = packageProviders.size(); 8157 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8158 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8159 8160 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8161 for (int i = 0; i < N; ++i) { 8162 intentFilters = packageProviders.get(i).intents; 8163 if (intentFilters != null && intentFilters.size() > 0) { 8164 PackageParser.ProviderIntentInfo[] array = 8165 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8166 intentFilters.toArray(array); 8167 listCut.add(array); 8168 } 8169 } 8170 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8171 } 8172 8173 public final void addProvider(PackageParser.Provider p) { 8174 if (mProviders.containsKey(p.getComponentName())) { 8175 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8176 return; 8177 } 8178 8179 mProviders.put(p.getComponentName(), p); 8180 if (DEBUG_SHOW_INFO) { 8181 Log.v(TAG, " " 8182 + (p.info.nonLocalizedLabel != null 8183 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8184 Log.v(TAG, " Class=" + p.info.name); 8185 } 8186 final int NI = p.intents.size(); 8187 int j; 8188 for (j = 0; j < NI; j++) { 8189 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8190 if (DEBUG_SHOW_INFO) { 8191 Log.v(TAG, " IntentFilter:"); 8192 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8193 } 8194 if (!intent.debugCheck()) { 8195 Log.w(TAG, "==> For Provider " + p.info.name); 8196 } 8197 addFilter(intent); 8198 } 8199 } 8200 8201 public final void removeProvider(PackageParser.Provider p) { 8202 mProviders.remove(p.getComponentName()); 8203 if (DEBUG_SHOW_INFO) { 8204 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8205 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8206 Log.v(TAG, " Class=" + p.info.name); 8207 } 8208 final int NI = p.intents.size(); 8209 int j; 8210 for (j = 0; j < NI; j++) { 8211 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8212 if (DEBUG_SHOW_INFO) { 8213 Log.v(TAG, " IntentFilter:"); 8214 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8215 } 8216 removeFilter(intent); 8217 } 8218 } 8219 8220 @Override 8221 protected boolean allowFilterResult( 8222 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8223 ProviderInfo filterPi = filter.provider.info; 8224 for (int i = dest.size() - 1; i >= 0; i--) { 8225 ProviderInfo destPi = dest.get(i).providerInfo; 8226 if (destPi.name == filterPi.name 8227 && destPi.packageName == filterPi.packageName) { 8228 return false; 8229 } 8230 } 8231 return true; 8232 } 8233 8234 @Override 8235 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8236 return new PackageParser.ProviderIntentInfo[size]; 8237 } 8238 8239 @Override 8240 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8241 if (!sUserManager.exists(userId)) 8242 return true; 8243 PackageParser.Package p = filter.provider.owner; 8244 if (p != null) { 8245 PackageSetting ps = (PackageSetting) p.mExtras; 8246 if (ps != null) { 8247 // System apps are never considered stopped for purposes of 8248 // filtering, because there may be no way for the user to 8249 // actually re-launch them. 8250 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8251 && ps.getStopped(userId); 8252 } 8253 } 8254 return false; 8255 } 8256 8257 @Override 8258 protected boolean isPackageForFilter(String packageName, 8259 PackageParser.ProviderIntentInfo info) { 8260 return packageName.equals(info.provider.owner.packageName); 8261 } 8262 8263 @Override 8264 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8265 int match, int userId) { 8266 if (!sUserManager.exists(userId)) 8267 return null; 8268 final PackageParser.ProviderIntentInfo info = filter; 8269 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8270 return null; 8271 } 8272 final PackageParser.Provider provider = info.provider; 8273 if (mSafeMode && (provider.info.applicationInfo.flags 8274 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8275 return null; 8276 } 8277 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8278 if (ps == null) { 8279 return null; 8280 } 8281 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8282 ps.readUserState(userId), userId); 8283 if (pi == null) { 8284 return null; 8285 } 8286 final ResolveInfo res = new ResolveInfo(); 8287 res.providerInfo = pi; 8288 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8289 res.filter = filter; 8290 } 8291 res.priority = info.getPriority(); 8292 res.preferredOrder = provider.owner.mPreferredOrder; 8293 res.match = match; 8294 res.isDefault = info.hasDefault; 8295 res.labelRes = info.labelRes; 8296 res.nonLocalizedLabel = info.nonLocalizedLabel; 8297 res.icon = info.icon; 8298 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8299 return res; 8300 } 8301 8302 @Override 8303 protected void sortResults(List<ResolveInfo> results) { 8304 Collections.sort(results, mResolvePrioritySorter); 8305 } 8306 8307 @Override 8308 protected void dumpFilter(PrintWriter out, String prefix, 8309 PackageParser.ProviderIntentInfo filter) { 8310 out.print(prefix); 8311 out.print( 8312 Integer.toHexString(System.identityHashCode(filter.provider))); 8313 out.print(' '); 8314 filter.provider.printComponentShortName(out); 8315 out.print(" filter "); 8316 out.println(Integer.toHexString(System.identityHashCode(filter))); 8317 } 8318 8319 @Override 8320 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8321 return filter.provider; 8322 } 8323 8324 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8325 PackageParser.Provider provider = (PackageParser.Provider)label; 8326 out.print(prefix); out.print( 8327 Integer.toHexString(System.identityHashCode(provider))); 8328 out.print(' '); 8329 provider.printComponentShortName(out); 8330 if (count > 1) { 8331 out.print(" ("); out.print(count); out.print(" filters)"); 8332 } 8333 out.println(); 8334 } 8335 8336 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8337 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8338 private int mFlags; 8339 }; 8340 8341 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8342 new Comparator<ResolveInfo>() { 8343 public int compare(ResolveInfo r1, ResolveInfo r2) { 8344 int v1 = r1.priority; 8345 int v2 = r2.priority; 8346 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8347 if (v1 != v2) { 8348 return (v1 > v2) ? -1 : 1; 8349 } 8350 v1 = r1.preferredOrder; 8351 v2 = r2.preferredOrder; 8352 if (v1 != v2) { 8353 return (v1 > v2) ? -1 : 1; 8354 } 8355 if (r1.isDefault != r2.isDefault) { 8356 return r1.isDefault ? -1 : 1; 8357 } 8358 v1 = r1.match; 8359 v2 = r2.match; 8360 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8361 if (v1 != v2) { 8362 return (v1 > v2) ? -1 : 1; 8363 } 8364 if (r1.system != r2.system) { 8365 return r1.system ? -1 : 1; 8366 } 8367 return 0; 8368 } 8369 }; 8370 8371 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8372 new Comparator<ProviderInfo>() { 8373 public int compare(ProviderInfo p1, ProviderInfo p2) { 8374 final int v1 = p1.initOrder; 8375 final int v2 = p2.initOrder; 8376 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8377 } 8378 }; 8379 8380 static final void sendPackageBroadcast(String action, String pkg, 8381 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8382 int[] userIds) { 8383 IActivityManager am = ActivityManagerNative.getDefault(); 8384 if (am != null) { 8385 try { 8386 if (userIds == null) { 8387 userIds = am.getRunningUserIds(); 8388 } 8389 for (int id : userIds) { 8390 final Intent intent = new Intent(action, 8391 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8392 if (extras != null) { 8393 intent.putExtras(extras); 8394 } 8395 if (targetPkg != null) { 8396 intent.setPackage(targetPkg); 8397 } 8398 // Modify the UID when posting to other users 8399 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8400 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8401 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8402 intent.putExtra(Intent.EXTRA_UID, uid); 8403 } 8404 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8406 if (DEBUG_BROADCASTS) { 8407 RuntimeException here = new RuntimeException("here"); 8408 here.fillInStackTrace(); 8409 Slog.d(TAG, "Sending to user " + id + ": " 8410 + intent.toShortString(false, true, false, false) 8411 + " " + intent.getExtras(), here); 8412 } 8413 am.broadcastIntent(null, intent, null, finishedReceiver, 8414 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8415 finishedReceiver != null, false, id); 8416 } 8417 } catch (RemoteException ex) { 8418 } 8419 } 8420 } 8421 8422 /** 8423 * Check if the external storage media is available. This is true if there 8424 * is a mounted external storage medium or if the external storage is 8425 * emulated. 8426 */ 8427 private boolean isExternalMediaAvailable() { 8428 return mMediaMounted || Environment.isExternalStorageEmulated(); 8429 } 8430 8431 @Override 8432 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8433 // writer 8434 synchronized (mPackages) { 8435 if (!isExternalMediaAvailable()) { 8436 // If the external storage is no longer mounted at this point, 8437 // the caller may not have been able to delete all of this 8438 // packages files and can not delete any more. Bail. 8439 return null; 8440 } 8441 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8442 if (lastPackage != null) { 8443 pkgs.remove(lastPackage); 8444 } 8445 if (pkgs.size() > 0) { 8446 return pkgs.get(0); 8447 } 8448 } 8449 return null; 8450 } 8451 8452 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8453 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8454 userId, andCode ? 1 : 0, packageName); 8455 if (mSystemReady) { 8456 msg.sendToTarget(); 8457 } else { 8458 if (mPostSystemReadyMessages == null) { 8459 mPostSystemReadyMessages = new ArrayList<>(); 8460 } 8461 mPostSystemReadyMessages.add(msg); 8462 } 8463 } 8464 8465 void startCleaningPackages() { 8466 // reader 8467 synchronized (mPackages) { 8468 if (!isExternalMediaAvailable()) { 8469 return; 8470 } 8471 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8472 return; 8473 } 8474 } 8475 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8476 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8477 IActivityManager am = ActivityManagerNative.getDefault(); 8478 if (am != null) { 8479 try { 8480 am.startService(null, intent, null, UserHandle.USER_OWNER); 8481 } catch (RemoteException e) { 8482 } 8483 } 8484 } 8485 8486 @Override 8487 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8488 int installFlags, String installerPackageName, VerificationParams verificationParams, 8489 String packageAbiOverride) { 8490 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8491 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8492 } 8493 8494 @Override 8495 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8496 int installFlags, String installerPackageName, VerificationParams verificationParams, 8497 String packageAbiOverride, int userId) { 8498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8499 8500 final int callingUid = Binder.getCallingUid(); 8501 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8502 8503 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8504 try { 8505 if (observer != null) { 8506 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8507 } 8508 } catch (RemoteException re) { 8509 } 8510 return; 8511 } 8512 8513 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8514 installFlags |= PackageManager.INSTALL_FROM_ADB; 8515 8516 } else { 8517 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8518 // about installerPackageName. 8519 8520 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8521 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8522 } 8523 8524 UserHandle user; 8525 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8526 user = UserHandle.ALL; 8527 } else { 8528 user = new UserHandle(userId); 8529 } 8530 8531 // Only system components can circumvent runtime permissions when installing. 8532 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8533 && mContext.checkCallingOrSelfPermission(Manifest.permission 8534 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8535 throw new SecurityException("You need the " 8536 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8537 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8538 } 8539 8540 verificationParams.setInstallerUid(callingUid); 8541 8542 final File originFile = new File(originPath); 8543 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8544 8545 final Message msg = mHandler.obtainMessage(INIT_COPY); 8546 msg.obj = new InstallParams(origin, observer, installFlags, 8547 installerPackageName, null, verificationParams, user, packageAbiOverride); 8548 mHandler.sendMessage(msg); 8549 } 8550 8551 void installStage(String packageName, File stagedDir, String stagedCid, 8552 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8553 String installerPackageName, int installerUid, UserHandle user) { 8554 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8555 params.referrerUri, installerUid, null); 8556 8557 final OriginInfo origin; 8558 if (stagedDir != null) { 8559 origin = OriginInfo.fromStagedFile(stagedDir); 8560 } else { 8561 origin = OriginInfo.fromStagedContainer(stagedCid); 8562 } 8563 8564 final Message msg = mHandler.obtainMessage(INIT_COPY); 8565 msg.obj = new InstallParams(origin, observer, params.installFlags, 8566 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8567 mHandler.sendMessage(msg); 8568 } 8569 8570 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8571 Bundle extras = new Bundle(1); 8572 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8573 8574 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8575 packageName, extras, null, null, new int[] {userId}); 8576 try { 8577 IActivityManager am = ActivityManagerNative.getDefault(); 8578 final boolean isSystem = 8579 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8580 if (isSystem && am.isUserRunning(userId, false)) { 8581 // The just-installed/enabled app is bundled on the system, so presumed 8582 // to be able to run automatically without needing an explicit launch. 8583 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8584 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8585 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8586 .setPackage(packageName); 8587 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8588 android.app.AppOpsManager.OP_NONE, false, false, userId); 8589 } 8590 } catch (RemoteException e) { 8591 // shouldn't happen 8592 Slog.w(TAG, "Unable to bootstrap installed package", e); 8593 } 8594 } 8595 8596 @Override 8597 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8598 int userId) { 8599 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8600 PackageSetting pkgSetting; 8601 final int uid = Binder.getCallingUid(); 8602 enforceCrossUserPermission(uid, userId, true, true, 8603 "setApplicationHiddenSetting for user " + userId); 8604 8605 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8606 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8607 return false; 8608 } 8609 8610 long callingId = Binder.clearCallingIdentity(); 8611 try { 8612 boolean sendAdded = false; 8613 boolean sendRemoved = false; 8614 // writer 8615 synchronized (mPackages) { 8616 pkgSetting = mSettings.mPackages.get(packageName); 8617 if (pkgSetting == null) { 8618 return false; 8619 } 8620 if (pkgSetting.getHidden(userId) != hidden) { 8621 pkgSetting.setHidden(hidden, userId); 8622 mSettings.writePackageRestrictionsLPr(userId); 8623 if (hidden) { 8624 sendRemoved = true; 8625 } else { 8626 sendAdded = true; 8627 } 8628 } 8629 } 8630 if (sendAdded) { 8631 sendPackageAddedForUser(packageName, pkgSetting, userId); 8632 return true; 8633 } 8634 if (sendRemoved) { 8635 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8636 "hiding pkg"); 8637 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8638 } 8639 } finally { 8640 Binder.restoreCallingIdentity(callingId); 8641 } 8642 return false; 8643 } 8644 8645 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8646 int userId) { 8647 final PackageRemovedInfo info = new PackageRemovedInfo(); 8648 info.removedPackage = packageName; 8649 info.removedUsers = new int[] {userId}; 8650 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8651 info.sendBroadcast(false, false, false); 8652 } 8653 8654 /** 8655 * Returns true if application is not found or there was an error. Otherwise it returns 8656 * the hidden state of the package for the given user. 8657 */ 8658 @Override 8659 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8661 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8662 false, "getApplicationHidden for user " + userId); 8663 PackageSetting pkgSetting; 8664 long callingId = Binder.clearCallingIdentity(); 8665 try { 8666 // writer 8667 synchronized (mPackages) { 8668 pkgSetting = mSettings.mPackages.get(packageName); 8669 if (pkgSetting == null) { 8670 return true; 8671 } 8672 return pkgSetting.getHidden(userId); 8673 } 8674 } finally { 8675 Binder.restoreCallingIdentity(callingId); 8676 } 8677 } 8678 8679 /** 8680 * @hide 8681 */ 8682 @Override 8683 public int installExistingPackageAsUser(String packageName, int userId) { 8684 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8685 null); 8686 PackageSetting pkgSetting; 8687 final int uid = Binder.getCallingUid(); 8688 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8689 + userId); 8690 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8691 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8692 } 8693 8694 long callingId = Binder.clearCallingIdentity(); 8695 try { 8696 boolean sendAdded = false; 8697 8698 // writer 8699 synchronized (mPackages) { 8700 pkgSetting = mSettings.mPackages.get(packageName); 8701 if (pkgSetting == null) { 8702 return PackageManager.INSTALL_FAILED_INVALID_URI; 8703 } 8704 if (!pkgSetting.getInstalled(userId)) { 8705 pkgSetting.setInstalled(true, userId); 8706 pkgSetting.setHidden(false, userId); 8707 mSettings.writePackageRestrictionsLPr(userId); 8708 sendAdded = true; 8709 } 8710 } 8711 8712 if (sendAdded) { 8713 sendPackageAddedForUser(packageName, pkgSetting, userId); 8714 } 8715 } finally { 8716 Binder.restoreCallingIdentity(callingId); 8717 } 8718 8719 return PackageManager.INSTALL_SUCCEEDED; 8720 } 8721 8722 boolean isUserRestricted(int userId, String restrictionKey) { 8723 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8724 if (restrictions.getBoolean(restrictionKey, false)) { 8725 Log.w(TAG, "User is restricted: " + restrictionKey); 8726 return true; 8727 } 8728 return false; 8729 } 8730 8731 @Override 8732 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8733 mContext.enforceCallingOrSelfPermission( 8734 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8735 "Only package verification agents can verify applications"); 8736 8737 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8738 final PackageVerificationResponse response = new PackageVerificationResponse( 8739 verificationCode, Binder.getCallingUid()); 8740 msg.arg1 = id; 8741 msg.obj = response; 8742 mHandler.sendMessage(msg); 8743 } 8744 8745 @Override 8746 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8747 long millisecondsToDelay) { 8748 mContext.enforceCallingOrSelfPermission( 8749 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8750 "Only package verification agents can extend verification timeouts"); 8751 8752 final PackageVerificationState state = mPendingVerification.get(id); 8753 final PackageVerificationResponse response = new PackageVerificationResponse( 8754 verificationCodeAtTimeout, Binder.getCallingUid()); 8755 8756 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8757 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8758 } 8759 if (millisecondsToDelay < 0) { 8760 millisecondsToDelay = 0; 8761 } 8762 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8763 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8764 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8765 } 8766 8767 if ((state != null) && !state.timeoutExtended()) { 8768 state.extendTimeout(); 8769 8770 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8771 msg.arg1 = id; 8772 msg.obj = response; 8773 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8774 } 8775 } 8776 8777 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8778 int verificationCode, UserHandle user) { 8779 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8780 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8781 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8782 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8783 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8784 8785 mContext.sendBroadcastAsUser(intent, user, 8786 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8787 } 8788 8789 private ComponentName matchComponentForVerifier(String packageName, 8790 List<ResolveInfo> receivers) { 8791 ActivityInfo targetReceiver = null; 8792 8793 final int NR = receivers.size(); 8794 for (int i = 0; i < NR; i++) { 8795 final ResolveInfo info = receivers.get(i); 8796 if (info.activityInfo == null) { 8797 continue; 8798 } 8799 8800 if (packageName.equals(info.activityInfo.packageName)) { 8801 targetReceiver = info.activityInfo; 8802 break; 8803 } 8804 } 8805 8806 if (targetReceiver == null) { 8807 return null; 8808 } 8809 8810 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8811 } 8812 8813 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8814 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8815 if (pkgInfo.verifiers.length == 0) { 8816 return null; 8817 } 8818 8819 final int N = pkgInfo.verifiers.length; 8820 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8821 for (int i = 0; i < N; i++) { 8822 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8823 8824 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8825 receivers); 8826 if (comp == null) { 8827 continue; 8828 } 8829 8830 final int verifierUid = getUidForVerifier(verifierInfo); 8831 if (verifierUid == -1) { 8832 continue; 8833 } 8834 8835 if (DEBUG_VERIFY) { 8836 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8837 + " with the correct signature"); 8838 } 8839 sufficientVerifiers.add(comp); 8840 verificationState.addSufficientVerifier(verifierUid); 8841 } 8842 8843 return sufficientVerifiers; 8844 } 8845 8846 private int getUidForVerifier(VerifierInfo verifierInfo) { 8847 synchronized (mPackages) { 8848 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8849 if (pkg == null) { 8850 return -1; 8851 } else if (pkg.mSignatures.length != 1) { 8852 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8853 + " has more than one signature; ignoring"); 8854 return -1; 8855 } 8856 8857 /* 8858 * If the public key of the package's signature does not match 8859 * our expected public key, then this is a different package and 8860 * we should skip. 8861 */ 8862 8863 final byte[] expectedPublicKey; 8864 try { 8865 final Signature verifierSig = pkg.mSignatures[0]; 8866 final PublicKey publicKey = verifierSig.getPublicKey(); 8867 expectedPublicKey = publicKey.getEncoded(); 8868 } catch (CertificateException e) { 8869 return -1; 8870 } 8871 8872 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8873 8874 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8875 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8876 + " does not have the expected public key; ignoring"); 8877 return -1; 8878 } 8879 8880 return pkg.applicationInfo.uid; 8881 } 8882 } 8883 8884 @Override 8885 public void finishPackageInstall(int token) { 8886 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8887 8888 if (DEBUG_INSTALL) { 8889 Slog.v(TAG, "BM finishing package install for " + token); 8890 } 8891 8892 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8893 mHandler.sendMessage(msg); 8894 } 8895 8896 /** 8897 * Get the verification agent timeout. 8898 * 8899 * @return verification timeout in milliseconds 8900 */ 8901 private long getVerificationTimeout() { 8902 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8903 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8904 DEFAULT_VERIFICATION_TIMEOUT); 8905 } 8906 8907 /** 8908 * Get the default verification agent response code. 8909 * 8910 * @return default verification response code 8911 */ 8912 private int getDefaultVerificationResponse() { 8913 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8914 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8915 DEFAULT_VERIFICATION_RESPONSE); 8916 } 8917 8918 /** 8919 * Check whether or not package verification has been enabled. 8920 * 8921 * @return true if verification should be performed 8922 */ 8923 private boolean isVerificationEnabled(int userId, int installFlags) { 8924 if (!DEFAULT_VERIFY_ENABLE) { 8925 return false; 8926 } 8927 8928 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8929 8930 // Check if installing from ADB 8931 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8932 // Do not run verification in a test harness environment 8933 if (ActivityManager.isRunningInTestHarness()) { 8934 return false; 8935 } 8936 if (ensureVerifyAppsEnabled) { 8937 return true; 8938 } 8939 // Check if the developer does not want package verification for ADB installs 8940 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8941 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8942 return false; 8943 } 8944 } 8945 8946 if (ensureVerifyAppsEnabled) { 8947 return true; 8948 } 8949 8950 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8951 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8952 } 8953 8954 @Override 8955 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 8956 throws RemoteException { 8957 mContext.enforceCallingOrSelfPermission( 8958 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8959 "Only intentfilter verification agents can verify applications"); 8960 8961 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8962 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8963 Binder.getCallingUid(), verificationCode, failedDomains); 8964 msg.arg1 = id; 8965 msg.obj = response; 8966 mHandler.sendMessage(msg); 8967 } 8968 8969 @Override 8970 public int getIntentVerificationStatus(String packageName, int userId) { 8971 synchronized (mPackages) { 8972 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8973 } 8974 } 8975 8976 @Override 8977 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8978 boolean result = false; 8979 synchronized (mPackages) { 8980 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8981 } 8982 scheduleWritePackageRestrictionsLocked(userId); 8983 return result; 8984 } 8985 8986 @Override 8987 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8988 synchronized (mPackages) { 8989 return mSettings.getIntentFilterVerificationsLPr(packageName); 8990 } 8991 } 8992 8993 @Override 8994 public List<IntentFilter> getAllIntentFilters(String packageName) { 8995 if (TextUtils.isEmpty(packageName)) { 8996 return Collections.<IntentFilter>emptyList(); 8997 } 8998 synchronized (mPackages) { 8999 PackageParser.Package pkg = mPackages.get(packageName); 9000 if (pkg == null || pkg.activities == null) { 9001 return Collections.<IntentFilter>emptyList(); 9002 } 9003 final int count = pkg.activities.size(); 9004 ArrayList<IntentFilter> result = new ArrayList<>(); 9005 for (int n=0; n<count; n++) { 9006 PackageParser.Activity activity = pkg.activities.get(n); 9007 if (activity.intents != null || activity.intents.size() > 0) { 9008 result.addAll(activity.intents); 9009 } 9010 } 9011 return result; 9012 } 9013 } 9014 9015 /** 9016 * Get the "allow unknown sources" setting. 9017 * 9018 * @return the current "allow unknown sources" setting 9019 */ 9020 private int getUnknownSourcesSettings() { 9021 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9022 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9023 -1); 9024 } 9025 9026 @Override 9027 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9028 final int uid = Binder.getCallingUid(); 9029 // writer 9030 synchronized (mPackages) { 9031 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9032 if (targetPackageSetting == null) { 9033 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9034 } 9035 9036 PackageSetting installerPackageSetting; 9037 if (installerPackageName != null) { 9038 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9039 if (installerPackageSetting == null) { 9040 throw new IllegalArgumentException("Unknown installer package: " 9041 + installerPackageName); 9042 } 9043 } else { 9044 installerPackageSetting = null; 9045 } 9046 9047 Signature[] callerSignature; 9048 Object obj = mSettings.getUserIdLPr(uid); 9049 if (obj != null) { 9050 if (obj instanceof SharedUserSetting) { 9051 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9052 } else if (obj instanceof PackageSetting) { 9053 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9054 } else { 9055 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9056 } 9057 } else { 9058 throw new SecurityException("Unknown calling uid " + uid); 9059 } 9060 9061 // Verify: can't set installerPackageName to a package that is 9062 // not signed with the same cert as the caller. 9063 if (installerPackageSetting != null) { 9064 if (compareSignatures(callerSignature, 9065 installerPackageSetting.signatures.mSignatures) 9066 != PackageManager.SIGNATURE_MATCH) { 9067 throw new SecurityException( 9068 "Caller does not have same cert as new installer package " 9069 + installerPackageName); 9070 } 9071 } 9072 9073 // Verify: if target already has an installer package, it must 9074 // be signed with the same cert as the caller. 9075 if (targetPackageSetting.installerPackageName != null) { 9076 PackageSetting setting = mSettings.mPackages.get( 9077 targetPackageSetting.installerPackageName); 9078 // If the currently set package isn't valid, then it's always 9079 // okay to change it. 9080 if (setting != null) { 9081 if (compareSignatures(callerSignature, 9082 setting.signatures.mSignatures) 9083 != PackageManager.SIGNATURE_MATCH) { 9084 throw new SecurityException( 9085 "Caller does not have same cert as old installer package " 9086 + targetPackageSetting.installerPackageName); 9087 } 9088 } 9089 } 9090 9091 // Okay! 9092 targetPackageSetting.installerPackageName = installerPackageName; 9093 scheduleWriteSettingsLocked(); 9094 } 9095 } 9096 9097 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9098 // Queue up an async operation since the package installation may take a little while. 9099 mHandler.post(new Runnable() { 9100 public void run() { 9101 mHandler.removeCallbacks(this); 9102 // Result object to be returned 9103 PackageInstalledInfo res = new PackageInstalledInfo(); 9104 res.returnCode = currentStatus; 9105 res.uid = -1; 9106 res.pkg = null; 9107 res.removedInfo = new PackageRemovedInfo(); 9108 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9109 args.doPreInstall(res.returnCode); 9110 synchronized (mInstallLock) { 9111 installPackageLI(args, res); 9112 } 9113 args.doPostInstall(res.returnCode, res.uid); 9114 } 9115 9116 // A restore should be performed at this point if (a) the install 9117 // succeeded, (b) the operation is not an update, and (c) the new 9118 // package has not opted out of backup participation. 9119 final boolean update = res.removedInfo.removedPackage != null; 9120 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9121 boolean doRestore = !update 9122 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9123 9124 // Set up the post-install work request bookkeeping. This will be used 9125 // and cleaned up by the post-install event handling regardless of whether 9126 // there's a restore pass performed. Token values are >= 1. 9127 int token; 9128 if (mNextInstallToken < 0) mNextInstallToken = 1; 9129 token = mNextInstallToken++; 9130 9131 PostInstallData data = new PostInstallData(args, res); 9132 mRunningInstalls.put(token, data); 9133 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9134 9135 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9136 // Pass responsibility to the Backup Manager. It will perform a 9137 // restore if appropriate, then pass responsibility back to the 9138 // Package Manager to run the post-install observer callbacks 9139 // and broadcasts. 9140 IBackupManager bm = IBackupManager.Stub.asInterface( 9141 ServiceManager.getService(Context.BACKUP_SERVICE)); 9142 if (bm != null) { 9143 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9144 + " to BM for possible restore"); 9145 try { 9146 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9147 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9148 } else { 9149 doRestore = false; 9150 } 9151 } catch (RemoteException e) { 9152 // can't happen; the backup manager is local 9153 } catch (Exception e) { 9154 Slog.e(TAG, "Exception trying to enqueue restore", e); 9155 doRestore = false; 9156 } 9157 } else { 9158 Slog.e(TAG, "Backup Manager not found!"); 9159 doRestore = false; 9160 } 9161 } 9162 9163 if (!doRestore) { 9164 // No restore possible, or the Backup Manager was mysteriously not 9165 // available -- just fire the post-install work request directly. 9166 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9167 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9168 mHandler.sendMessage(msg); 9169 } 9170 } 9171 }); 9172 } 9173 9174 private abstract class HandlerParams { 9175 private static final int MAX_RETRIES = 4; 9176 9177 /** 9178 * Number of times startCopy() has been attempted and had a non-fatal 9179 * error. 9180 */ 9181 private int mRetries = 0; 9182 9183 /** User handle for the user requesting the information or installation. */ 9184 private final UserHandle mUser; 9185 9186 HandlerParams(UserHandle user) { 9187 mUser = user; 9188 } 9189 9190 UserHandle getUser() { 9191 return mUser; 9192 } 9193 9194 final boolean startCopy() { 9195 boolean res; 9196 try { 9197 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9198 9199 if (++mRetries > MAX_RETRIES) { 9200 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9201 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9202 handleServiceError(); 9203 return false; 9204 } else { 9205 handleStartCopy(); 9206 res = true; 9207 } 9208 } catch (RemoteException e) { 9209 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9210 mHandler.sendEmptyMessage(MCS_RECONNECT); 9211 res = false; 9212 } 9213 handleReturnCode(); 9214 return res; 9215 } 9216 9217 final void serviceError() { 9218 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9219 handleServiceError(); 9220 handleReturnCode(); 9221 } 9222 9223 abstract void handleStartCopy() throws RemoteException; 9224 abstract void handleServiceError(); 9225 abstract void handleReturnCode(); 9226 } 9227 9228 class MeasureParams extends HandlerParams { 9229 private final PackageStats mStats; 9230 private boolean mSuccess; 9231 9232 private final IPackageStatsObserver mObserver; 9233 9234 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9235 super(new UserHandle(stats.userHandle)); 9236 mObserver = observer; 9237 mStats = stats; 9238 } 9239 9240 @Override 9241 public String toString() { 9242 return "MeasureParams{" 9243 + Integer.toHexString(System.identityHashCode(this)) 9244 + " " + mStats.packageName + "}"; 9245 } 9246 9247 @Override 9248 void handleStartCopy() throws RemoteException { 9249 synchronized (mInstallLock) { 9250 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9251 } 9252 9253 if (mSuccess) { 9254 final boolean mounted; 9255 if (Environment.isExternalStorageEmulated()) { 9256 mounted = true; 9257 } else { 9258 final String status = Environment.getExternalStorageState(); 9259 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9260 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9261 } 9262 9263 if (mounted) { 9264 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9265 9266 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9267 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9268 9269 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9270 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9271 9272 // Always subtract cache size, since it's a subdirectory 9273 mStats.externalDataSize -= mStats.externalCacheSize; 9274 9275 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9276 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9277 9278 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9279 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9280 } 9281 } 9282 } 9283 9284 @Override 9285 void handleReturnCode() { 9286 if (mObserver != null) { 9287 try { 9288 mObserver.onGetStatsCompleted(mStats, mSuccess); 9289 } catch (RemoteException e) { 9290 Slog.i(TAG, "Observer no longer exists."); 9291 } 9292 } 9293 } 9294 9295 @Override 9296 void handleServiceError() { 9297 Slog.e(TAG, "Could not measure application " + mStats.packageName 9298 + " external storage"); 9299 } 9300 } 9301 9302 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9303 throws RemoteException { 9304 long result = 0; 9305 for (File path : paths) { 9306 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9307 } 9308 return result; 9309 } 9310 9311 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9312 for (File path : paths) { 9313 try { 9314 mcs.clearDirectory(path.getAbsolutePath()); 9315 } catch (RemoteException e) { 9316 } 9317 } 9318 } 9319 9320 static class OriginInfo { 9321 /** 9322 * Location where install is coming from, before it has been 9323 * copied/renamed into place. This could be a single monolithic APK 9324 * file, or a cluster directory. This location may be untrusted. 9325 */ 9326 final File file; 9327 final String cid; 9328 9329 /** 9330 * Flag indicating that {@link #file} or {@link #cid} has already been 9331 * staged, meaning downstream users don't need to defensively copy the 9332 * contents. 9333 */ 9334 final boolean staged; 9335 9336 /** 9337 * Flag indicating that {@link #file} or {@link #cid} is an already 9338 * installed app that is being moved. 9339 */ 9340 final boolean existing; 9341 9342 final String resolvedPath; 9343 final File resolvedFile; 9344 9345 static OriginInfo fromNothing() { 9346 return new OriginInfo(null, null, false, false); 9347 } 9348 9349 static OriginInfo fromUntrustedFile(File file) { 9350 return new OriginInfo(file, null, false, false); 9351 } 9352 9353 static OriginInfo fromExistingFile(File file) { 9354 return new OriginInfo(file, null, false, true); 9355 } 9356 9357 static OriginInfo fromStagedFile(File file) { 9358 return new OriginInfo(file, null, true, false); 9359 } 9360 9361 static OriginInfo fromStagedContainer(String cid) { 9362 return new OriginInfo(null, cid, true, false); 9363 } 9364 9365 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9366 this.file = file; 9367 this.cid = cid; 9368 this.staged = staged; 9369 this.existing = existing; 9370 9371 if (cid != null) { 9372 resolvedPath = PackageHelper.getSdDir(cid); 9373 resolvedFile = new File(resolvedPath); 9374 } else if (file != null) { 9375 resolvedPath = file.getAbsolutePath(); 9376 resolvedFile = file; 9377 } else { 9378 resolvedPath = null; 9379 resolvedFile = null; 9380 } 9381 } 9382 } 9383 9384 class InstallParams extends HandlerParams { 9385 final OriginInfo origin; 9386 final IPackageInstallObserver2 observer; 9387 int installFlags; 9388 final String installerPackageName; 9389 final String volumeUuid; 9390 final VerificationParams verificationParams; 9391 private InstallArgs mArgs; 9392 private int mRet; 9393 final String packageAbiOverride; 9394 9395 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9396 String installerPackageName, String volumeUuid, 9397 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9398 super(user); 9399 this.origin = origin; 9400 this.observer = observer; 9401 this.installFlags = installFlags; 9402 this.installerPackageName = installerPackageName; 9403 this.volumeUuid = volumeUuid; 9404 this.verificationParams = verificationParams; 9405 this.packageAbiOverride = packageAbiOverride; 9406 } 9407 9408 @Override 9409 public String toString() { 9410 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9411 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9412 } 9413 9414 public ManifestDigest getManifestDigest() { 9415 if (verificationParams == null) { 9416 return null; 9417 } 9418 return verificationParams.getManifestDigest(); 9419 } 9420 9421 private int installLocationPolicy(PackageInfoLite pkgLite) { 9422 String packageName = pkgLite.packageName; 9423 int installLocation = pkgLite.installLocation; 9424 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9425 // reader 9426 synchronized (mPackages) { 9427 PackageParser.Package pkg = mPackages.get(packageName); 9428 if (pkg != null) { 9429 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9430 // Check for downgrading. 9431 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9432 try { 9433 checkDowngrade(pkg, pkgLite); 9434 } catch (PackageManagerException e) { 9435 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9436 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9437 } 9438 } 9439 // Check for updated system application. 9440 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9441 if (onSd) { 9442 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9443 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9444 } 9445 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9446 } else { 9447 if (onSd) { 9448 // Install flag overrides everything. 9449 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9450 } 9451 // If current upgrade specifies particular preference 9452 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9453 // Application explicitly specified internal. 9454 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9455 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9456 // App explictly prefers external. Let policy decide 9457 } else { 9458 // Prefer previous location 9459 if (isExternal(pkg)) { 9460 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9461 } 9462 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9463 } 9464 } 9465 } else { 9466 // Invalid install. Return error code 9467 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9468 } 9469 } 9470 } 9471 // All the special cases have been taken care of. 9472 // Return result based on recommended install location. 9473 if (onSd) { 9474 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9475 } 9476 return pkgLite.recommendedInstallLocation; 9477 } 9478 9479 /* 9480 * Invoke remote method to get package information and install 9481 * location values. Override install location based on default 9482 * policy if needed and then create install arguments based 9483 * on the install location. 9484 */ 9485 public void handleStartCopy() throws RemoteException { 9486 int ret = PackageManager.INSTALL_SUCCEEDED; 9487 9488 // If we're already staged, we've firmly committed to an install location 9489 if (origin.staged) { 9490 if (origin.file != null) { 9491 installFlags |= PackageManager.INSTALL_INTERNAL; 9492 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9493 } else if (origin.cid != null) { 9494 installFlags |= PackageManager.INSTALL_EXTERNAL; 9495 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9496 } else { 9497 throw new IllegalStateException("Invalid stage location"); 9498 } 9499 } 9500 9501 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9502 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9503 9504 PackageInfoLite pkgLite = null; 9505 9506 if (onInt && onSd) { 9507 // Check if both bits are set. 9508 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9509 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9510 } else { 9511 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9512 packageAbiOverride); 9513 9514 /* 9515 * If we have too little free space, try to free cache 9516 * before giving up. 9517 */ 9518 if (!origin.staged && pkgLite.recommendedInstallLocation 9519 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9520 // TODO: focus freeing disk space on the target device 9521 final StorageManager storage = StorageManager.from(mContext); 9522 final long lowThreshold = storage.getStorageLowBytes( 9523 Environment.getDataDirectory()); 9524 9525 final long sizeBytes = mContainerService.calculateInstalledSize( 9526 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9527 9528 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9529 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9530 installFlags, packageAbiOverride); 9531 } 9532 9533 /* 9534 * The cache free must have deleted the file we 9535 * downloaded to install. 9536 * 9537 * TODO: fix the "freeCache" call to not delete 9538 * the file we care about. 9539 */ 9540 if (pkgLite.recommendedInstallLocation 9541 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9542 pkgLite.recommendedInstallLocation 9543 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9544 } 9545 } 9546 } 9547 9548 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9549 int loc = pkgLite.recommendedInstallLocation; 9550 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9551 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9552 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9553 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9554 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9555 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9556 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9557 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9558 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9559 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9560 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9561 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9562 } else { 9563 // Override with defaults if needed. 9564 loc = installLocationPolicy(pkgLite); 9565 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9566 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9567 } else if (!onSd && !onInt) { 9568 // Override install location with flags 9569 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9570 // Set the flag to install on external media. 9571 installFlags |= PackageManager.INSTALL_EXTERNAL; 9572 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9573 } else { 9574 // Make sure the flag for installing on external 9575 // media is unset 9576 installFlags |= PackageManager.INSTALL_INTERNAL; 9577 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9578 } 9579 } 9580 } 9581 } 9582 9583 final InstallArgs args = createInstallArgs(this); 9584 mArgs = args; 9585 9586 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9587 /* 9588 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9589 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9590 */ 9591 int userIdentifier = getUser().getIdentifier(); 9592 if (userIdentifier == UserHandle.USER_ALL 9593 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9594 userIdentifier = UserHandle.USER_OWNER; 9595 } 9596 9597 /* 9598 * Determine if we have any installed package verifiers. If we 9599 * do, then we'll defer to them to verify the packages. 9600 */ 9601 final int requiredUid = mRequiredVerifierPackage == null ? -1 9602 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9603 if (!origin.existing && requiredUid != -1 9604 && isVerificationEnabled(userIdentifier, installFlags)) { 9605 final Intent verification = new Intent( 9606 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9607 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9608 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9609 PACKAGE_MIME_TYPE); 9610 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9611 9612 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9613 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9614 0 /* TODO: Which userId? */); 9615 9616 if (DEBUG_VERIFY) { 9617 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9618 + verification.toString() + " with " + pkgLite.verifiers.length 9619 + " optional verifiers"); 9620 } 9621 9622 final int verificationId = mPendingVerificationToken++; 9623 9624 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9625 9626 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9627 installerPackageName); 9628 9629 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9630 installFlags); 9631 9632 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9633 pkgLite.packageName); 9634 9635 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9636 pkgLite.versionCode); 9637 9638 if (verificationParams != null) { 9639 if (verificationParams.getVerificationURI() != null) { 9640 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9641 verificationParams.getVerificationURI()); 9642 } 9643 if (verificationParams.getOriginatingURI() != null) { 9644 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9645 verificationParams.getOriginatingURI()); 9646 } 9647 if (verificationParams.getReferrer() != null) { 9648 verification.putExtra(Intent.EXTRA_REFERRER, 9649 verificationParams.getReferrer()); 9650 } 9651 if (verificationParams.getOriginatingUid() >= 0) { 9652 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9653 verificationParams.getOriginatingUid()); 9654 } 9655 if (verificationParams.getInstallerUid() >= 0) { 9656 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9657 verificationParams.getInstallerUid()); 9658 } 9659 } 9660 9661 final PackageVerificationState verificationState = new PackageVerificationState( 9662 requiredUid, args); 9663 9664 mPendingVerification.append(verificationId, verificationState); 9665 9666 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9667 receivers, verificationState); 9668 9669 /* 9670 * If any sufficient verifiers were listed in the package 9671 * manifest, attempt to ask them. 9672 */ 9673 if (sufficientVerifiers != null) { 9674 final int N = sufficientVerifiers.size(); 9675 if (N == 0) { 9676 Slog.i(TAG, "Additional verifiers required, but none installed."); 9677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9678 } else { 9679 for (int i = 0; i < N; i++) { 9680 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9681 9682 final Intent sufficientIntent = new Intent(verification); 9683 sufficientIntent.setComponent(verifierComponent); 9684 9685 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9686 } 9687 } 9688 } 9689 9690 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9691 mRequiredVerifierPackage, receivers); 9692 if (ret == PackageManager.INSTALL_SUCCEEDED 9693 && mRequiredVerifierPackage != null) { 9694 /* 9695 * Send the intent to the required verification agent, 9696 * but only start the verification timeout after the 9697 * target BroadcastReceivers have run. 9698 */ 9699 verification.setComponent(requiredVerifierComponent); 9700 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9701 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9702 new BroadcastReceiver() { 9703 @Override 9704 public void onReceive(Context context, Intent intent) { 9705 final Message msg = mHandler 9706 .obtainMessage(CHECK_PENDING_VERIFICATION); 9707 msg.arg1 = verificationId; 9708 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9709 } 9710 }, null, 0, null, null); 9711 9712 /* 9713 * We don't want the copy to proceed until verification 9714 * succeeds, so null out this field. 9715 */ 9716 mArgs = null; 9717 } 9718 } else { 9719 /* 9720 * No package verification is enabled, so immediately start 9721 * the remote call to initiate copy using temporary file. 9722 */ 9723 ret = args.copyApk(mContainerService, true); 9724 } 9725 } 9726 9727 mRet = ret; 9728 } 9729 9730 @Override 9731 void handleReturnCode() { 9732 // If mArgs is null, then MCS couldn't be reached. When it 9733 // reconnects, it will try again to install. At that point, this 9734 // will succeed. 9735 if (mArgs != null) { 9736 processPendingInstall(mArgs, mRet); 9737 } 9738 } 9739 9740 @Override 9741 void handleServiceError() { 9742 mArgs = createInstallArgs(this); 9743 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9744 } 9745 9746 public boolean isForwardLocked() { 9747 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9748 } 9749 } 9750 9751 /** 9752 * Used during creation of InstallArgs 9753 * 9754 * @param installFlags package installation flags 9755 * @return true if should be installed on external storage 9756 */ 9757 private static boolean installOnExternalAsec(int installFlags) { 9758 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9759 return false; 9760 } 9761 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9762 return true; 9763 } 9764 return false; 9765 } 9766 9767 /** 9768 * Used during creation of InstallArgs 9769 * 9770 * @param installFlags package installation flags 9771 * @return true if should be installed as forward locked 9772 */ 9773 private static boolean installForwardLocked(int installFlags) { 9774 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9775 } 9776 9777 private InstallArgs createInstallArgs(InstallParams params) { 9778 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9779 return new AsecInstallArgs(params); 9780 } else { 9781 return new FileInstallArgs(params); 9782 } 9783 } 9784 9785 /** 9786 * Create args that describe an existing installed package. Typically used 9787 * when cleaning up old installs, or used as a move source. 9788 */ 9789 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9790 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9791 final boolean isInAsec; 9792 if (installOnExternalAsec(installFlags)) { 9793 /* Apps on SD card are always in ASEC containers. */ 9794 isInAsec = true; 9795 } else if (installForwardLocked(installFlags) 9796 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9797 /* 9798 * Forward-locked apps are only in ASEC containers if they're the 9799 * new style 9800 */ 9801 isInAsec = true; 9802 } else { 9803 isInAsec = false; 9804 } 9805 9806 if (isInAsec) { 9807 return new AsecInstallArgs(codePath, instructionSets, 9808 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9809 } else { 9810 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9811 instructionSets); 9812 } 9813 } 9814 9815 static abstract class InstallArgs { 9816 /** @see InstallParams#origin */ 9817 final OriginInfo origin; 9818 9819 final IPackageInstallObserver2 observer; 9820 // Always refers to PackageManager flags only 9821 final int installFlags; 9822 final String installerPackageName; 9823 final String volumeUuid; 9824 final ManifestDigest manifestDigest; 9825 final UserHandle user; 9826 final String abiOverride; 9827 9828 // The list of instruction sets supported by this app. This is currently 9829 // only used during the rmdex() phase to clean up resources. We can get rid of this 9830 // if we move dex files under the common app path. 9831 /* nullable */ String[] instructionSets; 9832 9833 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9834 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9835 UserHandle user, String[] instructionSets, String abiOverride) { 9836 this.origin = origin; 9837 this.installFlags = installFlags; 9838 this.observer = observer; 9839 this.installerPackageName = installerPackageName; 9840 this.volumeUuid = volumeUuid; 9841 this.manifestDigest = manifestDigest; 9842 this.user = user; 9843 this.instructionSets = instructionSets; 9844 this.abiOverride = abiOverride; 9845 } 9846 9847 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9848 abstract int doPreInstall(int status); 9849 9850 /** 9851 * Rename package into final resting place. All paths on the given 9852 * scanned package should be updated to reflect the rename. 9853 */ 9854 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9855 abstract int doPostInstall(int status, int uid); 9856 9857 /** @see PackageSettingBase#codePathString */ 9858 abstract String getCodePath(); 9859 /** @see PackageSettingBase#resourcePathString */ 9860 abstract String getResourcePath(); 9861 abstract String getLegacyNativeLibraryPath(); 9862 9863 // Need installer lock especially for dex file removal. 9864 abstract void cleanUpResourcesLI(); 9865 abstract boolean doPostDeleteLI(boolean delete); 9866 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9867 9868 /** 9869 * Called before the source arguments are copied. This is used mostly 9870 * for MoveParams when it needs to read the source file to put it in the 9871 * destination. 9872 */ 9873 int doPreCopy() { 9874 return PackageManager.INSTALL_SUCCEEDED; 9875 } 9876 9877 /** 9878 * Called after the source arguments are copied. This is used mostly for 9879 * MoveParams when it needs to read the source file to put it in the 9880 * destination. 9881 * 9882 * @return 9883 */ 9884 int doPostCopy(int uid) { 9885 return PackageManager.INSTALL_SUCCEEDED; 9886 } 9887 9888 protected boolean isFwdLocked() { 9889 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9890 } 9891 9892 protected boolean isExternalAsec() { 9893 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9894 } 9895 9896 UserHandle getUser() { 9897 return user; 9898 } 9899 } 9900 9901 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9902 if (!allCodePaths.isEmpty()) { 9903 if (instructionSets == null) { 9904 throw new IllegalStateException("instructionSet == null"); 9905 } 9906 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9907 for (String codePath : allCodePaths) { 9908 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9909 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9910 if (retCode < 0) { 9911 Slog.w(TAG, "Couldn't remove dex file for package: " 9912 + " at location " + codePath + ", retcode=" + retCode); 9913 // we don't consider this to be a failure of the core package deletion 9914 } 9915 } 9916 } 9917 } 9918 } 9919 9920 /** 9921 * Logic to handle installation of non-ASEC applications, including copying 9922 * and renaming logic. 9923 */ 9924 class FileInstallArgs extends InstallArgs { 9925 private File codeFile; 9926 private File resourceFile; 9927 private File legacyNativeLibraryPath; 9928 9929 // Example topology: 9930 // /data/app/com.example/base.apk 9931 // /data/app/com.example/split_foo.apk 9932 // /data/app/com.example/lib/arm/libfoo.so 9933 // /data/app/com.example/lib/arm64/libfoo.so 9934 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9935 9936 /** New install */ 9937 FileInstallArgs(InstallParams params) { 9938 super(params.origin, params.observer, params.installFlags, 9939 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 9940 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 9941 if (isFwdLocked()) { 9942 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9943 } 9944 } 9945 9946 /** Existing install */ 9947 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9948 String[] instructionSets) { 9949 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 9950 this.codeFile = (codePath != null) ? new File(codePath) : null; 9951 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9952 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9953 new File(legacyNativeLibraryPath) : null; 9954 } 9955 9956 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9957 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9958 isFwdLocked(), abiOverride); 9959 9960 final StorageManager storage = StorageManager.from(mContext); 9961 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9962 } 9963 9964 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9965 if (origin.staged) { 9966 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9967 codeFile = origin.file; 9968 resourceFile = origin.file; 9969 return PackageManager.INSTALL_SUCCEEDED; 9970 } 9971 9972 try { 9973 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 9974 codeFile = tempDir; 9975 resourceFile = tempDir; 9976 } catch (IOException e) { 9977 Slog.w(TAG, "Failed to create copy file: " + e); 9978 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9979 } 9980 9981 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9982 @Override 9983 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9984 if (!FileUtils.isValidExtFilename(name)) { 9985 throw new IllegalArgumentException("Invalid filename: " + name); 9986 } 9987 try { 9988 final File file = new File(codeFile, name); 9989 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9990 O_RDWR | O_CREAT, 0644); 9991 Os.chmod(file.getAbsolutePath(), 0644); 9992 return new ParcelFileDescriptor(fd); 9993 } catch (ErrnoException e) { 9994 throw new RemoteException("Failed to open: " + e.getMessage()); 9995 } 9996 } 9997 }; 9998 9999 int ret = PackageManager.INSTALL_SUCCEEDED; 10000 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10001 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10002 Slog.e(TAG, "Failed to copy package"); 10003 return ret; 10004 } 10005 10006 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10007 NativeLibraryHelper.Handle handle = null; 10008 try { 10009 handle = NativeLibraryHelper.Handle.create(codeFile); 10010 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10011 abiOverride); 10012 } catch (IOException e) { 10013 Slog.e(TAG, "Copying native libraries failed", e); 10014 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10015 } finally { 10016 IoUtils.closeQuietly(handle); 10017 } 10018 10019 return ret; 10020 } 10021 10022 int doPreInstall(int status) { 10023 if (status != PackageManager.INSTALL_SUCCEEDED) { 10024 cleanUp(); 10025 } 10026 return status; 10027 } 10028 10029 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10030 if (status != PackageManager.INSTALL_SUCCEEDED) { 10031 cleanUp(); 10032 return false; 10033 } else { 10034 final File targetDir = codeFile.getParentFile(); 10035 final File beforeCodeFile = codeFile; 10036 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10037 10038 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10039 try { 10040 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10041 } catch (ErrnoException e) { 10042 Slog.d(TAG, "Failed to rename", e); 10043 return false; 10044 } 10045 10046 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10047 Slog.d(TAG, "Failed to restorecon"); 10048 return false; 10049 } 10050 10051 // Reflect the rename internally 10052 codeFile = afterCodeFile; 10053 resourceFile = afterCodeFile; 10054 10055 // Reflect the rename in scanned details 10056 pkg.codePath = afterCodeFile.getAbsolutePath(); 10057 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10058 pkg.baseCodePath); 10059 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10060 pkg.splitCodePaths); 10061 10062 // Reflect the rename in app info 10063 pkg.applicationInfo.setCodePath(pkg.codePath); 10064 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10065 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10066 pkg.applicationInfo.setResourcePath(pkg.codePath); 10067 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10068 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10069 10070 return true; 10071 } 10072 } 10073 10074 int doPostInstall(int status, int uid) { 10075 if (status != PackageManager.INSTALL_SUCCEEDED) { 10076 cleanUp(); 10077 } 10078 return status; 10079 } 10080 10081 @Override 10082 String getCodePath() { 10083 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10084 } 10085 10086 @Override 10087 String getResourcePath() { 10088 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10089 } 10090 10091 @Override 10092 String getLegacyNativeLibraryPath() { 10093 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10094 } 10095 10096 private boolean cleanUp() { 10097 if (codeFile == null || !codeFile.exists()) { 10098 return false; 10099 } 10100 10101 if (codeFile.isDirectory()) { 10102 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10103 } else { 10104 codeFile.delete(); 10105 } 10106 10107 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10108 resourceFile.delete(); 10109 } 10110 10111 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10112 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10113 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10114 } 10115 legacyNativeLibraryPath.delete(); 10116 } 10117 10118 return true; 10119 } 10120 10121 void cleanUpResourcesLI() { 10122 // Try enumerating all code paths before deleting 10123 List<String> allCodePaths = Collections.EMPTY_LIST; 10124 if (codeFile != null && codeFile.exists()) { 10125 try { 10126 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10127 allCodePaths = pkg.getAllCodePaths(); 10128 } catch (PackageParserException e) { 10129 // Ignored; we tried our best 10130 } 10131 } 10132 10133 cleanUp(); 10134 removeDexFiles(allCodePaths, instructionSets); 10135 } 10136 10137 boolean doPostDeleteLI(boolean delete) { 10138 // XXX err, shouldn't we respect the delete flag? 10139 cleanUpResourcesLI(); 10140 return true; 10141 } 10142 } 10143 10144 private boolean isAsecExternal(String cid) { 10145 final String asecPath = PackageHelper.getSdFilesystem(cid); 10146 return !asecPath.startsWith(mAsecInternalPath); 10147 } 10148 10149 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10150 PackageManagerException { 10151 if (copyRet < 0) { 10152 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10153 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10154 throw new PackageManagerException(copyRet, message); 10155 } 10156 } 10157 } 10158 10159 /** 10160 * Extract the MountService "container ID" from the full code path of an 10161 * .apk. 10162 */ 10163 static String cidFromCodePath(String fullCodePath) { 10164 int eidx = fullCodePath.lastIndexOf("/"); 10165 String subStr1 = fullCodePath.substring(0, eidx); 10166 int sidx = subStr1.lastIndexOf("/"); 10167 return subStr1.substring(sidx+1, eidx); 10168 } 10169 10170 /** 10171 * Logic to handle installation of ASEC applications, including copying and 10172 * renaming logic. 10173 */ 10174 class AsecInstallArgs extends InstallArgs { 10175 static final String RES_FILE_NAME = "pkg.apk"; 10176 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10177 10178 String cid; 10179 String packagePath; 10180 String resourcePath; 10181 String legacyNativeLibraryDir; 10182 10183 /** New install */ 10184 AsecInstallArgs(InstallParams params) { 10185 super(params.origin, params.observer, params.installFlags, 10186 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10187 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10188 } 10189 10190 /** Existing install */ 10191 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10192 boolean isExternal, boolean isForwardLocked) { 10193 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10194 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10195 instructionSets, null); 10196 // Hackily pretend we're still looking at a full code path 10197 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10198 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10199 } 10200 10201 // Extract cid from fullCodePath 10202 int eidx = fullCodePath.lastIndexOf("/"); 10203 String subStr1 = fullCodePath.substring(0, eidx); 10204 int sidx = subStr1.lastIndexOf("/"); 10205 cid = subStr1.substring(sidx+1, eidx); 10206 setMountPath(subStr1); 10207 } 10208 10209 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10210 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10211 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10212 instructionSets, null); 10213 this.cid = cid; 10214 setMountPath(PackageHelper.getSdDir(cid)); 10215 } 10216 10217 void createCopyFile() { 10218 cid = mInstallerService.allocateExternalStageCidLegacy(); 10219 } 10220 10221 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10222 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10223 abiOverride); 10224 10225 final File target; 10226 if (isExternalAsec()) { 10227 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10228 } else { 10229 target = Environment.getDataDirectory(); 10230 } 10231 10232 final StorageManager storage = StorageManager.from(mContext); 10233 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10234 } 10235 10236 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10237 if (origin.staged) { 10238 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10239 cid = origin.cid; 10240 setMountPath(PackageHelper.getSdDir(cid)); 10241 return PackageManager.INSTALL_SUCCEEDED; 10242 } 10243 10244 if (temp) { 10245 createCopyFile(); 10246 } else { 10247 /* 10248 * Pre-emptively destroy the container since it's destroyed if 10249 * copying fails due to it existing anyway. 10250 */ 10251 PackageHelper.destroySdDir(cid); 10252 } 10253 10254 final String newMountPath = imcs.copyPackageToContainer( 10255 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10256 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10257 10258 if (newMountPath != null) { 10259 setMountPath(newMountPath); 10260 return PackageManager.INSTALL_SUCCEEDED; 10261 } else { 10262 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10263 } 10264 } 10265 10266 @Override 10267 String getCodePath() { 10268 return packagePath; 10269 } 10270 10271 @Override 10272 String getResourcePath() { 10273 return resourcePath; 10274 } 10275 10276 @Override 10277 String getLegacyNativeLibraryPath() { 10278 return legacyNativeLibraryDir; 10279 } 10280 10281 int doPreInstall(int status) { 10282 if (status != PackageManager.INSTALL_SUCCEEDED) { 10283 // Destroy container 10284 PackageHelper.destroySdDir(cid); 10285 } else { 10286 boolean mounted = PackageHelper.isContainerMounted(cid); 10287 if (!mounted) { 10288 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10289 Process.SYSTEM_UID); 10290 if (newMountPath != null) { 10291 setMountPath(newMountPath); 10292 } else { 10293 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10294 } 10295 } 10296 } 10297 return status; 10298 } 10299 10300 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10301 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10302 String newMountPath = null; 10303 if (PackageHelper.isContainerMounted(cid)) { 10304 // Unmount the container 10305 if (!PackageHelper.unMountSdDir(cid)) { 10306 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10307 return false; 10308 } 10309 } 10310 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10311 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10312 " which might be stale. Will try to clean up."); 10313 // Clean up the stale container and proceed to recreate. 10314 if (!PackageHelper.destroySdDir(newCacheId)) { 10315 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10316 return false; 10317 } 10318 // Successfully cleaned up stale container. Try to rename again. 10319 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10320 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10321 + " inspite of cleaning it up."); 10322 return false; 10323 } 10324 } 10325 if (!PackageHelper.isContainerMounted(newCacheId)) { 10326 Slog.w(TAG, "Mounting container " + newCacheId); 10327 newMountPath = PackageHelper.mountSdDir(newCacheId, 10328 getEncryptKey(), Process.SYSTEM_UID); 10329 } else { 10330 newMountPath = PackageHelper.getSdDir(newCacheId); 10331 } 10332 if (newMountPath == null) { 10333 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10334 return false; 10335 } 10336 Log.i(TAG, "Succesfully renamed " + cid + 10337 " to " + newCacheId + 10338 " at new path: " + newMountPath); 10339 cid = newCacheId; 10340 10341 final File beforeCodeFile = new File(packagePath); 10342 setMountPath(newMountPath); 10343 final File afterCodeFile = new File(packagePath); 10344 10345 // Reflect the rename in scanned details 10346 pkg.codePath = afterCodeFile.getAbsolutePath(); 10347 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10348 pkg.baseCodePath); 10349 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10350 pkg.splitCodePaths); 10351 10352 // Reflect the rename in app info 10353 pkg.applicationInfo.setCodePath(pkg.codePath); 10354 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10355 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10356 pkg.applicationInfo.setResourcePath(pkg.codePath); 10357 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10358 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10359 10360 return true; 10361 } 10362 10363 private void setMountPath(String mountPath) { 10364 final File mountFile = new File(mountPath); 10365 10366 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10367 if (monolithicFile.exists()) { 10368 packagePath = monolithicFile.getAbsolutePath(); 10369 if (isFwdLocked()) { 10370 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10371 } else { 10372 resourcePath = packagePath; 10373 } 10374 } else { 10375 packagePath = mountFile.getAbsolutePath(); 10376 resourcePath = packagePath; 10377 } 10378 10379 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10380 } 10381 10382 int doPostInstall(int status, int uid) { 10383 if (status != PackageManager.INSTALL_SUCCEEDED) { 10384 cleanUp(); 10385 } else { 10386 final int groupOwner; 10387 final String protectedFile; 10388 if (isFwdLocked()) { 10389 groupOwner = UserHandle.getSharedAppGid(uid); 10390 protectedFile = RES_FILE_NAME; 10391 } else { 10392 groupOwner = -1; 10393 protectedFile = null; 10394 } 10395 10396 if (uid < Process.FIRST_APPLICATION_UID 10397 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10398 Slog.e(TAG, "Failed to finalize " + cid); 10399 PackageHelper.destroySdDir(cid); 10400 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10401 } 10402 10403 boolean mounted = PackageHelper.isContainerMounted(cid); 10404 if (!mounted) { 10405 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10406 } 10407 } 10408 return status; 10409 } 10410 10411 private void cleanUp() { 10412 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10413 10414 // Destroy secure container 10415 PackageHelper.destroySdDir(cid); 10416 } 10417 10418 private List<String> getAllCodePaths() { 10419 final File codeFile = new File(getCodePath()); 10420 if (codeFile != null && codeFile.exists()) { 10421 try { 10422 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10423 return pkg.getAllCodePaths(); 10424 } catch (PackageParserException e) { 10425 // Ignored; we tried our best 10426 } 10427 } 10428 return Collections.EMPTY_LIST; 10429 } 10430 10431 void cleanUpResourcesLI() { 10432 // Enumerate all code paths before deleting 10433 cleanUpResourcesLI(getAllCodePaths()); 10434 } 10435 10436 private void cleanUpResourcesLI(List<String> allCodePaths) { 10437 cleanUp(); 10438 removeDexFiles(allCodePaths, instructionSets); 10439 } 10440 10441 10442 10443 String getPackageName() { 10444 return getAsecPackageName(cid); 10445 } 10446 10447 boolean doPostDeleteLI(boolean delete) { 10448 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10449 final List<String> allCodePaths = getAllCodePaths(); 10450 boolean mounted = PackageHelper.isContainerMounted(cid); 10451 if (mounted) { 10452 // Unmount first 10453 if (PackageHelper.unMountSdDir(cid)) { 10454 mounted = false; 10455 } 10456 } 10457 if (!mounted && delete) { 10458 cleanUpResourcesLI(allCodePaths); 10459 } 10460 return !mounted; 10461 } 10462 10463 @Override 10464 int doPreCopy() { 10465 if (isFwdLocked()) { 10466 if (!PackageHelper.fixSdPermissions(cid, 10467 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10468 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10469 } 10470 } 10471 10472 return PackageManager.INSTALL_SUCCEEDED; 10473 } 10474 10475 @Override 10476 int doPostCopy(int uid) { 10477 if (isFwdLocked()) { 10478 if (uid < Process.FIRST_APPLICATION_UID 10479 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10480 RES_FILE_NAME)) { 10481 Slog.e(TAG, "Failed to finalize " + cid); 10482 PackageHelper.destroySdDir(cid); 10483 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10484 } 10485 } 10486 10487 return PackageManager.INSTALL_SUCCEEDED; 10488 } 10489 } 10490 10491 static String getAsecPackageName(String packageCid) { 10492 int idx = packageCid.lastIndexOf("-"); 10493 if (idx == -1) { 10494 return packageCid; 10495 } 10496 return packageCid.substring(0, idx); 10497 } 10498 10499 // Utility method used to create code paths based on package name and available index. 10500 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10501 String idxStr = ""; 10502 int idx = 1; 10503 // Fall back to default value of idx=1 if prefix is not 10504 // part of oldCodePath 10505 if (oldCodePath != null) { 10506 String subStr = oldCodePath; 10507 // Drop the suffix right away 10508 if (suffix != null && subStr.endsWith(suffix)) { 10509 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10510 } 10511 // If oldCodePath already contains prefix find out the 10512 // ending index to either increment or decrement. 10513 int sidx = subStr.lastIndexOf(prefix); 10514 if (sidx != -1) { 10515 subStr = subStr.substring(sidx + prefix.length()); 10516 if (subStr != null) { 10517 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10518 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10519 } 10520 try { 10521 idx = Integer.parseInt(subStr); 10522 if (idx <= 1) { 10523 idx++; 10524 } else { 10525 idx--; 10526 } 10527 } catch(NumberFormatException e) { 10528 } 10529 } 10530 } 10531 } 10532 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10533 return prefix + idxStr; 10534 } 10535 10536 private File getNextCodePath(File targetDir, String packageName) { 10537 int suffix = 1; 10538 File result; 10539 do { 10540 result = new File(targetDir, packageName + "-" + suffix); 10541 suffix++; 10542 } while (result.exists()); 10543 return result; 10544 } 10545 10546 // Utility method that returns the relative package path with respect 10547 // to the installation directory. Like say for /data/data/com.test-1.apk 10548 // string com.test-1 is returned. 10549 static String deriveCodePathName(String codePath) { 10550 if (codePath == null) { 10551 return null; 10552 } 10553 final File codeFile = new File(codePath); 10554 final String name = codeFile.getName(); 10555 if (codeFile.isDirectory()) { 10556 return name; 10557 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10558 final int lastDot = name.lastIndexOf('.'); 10559 return name.substring(0, lastDot); 10560 } else { 10561 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10562 return null; 10563 } 10564 } 10565 10566 class PackageInstalledInfo { 10567 String name; 10568 int uid; 10569 // The set of users that originally had this package installed. 10570 int[] origUsers; 10571 // The set of users that now have this package installed. 10572 int[] newUsers; 10573 PackageParser.Package pkg; 10574 int returnCode; 10575 String returnMsg; 10576 PackageRemovedInfo removedInfo; 10577 10578 public void setError(int code, String msg) { 10579 returnCode = code; 10580 returnMsg = msg; 10581 Slog.w(TAG, msg); 10582 } 10583 10584 public void setError(String msg, PackageParserException e) { 10585 returnCode = e.error; 10586 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10587 Slog.w(TAG, msg, e); 10588 } 10589 10590 public void setError(String msg, PackageManagerException e) { 10591 returnCode = e.error; 10592 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10593 Slog.w(TAG, msg, e); 10594 } 10595 10596 // In some error cases we want to convey more info back to the observer 10597 String origPackage; 10598 String origPermission; 10599 } 10600 10601 /* 10602 * Install a non-existing package. 10603 */ 10604 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10605 UserHandle user, String installerPackageName, String volumeUuid, 10606 PackageInstalledInfo res) { 10607 // Remember this for later, in case we need to rollback this install 10608 String pkgName = pkg.packageName; 10609 10610 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10611 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10612 synchronized(mPackages) { 10613 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10614 // A package with the same name is already installed, though 10615 // it has been renamed to an older name. The package we 10616 // are trying to install should be installed as an update to 10617 // the existing one, but that has not been requested, so bail. 10618 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10619 + " without first uninstalling package running as " 10620 + mSettings.mRenamedPackages.get(pkgName)); 10621 return; 10622 } 10623 if (mPackages.containsKey(pkgName)) { 10624 // Don't allow installation over an existing package with the same name. 10625 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10626 + " without first uninstalling."); 10627 return; 10628 } 10629 } 10630 10631 try { 10632 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10633 System.currentTimeMillis(), user); 10634 10635 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10636 // delete the partially installed application. the data directory will have to be 10637 // restored if it was already existing 10638 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10639 // remove package from internal structures. Note that we want deletePackageX to 10640 // delete the package data and cache directories that it created in 10641 // scanPackageLocked, unless those directories existed before we even tried to 10642 // install. 10643 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10644 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10645 res.removedInfo, true); 10646 } 10647 10648 } catch (PackageManagerException e) { 10649 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10650 } 10651 } 10652 10653 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10654 // Upgrade keysets are being used. Determine if new package has a superset of the 10655 // required keys. 10656 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10657 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10658 for (int i = 0; i < upgradeKeySets.length; i++) { 10659 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10660 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10661 return true; 10662 } 10663 } 10664 return false; 10665 } 10666 10667 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10668 UserHandle user, String installerPackageName, String volumeUuid, 10669 PackageInstalledInfo res) { 10670 PackageParser.Package oldPackage; 10671 String pkgName = pkg.packageName; 10672 int[] allUsers; 10673 boolean[] perUserInstalled; 10674 10675 // First find the old package info and check signatures 10676 synchronized(mPackages) { 10677 oldPackage = mPackages.get(pkgName); 10678 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10679 PackageSetting ps = mSettings.mPackages.get(pkgName); 10680 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10681 // default to original signature matching 10682 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10683 != PackageManager.SIGNATURE_MATCH) { 10684 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10685 "New package has a different signature: " + pkgName); 10686 return; 10687 } 10688 } else { 10689 if(!checkUpgradeKeySetLP(ps, pkg)) { 10690 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10691 "New package not signed by keys specified by upgrade-keysets: " 10692 + pkgName); 10693 return; 10694 } 10695 } 10696 10697 // In case of rollback, remember per-user/profile install state 10698 allUsers = sUserManager.getUserIds(); 10699 perUserInstalled = new boolean[allUsers.length]; 10700 for (int i = 0; i < allUsers.length; i++) { 10701 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10702 } 10703 } 10704 10705 boolean sysPkg = (isSystemApp(oldPackage)); 10706 if (sysPkg) { 10707 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10708 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10709 } else { 10710 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10711 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10712 } 10713 } 10714 10715 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10716 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10717 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10718 String volumeUuid, PackageInstalledInfo res) { 10719 String pkgName = deletedPackage.packageName; 10720 boolean deletedPkg = true; 10721 boolean updatedSettings = false; 10722 10723 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10724 + deletedPackage); 10725 long origUpdateTime; 10726 if (pkg.mExtras != null) { 10727 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10728 } else { 10729 origUpdateTime = 0; 10730 } 10731 10732 // First delete the existing package while retaining the data directory 10733 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10734 res.removedInfo, true)) { 10735 // If the existing package wasn't successfully deleted 10736 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10737 deletedPkg = false; 10738 } else { 10739 // Successfully deleted the old package; proceed with replace. 10740 10741 // If deleted package lived in a container, give users a chance to 10742 // relinquish resources before killing. 10743 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10744 if (DEBUG_INSTALL) { 10745 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10746 } 10747 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10748 final ArrayList<String> pkgList = new ArrayList<String>(1); 10749 pkgList.add(deletedPackage.applicationInfo.packageName); 10750 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10751 } 10752 10753 deleteCodeCacheDirsLI(pkgName); 10754 try { 10755 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10756 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10757 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10758 perUserInstalled, res, user); 10759 updatedSettings = true; 10760 } catch (PackageManagerException e) { 10761 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10762 } 10763 } 10764 10765 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10766 // remove package from internal structures. Note that we want deletePackageX to 10767 // delete the package data and cache directories that it created in 10768 // scanPackageLocked, unless those directories existed before we even tried to 10769 // install. 10770 if(updatedSettings) { 10771 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10772 deletePackageLI( 10773 pkgName, null, true, allUsers, perUserInstalled, 10774 PackageManager.DELETE_KEEP_DATA, 10775 res.removedInfo, true); 10776 } 10777 // Since we failed to install the new package we need to restore the old 10778 // package that we deleted. 10779 if (deletedPkg) { 10780 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10781 File restoreFile = new File(deletedPackage.codePath); 10782 // Parse old package 10783 boolean oldExternal = isExternal(deletedPackage); 10784 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10785 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10786 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10787 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10788 try { 10789 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10790 } catch (PackageManagerException e) { 10791 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10792 + e.getMessage()); 10793 return; 10794 } 10795 // Restore of old package succeeded. Update permissions. 10796 // writer 10797 synchronized (mPackages) { 10798 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10799 UPDATE_PERMISSIONS_ALL); 10800 // can downgrade to reader 10801 mSettings.writeLPr(); 10802 } 10803 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10804 } 10805 } 10806 } 10807 10808 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10809 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10810 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10811 String volumeUuid, PackageInstalledInfo res) { 10812 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10813 + ", old=" + deletedPackage); 10814 boolean disabledSystem = false; 10815 boolean updatedSettings = false; 10816 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10817 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10818 != 0) { 10819 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10820 } 10821 String packageName = deletedPackage.packageName; 10822 if (packageName == null) { 10823 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10824 "Attempt to delete null packageName."); 10825 return; 10826 } 10827 PackageParser.Package oldPkg; 10828 PackageSetting oldPkgSetting; 10829 // reader 10830 synchronized (mPackages) { 10831 oldPkg = mPackages.get(packageName); 10832 oldPkgSetting = mSettings.mPackages.get(packageName); 10833 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10834 (oldPkgSetting == null)) { 10835 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10836 "Couldn't find package:" + packageName + " information"); 10837 return; 10838 } 10839 } 10840 10841 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10842 10843 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10844 res.removedInfo.removedPackage = packageName; 10845 // Remove existing system package 10846 removePackageLI(oldPkgSetting, true); 10847 // writer 10848 synchronized (mPackages) { 10849 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10850 if (!disabledSystem && deletedPackage != null) { 10851 // We didn't need to disable the .apk as a current system package, 10852 // which means we are replacing another update that is already 10853 // installed. We need to make sure to delete the older one's .apk. 10854 res.removedInfo.args = createInstallArgsForExisting(0, 10855 deletedPackage.applicationInfo.getCodePath(), 10856 deletedPackage.applicationInfo.getResourcePath(), 10857 deletedPackage.applicationInfo.nativeLibraryRootDir, 10858 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10859 } else { 10860 res.removedInfo.args = null; 10861 } 10862 } 10863 10864 // Successfully disabled the old package. Now proceed with re-installation 10865 deleteCodeCacheDirsLI(packageName); 10866 10867 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10868 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10869 10870 PackageParser.Package newPackage = null; 10871 try { 10872 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10873 if (newPackage.mExtras != null) { 10874 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10875 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10876 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10877 10878 // is the update attempting to change shared user? that isn't going to work... 10879 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10880 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10881 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10882 + " to " + newPkgSetting.sharedUser); 10883 updatedSettings = true; 10884 } 10885 } 10886 10887 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10888 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10889 perUserInstalled, res, user); 10890 updatedSettings = true; 10891 } 10892 10893 } catch (PackageManagerException e) { 10894 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10895 } 10896 10897 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10898 // Re installation failed. Restore old information 10899 // Remove new pkg information 10900 if (newPackage != null) { 10901 removeInstalledPackageLI(newPackage, true); 10902 } 10903 // Add back the old system package 10904 try { 10905 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10906 } catch (PackageManagerException e) { 10907 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10908 } 10909 // Restore the old system information in Settings 10910 synchronized (mPackages) { 10911 if (disabledSystem) { 10912 mSettings.enableSystemPackageLPw(packageName); 10913 } 10914 if (updatedSettings) { 10915 mSettings.setInstallerPackageName(packageName, 10916 oldPkgSetting.installerPackageName); 10917 } 10918 mSettings.writeLPr(); 10919 } 10920 } 10921 } 10922 10923 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10924 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10925 UserHandle user) { 10926 String pkgName = newPackage.packageName; 10927 synchronized (mPackages) { 10928 //write settings. the installStatus will be incomplete at this stage. 10929 //note that the new package setting would have already been 10930 //added to mPackages. It hasn't been persisted yet. 10931 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10932 mSettings.writeLPr(); 10933 } 10934 10935 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10936 10937 synchronized (mPackages) { 10938 updatePermissionsLPw(newPackage.packageName, newPackage, 10939 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10940 ? UPDATE_PERMISSIONS_ALL : 0)); 10941 // For system-bundled packages, we assume that installing an upgraded version 10942 // of the package implies that the user actually wants to run that new code, 10943 // so we enable the package. 10944 PackageSetting ps = mSettings.mPackages.get(pkgName); 10945 if (ps != null) { 10946 if (isSystemApp(newPackage)) { 10947 // NB: implicit assumption that system package upgrades apply to all users 10948 if (DEBUG_INSTALL) { 10949 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10950 } 10951 if (res.origUsers != null) { 10952 for (int userHandle : res.origUsers) { 10953 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10954 userHandle, installerPackageName); 10955 } 10956 } 10957 // Also convey the prior install/uninstall state 10958 if (allUsers != null && perUserInstalled != null) { 10959 for (int i = 0; i < allUsers.length; i++) { 10960 if (DEBUG_INSTALL) { 10961 Slog.d(TAG, " user " + allUsers[i] 10962 + " => " + perUserInstalled[i]); 10963 } 10964 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10965 } 10966 // these install state changes will be persisted in the 10967 // upcoming call to mSettings.writeLPr(). 10968 } 10969 } 10970 // It's implied that when a user requests installation, they want the app to be 10971 // installed and enabled. 10972 int userId = user.getIdentifier(); 10973 if (userId != UserHandle.USER_ALL) { 10974 ps.setInstalled(true, userId); 10975 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10976 } 10977 } 10978 res.name = pkgName; 10979 res.uid = newPackage.applicationInfo.uid; 10980 res.pkg = newPackage; 10981 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10982 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10983 mSettings.setVolumeUuid(pkgName, volumeUuid); 10984 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10985 //to update install status 10986 mSettings.writeLPr(); 10987 } 10988 } 10989 10990 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10991 final int installFlags = args.installFlags; 10992 final String installerPackageName = args.installerPackageName; 10993 final String volumeUuid = args.volumeUuid; 10994 final File tmpPackageFile = new File(args.getCodePath()); 10995 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10996 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 10997 || (args.volumeUuid != null)); 10998 boolean replace = false; 10999 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11000 // Result object to be returned 11001 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11002 11003 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11004 // Retrieve PackageSettings and parse package 11005 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11006 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11007 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11008 PackageParser pp = new PackageParser(); 11009 pp.setSeparateProcesses(mSeparateProcesses); 11010 pp.setDisplayMetrics(mMetrics); 11011 11012 final PackageParser.Package pkg; 11013 try { 11014 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11015 } catch (PackageParserException e) { 11016 res.setError("Failed parse during installPackageLI", e); 11017 return; 11018 } 11019 11020 // Mark that we have an install time CPU ABI override. 11021 pkg.cpuAbiOverride = args.abiOverride; 11022 11023 String pkgName = res.name = pkg.packageName; 11024 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11025 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11026 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11027 return; 11028 } 11029 } 11030 11031 try { 11032 pp.collectCertificates(pkg, parseFlags); 11033 pp.collectManifestDigest(pkg); 11034 } catch (PackageParserException e) { 11035 res.setError("Failed collect during installPackageLI", e); 11036 return; 11037 } 11038 11039 /* If the installer passed in a manifest digest, compare it now. */ 11040 if (args.manifestDigest != null) { 11041 if (DEBUG_INSTALL) { 11042 final String parsedManifest = pkg.manifestDigest == null ? "null" 11043 : pkg.manifestDigest.toString(); 11044 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11045 + parsedManifest); 11046 } 11047 11048 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11049 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11050 return; 11051 } 11052 } else if (DEBUG_INSTALL) { 11053 final String parsedManifest = pkg.manifestDigest == null 11054 ? "null" : pkg.manifestDigest.toString(); 11055 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11056 } 11057 11058 // Get rid of all references to package scan path via parser. 11059 pp = null; 11060 String oldCodePath = null; 11061 boolean systemApp = false; 11062 synchronized (mPackages) { 11063 // Check if installing already existing package 11064 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11065 String oldName = mSettings.mRenamedPackages.get(pkgName); 11066 if (pkg.mOriginalPackages != null 11067 && pkg.mOriginalPackages.contains(oldName) 11068 && mPackages.containsKey(oldName)) { 11069 // This package is derived from an original package, 11070 // and this device has been updating from that original 11071 // name. We must continue using the original name, so 11072 // rename the new package here. 11073 pkg.setPackageName(oldName); 11074 pkgName = pkg.packageName; 11075 replace = true; 11076 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11077 + oldName + " pkgName=" + pkgName); 11078 } else if (mPackages.containsKey(pkgName)) { 11079 // This package, under its official name, already exists 11080 // on the device; we should replace it. 11081 replace = true; 11082 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11083 } 11084 } 11085 11086 PackageSetting ps = mSettings.mPackages.get(pkgName); 11087 if (ps != null) { 11088 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11089 11090 // Quick sanity check that we're signed correctly if updating; 11091 // we'll check this again later when scanning, but we want to 11092 // bail early here before tripping over redefined permissions. 11093 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11094 try { 11095 verifySignaturesLP(ps, pkg); 11096 } catch (PackageManagerException e) { 11097 res.setError(e.error, e.getMessage()); 11098 return; 11099 } 11100 } else { 11101 if (!checkUpgradeKeySetLP(ps, pkg)) { 11102 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11103 + pkg.packageName + " upgrade keys do not match the " 11104 + "previously installed version"); 11105 return; 11106 } 11107 } 11108 11109 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11110 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11111 systemApp = (ps.pkg.applicationInfo.flags & 11112 ApplicationInfo.FLAG_SYSTEM) != 0; 11113 } 11114 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11115 } 11116 11117 // Check whether the newly-scanned package wants to define an already-defined perm 11118 int N = pkg.permissions.size(); 11119 for (int i = N-1; i >= 0; i--) { 11120 PackageParser.Permission perm = pkg.permissions.get(i); 11121 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11122 if (bp != null) { 11123 // If the defining package is signed with our cert, it's okay. This 11124 // also includes the "updating the same package" case, of course. 11125 // "updating same package" could also involve key-rotation. 11126 final boolean sigsOk; 11127 if (!bp.sourcePackage.equals(pkg.packageName) 11128 || !(bp.packageSetting instanceof PackageSetting) 11129 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11130 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11131 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11132 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11133 } else { 11134 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11135 } 11136 if (!sigsOk) { 11137 // If the owning package is the system itself, we log but allow 11138 // install to proceed; we fail the install on all other permission 11139 // redefinitions. 11140 if (!bp.sourcePackage.equals("android")) { 11141 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11142 + pkg.packageName + " attempting to redeclare permission " 11143 + perm.info.name + " already owned by " + bp.sourcePackage); 11144 res.origPermission = perm.info.name; 11145 res.origPackage = bp.sourcePackage; 11146 return; 11147 } else { 11148 Slog.w(TAG, "Package " + pkg.packageName 11149 + " attempting to redeclare system permission " 11150 + perm.info.name + "; ignoring new declaration"); 11151 pkg.permissions.remove(i); 11152 } 11153 } 11154 } 11155 } 11156 11157 } 11158 11159 if (systemApp && onExternal) { 11160 // Disable updates to system apps on sdcard 11161 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11162 "Cannot install updates to system apps on sdcard"); 11163 return; 11164 } 11165 11166 // Run dexopt before old package gets removed, to minimize time when app is not available 11167 int result = mPackageDexOptimizer 11168 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11169 false /* defer */, false /* inclDependencies */); 11170 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11171 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11172 return; 11173 } 11174 11175 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11176 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11177 return; 11178 } 11179 11180 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11181 11182 // Call with SCAN_NO_DEX, since dexopt has already been made 11183 if (replace) { 11184 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11185 installerPackageName, volumeUuid, res); 11186 } else { 11187 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES 11188 | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res); 11189 } 11190 synchronized (mPackages) { 11191 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11192 if (ps != null) { 11193 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11194 } 11195 } 11196 } 11197 11198 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11199 if (mIntentFilterVerifierComponent == null) { 11200 Slog.d(TAG, "No IntentFilter verification will not be done as " 11201 + "there is no IntentFilterVerifier available!"); 11202 return; 11203 } 11204 11205 final int verifierUid = getPackageUid( 11206 mIntentFilterVerifierComponent.getPackageName(), 11207 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11208 11209 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11210 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11211 msg.obj = pkg; 11212 msg.arg1 = userId; 11213 msg.arg2 = verifierUid; 11214 11215 mHandler.sendMessage(msg); 11216 } 11217 11218 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11219 PackageParser.Package pkg) { 11220 int size = pkg.activities.size(); 11221 if (size == 0) { 11222 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11223 return; 11224 } 11225 11226 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11227 + " Activities needs verification ..."); 11228 11229 final int verificationId = mIntentFilterVerificationToken++; 11230 int count = 0; 11231 final String packageName = pkg.packageName; 11232 ArrayList<String> allHosts = new ArrayList<>(); 11233 synchronized (mPackages) { 11234 for (PackageParser.Activity a : pkg.activities) { 11235 for (ActivityIntentInfo filter : a.intents) { 11236 boolean needFilterVerification = filter.needsVerification() && 11237 !filter.isVerified(); 11238 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11239 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11240 mIntentFilterVerifier.addOneIntentFilterVerification( 11241 verifierUid, userId, verificationId, filter, packageName); 11242 count++; 11243 } else { 11244 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11245 ArrayList<String> list = filter.getHostsList(); 11246 if (hasValidHosts(list)) { 11247 allHosts.addAll(list); 11248 } 11249 } 11250 } 11251 } 11252 } 11253 11254 if (count > 0) { 11255 mIntentFilterVerifier.startVerifications(userId); 11256 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11257 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11258 } else { 11259 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11260 if (allHosts.size() > 0 && hasDomainURLs(pkg) && 11261 mSettings.createIntentFilterVerificationIfNeededLPw( 11262 packageName, allHosts)) { 11263 scheduleWriteSettingsLocked(); 11264 } 11265 } 11266 } 11267 11268 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11269 final ComponentName cn = filter.activity.getComponentName(); 11270 final String packageName = cn.getPackageName(); 11271 11272 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11273 packageName); 11274 if (ivi == null) { 11275 return true; 11276 } 11277 int status = ivi.getStatus(); 11278 switch (status) { 11279 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11280 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11281 return true; 11282 11283 default: 11284 // Nothing to do 11285 return false; 11286 } 11287 } 11288 11289 private static boolean isMultiArch(PackageSetting ps) { 11290 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11291 } 11292 11293 private static boolean isMultiArch(ApplicationInfo info) { 11294 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11295 } 11296 11297 private static boolean isExternal(PackageParser.Package pkg) { 11298 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11299 } 11300 11301 private static boolean isExternal(PackageSetting ps) { 11302 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11303 } 11304 11305 private static boolean isExternal(ApplicationInfo info) { 11306 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11307 } 11308 11309 private static boolean isSystemApp(PackageParser.Package pkg) { 11310 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11311 } 11312 11313 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11314 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11315 } 11316 11317 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11318 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11319 } 11320 11321 private static boolean isSystemApp(PackageSetting ps) { 11322 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11323 } 11324 11325 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11326 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11327 } 11328 11329 private int packageFlagsToInstallFlags(PackageSetting ps) { 11330 int installFlags = 0; 11331 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11332 // This existing package was an external ASEC install when we have 11333 // the external flag without a UUID 11334 installFlags |= PackageManager.INSTALL_EXTERNAL; 11335 } 11336 if (ps.isForwardLocked()) { 11337 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11338 } 11339 return installFlags; 11340 } 11341 11342 private void deleteTempPackageFiles() { 11343 final FilenameFilter filter = new FilenameFilter() { 11344 public boolean accept(File dir, String name) { 11345 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11346 } 11347 }; 11348 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11349 file.delete(); 11350 } 11351 } 11352 11353 @Override 11354 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11355 int flags) { 11356 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11357 flags); 11358 } 11359 11360 @Override 11361 public void deletePackage(final String packageName, 11362 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11363 mContext.enforceCallingOrSelfPermission( 11364 android.Manifest.permission.DELETE_PACKAGES, null); 11365 final int uid = Binder.getCallingUid(); 11366 if (UserHandle.getUserId(uid) != userId) { 11367 mContext.enforceCallingPermission( 11368 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11369 "deletePackage for user " + userId); 11370 } 11371 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11372 try { 11373 observer.onPackageDeleted(packageName, 11374 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11375 } catch (RemoteException re) { 11376 } 11377 return; 11378 } 11379 11380 boolean uninstallBlocked = false; 11381 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11382 int[] users = sUserManager.getUserIds(); 11383 for (int i = 0; i < users.length; ++i) { 11384 if (getBlockUninstallForUser(packageName, users[i])) { 11385 uninstallBlocked = true; 11386 break; 11387 } 11388 } 11389 } else { 11390 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11391 } 11392 if (uninstallBlocked) { 11393 try { 11394 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11395 null); 11396 } catch (RemoteException re) { 11397 } 11398 return; 11399 } 11400 11401 if (DEBUG_REMOVE) { 11402 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11403 } 11404 // Queue up an async operation since the package deletion may take a little while. 11405 mHandler.post(new Runnable() { 11406 public void run() { 11407 mHandler.removeCallbacks(this); 11408 final int returnCode = deletePackageX(packageName, userId, flags); 11409 if (observer != null) { 11410 try { 11411 observer.onPackageDeleted(packageName, returnCode, null); 11412 } catch (RemoteException e) { 11413 Log.i(TAG, "Observer no longer exists."); 11414 } //end catch 11415 } //end if 11416 } //end run 11417 }); 11418 } 11419 11420 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11421 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11422 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11423 try { 11424 if (dpm != null) { 11425 if (dpm.isDeviceOwner(packageName)) { 11426 return true; 11427 } 11428 int[] users; 11429 if (userId == UserHandle.USER_ALL) { 11430 users = sUserManager.getUserIds(); 11431 } else { 11432 users = new int[]{userId}; 11433 } 11434 for (int i = 0; i < users.length; ++i) { 11435 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11436 return true; 11437 } 11438 } 11439 } 11440 } catch (RemoteException e) { 11441 } 11442 return false; 11443 } 11444 11445 /** 11446 * This method is an internal method that could be get invoked either 11447 * to delete an installed package or to clean up a failed installation. 11448 * After deleting an installed package, a broadcast is sent to notify any 11449 * listeners that the package has been installed. For cleaning up a failed 11450 * installation, the broadcast is not necessary since the package's 11451 * installation wouldn't have sent the initial broadcast either 11452 * The key steps in deleting a package are 11453 * deleting the package information in internal structures like mPackages, 11454 * deleting the packages base directories through installd 11455 * updating mSettings to reflect current status 11456 * persisting settings for later use 11457 * sending a broadcast if necessary 11458 */ 11459 private int deletePackageX(String packageName, int userId, int flags) { 11460 final PackageRemovedInfo info = new PackageRemovedInfo(); 11461 final boolean res; 11462 11463 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11464 ? UserHandle.ALL : new UserHandle(userId); 11465 11466 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11467 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11468 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11469 } 11470 11471 boolean removedForAllUsers = false; 11472 boolean systemUpdate = false; 11473 11474 // for the uninstall-updates case and restricted profiles, remember the per- 11475 // userhandle installed state 11476 int[] allUsers; 11477 boolean[] perUserInstalled; 11478 synchronized (mPackages) { 11479 PackageSetting ps = mSettings.mPackages.get(packageName); 11480 allUsers = sUserManager.getUserIds(); 11481 perUserInstalled = new boolean[allUsers.length]; 11482 for (int i = 0; i < allUsers.length; i++) { 11483 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11484 } 11485 } 11486 11487 synchronized (mInstallLock) { 11488 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11489 res = deletePackageLI(packageName, removeForUser, 11490 true, allUsers, perUserInstalled, 11491 flags | REMOVE_CHATTY, info, true); 11492 systemUpdate = info.isRemovedPackageSystemUpdate; 11493 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11494 removedForAllUsers = true; 11495 } 11496 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11497 + " removedForAllUsers=" + removedForAllUsers); 11498 } 11499 11500 if (res) { 11501 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11502 11503 // If the removed package was a system update, the old system package 11504 // was re-enabled; we need to broadcast this information 11505 if (systemUpdate) { 11506 Bundle extras = new Bundle(1); 11507 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11508 ? info.removedAppId : info.uid); 11509 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11510 11511 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11512 extras, null, null, null); 11513 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11514 extras, null, null, null); 11515 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11516 null, packageName, null, null); 11517 } 11518 } 11519 // Force a gc here. 11520 Runtime.getRuntime().gc(); 11521 // Delete the resources here after sending the broadcast to let 11522 // other processes clean up before deleting resources. 11523 if (info.args != null) { 11524 synchronized (mInstallLock) { 11525 info.args.doPostDeleteLI(true); 11526 } 11527 } 11528 11529 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11530 } 11531 11532 static class PackageRemovedInfo { 11533 String removedPackage; 11534 int uid = -1; 11535 int removedAppId = -1; 11536 int[] removedUsers = null; 11537 boolean isRemovedPackageSystemUpdate = false; 11538 // Clean up resources deleted packages. 11539 InstallArgs args = null; 11540 11541 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11542 Bundle extras = new Bundle(1); 11543 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11544 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11545 if (replacing) { 11546 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11547 } 11548 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11549 if (removedPackage != null) { 11550 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11551 extras, null, null, removedUsers); 11552 if (fullRemove && !replacing) { 11553 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11554 extras, null, null, removedUsers); 11555 } 11556 } 11557 if (removedAppId >= 0) { 11558 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11559 removedUsers); 11560 } 11561 } 11562 } 11563 11564 /* 11565 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11566 * flag is not set, the data directory is removed as well. 11567 * make sure this flag is set for partially installed apps. If not its meaningless to 11568 * delete a partially installed application. 11569 */ 11570 private void removePackageDataLI(PackageSetting ps, 11571 int[] allUserHandles, boolean[] perUserInstalled, 11572 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11573 String packageName = ps.name; 11574 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11575 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11576 // Retrieve object to delete permissions for shared user later on 11577 final PackageSetting deletedPs; 11578 // reader 11579 synchronized (mPackages) { 11580 deletedPs = mSettings.mPackages.get(packageName); 11581 if (outInfo != null) { 11582 outInfo.removedPackage = packageName; 11583 outInfo.removedUsers = deletedPs != null 11584 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11585 : null; 11586 } 11587 } 11588 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11589 removeDataDirsLI(packageName); 11590 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11591 } 11592 // writer 11593 synchronized (mPackages) { 11594 if (deletedPs != null) { 11595 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11596 if (outInfo != null) { 11597 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11598 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11599 } 11600 updatePermissionsLPw(deletedPs.name, null, 0); 11601 if (deletedPs.sharedUser != null) { 11602 // Remove permissions associated with package. Since runtime 11603 // permissions are per user we have to kill the removed package 11604 // or packages running under the shared user of the removed 11605 // package if revoking the permissions requested only by the removed 11606 // package is successful and this causes a change in gids. 11607 for (int userId : UserManagerService.getInstance().getUserIds()) { 11608 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11609 userId); 11610 if (userIdToKill == UserHandle.USER_ALL 11611 || userIdToKill >= UserHandle.USER_OWNER) { 11612 // If gids changed for this user, kill all affected packages. 11613 mHandler.post(new Runnable() { 11614 @Override 11615 public void run() { 11616 // This has to happen with no lock held. 11617 killSettingPackagesForUser(deletedPs, userIdToKill, 11618 KILL_APP_REASON_GIDS_CHANGED); 11619 } 11620 }); 11621 break; 11622 } 11623 } 11624 } 11625 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11626 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11627 } 11628 // make sure to preserve per-user disabled state if this removal was just 11629 // a downgrade of a system app to the factory package 11630 if (allUserHandles != null && perUserInstalled != null) { 11631 if (DEBUG_REMOVE) { 11632 Slog.d(TAG, "Propagating install state across downgrade"); 11633 } 11634 for (int i = 0; i < allUserHandles.length; i++) { 11635 if (DEBUG_REMOVE) { 11636 Slog.d(TAG, " user " + allUserHandles[i] 11637 + " => " + perUserInstalled[i]); 11638 } 11639 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11640 } 11641 } 11642 } 11643 // can downgrade to reader 11644 if (writeSettings) { 11645 // Save settings now 11646 mSettings.writeLPr(); 11647 } 11648 } 11649 if (outInfo != null) { 11650 // A user ID was deleted here. Go through all users and remove it 11651 // from KeyStore. 11652 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11653 } 11654 } 11655 11656 static boolean locationIsPrivileged(File path) { 11657 try { 11658 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11659 .getCanonicalPath(); 11660 return path.getCanonicalPath().startsWith(privilegedAppDir); 11661 } catch (IOException e) { 11662 Slog.e(TAG, "Unable to access code path " + path); 11663 } 11664 return false; 11665 } 11666 11667 /* 11668 * Tries to delete system package. 11669 */ 11670 private boolean deleteSystemPackageLI(PackageSetting newPs, 11671 int[] allUserHandles, boolean[] perUserInstalled, 11672 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11673 final boolean applyUserRestrictions 11674 = (allUserHandles != null) && (perUserInstalled != null); 11675 PackageSetting disabledPs = null; 11676 // Confirm if the system package has been updated 11677 // An updated system app can be deleted. This will also have to restore 11678 // the system pkg from system partition 11679 // reader 11680 synchronized (mPackages) { 11681 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11682 } 11683 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11684 + " disabledPs=" + disabledPs); 11685 if (disabledPs == null) { 11686 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11687 return false; 11688 } else if (DEBUG_REMOVE) { 11689 Slog.d(TAG, "Deleting system pkg from data partition"); 11690 } 11691 if (DEBUG_REMOVE) { 11692 if (applyUserRestrictions) { 11693 Slog.d(TAG, "Remembering install states:"); 11694 for (int i = 0; i < allUserHandles.length; i++) { 11695 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11696 } 11697 } 11698 } 11699 // Delete the updated package 11700 outInfo.isRemovedPackageSystemUpdate = true; 11701 if (disabledPs.versionCode < newPs.versionCode) { 11702 // Delete data for downgrades 11703 flags &= ~PackageManager.DELETE_KEEP_DATA; 11704 } else { 11705 // Preserve data by setting flag 11706 flags |= PackageManager.DELETE_KEEP_DATA; 11707 } 11708 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11709 allUserHandles, perUserInstalled, outInfo, writeSettings); 11710 if (!ret) { 11711 return false; 11712 } 11713 // writer 11714 synchronized (mPackages) { 11715 // Reinstate the old system package 11716 mSettings.enableSystemPackageLPw(newPs.name); 11717 // Remove any native libraries from the upgraded package. 11718 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11719 } 11720 // Install the system package 11721 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11722 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11723 if (locationIsPrivileged(disabledPs.codePath)) { 11724 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11725 } 11726 11727 final PackageParser.Package newPkg; 11728 try { 11729 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11730 } catch (PackageManagerException e) { 11731 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11732 return false; 11733 } 11734 11735 // writer 11736 synchronized (mPackages) { 11737 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11738 updatePermissionsLPw(newPkg.packageName, newPkg, 11739 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11740 if (applyUserRestrictions) { 11741 if (DEBUG_REMOVE) { 11742 Slog.d(TAG, "Propagating install state across reinstall"); 11743 } 11744 for (int i = 0; i < allUserHandles.length; i++) { 11745 if (DEBUG_REMOVE) { 11746 Slog.d(TAG, " user " + allUserHandles[i] 11747 + " => " + perUserInstalled[i]); 11748 } 11749 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11750 } 11751 // Regardless of writeSettings we need to ensure that this restriction 11752 // state propagation is persisted 11753 mSettings.writeAllUsersPackageRestrictionsLPr(); 11754 } 11755 // can downgrade to reader here 11756 if (writeSettings) { 11757 mSettings.writeLPr(); 11758 } 11759 } 11760 return true; 11761 } 11762 11763 private boolean deleteInstalledPackageLI(PackageSetting ps, 11764 boolean deleteCodeAndResources, int flags, 11765 int[] allUserHandles, boolean[] perUserInstalled, 11766 PackageRemovedInfo outInfo, boolean writeSettings) { 11767 if (outInfo != null) { 11768 outInfo.uid = ps.appId; 11769 } 11770 11771 // Delete package data from internal structures and also remove data if flag is set 11772 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11773 11774 // Delete application code and resources 11775 if (deleteCodeAndResources && (outInfo != null)) { 11776 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11777 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11778 getAppDexInstructionSets(ps)); 11779 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11780 } 11781 return true; 11782 } 11783 11784 @Override 11785 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11786 int userId) { 11787 mContext.enforceCallingOrSelfPermission( 11788 android.Manifest.permission.DELETE_PACKAGES, null); 11789 synchronized (mPackages) { 11790 PackageSetting ps = mSettings.mPackages.get(packageName); 11791 if (ps == null) { 11792 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11793 return false; 11794 } 11795 if (!ps.getInstalled(userId)) { 11796 // Can't block uninstall for an app that is not installed or enabled. 11797 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11798 return false; 11799 } 11800 ps.setBlockUninstall(blockUninstall, userId); 11801 mSettings.writePackageRestrictionsLPr(userId); 11802 } 11803 return true; 11804 } 11805 11806 @Override 11807 public boolean getBlockUninstallForUser(String packageName, int userId) { 11808 synchronized (mPackages) { 11809 PackageSetting ps = mSettings.mPackages.get(packageName); 11810 if (ps == null) { 11811 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11812 return false; 11813 } 11814 return ps.getBlockUninstall(userId); 11815 } 11816 } 11817 11818 /* 11819 * This method handles package deletion in general 11820 */ 11821 private boolean deletePackageLI(String packageName, UserHandle user, 11822 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11823 int flags, PackageRemovedInfo outInfo, 11824 boolean writeSettings) { 11825 if (packageName == null) { 11826 Slog.w(TAG, "Attempt to delete null packageName."); 11827 return false; 11828 } 11829 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11830 PackageSetting ps; 11831 boolean dataOnly = false; 11832 int removeUser = -1; 11833 int appId = -1; 11834 synchronized (mPackages) { 11835 ps = mSettings.mPackages.get(packageName); 11836 if (ps == null) { 11837 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11838 return false; 11839 } 11840 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11841 && user.getIdentifier() != UserHandle.USER_ALL) { 11842 // The caller is asking that the package only be deleted for a single 11843 // user. To do this, we just mark its uninstalled state and delete 11844 // its data. If this is a system app, we only allow this to happen if 11845 // they have set the special DELETE_SYSTEM_APP which requests different 11846 // semantics than normal for uninstalling system apps. 11847 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11848 ps.setUserState(user.getIdentifier(), 11849 COMPONENT_ENABLED_STATE_DEFAULT, 11850 false, //installed 11851 true, //stopped 11852 true, //notLaunched 11853 false, //hidden 11854 null, null, null, 11855 false, // blockUninstall 11856 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11857 if (!isSystemApp(ps)) { 11858 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11859 // Other user still have this package installed, so all 11860 // we need to do is clear this user's data and save that 11861 // it is uninstalled. 11862 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11863 removeUser = user.getIdentifier(); 11864 appId = ps.appId; 11865 mSettings.writePackageRestrictionsLPr(removeUser); 11866 } else { 11867 // We need to set it back to 'installed' so the uninstall 11868 // broadcasts will be sent correctly. 11869 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11870 ps.setInstalled(true, user.getIdentifier()); 11871 } 11872 } else { 11873 // This is a system app, so we assume that the 11874 // other users still have this package installed, so all 11875 // we need to do is clear this user's data and save that 11876 // it is uninstalled. 11877 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11878 removeUser = user.getIdentifier(); 11879 appId = ps.appId; 11880 mSettings.writePackageRestrictionsLPr(removeUser); 11881 } 11882 } 11883 } 11884 11885 if (removeUser >= 0) { 11886 // From above, we determined that we are deleting this only 11887 // for a single user. Continue the work here. 11888 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11889 if (outInfo != null) { 11890 outInfo.removedPackage = packageName; 11891 outInfo.removedAppId = appId; 11892 outInfo.removedUsers = new int[] {removeUser}; 11893 } 11894 mInstaller.clearUserData(packageName, removeUser); 11895 removeKeystoreDataIfNeeded(removeUser, appId); 11896 schedulePackageCleaning(packageName, removeUser, false); 11897 return true; 11898 } 11899 11900 if (dataOnly) { 11901 // Delete application data first 11902 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11903 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11904 return true; 11905 } 11906 11907 boolean ret = false; 11908 if (isSystemApp(ps)) { 11909 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11910 // When an updated system application is deleted we delete the existing resources as well and 11911 // fall back to existing code in system partition 11912 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11913 flags, outInfo, writeSettings); 11914 } else { 11915 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11916 // Kill application pre-emptively especially for apps on sd. 11917 killApplication(packageName, ps.appId, "uninstall pkg"); 11918 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11919 allUserHandles, perUserInstalled, 11920 outInfo, writeSettings); 11921 } 11922 11923 return ret; 11924 } 11925 11926 private final class ClearStorageConnection implements ServiceConnection { 11927 IMediaContainerService mContainerService; 11928 11929 @Override 11930 public void onServiceConnected(ComponentName name, IBinder service) { 11931 synchronized (this) { 11932 mContainerService = IMediaContainerService.Stub.asInterface(service); 11933 notifyAll(); 11934 } 11935 } 11936 11937 @Override 11938 public void onServiceDisconnected(ComponentName name) { 11939 } 11940 } 11941 11942 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11943 final boolean mounted; 11944 if (Environment.isExternalStorageEmulated()) { 11945 mounted = true; 11946 } else { 11947 final String status = Environment.getExternalStorageState(); 11948 11949 mounted = status.equals(Environment.MEDIA_MOUNTED) 11950 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11951 } 11952 11953 if (!mounted) { 11954 return; 11955 } 11956 11957 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11958 int[] users; 11959 if (userId == UserHandle.USER_ALL) { 11960 users = sUserManager.getUserIds(); 11961 } else { 11962 users = new int[] { userId }; 11963 } 11964 final ClearStorageConnection conn = new ClearStorageConnection(); 11965 if (mContext.bindServiceAsUser( 11966 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11967 try { 11968 for (int curUser : users) { 11969 long timeout = SystemClock.uptimeMillis() + 5000; 11970 synchronized (conn) { 11971 long now = SystemClock.uptimeMillis(); 11972 while (conn.mContainerService == null && now < timeout) { 11973 try { 11974 conn.wait(timeout - now); 11975 } catch (InterruptedException e) { 11976 } 11977 } 11978 } 11979 if (conn.mContainerService == null) { 11980 return; 11981 } 11982 11983 final UserEnvironment userEnv = new UserEnvironment(curUser); 11984 clearDirectory(conn.mContainerService, 11985 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11986 if (allData) { 11987 clearDirectory(conn.mContainerService, 11988 userEnv.buildExternalStorageAppDataDirs(packageName)); 11989 clearDirectory(conn.mContainerService, 11990 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11991 } 11992 } 11993 } finally { 11994 mContext.unbindService(conn); 11995 } 11996 } 11997 } 11998 11999 @Override 12000 public void clearApplicationUserData(final String packageName, 12001 final IPackageDataObserver observer, final int userId) { 12002 mContext.enforceCallingOrSelfPermission( 12003 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12004 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12005 // Queue up an async operation since the package deletion may take a little while. 12006 mHandler.post(new Runnable() { 12007 public void run() { 12008 mHandler.removeCallbacks(this); 12009 final boolean succeeded; 12010 synchronized (mInstallLock) { 12011 succeeded = clearApplicationUserDataLI(packageName, userId); 12012 } 12013 clearExternalStorageDataSync(packageName, userId, true); 12014 if (succeeded) { 12015 // invoke DeviceStorageMonitor's update method to clear any notifications 12016 DeviceStorageMonitorInternal 12017 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12018 if (dsm != null) { 12019 dsm.checkMemory(); 12020 } 12021 } 12022 if(observer != null) { 12023 try { 12024 observer.onRemoveCompleted(packageName, succeeded); 12025 } catch (RemoteException e) { 12026 Log.i(TAG, "Observer no longer exists."); 12027 } 12028 } //end if observer 12029 } //end run 12030 }); 12031 } 12032 12033 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12034 if (packageName == null) { 12035 Slog.w(TAG, "Attempt to delete null packageName."); 12036 return false; 12037 } 12038 12039 // Try finding details about the requested package 12040 PackageParser.Package pkg; 12041 synchronized (mPackages) { 12042 pkg = mPackages.get(packageName); 12043 if (pkg == null) { 12044 final PackageSetting ps = mSettings.mPackages.get(packageName); 12045 if (ps != null) { 12046 pkg = ps.pkg; 12047 } 12048 } 12049 } 12050 12051 if (pkg == null) { 12052 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12053 } 12054 12055 // Always delete data directories for package, even if we found no other 12056 // record of app. This helps users recover from UID mismatches without 12057 // resorting to a full data wipe. 12058 int retCode = mInstaller.clearUserData(packageName, userId); 12059 if (retCode < 0) { 12060 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12061 return false; 12062 } 12063 12064 if (pkg == null) { 12065 return false; 12066 } 12067 12068 if (pkg != null && pkg.applicationInfo != null) { 12069 final int appId = pkg.applicationInfo.uid; 12070 removeKeystoreDataIfNeeded(userId, appId); 12071 } 12072 12073 // Create a native library symlink only if we have native libraries 12074 // and if the native libraries are 32 bit libraries. We do not provide 12075 // this symlink for 64 bit libraries. 12076 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12077 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12078 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12079 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12080 Slog.w(TAG, "Failed linking native library dir"); 12081 return false; 12082 } 12083 } 12084 12085 return true; 12086 } 12087 12088 /** 12089 * Remove entries from the keystore daemon. Will only remove it if the 12090 * {@code appId} is valid. 12091 */ 12092 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12093 if (appId < 0) { 12094 return; 12095 } 12096 12097 final KeyStore keyStore = KeyStore.getInstance(); 12098 if (keyStore != null) { 12099 if (userId == UserHandle.USER_ALL) { 12100 for (final int individual : sUserManager.getUserIds()) { 12101 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12102 } 12103 } else { 12104 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12105 } 12106 } else { 12107 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12108 } 12109 } 12110 12111 @Override 12112 public void deleteApplicationCacheFiles(final String packageName, 12113 final IPackageDataObserver observer) { 12114 mContext.enforceCallingOrSelfPermission( 12115 android.Manifest.permission.DELETE_CACHE_FILES, null); 12116 // Queue up an async operation since the package deletion may take a little while. 12117 final int userId = UserHandle.getCallingUserId(); 12118 mHandler.post(new Runnable() { 12119 public void run() { 12120 mHandler.removeCallbacks(this); 12121 final boolean succeded; 12122 synchronized (mInstallLock) { 12123 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12124 } 12125 clearExternalStorageDataSync(packageName, userId, false); 12126 if(observer != null) { 12127 try { 12128 observer.onRemoveCompleted(packageName, succeded); 12129 } catch (RemoteException e) { 12130 Log.i(TAG, "Observer no longer exists."); 12131 } 12132 } //end if observer 12133 } //end run 12134 }); 12135 } 12136 12137 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12138 if (packageName == null) { 12139 Slog.w(TAG, "Attempt to delete null packageName."); 12140 return false; 12141 } 12142 PackageParser.Package p; 12143 synchronized (mPackages) { 12144 p = mPackages.get(packageName); 12145 } 12146 if (p == null) { 12147 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12148 return false; 12149 } 12150 final ApplicationInfo applicationInfo = p.applicationInfo; 12151 if (applicationInfo == null) { 12152 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12153 return false; 12154 } 12155 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12156 if (retCode < 0) { 12157 Slog.w(TAG, "Couldn't remove cache files for package: " 12158 + packageName + " u" + userId); 12159 return false; 12160 } 12161 return true; 12162 } 12163 12164 @Override 12165 public void getPackageSizeInfo(final String packageName, int userHandle, 12166 final IPackageStatsObserver observer) { 12167 mContext.enforceCallingOrSelfPermission( 12168 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12169 if (packageName == null) { 12170 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12171 } 12172 12173 PackageStats stats = new PackageStats(packageName, userHandle); 12174 12175 /* 12176 * Queue up an async operation since the package measurement may take a 12177 * little while. 12178 */ 12179 Message msg = mHandler.obtainMessage(INIT_COPY); 12180 msg.obj = new MeasureParams(stats, observer); 12181 mHandler.sendMessage(msg); 12182 } 12183 12184 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12185 PackageStats pStats) { 12186 if (packageName == null) { 12187 Slog.w(TAG, "Attempt to get size of null packageName."); 12188 return false; 12189 } 12190 PackageParser.Package p; 12191 boolean dataOnly = false; 12192 String libDirRoot = null; 12193 String asecPath = null; 12194 PackageSetting ps = null; 12195 synchronized (mPackages) { 12196 p = mPackages.get(packageName); 12197 ps = mSettings.mPackages.get(packageName); 12198 if(p == null) { 12199 dataOnly = true; 12200 if((ps == null) || (ps.pkg == null)) { 12201 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12202 return false; 12203 } 12204 p = ps.pkg; 12205 } 12206 if (ps != null) { 12207 libDirRoot = ps.legacyNativeLibraryPathString; 12208 } 12209 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12210 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12211 if (secureContainerId != null) { 12212 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12213 } 12214 } 12215 } 12216 String publicSrcDir = null; 12217 if(!dataOnly) { 12218 final ApplicationInfo applicationInfo = p.applicationInfo; 12219 if (applicationInfo == null) { 12220 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12221 return false; 12222 } 12223 if (p.isForwardLocked()) { 12224 publicSrcDir = applicationInfo.getBaseResourcePath(); 12225 } 12226 } 12227 // TODO: extend to measure size of split APKs 12228 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12229 // not just the first level. 12230 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12231 // just the primary. 12232 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12233 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12234 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12235 if (res < 0) { 12236 return false; 12237 } 12238 12239 // Fix-up for forward-locked applications in ASEC containers. 12240 if (!isExternal(p)) { 12241 pStats.codeSize += pStats.externalCodeSize; 12242 pStats.externalCodeSize = 0L; 12243 } 12244 12245 return true; 12246 } 12247 12248 12249 @Override 12250 public void addPackageToPreferred(String packageName) { 12251 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12252 } 12253 12254 @Override 12255 public void removePackageFromPreferred(String packageName) { 12256 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12257 } 12258 12259 @Override 12260 public List<PackageInfo> getPreferredPackages(int flags) { 12261 return new ArrayList<PackageInfo>(); 12262 } 12263 12264 private int getUidTargetSdkVersionLockedLPr(int uid) { 12265 Object obj = mSettings.getUserIdLPr(uid); 12266 if (obj instanceof SharedUserSetting) { 12267 final SharedUserSetting sus = (SharedUserSetting) obj; 12268 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12269 final Iterator<PackageSetting> it = sus.packages.iterator(); 12270 while (it.hasNext()) { 12271 final PackageSetting ps = it.next(); 12272 if (ps.pkg != null) { 12273 int v = ps.pkg.applicationInfo.targetSdkVersion; 12274 if (v < vers) vers = v; 12275 } 12276 } 12277 return vers; 12278 } else if (obj instanceof PackageSetting) { 12279 final PackageSetting ps = (PackageSetting) obj; 12280 if (ps.pkg != null) { 12281 return ps.pkg.applicationInfo.targetSdkVersion; 12282 } 12283 } 12284 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12285 } 12286 12287 @Override 12288 public void addPreferredActivity(IntentFilter filter, int match, 12289 ComponentName[] set, ComponentName activity, int userId) { 12290 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12291 "Adding preferred"); 12292 } 12293 12294 private void addPreferredActivityInternal(IntentFilter filter, int match, 12295 ComponentName[] set, ComponentName activity, boolean always, int userId, 12296 String opname) { 12297 // writer 12298 int callingUid = Binder.getCallingUid(); 12299 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12300 if (filter.countActions() == 0) { 12301 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12302 return; 12303 } 12304 synchronized (mPackages) { 12305 if (mContext.checkCallingOrSelfPermission( 12306 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12307 != PackageManager.PERMISSION_GRANTED) { 12308 if (getUidTargetSdkVersionLockedLPr(callingUid) 12309 < Build.VERSION_CODES.FROYO) { 12310 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12311 + callingUid); 12312 return; 12313 } 12314 mContext.enforceCallingOrSelfPermission( 12315 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12316 } 12317 12318 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12319 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12320 + userId + ":"); 12321 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12322 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12323 scheduleWritePackageRestrictionsLocked(userId); 12324 } 12325 } 12326 12327 @Override 12328 public void replacePreferredActivity(IntentFilter filter, int match, 12329 ComponentName[] set, ComponentName activity, int userId) { 12330 if (filter.countActions() != 1) { 12331 throw new IllegalArgumentException( 12332 "replacePreferredActivity expects filter to have only 1 action."); 12333 } 12334 if (filter.countDataAuthorities() != 0 12335 || filter.countDataPaths() != 0 12336 || filter.countDataSchemes() > 1 12337 || filter.countDataTypes() != 0) { 12338 throw new IllegalArgumentException( 12339 "replacePreferredActivity expects filter to have no data authorities, " + 12340 "paths, or types; and at most one scheme."); 12341 } 12342 12343 final int callingUid = Binder.getCallingUid(); 12344 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12345 synchronized (mPackages) { 12346 if (mContext.checkCallingOrSelfPermission( 12347 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12348 != PackageManager.PERMISSION_GRANTED) { 12349 if (getUidTargetSdkVersionLockedLPr(callingUid) 12350 < Build.VERSION_CODES.FROYO) { 12351 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12352 + Binder.getCallingUid()); 12353 return; 12354 } 12355 mContext.enforceCallingOrSelfPermission( 12356 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12357 } 12358 12359 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12360 if (pir != null) { 12361 // Get all of the existing entries that exactly match this filter. 12362 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12363 if (existing != null && existing.size() == 1) { 12364 PreferredActivity cur = existing.get(0); 12365 if (DEBUG_PREFERRED) { 12366 Slog.i(TAG, "Checking replace of preferred:"); 12367 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12368 if (!cur.mPref.mAlways) { 12369 Slog.i(TAG, " -- CUR; not mAlways!"); 12370 } else { 12371 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12372 Slog.i(TAG, " -- CUR: mSet=" 12373 + Arrays.toString(cur.mPref.mSetComponents)); 12374 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12375 Slog.i(TAG, " -- NEW: mMatch=" 12376 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12377 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12378 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12379 } 12380 } 12381 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12382 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12383 && cur.mPref.sameSet(set)) { 12384 // Setting the preferred activity to what it happens to be already 12385 if (DEBUG_PREFERRED) { 12386 Slog.i(TAG, "Replacing with same preferred activity " 12387 + cur.mPref.mShortComponent + " for user " 12388 + userId + ":"); 12389 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12390 } 12391 return; 12392 } 12393 } 12394 12395 if (existing != null) { 12396 if (DEBUG_PREFERRED) { 12397 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12398 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12399 } 12400 for (int i = 0; i < existing.size(); i++) { 12401 PreferredActivity pa = existing.get(i); 12402 if (DEBUG_PREFERRED) { 12403 Slog.i(TAG, "Removing existing preferred activity " 12404 + pa.mPref.mComponent + ":"); 12405 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12406 } 12407 pir.removeFilter(pa); 12408 } 12409 } 12410 } 12411 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12412 "Replacing preferred"); 12413 } 12414 } 12415 12416 @Override 12417 public void clearPackagePreferredActivities(String packageName) { 12418 final int uid = Binder.getCallingUid(); 12419 // writer 12420 synchronized (mPackages) { 12421 PackageParser.Package pkg = mPackages.get(packageName); 12422 if (pkg == null || pkg.applicationInfo.uid != uid) { 12423 if (mContext.checkCallingOrSelfPermission( 12424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12425 != PackageManager.PERMISSION_GRANTED) { 12426 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12427 < Build.VERSION_CODES.FROYO) { 12428 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12429 + Binder.getCallingUid()); 12430 return; 12431 } 12432 mContext.enforceCallingOrSelfPermission( 12433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12434 } 12435 } 12436 12437 int user = UserHandle.getCallingUserId(); 12438 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12439 scheduleWritePackageRestrictionsLocked(user); 12440 } 12441 } 12442 } 12443 12444 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12445 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12446 ArrayList<PreferredActivity> removed = null; 12447 boolean changed = false; 12448 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12449 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12450 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12451 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12452 continue; 12453 } 12454 Iterator<PreferredActivity> it = pir.filterIterator(); 12455 while (it.hasNext()) { 12456 PreferredActivity pa = it.next(); 12457 // Mark entry for removal only if it matches the package name 12458 // and the entry is of type "always". 12459 if (packageName == null || 12460 (pa.mPref.mComponent.getPackageName().equals(packageName) 12461 && pa.mPref.mAlways)) { 12462 if (removed == null) { 12463 removed = new ArrayList<PreferredActivity>(); 12464 } 12465 removed.add(pa); 12466 } 12467 } 12468 if (removed != null) { 12469 for (int j=0; j<removed.size(); j++) { 12470 PreferredActivity pa = removed.get(j); 12471 pir.removeFilter(pa); 12472 } 12473 changed = true; 12474 } 12475 } 12476 return changed; 12477 } 12478 12479 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12480 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12481 if (userId == UserHandle.USER_ALL) { 12482 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12483 for (int oneUserId : sUserManager.getUserIds()) { 12484 scheduleWritePackageRestrictionsLocked(oneUserId); 12485 } 12486 } else { 12487 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12488 scheduleWritePackageRestrictionsLocked(userId); 12489 } 12490 } 12491 12492 @Override 12493 public void resetPreferredActivities(int userId) { 12494 /* TODO: Actually use userId. Why is it being passed in? */ 12495 mContext.enforceCallingOrSelfPermission( 12496 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12497 // writer 12498 synchronized (mPackages) { 12499 int user = UserHandle.getCallingUserId(); 12500 clearPackagePreferredActivitiesLPw(null, user); 12501 mSettings.readDefaultPreferredAppsLPw(this, user); 12502 scheduleWritePackageRestrictionsLocked(user); 12503 } 12504 } 12505 12506 @Override 12507 public int getPreferredActivities(List<IntentFilter> outFilters, 12508 List<ComponentName> outActivities, String packageName) { 12509 12510 int num = 0; 12511 final int userId = UserHandle.getCallingUserId(); 12512 // reader 12513 synchronized (mPackages) { 12514 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12515 if (pir != null) { 12516 final Iterator<PreferredActivity> it = pir.filterIterator(); 12517 while (it.hasNext()) { 12518 final PreferredActivity pa = it.next(); 12519 if (packageName == null 12520 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12521 && pa.mPref.mAlways)) { 12522 if (outFilters != null) { 12523 outFilters.add(new IntentFilter(pa)); 12524 } 12525 if (outActivities != null) { 12526 outActivities.add(pa.mPref.mComponent); 12527 } 12528 } 12529 } 12530 } 12531 } 12532 12533 return num; 12534 } 12535 12536 @Override 12537 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12538 int userId) { 12539 int callingUid = Binder.getCallingUid(); 12540 if (callingUid != Process.SYSTEM_UID) { 12541 throw new SecurityException( 12542 "addPersistentPreferredActivity can only be run by the system"); 12543 } 12544 if (filter.countActions() == 0) { 12545 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12546 return; 12547 } 12548 synchronized (mPackages) { 12549 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12550 " :"); 12551 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12552 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12553 new PersistentPreferredActivity(filter, activity)); 12554 scheduleWritePackageRestrictionsLocked(userId); 12555 } 12556 } 12557 12558 @Override 12559 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12560 int callingUid = Binder.getCallingUid(); 12561 if (callingUid != Process.SYSTEM_UID) { 12562 throw new SecurityException( 12563 "clearPackagePersistentPreferredActivities can only be run by the system"); 12564 } 12565 ArrayList<PersistentPreferredActivity> removed = null; 12566 boolean changed = false; 12567 synchronized (mPackages) { 12568 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12569 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12570 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12571 .valueAt(i); 12572 if (userId != thisUserId) { 12573 continue; 12574 } 12575 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12576 while (it.hasNext()) { 12577 PersistentPreferredActivity ppa = it.next(); 12578 // Mark entry for removal only if it matches the package name. 12579 if (ppa.mComponent.getPackageName().equals(packageName)) { 12580 if (removed == null) { 12581 removed = new ArrayList<PersistentPreferredActivity>(); 12582 } 12583 removed.add(ppa); 12584 } 12585 } 12586 if (removed != null) { 12587 for (int j=0; j<removed.size(); j++) { 12588 PersistentPreferredActivity ppa = removed.get(j); 12589 ppir.removeFilter(ppa); 12590 } 12591 changed = true; 12592 } 12593 } 12594 12595 if (changed) { 12596 scheduleWritePackageRestrictionsLocked(userId); 12597 } 12598 } 12599 } 12600 12601 /** 12602 * Non-Binder method, support for the backup/restore mechanism: write the 12603 * full set of preferred activities in its canonical XML format. Returns true 12604 * on success; false otherwise. 12605 */ 12606 @Override 12607 public byte[] getPreferredActivityBackup(int userId) { 12608 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12609 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12610 } 12611 12612 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12613 try { 12614 final XmlSerializer serializer = new FastXmlSerializer(); 12615 serializer.setOutput(dataStream, "utf-8"); 12616 serializer.startDocument(null, true); 12617 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12618 12619 synchronized (mPackages) { 12620 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12621 } 12622 12623 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12624 serializer.endDocument(); 12625 serializer.flush(); 12626 } catch (Exception e) { 12627 if (DEBUG_BACKUP) { 12628 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12629 } 12630 return null; 12631 } 12632 12633 return dataStream.toByteArray(); 12634 } 12635 12636 @Override 12637 public void restorePreferredActivities(byte[] backup, int userId) { 12638 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12639 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12640 } 12641 12642 try { 12643 final XmlPullParser parser = Xml.newPullParser(); 12644 parser.setInput(new ByteArrayInputStream(backup), null); 12645 12646 int type; 12647 while ((type = parser.next()) != XmlPullParser.START_TAG 12648 && type != XmlPullParser.END_DOCUMENT) { 12649 } 12650 if (type != XmlPullParser.START_TAG) { 12651 // oops didn't find a start tag?! 12652 if (DEBUG_BACKUP) { 12653 Slog.e(TAG, "Didn't find start tag during restore"); 12654 } 12655 return; 12656 } 12657 12658 // this is supposed to be TAG_PREFERRED_BACKUP 12659 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12660 if (DEBUG_BACKUP) { 12661 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12662 } 12663 return; 12664 } 12665 12666 // skip interfering stuff, then we're aligned with the backing implementation 12667 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12668 synchronized (mPackages) { 12669 mSettings.readPreferredActivitiesLPw(parser, userId); 12670 } 12671 } catch (Exception e) { 12672 if (DEBUG_BACKUP) { 12673 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12674 } 12675 } 12676 } 12677 12678 @Override 12679 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12680 int sourceUserId, int targetUserId, int flags) { 12681 mContext.enforceCallingOrSelfPermission( 12682 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12683 int callingUid = Binder.getCallingUid(); 12684 enforceOwnerRights(ownerPackage, callingUid); 12685 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12686 if (intentFilter.countActions() == 0) { 12687 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12688 return; 12689 } 12690 synchronized (mPackages) { 12691 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12692 ownerPackage, targetUserId, flags); 12693 CrossProfileIntentResolver resolver = 12694 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12695 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12696 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12697 if (existing != null) { 12698 int size = existing.size(); 12699 for (int i = 0; i < size; i++) { 12700 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12701 return; 12702 } 12703 } 12704 } 12705 resolver.addFilter(newFilter); 12706 scheduleWritePackageRestrictionsLocked(sourceUserId); 12707 } 12708 } 12709 12710 @Override 12711 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12712 mContext.enforceCallingOrSelfPermission( 12713 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12714 int callingUid = Binder.getCallingUid(); 12715 enforceOwnerRights(ownerPackage, callingUid); 12716 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12717 synchronized (mPackages) { 12718 CrossProfileIntentResolver resolver = 12719 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12720 ArraySet<CrossProfileIntentFilter> set = 12721 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12722 for (CrossProfileIntentFilter filter : set) { 12723 if (filter.getOwnerPackage().equals(ownerPackage)) { 12724 resolver.removeFilter(filter); 12725 } 12726 } 12727 scheduleWritePackageRestrictionsLocked(sourceUserId); 12728 } 12729 } 12730 12731 // Enforcing that callingUid is owning pkg on userId 12732 private void enforceOwnerRights(String pkg, int callingUid) { 12733 // The system owns everything. 12734 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12735 return; 12736 } 12737 int callingUserId = UserHandle.getUserId(callingUid); 12738 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12739 if (pi == null) { 12740 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12741 + callingUserId); 12742 } 12743 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12744 throw new SecurityException("Calling uid " + callingUid 12745 + " does not own package " + pkg); 12746 } 12747 } 12748 12749 @Override 12750 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12751 Intent intent = new Intent(Intent.ACTION_MAIN); 12752 intent.addCategory(Intent.CATEGORY_HOME); 12753 12754 final int callingUserId = UserHandle.getCallingUserId(); 12755 List<ResolveInfo> list = queryIntentActivities(intent, null, 12756 PackageManager.GET_META_DATA, callingUserId); 12757 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12758 true, false, false, callingUserId); 12759 12760 allHomeCandidates.clear(); 12761 if (list != null) { 12762 for (ResolveInfo ri : list) { 12763 allHomeCandidates.add(ri); 12764 } 12765 } 12766 return (preferred == null || preferred.activityInfo == null) 12767 ? null 12768 : new ComponentName(preferred.activityInfo.packageName, 12769 preferred.activityInfo.name); 12770 } 12771 12772 @Override 12773 public void setApplicationEnabledSetting(String appPackageName, 12774 int newState, int flags, int userId, String callingPackage) { 12775 if (!sUserManager.exists(userId)) return; 12776 if (callingPackage == null) { 12777 callingPackage = Integer.toString(Binder.getCallingUid()); 12778 } 12779 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12780 } 12781 12782 @Override 12783 public void setComponentEnabledSetting(ComponentName componentName, 12784 int newState, int flags, int userId) { 12785 if (!sUserManager.exists(userId)) return; 12786 setEnabledSetting(componentName.getPackageName(), 12787 componentName.getClassName(), newState, flags, userId, null); 12788 } 12789 12790 private void setEnabledSetting(final String packageName, String className, int newState, 12791 final int flags, int userId, String callingPackage) { 12792 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12793 || newState == COMPONENT_ENABLED_STATE_ENABLED 12794 || newState == COMPONENT_ENABLED_STATE_DISABLED 12795 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12796 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12797 throw new IllegalArgumentException("Invalid new component state: " 12798 + newState); 12799 } 12800 PackageSetting pkgSetting; 12801 final int uid = Binder.getCallingUid(); 12802 final int permission = mContext.checkCallingOrSelfPermission( 12803 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12804 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12805 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12806 boolean sendNow = false; 12807 boolean isApp = (className == null); 12808 String componentName = isApp ? packageName : className; 12809 int packageUid = -1; 12810 ArrayList<String> components; 12811 12812 // writer 12813 synchronized (mPackages) { 12814 pkgSetting = mSettings.mPackages.get(packageName); 12815 if (pkgSetting == null) { 12816 if (className == null) { 12817 throw new IllegalArgumentException( 12818 "Unknown package: " + packageName); 12819 } 12820 throw new IllegalArgumentException( 12821 "Unknown component: " + packageName 12822 + "/" + className); 12823 } 12824 // Allow root and verify that userId is not being specified by a different user 12825 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12826 throw new SecurityException( 12827 "Permission Denial: attempt to change component state from pid=" 12828 + Binder.getCallingPid() 12829 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12830 } 12831 if (className == null) { 12832 // We're dealing with an application/package level state change 12833 if (pkgSetting.getEnabled(userId) == newState) { 12834 // Nothing to do 12835 return; 12836 } 12837 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12838 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12839 // Don't care about who enables an app. 12840 callingPackage = null; 12841 } 12842 pkgSetting.setEnabled(newState, userId, callingPackage); 12843 // pkgSetting.pkg.mSetEnabled = newState; 12844 } else { 12845 // We're dealing with a component level state change 12846 // First, verify that this is a valid class name. 12847 PackageParser.Package pkg = pkgSetting.pkg; 12848 if (pkg == null || !pkg.hasComponentClassName(className)) { 12849 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12850 throw new IllegalArgumentException("Component class " + className 12851 + " does not exist in " + packageName); 12852 } else { 12853 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12854 + className + " does not exist in " + packageName); 12855 } 12856 } 12857 switch (newState) { 12858 case COMPONENT_ENABLED_STATE_ENABLED: 12859 if (!pkgSetting.enableComponentLPw(className, userId)) { 12860 return; 12861 } 12862 break; 12863 case COMPONENT_ENABLED_STATE_DISABLED: 12864 if (!pkgSetting.disableComponentLPw(className, userId)) { 12865 return; 12866 } 12867 break; 12868 case COMPONENT_ENABLED_STATE_DEFAULT: 12869 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12870 return; 12871 } 12872 break; 12873 default: 12874 Slog.e(TAG, "Invalid new component state: " + newState); 12875 return; 12876 } 12877 } 12878 scheduleWritePackageRestrictionsLocked(userId); 12879 components = mPendingBroadcasts.get(userId, packageName); 12880 final boolean newPackage = components == null; 12881 if (newPackage) { 12882 components = new ArrayList<String>(); 12883 } 12884 if (!components.contains(componentName)) { 12885 components.add(componentName); 12886 } 12887 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12888 sendNow = true; 12889 // Purge entry from pending broadcast list if another one exists already 12890 // since we are sending one right away. 12891 mPendingBroadcasts.remove(userId, packageName); 12892 } else { 12893 if (newPackage) { 12894 mPendingBroadcasts.put(userId, packageName, components); 12895 } 12896 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12897 // Schedule a message 12898 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12899 } 12900 } 12901 } 12902 12903 long callingId = Binder.clearCallingIdentity(); 12904 try { 12905 if (sendNow) { 12906 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12907 sendPackageChangedBroadcast(packageName, 12908 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12909 } 12910 } finally { 12911 Binder.restoreCallingIdentity(callingId); 12912 } 12913 } 12914 12915 private void sendPackageChangedBroadcast(String packageName, 12916 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12917 if (DEBUG_INSTALL) 12918 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12919 + componentNames); 12920 Bundle extras = new Bundle(4); 12921 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12922 String nameList[] = new String[componentNames.size()]; 12923 componentNames.toArray(nameList); 12924 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12925 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12926 extras.putInt(Intent.EXTRA_UID, packageUid); 12927 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12928 new int[] {UserHandle.getUserId(packageUid)}); 12929 } 12930 12931 @Override 12932 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12933 if (!sUserManager.exists(userId)) return; 12934 final int uid = Binder.getCallingUid(); 12935 final int permission = mContext.checkCallingOrSelfPermission( 12936 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12937 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12938 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12939 // writer 12940 synchronized (mPackages) { 12941 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12942 uid, userId)) { 12943 scheduleWritePackageRestrictionsLocked(userId); 12944 } 12945 } 12946 } 12947 12948 @Override 12949 public String getInstallerPackageName(String packageName) { 12950 // reader 12951 synchronized (mPackages) { 12952 return mSettings.getInstallerPackageNameLPr(packageName); 12953 } 12954 } 12955 12956 @Override 12957 public int getApplicationEnabledSetting(String packageName, int userId) { 12958 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12959 int uid = Binder.getCallingUid(); 12960 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12961 // reader 12962 synchronized (mPackages) { 12963 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12964 } 12965 } 12966 12967 @Override 12968 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12969 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12970 int uid = Binder.getCallingUid(); 12971 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12972 // reader 12973 synchronized (mPackages) { 12974 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12975 } 12976 } 12977 12978 @Override 12979 public void enterSafeMode() { 12980 enforceSystemOrRoot("Only the system can request entering safe mode"); 12981 12982 if (!mSystemReady) { 12983 mSafeMode = true; 12984 } 12985 } 12986 12987 @Override 12988 public void systemReady() { 12989 mSystemReady = true; 12990 12991 // Read the compatibilty setting when the system is ready. 12992 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12993 mContext.getContentResolver(), 12994 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12995 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12996 if (DEBUG_SETTINGS) { 12997 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12998 } 12999 13000 synchronized (mPackages) { 13001 // Verify that all of the preferred activity components actually 13002 // exist. It is possible for applications to be updated and at 13003 // that point remove a previously declared activity component that 13004 // had been set as a preferred activity. We try to clean this up 13005 // the next time we encounter that preferred activity, but it is 13006 // possible for the user flow to never be able to return to that 13007 // situation so here we do a sanity check to make sure we haven't 13008 // left any junk around. 13009 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13010 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13011 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13012 removed.clear(); 13013 for (PreferredActivity pa : pir.filterSet()) { 13014 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13015 removed.add(pa); 13016 } 13017 } 13018 if (removed.size() > 0) { 13019 for (int r=0; r<removed.size(); r++) { 13020 PreferredActivity pa = removed.get(r); 13021 Slog.w(TAG, "Removing dangling preferred activity: " 13022 + pa.mPref.mComponent); 13023 pir.removeFilter(pa); 13024 } 13025 mSettings.writePackageRestrictionsLPr( 13026 mSettings.mPreferredActivities.keyAt(i)); 13027 } 13028 } 13029 } 13030 sUserManager.systemReady(); 13031 13032 // Kick off any messages waiting for system ready 13033 if (mPostSystemReadyMessages != null) { 13034 for (Message msg : mPostSystemReadyMessages) { 13035 msg.sendToTarget(); 13036 } 13037 mPostSystemReadyMessages = null; 13038 } 13039 13040 // Watch for external volumes that come and go over time 13041 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13042 storage.registerListener(mStorageListener); 13043 13044 mInstallerService.systemReady(); 13045 } 13046 13047 @Override 13048 public boolean isSafeMode() { 13049 return mSafeMode; 13050 } 13051 13052 @Override 13053 public boolean hasSystemUidErrors() { 13054 return mHasSystemUidErrors; 13055 } 13056 13057 static String arrayToString(int[] array) { 13058 StringBuffer buf = new StringBuffer(128); 13059 buf.append('['); 13060 if (array != null) { 13061 for (int i=0; i<array.length; i++) { 13062 if (i > 0) buf.append(", "); 13063 buf.append(array[i]); 13064 } 13065 } 13066 buf.append(']'); 13067 return buf.toString(); 13068 } 13069 13070 static class DumpState { 13071 public static final int DUMP_LIBS = 1 << 0; 13072 public static final int DUMP_FEATURES = 1 << 1; 13073 public static final int DUMP_RESOLVERS = 1 << 2; 13074 public static final int DUMP_PERMISSIONS = 1 << 3; 13075 public static final int DUMP_PACKAGES = 1 << 4; 13076 public static final int DUMP_SHARED_USERS = 1 << 5; 13077 public static final int DUMP_MESSAGES = 1 << 6; 13078 public static final int DUMP_PROVIDERS = 1 << 7; 13079 public static final int DUMP_VERIFIERS = 1 << 8; 13080 public static final int DUMP_PREFERRED = 1 << 9; 13081 public static final int DUMP_PREFERRED_XML = 1 << 10; 13082 public static final int DUMP_KEYSETS = 1 << 11; 13083 public static final int DUMP_VERSION = 1 << 12; 13084 public static final int DUMP_INSTALLS = 1 << 13; 13085 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13086 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13087 13088 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13089 13090 private int mTypes; 13091 13092 private int mOptions; 13093 13094 private boolean mTitlePrinted; 13095 13096 private SharedUserSetting mSharedUser; 13097 13098 public boolean isDumping(int type) { 13099 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13100 return true; 13101 } 13102 13103 return (mTypes & type) != 0; 13104 } 13105 13106 public void setDump(int type) { 13107 mTypes |= type; 13108 } 13109 13110 public boolean isOptionEnabled(int option) { 13111 return (mOptions & option) != 0; 13112 } 13113 13114 public void setOptionEnabled(int option) { 13115 mOptions |= option; 13116 } 13117 13118 public boolean onTitlePrinted() { 13119 final boolean printed = mTitlePrinted; 13120 mTitlePrinted = true; 13121 return printed; 13122 } 13123 13124 public boolean getTitlePrinted() { 13125 return mTitlePrinted; 13126 } 13127 13128 public void setTitlePrinted(boolean enabled) { 13129 mTitlePrinted = enabled; 13130 } 13131 13132 public SharedUserSetting getSharedUser() { 13133 return mSharedUser; 13134 } 13135 13136 public void setSharedUser(SharedUserSetting user) { 13137 mSharedUser = user; 13138 } 13139 } 13140 13141 @Override 13142 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13143 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13144 != PackageManager.PERMISSION_GRANTED) { 13145 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13146 + Binder.getCallingPid() 13147 + ", uid=" + Binder.getCallingUid() 13148 + " without permission " 13149 + android.Manifest.permission.DUMP); 13150 return; 13151 } 13152 13153 DumpState dumpState = new DumpState(); 13154 boolean fullPreferred = false; 13155 boolean checkin = false; 13156 13157 String packageName = null; 13158 13159 int opti = 0; 13160 while (opti < args.length) { 13161 String opt = args[opti]; 13162 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13163 break; 13164 } 13165 opti++; 13166 13167 if ("-a".equals(opt)) { 13168 // Right now we only know how to print all. 13169 } else if ("-h".equals(opt)) { 13170 pw.println("Package manager dump options:"); 13171 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13172 pw.println(" --checkin: dump for a checkin"); 13173 pw.println(" -f: print details of intent filters"); 13174 pw.println(" -h: print this help"); 13175 pw.println(" cmd may be one of:"); 13176 pw.println(" l[ibraries]: list known shared libraries"); 13177 pw.println(" f[ibraries]: list device features"); 13178 pw.println(" k[eysets]: print known keysets"); 13179 pw.println(" r[esolvers]: dump intent resolvers"); 13180 pw.println(" perm[issions]: dump permissions"); 13181 pw.println(" pref[erred]: print preferred package settings"); 13182 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13183 pw.println(" prov[iders]: dump content providers"); 13184 pw.println(" p[ackages]: dump installed packages"); 13185 pw.println(" s[hared-users]: dump shared user IDs"); 13186 pw.println(" m[essages]: print collected runtime messages"); 13187 pw.println(" v[erifiers]: print package verifier info"); 13188 pw.println(" version: print database version info"); 13189 pw.println(" write: write current settings now"); 13190 pw.println(" <package.name>: info about given package"); 13191 pw.println(" installs: details about install sessions"); 13192 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13193 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13194 return; 13195 } else if ("--checkin".equals(opt)) { 13196 checkin = true; 13197 } else if ("-f".equals(opt)) { 13198 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13199 } else { 13200 pw.println("Unknown argument: " + opt + "; use -h for help"); 13201 } 13202 } 13203 13204 // Is the caller requesting to dump a particular piece of data? 13205 if (opti < args.length) { 13206 String cmd = args[opti]; 13207 opti++; 13208 // Is this a package name? 13209 if ("android".equals(cmd) || cmd.contains(".")) { 13210 packageName = cmd; 13211 // When dumping a single package, we always dump all of its 13212 // filter information since the amount of data will be reasonable. 13213 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13214 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13215 dumpState.setDump(DumpState.DUMP_LIBS); 13216 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13217 dumpState.setDump(DumpState.DUMP_FEATURES); 13218 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13219 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13220 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13221 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13222 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13223 dumpState.setDump(DumpState.DUMP_PREFERRED); 13224 } else if ("preferred-xml".equals(cmd)) { 13225 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13226 if (opti < args.length && "--full".equals(args[opti])) { 13227 fullPreferred = true; 13228 opti++; 13229 } 13230 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13231 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13232 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13233 dumpState.setDump(DumpState.DUMP_PACKAGES); 13234 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13235 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13236 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13237 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13238 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13239 dumpState.setDump(DumpState.DUMP_MESSAGES); 13240 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13241 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13242 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13243 || "intent-filter-verifiers".equals(cmd)) { 13244 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13245 } else if ("version".equals(cmd)) { 13246 dumpState.setDump(DumpState.DUMP_VERSION); 13247 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13248 dumpState.setDump(DumpState.DUMP_KEYSETS); 13249 } else if ("installs".equals(cmd)) { 13250 dumpState.setDump(DumpState.DUMP_INSTALLS); 13251 } else if ("write".equals(cmd)) { 13252 synchronized (mPackages) { 13253 mSettings.writeLPr(); 13254 pw.println("Settings written."); 13255 return; 13256 } 13257 } 13258 } 13259 13260 if (checkin) { 13261 pw.println("vers,1"); 13262 } 13263 13264 // reader 13265 synchronized (mPackages) { 13266 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13267 if (!checkin) { 13268 if (dumpState.onTitlePrinted()) 13269 pw.println(); 13270 pw.println("Database versions:"); 13271 pw.print(" SDK Version:"); 13272 pw.print(" internal="); 13273 pw.print(mSettings.mInternalSdkPlatform); 13274 pw.print(" external="); 13275 pw.println(mSettings.mExternalSdkPlatform); 13276 pw.print(" DB Version:"); 13277 pw.print(" internal="); 13278 pw.print(mSettings.mInternalDatabaseVersion); 13279 pw.print(" external="); 13280 pw.println(mSettings.mExternalDatabaseVersion); 13281 } 13282 } 13283 13284 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13285 if (!checkin) { 13286 if (dumpState.onTitlePrinted()) 13287 pw.println(); 13288 pw.println("Verifiers:"); 13289 pw.print(" Required: "); 13290 pw.print(mRequiredVerifierPackage); 13291 pw.print(" (uid="); 13292 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13293 pw.println(")"); 13294 } else if (mRequiredVerifierPackage != null) { 13295 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13296 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13297 } 13298 } 13299 13300 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13301 packageName == null) { 13302 if (mIntentFilterVerifierComponent != null) { 13303 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13304 if (!checkin) { 13305 if (dumpState.onTitlePrinted()) 13306 pw.println(); 13307 pw.println("Intent Filter Verifier:"); 13308 pw.print(" Using: "); 13309 pw.print(verifierPackageName); 13310 pw.print(" (uid="); 13311 pw.print(getPackageUid(verifierPackageName, 0)); 13312 pw.println(")"); 13313 } else if (verifierPackageName != null) { 13314 pw.print("ifv,"); pw.print(verifierPackageName); 13315 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13316 } 13317 } else { 13318 pw.println(); 13319 pw.println("No Intent Filter Verifier available!"); 13320 } 13321 } 13322 13323 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13324 boolean printedHeader = false; 13325 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13326 while (it.hasNext()) { 13327 String name = it.next(); 13328 SharedLibraryEntry ent = mSharedLibraries.get(name); 13329 if (!checkin) { 13330 if (!printedHeader) { 13331 if (dumpState.onTitlePrinted()) 13332 pw.println(); 13333 pw.println("Libraries:"); 13334 printedHeader = true; 13335 } 13336 pw.print(" "); 13337 } else { 13338 pw.print("lib,"); 13339 } 13340 pw.print(name); 13341 if (!checkin) { 13342 pw.print(" -> "); 13343 } 13344 if (ent.path != null) { 13345 if (!checkin) { 13346 pw.print("(jar) "); 13347 pw.print(ent.path); 13348 } else { 13349 pw.print(",jar,"); 13350 pw.print(ent.path); 13351 } 13352 } else { 13353 if (!checkin) { 13354 pw.print("(apk) "); 13355 pw.print(ent.apk); 13356 } else { 13357 pw.print(",apk,"); 13358 pw.print(ent.apk); 13359 } 13360 } 13361 pw.println(); 13362 } 13363 } 13364 13365 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13366 if (dumpState.onTitlePrinted()) 13367 pw.println(); 13368 if (!checkin) { 13369 pw.println("Features:"); 13370 } 13371 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13372 while (it.hasNext()) { 13373 String name = it.next(); 13374 if (!checkin) { 13375 pw.print(" "); 13376 } else { 13377 pw.print("feat,"); 13378 } 13379 pw.println(name); 13380 } 13381 } 13382 13383 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13384 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13385 : "Activity Resolver Table:", " ", packageName, 13386 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13387 dumpState.setTitlePrinted(true); 13388 } 13389 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13390 : "Receiver Resolver Table:", " ", packageName, 13391 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13392 dumpState.setTitlePrinted(true); 13393 } 13394 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13395 : "Service Resolver Table:", " ", packageName, 13396 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13397 dumpState.setTitlePrinted(true); 13398 } 13399 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13400 : "Provider Resolver Table:", " ", packageName, 13401 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13402 dumpState.setTitlePrinted(true); 13403 } 13404 } 13405 13406 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13407 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13408 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13409 int user = mSettings.mPreferredActivities.keyAt(i); 13410 if (pir.dump(pw, 13411 dumpState.getTitlePrinted() 13412 ? "\nPreferred Activities User " + user + ":" 13413 : "Preferred Activities User " + user + ":", " ", 13414 packageName, true, false)) { 13415 dumpState.setTitlePrinted(true); 13416 } 13417 } 13418 } 13419 13420 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13421 pw.flush(); 13422 FileOutputStream fout = new FileOutputStream(fd); 13423 BufferedOutputStream str = new BufferedOutputStream(fout); 13424 XmlSerializer serializer = new FastXmlSerializer(); 13425 try { 13426 serializer.setOutput(str, "utf-8"); 13427 serializer.startDocument(null, true); 13428 serializer.setFeature( 13429 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13430 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13431 serializer.endDocument(); 13432 serializer.flush(); 13433 } catch (IllegalArgumentException e) { 13434 pw.println("Failed writing: " + e); 13435 } catch (IllegalStateException e) { 13436 pw.println("Failed writing: " + e); 13437 } catch (IOException e) { 13438 pw.println("Failed writing: " + e); 13439 } 13440 } 13441 13442 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13443 pw.println(); 13444 int count = mSettings.mPackages.size(); 13445 if (count == 0) { 13446 pw.println("No domain preferred apps!"); 13447 pw.println(); 13448 } else { 13449 final String prefix = " "; 13450 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13451 if (allPackageSettings.size() == 0) { 13452 pw.println("No domain preferred apps!"); 13453 pw.println(); 13454 } else { 13455 pw.println("Domain preferred apps status:"); 13456 pw.println(); 13457 count = 0; 13458 for (PackageSetting ps : allPackageSettings) { 13459 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13460 if (ivi == null || ivi.getPackageName() == null) continue; 13461 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13462 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13463 pw.println(prefix + "Status: " + ivi.getStatusString()); 13464 pw.println(); 13465 count++; 13466 } 13467 if (count == 0) { 13468 pw.println(prefix + "No domain preferred app status!"); 13469 pw.println(); 13470 } 13471 for (int userId : sUserManager.getUserIds()) { 13472 pw.println("Domain preferred apps for User " + userId + ":"); 13473 pw.println(); 13474 count = 0; 13475 for (PackageSetting ps : allPackageSettings) { 13476 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13477 if (ivi == null || ivi.getPackageName() == null) { 13478 continue; 13479 } 13480 final int status = ps.getDomainVerificationStatusForUser(userId); 13481 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13482 continue; 13483 } 13484 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13485 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13486 String statusStr = IntentFilterVerificationInfo. 13487 getStatusStringFromValue(status); 13488 pw.println(prefix + "Status: " + statusStr); 13489 pw.println(); 13490 count++; 13491 } 13492 if (count == 0) { 13493 pw.println(prefix + "No domain preferred apps!"); 13494 pw.println(); 13495 } 13496 } 13497 } 13498 } 13499 } 13500 13501 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13502 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13503 if (packageName == null) { 13504 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13505 if (iperm == 0) { 13506 if (dumpState.onTitlePrinted()) 13507 pw.println(); 13508 pw.println("AppOp Permissions:"); 13509 } 13510 pw.print(" AppOp Permission "); 13511 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13512 pw.println(":"); 13513 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13514 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13515 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13516 } 13517 } 13518 } 13519 } 13520 13521 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13522 boolean printedSomething = false; 13523 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13524 if (packageName != null && !packageName.equals(p.info.packageName)) { 13525 continue; 13526 } 13527 if (!printedSomething) { 13528 if (dumpState.onTitlePrinted()) 13529 pw.println(); 13530 pw.println("Registered ContentProviders:"); 13531 printedSomething = true; 13532 } 13533 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13534 pw.print(" "); pw.println(p.toString()); 13535 } 13536 printedSomething = false; 13537 for (Map.Entry<String, PackageParser.Provider> entry : 13538 mProvidersByAuthority.entrySet()) { 13539 PackageParser.Provider p = entry.getValue(); 13540 if (packageName != null && !packageName.equals(p.info.packageName)) { 13541 continue; 13542 } 13543 if (!printedSomething) { 13544 if (dumpState.onTitlePrinted()) 13545 pw.println(); 13546 pw.println("ContentProvider Authorities:"); 13547 printedSomething = true; 13548 } 13549 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13550 pw.print(" "); pw.println(p.toString()); 13551 if (p.info != null && p.info.applicationInfo != null) { 13552 final String appInfo = p.info.applicationInfo.toString(); 13553 pw.print(" applicationInfo="); pw.println(appInfo); 13554 } 13555 } 13556 } 13557 13558 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13559 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13560 } 13561 13562 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13563 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13564 } 13565 13566 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13567 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13568 } 13569 13570 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13571 // XXX should handle packageName != null by dumping only install data that 13572 // the given package is involved with. 13573 if (dumpState.onTitlePrinted()) pw.println(); 13574 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13575 } 13576 13577 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13578 if (dumpState.onTitlePrinted()) pw.println(); 13579 mSettings.dumpReadMessagesLPr(pw, dumpState); 13580 13581 pw.println(); 13582 pw.println("Package warning messages:"); 13583 BufferedReader in = null; 13584 String line = null; 13585 try { 13586 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13587 while ((line = in.readLine()) != null) { 13588 if (line.contains("ignored: updated version")) continue; 13589 pw.println(line); 13590 } 13591 } catch (IOException ignored) { 13592 } finally { 13593 IoUtils.closeQuietly(in); 13594 } 13595 } 13596 13597 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13598 BufferedReader in = null; 13599 String line = null; 13600 try { 13601 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13602 while ((line = in.readLine()) != null) { 13603 if (line.contains("ignored: updated version")) continue; 13604 pw.print("msg,"); 13605 pw.println(line); 13606 } 13607 } catch (IOException ignored) { 13608 } finally { 13609 IoUtils.closeQuietly(in); 13610 } 13611 } 13612 } 13613 } 13614 13615 // ------- apps on sdcard specific code ------- 13616 static final boolean DEBUG_SD_INSTALL = false; 13617 13618 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13619 13620 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13621 13622 private boolean mMediaMounted = false; 13623 13624 static String getEncryptKey() { 13625 try { 13626 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13627 SD_ENCRYPTION_KEYSTORE_NAME); 13628 if (sdEncKey == null) { 13629 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13630 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13631 if (sdEncKey == null) { 13632 Slog.e(TAG, "Failed to create encryption keys"); 13633 return null; 13634 } 13635 } 13636 return sdEncKey; 13637 } catch (NoSuchAlgorithmException nsae) { 13638 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13639 return null; 13640 } catch (IOException ioe) { 13641 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13642 return null; 13643 } 13644 } 13645 13646 /* 13647 * Update media status on PackageManager. 13648 */ 13649 @Override 13650 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13651 int callingUid = Binder.getCallingUid(); 13652 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13653 throw new SecurityException("Media status can only be updated by the system"); 13654 } 13655 // reader; this apparently protects mMediaMounted, but should probably 13656 // be a different lock in that case. 13657 synchronized (mPackages) { 13658 Log.i(TAG, "Updating external media status from " 13659 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13660 + (mediaStatus ? "mounted" : "unmounted")); 13661 if (DEBUG_SD_INSTALL) 13662 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13663 + ", mMediaMounted=" + mMediaMounted); 13664 if (mediaStatus == mMediaMounted) { 13665 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13666 : 0, -1); 13667 mHandler.sendMessage(msg); 13668 return; 13669 } 13670 mMediaMounted = mediaStatus; 13671 } 13672 // Queue up an async operation since the package installation may take a 13673 // little while. 13674 mHandler.post(new Runnable() { 13675 public void run() { 13676 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13677 } 13678 }); 13679 } 13680 13681 /** 13682 * Called by MountService when the initial ASECs to scan are available. 13683 * Should block until all the ASEC containers are finished being scanned. 13684 */ 13685 public void scanAvailableAsecs() { 13686 updateExternalMediaStatusInner(true, false, false); 13687 if (mShouldRestoreconData) { 13688 SELinuxMMAC.setRestoreconDone(); 13689 mShouldRestoreconData = false; 13690 } 13691 } 13692 13693 /* 13694 * Collect information of applications on external media, map them against 13695 * existing containers and update information based on current mount status. 13696 * Please note that we always have to report status if reportStatus has been 13697 * set to true especially when unloading packages. 13698 */ 13699 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13700 boolean externalStorage) { 13701 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13702 int[] uidArr = EmptyArray.INT; 13703 13704 final String[] list = PackageHelper.getSecureContainerList(); 13705 if (ArrayUtils.isEmpty(list)) { 13706 Log.i(TAG, "No secure containers found"); 13707 } else { 13708 // Process list of secure containers and categorize them 13709 // as active or stale based on their package internal state. 13710 13711 // reader 13712 synchronized (mPackages) { 13713 for (String cid : list) { 13714 // Leave stages untouched for now; installer service owns them 13715 if (PackageInstallerService.isStageName(cid)) continue; 13716 13717 if (DEBUG_SD_INSTALL) 13718 Log.i(TAG, "Processing container " + cid); 13719 String pkgName = getAsecPackageName(cid); 13720 if (pkgName == null) { 13721 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13722 continue; 13723 } 13724 if (DEBUG_SD_INSTALL) 13725 Log.i(TAG, "Looking for pkg : " + pkgName); 13726 13727 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13728 if (ps == null) { 13729 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13730 continue; 13731 } 13732 13733 /* 13734 * Skip packages that are not external if we're unmounting 13735 * external storage. 13736 */ 13737 if (externalStorage && !isMounted && !isExternal(ps)) { 13738 continue; 13739 } 13740 13741 final AsecInstallArgs args = new AsecInstallArgs(cid, 13742 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13743 // The package status is changed only if the code path 13744 // matches between settings and the container id. 13745 if (ps.codePathString != null 13746 && ps.codePathString.startsWith(args.getCodePath())) { 13747 if (DEBUG_SD_INSTALL) { 13748 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13749 + " at code path: " + ps.codePathString); 13750 } 13751 13752 // We do have a valid package installed on sdcard 13753 processCids.put(args, ps.codePathString); 13754 final int uid = ps.appId; 13755 if (uid != -1) { 13756 uidArr = ArrayUtils.appendInt(uidArr, uid); 13757 } 13758 } else { 13759 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13760 + ps.codePathString); 13761 } 13762 } 13763 } 13764 13765 Arrays.sort(uidArr); 13766 } 13767 13768 // Process packages with valid entries. 13769 if (isMounted) { 13770 if (DEBUG_SD_INSTALL) 13771 Log.i(TAG, "Loading packages"); 13772 loadMediaPackages(processCids, uidArr); 13773 startCleaningPackages(); 13774 mInstallerService.onSecureContainersAvailable(); 13775 } else { 13776 if (DEBUG_SD_INSTALL) 13777 Log.i(TAG, "Unloading packages"); 13778 unloadMediaPackages(processCids, uidArr, reportStatus); 13779 } 13780 } 13781 13782 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13783 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13784 final int size = infos.size(); 13785 final String[] packageNames = new String[size]; 13786 final int[] packageUids = new int[size]; 13787 for (int i = 0; i < size; i++) { 13788 final ApplicationInfo info = infos.get(i); 13789 packageNames[i] = info.packageName; 13790 packageUids[i] = info.uid; 13791 } 13792 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13793 finishedReceiver); 13794 } 13795 13796 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13797 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13798 sendResourcesChangedBroadcast(mediaStatus, replacing, 13799 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13800 } 13801 13802 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13803 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13804 int size = pkgList.length; 13805 if (size > 0) { 13806 // Send broadcasts here 13807 Bundle extras = new Bundle(); 13808 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13809 if (uidArr != null) { 13810 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13811 } 13812 if (replacing) { 13813 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13814 } 13815 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13816 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13817 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13818 } 13819 } 13820 13821 /* 13822 * Look at potentially valid container ids from processCids If package 13823 * information doesn't match the one on record or package scanning fails, 13824 * the cid is added to list of removeCids. We currently don't delete stale 13825 * containers. 13826 */ 13827 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13828 ArrayList<String> pkgList = new ArrayList<String>(); 13829 Set<AsecInstallArgs> keys = processCids.keySet(); 13830 13831 for (AsecInstallArgs args : keys) { 13832 String codePath = processCids.get(args); 13833 if (DEBUG_SD_INSTALL) 13834 Log.i(TAG, "Loading container : " + args.cid); 13835 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13836 try { 13837 // Make sure there are no container errors first. 13838 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13839 Slog.e(TAG, "Failed to mount cid : " + args.cid 13840 + " when installing from sdcard"); 13841 continue; 13842 } 13843 // Check code path here. 13844 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13845 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13846 + " does not match one in settings " + codePath); 13847 continue; 13848 } 13849 // Parse package 13850 int parseFlags = mDefParseFlags; 13851 if (args.isExternalAsec()) { 13852 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13853 } 13854 if (args.isFwdLocked()) { 13855 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13856 } 13857 13858 synchronized (mInstallLock) { 13859 PackageParser.Package pkg = null; 13860 try { 13861 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13862 } catch (PackageManagerException e) { 13863 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13864 } 13865 // Scan the package 13866 if (pkg != null) { 13867 /* 13868 * TODO why is the lock being held? doPostInstall is 13869 * called in other places without the lock. This needs 13870 * to be straightened out. 13871 */ 13872 // writer 13873 synchronized (mPackages) { 13874 retCode = PackageManager.INSTALL_SUCCEEDED; 13875 pkgList.add(pkg.packageName); 13876 // Post process args 13877 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13878 pkg.applicationInfo.uid); 13879 } 13880 } else { 13881 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13882 } 13883 } 13884 13885 } finally { 13886 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13887 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13888 } 13889 } 13890 } 13891 // writer 13892 synchronized (mPackages) { 13893 // If the platform SDK has changed since the last time we booted, 13894 // we need to re-grant app permission to catch any new ones that 13895 // appear. This is really a hack, and means that apps can in some 13896 // cases get permissions that the user didn't initially explicitly 13897 // allow... it would be nice to have some better way to handle 13898 // this situation. 13899 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13900 if (regrantPermissions) 13901 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13902 + mSdkVersion + "; regranting permissions for external storage"); 13903 mSettings.mExternalSdkPlatform = mSdkVersion; 13904 13905 // Make sure group IDs have been assigned, and any permission 13906 // changes in other apps are accounted for 13907 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13908 | (regrantPermissions 13909 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13910 : 0)); 13911 13912 mSettings.updateExternalDatabaseVersion(); 13913 13914 // can downgrade to reader 13915 // Persist settings 13916 mSettings.writeLPr(); 13917 } 13918 // Send a broadcast to let everyone know we are done processing 13919 if (pkgList.size() > 0) { 13920 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13921 } 13922 } 13923 13924 /* 13925 * Utility method to unload a list of specified containers 13926 */ 13927 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13928 // Just unmount all valid containers. 13929 for (AsecInstallArgs arg : cidArgs) { 13930 synchronized (mInstallLock) { 13931 arg.doPostDeleteLI(false); 13932 } 13933 } 13934 } 13935 13936 /* 13937 * Unload packages mounted on external media. This involves deleting package 13938 * data from internal structures, sending broadcasts about diabled packages, 13939 * gc'ing to free up references, unmounting all secure containers 13940 * corresponding to packages on external media, and posting a 13941 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13942 * that we always have to post this message if status has been requested no 13943 * matter what. 13944 */ 13945 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13946 final boolean reportStatus) { 13947 if (DEBUG_SD_INSTALL) 13948 Log.i(TAG, "unloading media packages"); 13949 ArrayList<String> pkgList = new ArrayList<String>(); 13950 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13951 final Set<AsecInstallArgs> keys = processCids.keySet(); 13952 for (AsecInstallArgs args : keys) { 13953 String pkgName = args.getPackageName(); 13954 if (DEBUG_SD_INSTALL) 13955 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13956 // Delete package internally 13957 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13958 synchronized (mInstallLock) { 13959 boolean res = deletePackageLI(pkgName, null, false, null, null, 13960 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13961 if (res) { 13962 pkgList.add(pkgName); 13963 } else { 13964 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13965 failedList.add(args); 13966 } 13967 } 13968 } 13969 13970 // reader 13971 synchronized (mPackages) { 13972 // We didn't update the settings after removing each package; 13973 // write them now for all packages. 13974 mSettings.writeLPr(); 13975 } 13976 13977 // We have to absolutely send UPDATED_MEDIA_STATUS only 13978 // after confirming that all the receivers processed the ordered 13979 // broadcast when packages get disabled, force a gc to clean things up. 13980 // and unload all the containers. 13981 if (pkgList.size() > 0) { 13982 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13983 new IIntentReceiver.Stub() { 13984 public void performReceive(Intent intent, int resultCode, String data, 13985 Bundle extras, boolean ordered, boolean sticky, 13986 int sendingUser) throws RemoteException { 13987 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13988 reportStatus ? 1 : 0, 1, keys); 13989 mHandler.sendMessage(msg); 13990 } 13991 }); 13992 } else { 13993 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13994 keys); 13995 mHandler.sendMessage(msg); 13996 } 13997 } 13998 13999 private void loadPrivatePackages(VolumeInfo vol) { 14000 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14001 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14002 synchronized (mPackages) { 14003 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14004 for (PackageSetting ps : packages) { 14005 synchronized (mInstallLock) { 14006 final PackageParser.Package pkg; 14007 try { 14008 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14009 loaded.add(pkg.applicationInfo); 14010 } catch (PackageManagerException e) { 14011 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14012 } 14013 } 14014 } 14015 14016 // TODO: regrant any permissions that changed based since original install 14017 14018 mSettings.writeLPr(); 14019 } 14020 14021 Slog.d(TAG, "Loaded packages " + loaded); 14022 sendResourcesChangedBroadcast(true, false, loaded, null); 14023 } 14024 14025 private void unloadPrivatePackages(VolumeInfo vol) { 14026 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14027 synchronized (mPackages) { 14028 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14029 for (PackageSetting ps : packages) { 14030 if (ps.pkg == null) continue; 14031 synchronized (mInstallLock) { 14032 final ApplicationInfo info = ps.pkg.applicationInfo; 14033 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14034 if (deletePackageLI(ps.name, null, false, null, null, 14035 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14036 unloaded.add(info); 14037 } else { 14038 Slog.w(TAG, "Failed to unload " + ps.codePath); 14039 } 14040 } 14041 } 14042 14043 mSettings.writeLPr(); 14044 } 14045 14046 Slog.d(TAG, "Unloaded packages " + unloaded); 14047 sendResourcesChangedBroadcast(false, false, unloaded, null); 14048 } 14049 14050 @Override 14051 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14052 final int flags) { 14053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14054 14055 final int installFlags; 14056 if ((flags & MOVE_INTERNAL) != 0) { 14057 installFlags = INSTALL_INTERNAL; 14058 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14059 installFlags = INSTALL_EXTERNAL; 14060 } else { 14061 throw new IllegalArgumentException("Unsupported move flags " + flags); 14062 } 14063 14064 try { 14065 movePackageInternal(packageName, null, installFlags, false, observer); 14066 } catch (PackageManagerException e) { 14067 Slog.d(TAG, "Failed to move " + packageName, e); 14068 try { 14069 observer.packageMoved(packageName, e.error); 14070 } catch (RemoteException ignored) { 14071 } 14072 } 14073 } 14074 14075 @Override 14076 public void movePackageAndData(final String packageName, final String volumeUuid, 14077 final IPackageMoveObserver observer) { 14078 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14079 try { 14080 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14081 } catch (PackageManagerException e) { 14082 Slog.d(TAG, "Failed to move " + packageName, e); 14083 try { 14084 observer.packageMoved(packageName, e.error); 14085 } catch (RemoteException ignored) { 14086 } 14087 } 14088 } 14089 14090 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14091 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14092 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14093 14094 File codeFile = null; 14095 String installerPackageName = null; 14096 String packageAbiOverride = null; 14097 14098 // TOOD: move app private data before installing 14099 14100 // reader 14101 synchronized (mPackages) { 14102 final PackageParser.Package pkg = mPackages.get(packageName); 14103 final PackageSetting ps = mSettings.mPackages.get(packageName); 14104 if (pkg == null || ps == null) { 14105 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14106 } 14107 14108 if (pkg.applicationInfo.isSystemApp()) { 14109 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14110 "Cannot move system application"); 14111 } else if (pkg.mOperationPending) { 14112 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14113 "Attempt to move package which has pending operations"); 14114 } 14115 14116 // TODO: yell if already in desired location 14117 14118 pkg.mOperationPending = true; 14119 14120 codeFile = new File(pkg.codePath); 14121 installerPackageName = ps.installerPackageName; 14122 packageAbiOverride = ps.cpuAbiOverrideString; 14123 } 14124 14125 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14126 @Override 14127 public void onUserActionRequired(Intent intent) throws RemoteException { 14128 throw new IllegalStateException(); 14129 } 14130 14131 @Override 14132 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14133 Bundle extras) throws RemoteException { 14134 Slog.d(TAG, "Install result for move: " 14135 + PackageManager.installStatusToString(returnCode, msg)); 14136 14137 // We usually have a new package now after the install, but if 14138 // we failed we need to clear the pending flag on the original 14139 // package object. 14140 synchronized (mPackages) { 14141 final PackageParser.Package pkg = mPackages.get(packageName); 14142 if (pkg != null) { 14143 pkg.mOperationPending = false; 14144 } 14145 } 14146 14147 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14148 switch (status) { 14149 case PackageInstaller.STATUS_SUCCESS: 14150 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14151 break; 14152 case PackageInstaller.STATUS_FAILURE_STORAGE: 14153 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14154 break; 14155 default: 14156 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14157 break; 14158 } 14159 } 14160 }; 14161 14162 // Treat a move like reinstalling an existing app, which ensures that we 14163 // process everythign uniformly, like unpacking native libraries. 14164 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14165 14166 final Message msg = mHandler.obtainMessage(INIT_COPY); 14167 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14168 msg.obj = new InstallParams(origin, installObserver, installFlags, 14169 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14170 mHandler.sendMessage(msg); 14171 } 14172 14173 @Override 14174 public boolean setInstallLocation(int loc) { 14175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14176 null); 14177 if (getInstallLocation() == loc) { 14178 return true; 14179 } 14180 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14181 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14182 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14183 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14184 return true; 14185 } 14186 return false; 14187 } 14188 14189 @Override 14190 public int getInstallLocation() { 14191 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14192 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14193 PackageHelper.APP_INSTALL_AUTO); 14194 } 14195 14196 /** Called by UserManagerService */ 14197 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14198 mDirtyUsers.remove(userHandle); 14199 mSettings.removeUserLPw(userHandle); 14200 mPendingBroadcasts.remove(userHandle); 14201 if (mInstaller != null) { 14202 // Technically, we shouldn't be doing this with the package lock 14203 // held. However, this is very rare, and there is already so much 14204 // other disk I/O going on, that we'll let it slide for now. 14205 mInstaller.removeUserDataDirs(userHandle); 14206 } 14207 mUserNeedsBadging.delete(userHandle); 14208 removeUnusedPackagesLILPw(userManager, userHandle); 14209 } 14210 14211 /** 14212 * We're removing userHandle and would like to remove any downloaded packages 14213 * that are no longer in use by any other user. 14214 * @param userHandle the user being removed 14215 */ 14216 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14217 final boolean DEBUG_CLEAN_APKS = false; 14218 int [] users = userManager.getUserIdsLPr(); 14219 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14220 while (psit.hasNext()) { 14221 PackageSetting ps = psit.next(); 14222 if (ps.pkg == null) { 14223 continue; 14224 } 14225 final String packageName = ps.pkg.packageName; 14226 // Skip over if system app 14227 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14228 continue; 14229 } 14230 if (DEBUG_CLEAN_APKS) { 14231 Slog.i(TAG, "Checking package " + packageName); 14232 } 14233 boolean keep = false; 14234 for (int i = 0; i < users.length; i++) { 14235 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14236 keep = true; 14237 if (DEBUG_CLEAN_APKS) { 14238 Slog.i(TAG, " Keeping package " + packageName + " for user " 14239 + users[i]); 14240 } 14241 break; 14242 } 14243 } 14244 if (!keep) { 14245 if (DEBUG_CLEAN_APKS) { 14246 Slog.i(TAG, " Removing package " + packageName); 14247 } 14248 mHandler.post(new Runnable() { 14249 public void run() { 14250 deletePackageX(packageName, userHandle, 0); 14251 } //end run 14252 }); 14253 } 14254 } 14255 } 14256 14257 /** Called by UserManagerService */ 14258 void createNewUserLILPw(int userHandle, File path) { 14259 if (mInstaller != null) { 14260 mInstaller.createUserConfig(userHandle); 14261 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14262 } 14263 } 14264 14265 void newUserCreatedLILPw(int userHandle) { 14266 // Adding a user requires updating runtime permissions for system apps. 14267 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14268 } 14269 14270 @Override 14271 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14272 mContext.enforceCallingOrSelfPermission( 14273 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14274 "Only package verification agents can read the verifier device identity"); 14275 14276 synchronized (mPackages) { 14277 return mSettings.getVerifierDeviceIdentityLPw(); 14278 } 14279 } 14280 14281 @Override 14282 public void setPermissionEnforced(String permission, boolean enforced) { 14283 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14284 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14285 synchronized (mPackages) { 14286 if (mSettings.mReadExternalStorageEnforced == null 14287 || mSettings.mReadExternalStorageEnforced != enforced) { 14288 mSettings.mReadExternalStorageEnforced = enforced; 14289 mSettings.writeLPr(); 14290 } 14291 } 14292 // kill any non-foreground processes so we restart them and 14293 // grant/revoke the GID. 14294 final IActivityManager am = ActivityManagerNative.getDefault(); 14295 if (am != null) { 14296 final long token = Binder.clearCallingIdentity(); 14297 try { 14298 am.killProcessesBelowForeground("setPermissionEnforcement"); 14299 } catch (RemoteException e) { 14300 } finally { 14301 Binder.restoreCallingIdentity(token); 14302 } 14303 } 14304 } else { 14305 throw new IllegalArgumentException("No selective enforcement for " + permission); 14306 } 14307 } 14308 14309 @Override 14310 @Deprecated 14311 public boolean isPermissionEnforced(String permission) { 14312 return true; 14313 } 14314 14315 @Override 14316 public boolean isStorageLow() { 14317 final long token = Binder.clearCallingIdentity(); 14318 try { 14319 final DeviceStorageMonitorInternal 14320 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14321 if (dsm != null) { 14322 return dsm.isMemoryLow(); 14323 } else { 14324 return false; 14325 } 14326 } finally { 14327 Binder.restoreCallingIdentity(token); 14328 } 14329 } 14330 14331 @Override 14332 public IPackageInstaller getPackageInstaller() { 14333 return mInstallerService; 14334 } 14335 14336 private boolean userNeedsBadging(int userId) { 14337 int index = mUserNeedsBadging.indexOfKey(userId); 14338 if (index < 0) { 14339 final UserInfo userInfo; 14340 final long token = Binder.clearCallingIdentity(); 14341 try { 14342 userInfo = sUserManager.getUserInfo(userId); 14343 } finally { 14344 Binder.restoreCallingIdentity(token); 14345 } 14346 final boolean b; 14347 if (userInfo != null && userInfo.isManagedProfile()) { 14348 b = true; 14349 } else { 14350 b = false; 14351 } 14352 mUserNeedsBadging.put(userId, b); 14353 return b; 14354 } 14355 return mUserNeedsBadging.valueAt(index); 14356 } 14357 14358 @Override 14359 public KeySet getKeySetByAlias(String packageName, String alias) { 14360 if (packageName == null || alias == null) { 14361 return null; 14362 } 14363 synchronized(mPackages) { 14364 final PackageParser.Package pkg = mPackages.get(packageName); 14365 if (pkg == null) { 14366 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14367 throw new IllegalArgumentException("Unknown package: " + packageName); 14368 } 14369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14370 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14371 } 14372 } 14373 14374 @Override 14375 public KeySet getSigningKeySet(String packageName) { 14376 if (packageName == null) { 14377 return null; 14378 } 14379 synchronized(mPackages) { 14380 final PackageParser.Package pkg = mPackages.get(packageName); 14381 if (pkg == null) { 14382 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14383 throw new IllegalArgumentException("Unknown package: " + packageName); 14384 } 14385 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14386 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14387 throw new SecurityException("May not access signing KeySet of other apps."); 14388 } 14389 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14390 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14391 } 14392 } 14393 14394 @Override 14395 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14396 if (packageName == null || ks == null) { 14397 return false; 14398 } 14399 synchronized(mPackages) { 14400 final PackageParser.Package pkg = mPackages.get(packageName); 14401 if (pkg == null) { 14402 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14403 throw new IllegalArgumentException("Unknown package: " + packageName); 14404 } 14405 IBinder ksh = ks.getToken(); 14406 if (ksh instanceof KeySetHandle) { 14407 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14408 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14409 } 14410 return false; 14411 } 14412 } 14413 14414 @Override 14415 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14416 if (packageName == null || ks == null) { 14417 return false; 14418 } 14419 synchronized(mPackages) { 14420 final PackageParser.Package pkg = mPackages.get(packageName); 14421 if (pkg == null) { 14422 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14423 throw new IllegalArgumentException("Unknown package: " + packageName); 14424 } 14425 IBinder ksh = ks.getToken(); 14426 if (ksh instanceof KeySetHandle) { 14427 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14428 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14429 } 14430 return false; 14431 } 14432 } 14433 14434 public void getUsageStatsIfNoPackageUsageInfo() { 14435 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14436 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14437 if (usm == null) { 14438 throw new IllegalStateException("UsageStatsManager must be initialized"); 14439 } 14440 long now = System.currentTimeMillis(); 14441 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14442 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14443 String packageName = entry.getKey(); 14444 PackageParser.Package pkg = mPackages.get(packageName); 14445 if (pkg == null) { 14446 continue; 14447 } 14448 UsageStats usage = entry.getValue(); 14449 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14450 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14451 } 14452 } 14453 } 14454 14455 /** 14456 * Check and throw if the given before/after packages would be considered a 14457 * downgrade. 14458 */ 14459 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14460 throws PackageManagerException { 14461 if (after.versionCode < before.mVersionCode) { 14462 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14463 "Update version code " + after.versionCode + " is older than current " 14464 + before.mVersionCode); 14465 } else if (after.versionCode == before.mVersionCode) { 14466 if (after.baseRevisionCode < before.baseRevisionCode) { 14467 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14468 "Update base revision code " + after.baseRevisionCode 14469 + " is older than current " + before.baseRevisionCode); 14470 } 14471 14472 if (!ArrayUtils.isEmpty(after.splitNames)) { 14473 for (int i = 0; i < after.splitNames.length; i++) { 14474 final String splitName = after.splitNames[i]; 14475 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14476 if (j != -1) { 14477 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14478 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14479 "Update split " + splitName + " revision code " 14480 + after.splitRevisionCodes[i] + " is older than current " 14481 + before.splitRevisionCodes[j]); 14482 } 14483 } 14484 } 14485 } 14486 } 14487 } 14488} 14489