PackageManagerService.java revision 7c6a34e64a52b71a6ea00efd2127a4814b5c72a6
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 564 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 565 final int filterCount = filters.size(); 566 ArraySet<String> domainsSet = new ArraySet<>(); 567 for (int m=0; m<filterCount; m++) { 568 PackageParser.ActivityIntentInfo filter = filters.get(m); 569 domainsSet.addAll(filter.getHostsList()); 570 } 571 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 572 synchronized (mPackages) { 573 if (mSettings.createIntentFilterVerificationIfNeededLPw( 574 packageName, domainsList) != null) { 575 scheduleWriteSettingsLocked(); 576 } 577 } 578 sendVerificationRequest(userId, verificationId, ivs); 579 } 580 mCurrentIntentFilterVerifications.clear(); 581 } 582 583 private void sendVerificationRequest(int userId, int verificationId, 584 IntentFilterVerificationState ivs) { 585 586 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 587 verificationIntent.putExtra( 588 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 589 verificationId); 590 verificationIntent.putExtra( 591 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 592 getDefaultScheme()); 593 verificationIntent.putExtra( 594 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 595 ivs.getHostsString()); 596 verificationIntent.putExtra( 597 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 598 ivs.getPackageName()); 599 verificationIntent.setComponent(mIntentFilterVerifierComponent); 600 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 601 602 UserHandle user = new UserHandle(userId); 603 mContext.sendBroadcastAsUser(verificationIntent, user); 604 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 605 } 606 607 public void receiveVerificationResponse(int verificationId) { 608 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 609 610 final boolean verified = ivs.isVerified(); 611 612 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 613 final int count = filters.size(); 614 for (int n=0; n<count; n++) { 615 PackageParser.ActivityIntentInfo filter = filters.get(n); 616 filter.setVerified(verified); 617 618 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 619 + verified + " and hosts:" + ivs.getHostsString()); 620 } 621 622 mIntentFilterVerificationStates.remove(verificationId); 623 624 final String packageName = ivs.getPackageName(); 625 IntentFilterVerificationInfo ivi = null; 626 627 synchronized (mPackages) { 628 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 629 } 630 if (ivi == null) { 631 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 632 + verificationId + " packageName:" + packageName); 633 return; 634 } 635 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 636 + verificationId); 637 638 synchronized (mPackages) { 639 if (verified) { 640 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 641 } else { 642 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 643 } 644 scheduleWriteSettingsLocked(); 645 646 final int userId = ivs.getUserId(); 647 if (userId != UserHandle.USER_ALL) { 648 final int userStatus = 649 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 650 651 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 652 boolean needUpdate = false; 653 654 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 655 // already been set by the User thru the Disambiguation dialog 656 switch (userStatus) { 657 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 658 if (verified) { 659 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 660 } else { 661 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 662 } 663 needUpdate = true; 664 break; 665 666 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 667 if (verified) { 668 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 669 needUpdate = true; 670 } 671 break; 672 673 default: 674 // Nothing to do 675 } 676 677 if (needUpdate) { 678 mSettings.updateIntentFilterVerificationStatusLPw( 679 packageName, updatedStatus, userId); 680 scheduleWritePackageRestrictionsLocked(userId); 681 } 682 } 683 } 684 } 685 686 @Override 687 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 688 ActivityIntentInfo filter, String packageName) { 689 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 690 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 691 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 692 return false; 693 } 694 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 695 if (ivs == null) { 696 ivs = createDomainVerificationState(verifierId, userId, verificationId, 697 packageName); 698 } 699 if (!hasValidDomains(filter)) { 700 return false; 701 } 702 ivs.addFilter(filter); 703 return true; 704 } 705 706 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 707 int userId, int verificationId, String packageName) { 708 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 709 verifierId, userId, packageName); 710 ivs.setPendingState(); 711 synchronized (mPackages) { 712 mIntentFilterVerificationStates.append(verificationId, ivs); 713 mCurrentIntentFilterVerifications.add(verificationId); 714 } 715 return ivs; 716 } 717 } 718 719 private static boolean hasValidDomains(ActivityIntentInfo filter) { 720 return hasValidDomains(filter, true); 721 } 722 723 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 724 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 725 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 726 if (!hasHTTPorHTTPS) { 727 if (logging) { 728 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 729 } 730 return false; 731 } 732 ArrayList<String> hosts = filter.getHostsList(); 733 if (hosts.size() == 0) { 734 if (logging) { 735 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 736 } 737 // We still return true as this is the case of any Browser 738 return true; 739 } 740 String hostEndBase = null; 741 for (String host : hosts) { 742 String[] hostParts = host.split("\\."); 743 // Should be at minimum a host like "example.com" 744 if (hostParts.length < 2) { 745 if (logging) { 746 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 747 } 748 return false; 749 } 750 // Verify that we have the same ending domain 751 int length = hostParts.length; 752 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 753 if (hostEndBase == null) { 754 hostEndBase = hostEnd; 755 } 756 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 757 if (logging) { 758 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 759 } 760 return false; 761 } 762 } 763 return true; 764 } 765 766 private IntentFilterVerifier mIntentFilterVerifier; 767 768 // Set of pending broadcasts for aggregating enable/disable of components. 769 static class PendingPackageBroadcasts { 770 // for each user id, a map of <package name -> components within that package> 771 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 772 773 public PendingPackageBroadcasts() { 774 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 775 } 776 777 public ArrayList<String> get(int userId, String packageName) { 778 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 779 return packages.get(packageName); 780 } 781 782 public void put(int userId, String packageName, ArrayList<String> components) { 783 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 784 packages.put(packageName, components); 785 } 786 787 public void remove(int userId, String packageName) { 788 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 789 if (packages != null) { 790 packages.remove(packageName); 791 } 792 } 793 794 public void remove(int userId) { 795 mUidMap.remove(userId); 796 } 797 798 public int userIdCount() { 799 return mUidMap.size(); 800 } 801 802 public int userIdAt(int n) { 803 return mUidMap.keyAt(n); 804 } 805 806 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 807 return mUidMap.get(userId); 808 } 809 810 public int size() { 811 // total number of pending broadcast entries across all userIds 812 int num = 0; 813 for (int i = 0; i< mUidMap.size(); i++) { 814 num += mUidMap.valueAt(i).size(); 815 } 816 return num; 817 } 818 819 public void clear() { 820 mUidMap.clear(); 821 } 822 823 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 824 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 825 if (map == null) { 826 map = new ArrayMap<String, ArrayList<String>>(); 827 mUidMap.put(userId, map); 828 } 829 return map; 830 } 831 } 832 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 833 834 // Service Connection to remote media container service to copy 835 // package uri's from external media onto secure containers 836 // or internal storage. 837 private IMediaContainerService mContainerService = null; 838 839 static final int SEND_PENDING_BROADCAST = 1; 840 static final int MCS_BOUND = 3; 841 static final int END_COPY = 4; 842 static final int INIT_COPY = 5; 843 static final int MCS_UNBIND = 6; 844 static final int START_CLEANING_PACKAGE = 7; 845 static final int FIND_INSTALL_LOC = 8; 846 static final int POST_INSTALL = 9; 847 static final int MCS_RECONNECT = 10; 848 static final int MCS_GIVE_UP = 11; 849 static final int UPDATED_MEDIA_STATUS = 12; 850 static final int WRITE_SETTINGS = 13; 851 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 852 static final int PACKAGE_VERIFIED = 15; 853 static final int CHECK_PENDING_VERIFICATION = 16; 854 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 855 static final int INTENT_FILTER_VERIFIED = 18; 856 857 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 858 859 // Delay time in millisecs 860 static final int BROADCAST_DELAY = 10 * 1000; 861 862 static UserManagerService sUserManager; 863 864 // Stores a list of users whose package restrictions file needs to be updated 865 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 866 867 final private DefaultContainerConnection mDefContainerConn = 868 new DefaultContainerConnection(); 869 class DefaultContainerConnection implements ServiceConnection { 870 public void onServiceConnected(ComponentName name, IBinder service) { 871 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 872 IMediaContainerService imcs = 873 IMediaContainerService.Stub.asInterface(service); 874 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 875 } 876 877 public void onServiceDisconnected(ComponentName name) { 878 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 879 } 880 }; 881 882 // Recordkeeping of restore-after-install operations that are currently in flight 883 // between the Package Manager and the Backup Manager 884 class PostInstallData { 885 public InstallArgs args; 886 public PackageInstalledInfo res; 887 888 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 889 args = _a; 890 res = _r; 891 } 892 }; 893 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 894 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 895 896 // backup/restore of preferred activity state 897 private static final String TAG_PREFERRED_BACKUP = "pa"; 898 899 private final String mRequiredVerifierPackage; 900 901 private final PackageUsage mPackageUsage = new PackageUsage(); 902 903 private class PackageUsage { 904 private static final int WRITE_INTERVAL 905 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 906 907 private final Object mFileLock = new Object(); 908 private final AtomicLong mLastWritten = new AtomicLong(0); 909 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 910 911 private boolean mIsHistoricalPackageUsageAvailable = true; 912 913 boolean isHistoricalPackageUsageAvailable() { 914 return mIsHistoricalPackageUsageAvailable; 915 } 916 917 void write(boolean force) { 918 if (force) { 919 writeInternal(); 920 return; 921 } 922 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 923 && !DEBUG_DEXOPT) { 924 return; 925 } 926 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 927 new Thread("PackageUsage_DiskWriter") { 928 @Override 929 public void run() { 930 try { 931 writeInternal(); 932 } finally { 933 mBackgroundWriteRunning.set(false); 934 } 935 } 936 }.start(); 937 } 938 } 939 940 private void writeInternal() { 941 synchronized (mPackages) { 942 synchronized (mFileLock) { 943 AtomicFile file = getFile(); 944 FileOutputStream f = null; 945 try { 946 f = file.startWrite(); 947 BufferedOutputStream out = new BufferedOutputStream(f); 948 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 949 StringBuilder sb = new StringBuilder(); 950 for (PackageParser.Package pkg : mPackages.values()) { 951 if (pkg.mLastPackageUsageTimeInMills == 0) { 952 continue; 953 } 954 sb.setLength(0); 955 sb.append(pkg.packageName); 956 sb.append(' '); 957 sb.append((long)pkg.mLastPackageUsageTimeInMills); 958 sb.append('\n'); 959 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 960 } 961 out.flush(); 962 file.finishWrite(f); 963 } catch (IOException e) { 964 if (f != null) { 965 file.failWrite(f); 966 } 967 Log.e(TAG, "Failed to write package usage times", e); 968 } 969 } 970 } 971 mLastWritten.set(SystemClock.elapsedRealtime()); 972 } 973 974 void readLP() { 975 synchronized (mFileLock) { 976 AtomicFile file = getFile(); 977 BufferedInputStream in = null; 978 try { 979 in = new BufferedInputStream(file.openRead()); 980 StringBuffer sb = new StringBuffer(); 981 while (true) { 982 String packageName = readToken(in, sb, ' '); 983 if (packageName == null) { 984 break; 985 } 986 String timeInMillisString = readToken(in, sb, '\n'); 987 if (timeInMillisString == null) { 988 throw new IOException("Failed to find last usage time for package " 989 + packageName); 990 } 991 PackageParser.Package pkg = mPackages.get(packageName); 992 if (pkg == null) { 993 continue; 994 } 995 long timeInMillis; 996 try { 997 timeInMillis = Long.parseLong(timeInMillisString.toString()); 998 } catch (NumberFormatException e) { 999 throw new IOException("Failed to parse " + timeInMillisString 1000 + " as a long.", e); 1001 } 1002 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1003 } 1004 } catch (FileNotFoundException expected) { 1005 mIsHistoricalPackageUsageAvailable = false; 1006 } catch (IOException e) { 1007 Log.w(TAG, "Failed to read package usage times", e); 1008 } finally { 1009 IoUtils.closeQuietly(in); 1010 } 1011 } 1012 mLastWritten.set(SystemClock.elapsedRealtime()); 1013 } 1014 1015 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1016 throws IOException { 1017 sb.setLength(0); 1018 while (true) { 1019 int ch = in.read(); 1020 if (ch == -1) { 1021 if (sb.length() == 0) { 1022 return null; 1023 } 1024 throw new IOException("Unexpected EOF"); 1025 } 1026 if (ch == endOfToken) { 1027 return sb.toString(); 1028 } 1029 sb.append((char)ch); 1030 } 1031 } 1032 1033 private AtomicFile getFile() { 1034 File dataDir = Environment.getDataDirectory(); 1035 File systemDir = new File(dataDir, "system"); 1036 File fname = new File(systemDir, "package-usage.list"); 1037 return new AtomicFile(fname); 1038 } 1039 } 1040 1041 class PackageHandler extends Handler { 1042 private boolean mBound = false; 1043 final ArrayList<HandlerParams> mPendingInstalls = 1044 new ArrayList<HandlerParams>(); 1045 1046 private boolean connectToService() { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1048 " DefaultContainerService"); 1049 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1050 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1051 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1052 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1053 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1054 mBound = true; 1055 return true; 1056 } 1057 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1058 return false; 1059 } 1060 1061 private void disconnectService() { 1062 mContainerService = null; 1063 mBound = false; 1064 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1065 mContext.unbindService(mDefContainerConn); 1066 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1067 } 1068 1069 PackageHandler(Looper looper) { 1070 super(looper); 1071 } 1072 1073 public void handleMessage(Message msg) { 1074 try { 1075 doHandleMessage(msg); 1076 } finally { 1077 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1078 } 1079 } 1080 1081 void doHandleMessage(Message msg) { 1082 switch (msg.what) { 1083 case INIT_COPY: { 1084 HandlerParams params = (HandlerParams) msg.obj; 1085 int idx = mPendingInstalls.size(); 1086 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1087 // If a bind was already initiated we dont really 1088 // need to do anything. The pending install 1089 // will be processed later on. 1090 if (!mBound) { 1091 // If this is the only one pending we might 1092 // have to bind to the service again. 1093 if (!connectToService()) { 1094 Slog.e(TAG, "Failed to bind to media container service"); 1095 params.serviceError(); 1096 return; 1097 } else { 1098 // Once we bind to the service, the first 1099 // pending request will be processed. 1100 mPendingInstalls.add(idx, params); 1101 } 1102 } else { 1103 mPendingInstalls.add(idx, params); 1104 // Already bound to the service. Just make 1105 // sure we trigger off processing the first request. 1106 if (idx == 0) { 1107 mHandler.sendEmptyMessage(MCS_BOUND); 1108 } 1109 } 1110 break; 1111 } 1112 case MCS_BOUND: { 1113 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1114 if (msg.obj != null) { 1115 mContainerService = (IMediaContainerService) msg.obj; 1116 } 1117 if (mContainerService == null) { 1118 // Something seriously wrong. Bail out 1119 Slog.e(TAG, "Cannot bind to media container service"); 1120 for (HandlerParams params : mPendingInstalls) { 1121 // Indicate service bind error 1122 params.serviceError(); 1123 } 1124 mPendingInstalls.clear(); 1125 } else if (mPendingInstalls.size() > 0) { 1126 HandlerParams params = mPendingInstalls.get(0); 1127 if (params != null) { 1128 if (params.startCopy()) { 1129 // We are done... look for more work or to 1130 // go idle. 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Checking for more work or unbind..."); 1133 // Delete pending install 1134 if (mPendingInstalls.size() > 0) { 1135 mPendingInstalls.remove(0); 1136 } 1137 if (mPendingInstalls.size() == 0) { 1138 if (mBound) { 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, 1140 "Posting delayed MCS_UNBIND"); 1141 removeMessages(MCS_UNBIND); 1142 Message ubmsg = obtainMessage(MCS_UNBIND); 1143 // Unbind after a little delay, to avoid 1144 // continual thrashing. 1145 sendMessageDelayed(ubmsg, 10000); 1146 } 1147 } else { 1148 // There are more pending requests in queue. 1149 // Just post MCS_BOUND message to trigger processing 1150 // of next pending install. 1151 if (DEBUG_SD_INSTALL) Log.i(TAG, 1152 "Posting MCS_BOUND for next work"); 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 } 1157 } else { 1158 // Should never happen ideally. 1159 Slog.w(TAG, "Empty queue"); 1160 } 1161 break; 1162 } 1163 case MCS_RECONNECT: { 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1165 if (mPendingInstalls.size() > 0) { 1166 if (mBound) { 1167 disconnectService(); 1168 } 1169 if (!connectToService()) { 1170 Slog.e(TAG, "Failed to bind to media container service"); 1171 for (HandlerParams params : mPendingInstalls) { 1172 // Indicate service bind error 1173 params.serviceError(); 1174 } 1175 mPendingInstalls.clear(); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_UNBIND: { 1181 // If there is no actual work left, then time to unbind. 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1183 1184 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1185 if (mBound) { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1187 1188 disconnectService(); 1189 } 1190 } else if (mPendingInstalls.size() > 0) { 1191 // There are more pending requests in queue. 1192 // Just post MCS_BOUND message to trigger processing 1193 // of next pending install. 1194 mHandler.sendEmptyMessage(MCS_BOUND); 1195 } 1196 1197 break; 1198 } 1199 case MCS_GIVE_UP: { 1200 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1201 mPendingInstalls.remove(0); 1202 break; 1203 } 1204 case SEND_PENDING_BROADCAST: { 1205 String packages[]; 1206 ArrayList<String> components[]; 1207 int size = 0; 1208 int uids[]; 1209 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1210 synchronized (mPackages) { 1211 if (mPendingBroadcasts == null) { 1212 return; 1213 } 1214 size = mPendingBroadcasts.size(); 1215 if (size <= 0) { 1216 // Nothing to be done. Just return 1217 return; 1218 } 1219 packages = new String[size]; 1220 components = new ArrayList[size]; 1221 uids = new int[size]; 1222 int i = 0; // filling out the above arrays 1223 1224 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1225 int packageUserId = mPendingBroadcasts.userIdAt(n); 1226 Iterator<Map.Entry<String, ArrayList<String>>> it 1227 = mPendingBroadcasts.packagesForUserId(packageUserId) 1228 .entrySet().iterator(); 1229 while (it.hasNext() && i < size) { 1230 Map.Entry<String, ArrayList<String>> ent = it.next(); 1231 packages[i] = ent.getKey(); 1232 components[i] = ent.getValue(); 1233 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1234 uids[i] = (ps != null) 1235 ? UserHandle.getUid(packageUserId, ps.appId) 1236 : -1; 1237 i++; 1238 } 1239 } 1240 size = i; 1241 mPendingBroadcasts.clear(); 1242 } 1243 // Send broadcasts 1244 for (int i = 0; i < size; i++) { 1245 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1246 } 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1248 break; 1249 } 1250 case START_CLEANING_PACKAGE: { 1251 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1252 final String packageName = (String)msg.obj; 1253 final int userId = msg.arg1; 1254 final boolean andCode = msg.arg2 != 0; 1255 synchronized (mPackages) { 1256 if (userId == UserHandle.USER_ALL) { 1257 int[] users = sUserManager.getUserIds(); 1258 for (int user : users) { 1259 mSettings.addPackageToCleanLPw( 1260 new PackageCleanItem(user, packageName, andCode)); 1261 } 1262 } else { 1263 mSettings.addPackageToCleanLPw( 1264 new PackageCleanItem(userId, packageName, andCode)); 1265 } 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 startCleaningPackages(); 1269 } break; 1270 case POST_INSTALL: { 1271 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1272 PostInstallData data = mRunningInstalls.get(msg.arg1); 1273 mRunningInstalls.delete(msg.arg1); 1274 boolean deleteOld = false; 1275 1276 if (data != null) { 1277 InstallArgs args = data.args; 1278 PackageInstalledInfo res = data.res; 1279 1280 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1281 res.removedInfo.sendBroadcast(false, true, false); 1282 Bundle extras = new Bundle(1); 1283 extras.putInt(Intent.EXTRA_UID, res.uid); 1284 1285 // Now that we successfully installed the package, grant runtime 1286 // permissions if requested before broadcasting the install. 1287 if ((args.installFlags 1288 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1289 grantRequestedRuntimePermissions(res.pkg, 1290 args.user.getIdentifier()); 1291 } 1292 1293 // Determine the set of users who are adding this 1294 // package for the first time vs. those who are seeing 1295 // an update. 1296 int[] firstUsers; 1297 int[] updateUsers = new int[0]; 1298 if (res.origUsers == null || res.origUsers.length == 0) { 1299 firstUsers = res.newUsers; 1300 } else { 1301 firstUsers = new int[0]; 1302 for (int i=0; i<res.newUsers.length; i++) { 1303 int user = res.newUsers[i]; 1304 boolean isNew = true; 1305 for (int j=0; j<res.origUsers.length; j++) { 1306 if (res.origUsers[j] == user) { 1307 isNew = false; 1308 break; 1309 } 1310 } 1311 if (isNew) { 1312 int[] newFirst = new int[firstUsers.length+1]; 1313 System.arraycopy(firstUsers, 0, newFirst, 0, 1314 firstUsers.length); 1315 newFirst[firstUsers.length] = user; 1316 firstUsers = newFirst; 1317 } else { 1318 int[] newUpdate = new int[updateUsers.length+1]; 1319 System.arraycopy(updateUsers, 0, newUpdate, 0, 1320 updateUsers.length); 1321 newUpdate[updateUsers.length] = user; 1322 updateUsers = newUpdate; 1323 } 1324 } 1325 } 1326 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1327 res.pkg.applicationInfo.packageName, 1328 extras, null, null, firstUsers); 1329 final boolean update = res.removedInfo.removedPackage != null; 1330 if (update) { 1331 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1332 } 1333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1334 res.pkg.applicationInfo.packageName, 1335 extras, null, null, updateUsers); 1336 if (update) { 1337 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1338 res.pkg.applicationInfo.packageName, 1339 extras, null, null, updateUsers); 1340 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1341 null, null, 1342 res.pkg.applicationInfo.packageName, null, updateUsers); 1343 1344 // treat asec-hosted packages like removable media on upgrade 1345 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1346 if (DEBUG_INSTALL) { 1347 Slog.i(TAG, "upgrading pkg " + res.pkg 1348 + " is ASEC-hosted -> AVAILABLE"); 1349 } 1350 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1351 ArrayList<String> pkgList = new ArrayList<String>(1); 1352 pkgList.add(res.pkg.applicationInfo.packageName); 1353 sendResourcesChangedBroadcast(true, true, 1354 pkgList,uidArray, null); 1355 } 1356 } 1357 if (res.removedInfo.args != null) { 1358 // Remove the replaced package's older resources safely now 1359 deleteOld = true; 1360 } 1361 1362 // Log current value of "unknown sources" setting 1363 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1364 getUnknownSourcesSettings()); 1365 } 1366 // Force a gc to clear up things 1367 Runtime.getRuntime().gc(); 1368 // We delete after a gc for applications on sdcard. 1369 if (deleteOld) { 1370 synchronized (mInstallLock) { 1371 res.removedInfo.args.doPostDeleteLI(true); 1372 } 1373 } 1374 if (args.observer != null) { 1375 try { 1376 Bundle extras = extrasForInstallResult(res); 1377 args.observer.onPackageInstalled(res.name, res.returnCode, 1378 res.returnMsg, extras); 1379 } catch (RemoteException e) { 1380 Slog.i(TAG, "Observer no longer exists."); 1381 } 1382 } 1383 } else { 1384 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1385 } 1386 } break; 1387 case UPDATED_MEDIA_STATUS: { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1389 boolean reportStatus = msg.arg1 == 1; 1390 boolean doGc = msg.arg2 == 1; 1391 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1392 if (doGc) { 1393 // Force a gc to clear up stale containers. 1394 Runtime.getRuntime().gc(); 1395 } 1396 if (msg.obj != null) { 1397 @SuppressWarnings("unchecked") 1398 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1400 // Unload containers 1401 unloadAllContainers(args); 1402 } 1403 if (reportStatus) { 1404 try { 1405 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1406 PackageHelper.getMountService().finishMediaUpdate(); 1407 } catch (RemoteException e) { 1408 Log.e(TAG, "MountService not running?"); 1409 } 1410 } 1411 } break; 1412 case WRITE_SETTINGS: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 synchronized (mPackages) { 1415 removeMessages(WRITE_SETTINGS); 1416 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1417 mSettings.writeLPr(); 1418 mDirtyUsers.clear(); 1419 } 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1421 } break; 1422 case WRITE_PACKAGE_RESTRICTIONS: { 1423 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1424 synchronized (mPackages) { 1425 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1426 for (int userId : mDirtyUsers) { 1427 mSettings.writePackageRestrictionsLPr(userId); 1428 } 1429 mDirtyUsers.clear(); 1430 } 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 } break; 1433 case CHECK_PENDING_VERIFICATION: { 1434 final int verificationId = msg.arg1; 1435 final PackageVerificationState state = mPendingVerification.get(verificationId); 1436 1437 if ((state != null) && !state.timeoutExtended()) { 1438 final InstallArgs args = state.getInstallArgs(); 1439 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1440 1441 Slog.i(TAG, "Verification timed out for " + originUri); 1442 mPendingVerification.remove(verificationId); 1443 1444 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1445 1446 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1447 Slog.i(TAG, "Continuing with installation of " + originUri); 1448 state.setVerifierResponse(Binder.getCallingUid(), 1449 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1450 broadcastPackageVerified(verificationId, originUri, 1451 PackageManager.VERIFICATION_ALLOW, 1452 state.getInstallArgs().getUser()); 1453 try { 1454 ret = args.copyApk(mContainerService, true); 1455 } catch (RemoteException e) { 1456 Slog.e(TAG, "Could not contact the ContainerService"); 1457 } 1458 } else { 1459 broadcastPackageVerified(verificationId, originUri, 1460 PackageManager.VERIFICATION_REJECT, 1461 state.getInstallArgs().getUser()); 1462 } 1463 1464 processPendingInstall(args, ret); 1465 mHandler.sendEmptyMessage(MCS_UNBIND); 1466 } 1467 break; 1468 } 1469 case PACKAGE_VERIFIED: { 1470 final int verificationId = msg.arg1; 1471 1472 final PackageVerificationState state = mPendingVerification.get(verificationId); 1473 if (state == null) { 1474 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1475 break; 1476 } 1477 1478 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1479 1480 state.setVerifierResponse(response.callerUid, response.code); 1481 1482 if (state.isVerificationComplete()) { 1483 mPendingVerification.remove(verificationId); 1484 1485 final InstallArgs args = state.getInstallArgs(); 1486 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1487 1488 int ret; 1489 if (state.isInstallAllowed()) { 1490 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1491 broadcastPackageVerified(verificationId, originUri, 1492 response.code, state.getInstallArgs().getUser()); 1493 try { 1494 ret = args.copyApk(mContainerService, true); 1495 } catch (RemoteException e) { 1496 Slog.e(TAG, "Could not contact the ContainerService"); 1497 } 1498 } else { 1499 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1500 } 1501 1502 processPendingInstall(args, ret); 1503 1504 mHandler.sendEmptyMessage(MCS_UNBIND); 1505 } 1506 1507 break; 1508 } 1509 case START_INTENT_FILTER_VERIFICATIONS: { 1510 int userId = msg.arg1; 1511 int verifierUid = msg.arg2; 1512 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1513 1514 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1515 break; 1516 } 1517 case INTENT_FILTER_VERIFIED: { 1518 final int verificationId = msg.arg1; 1519 1520 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1521 verificationId); 1522 if (state == null) { 1523 Slog.w(TAG, "Invalid IntentFilter verification token " 1524 + verificationId + " received"); 1525 break; 1526 } 1527 1528 final int userId = state.getUserId(); 1529 1530 Slog.d(TAG, "Processing IntentFilter verification with token:" 1531 + verificationId + " and userId:" + userId); 1532 1533 final IntentFilterVerificationResponse response = 1534 (IntentFilterVerificationResponse) msg.obj; 1535 1536 state.setVerifierResponse(response.callerUid, response.code); 1537 1538 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1539 + " and userId:" + userId 1540 + " is settings verifier response with response code:" 1541 + response.code); 1542 1543 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1544 Slog.d(TAG, "Domains failing verification: " 1545 + response.getFailedDomainsString()); 1546 } 1547 1548 if (state.isVerificationComplete()) { 1549 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1550 } else { 1551 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1552 + " was not said to be complete"); 1553 } 1554 1555 break; 1556 } 1557 } 1558 } 1559 } 1560 1561 private StorageEventListener mStorageListener = new StorageEventListener() { 1562 @Override 1563 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1564 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1565 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1566 loadPrivatePackages(vol); 1567 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1568 unloadPrivatePackages(vol); 1569 } 1570 } 1571 1572 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1573 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1574 updateExternalMediaStatus(true, false); 1575 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1576 updateExternalMediaStatus(false, false); 1577 } 1578 } 1579 } 1580 }; 1581 1582 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1583 if (userId >= UserHandle.USER_OWNER) { 1584 grantRequestedRuntimePermissionsForUser(pkg, userId); 1585 } else if (userId == UserHandle.USER_ALL) { 1586 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1587 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1588 } 1589 } 1590 } 1591 1592 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1593 SettingBase sb = (SettingBase) pkg.mExtras; 1594 if (sb == null) { 1595 return; 1596 } 1597 1598 PermissionsState permissionsState = sb.getPermissionsState(); 1599 1600 for (String permission : pkg.requestedPermissions) { 1601 BasePermission bp = mSettings.mPermissions.get(permission); 1602 if (bp != null && bp.isRuntime()) { 1603 permissionsState.grantRuntimePermission(bp, userId); 1604 } 1605 } 1606 } 1607 1608 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1609 Bundle extras = null; 1610 switch (res.returnCode) { 1611 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1612 extras = new Bundle(); 1613 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1614 res.origPermission); 1615 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1616 res.origPackage); 1617 break; 1618 } 1619 } 1620 return extras; 1621 } 1622 1623 void scheduleWriteSettingsLocked() { 1624 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1625 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1626 } 1627 } 1628 1629 void scheduleWritePackageRestrictionsLocked(int userId) { 1630 if (!sUserManager.exists(userId)) return; 1631 mDirtyUsers.add(userId); 1632 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1633 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1634 } 1635 } 1636 1637 public static PackageManagerService main(Context context, Installer installer, 1638 boolean factoryTest, boolean onlyCore) { 1639 PackageManagerService m = new PackageManagerService(context, installer, 1640 factoryTest, onlyCore); 1641 ServiceManager.addService("package", m); 1642 return m; 1643 } 1644 1645 static String[] splitString(String str, char sep) { 1646 int count = 1; 1647 int i = 0; 1648 while ((i=str.indexOf(sep, i)) >= 0) { 1649 count++; 1650 i++; 1651 } 1652 1653 String[] res = new String[count]; 1654 i=0; 1655 count = 0; 1656 int lastI=0; 1657 while ((i=str.indexOf(sep, i)) >= 0) { 1658 res[count] = str.substring(lastI, i); 1659 count++; 1660 i++; 1661 lastI = i; 1662 } 1663 res[count] = str.substring(lastI, str.length()); 1664 return res; 1665 } 1666 1667 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1668 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1669 Context.DISPLAY_SERVICE); 1670 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1671 } 1672 1673 public PackageManagerService(Context context, Installer installer, 1674 boolean factoryTest, boolean onlyCore) { 1675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1676 SystemClock.uptimeMillis()); 1677 1678 if (mSdkVersion <= 0) { 1679 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1680 } 1681 1682 mContext = context; 1683 mFactoryTest = factoryTest; 1684 mOnlyCore = onlyCore; 1685 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1686 mMetrics = new DisplayMetrics(); 1687 mSettings = new Settings(mPackages); 1688 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1689 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1690 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1691 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1692 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1693 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1694 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 1701 // TODO: add a property to control this? 1702 long dexOptLRUThresholdInMinutes; 1703 if (mLazyDexOpt) { 1704 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1705 } else { 1706 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1707 } 1708 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1709 1710 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1711 if (separateProcesses != null && separateProcesses.length() > 0) { 1712 if ("*".equals(separateProcesses)) { 1713 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1714 mSeparateProcesses = null; 1715 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1716 } else { 1717 mDefParseFlags = 0; 1718 mSeparateProcesses = separateProcesses.split(","); 1719 Slog.w(TAG, "Running with debug.separate_processes: " 1720 + separateProcesses); 1721 } 1722 } else { 1723 mDefParseFlags = 0; 1724 mSeparateProcesses = null; 1725 } 1726 1727 mInstaller = installer; 1728 mPackageDexOptimizer = new PackageDexOptimizer(this); 1729 1730 getDefaultDisplayMetrics(context, mMetrics); 1731 1732 SystemConfig systemConfig = SystemConfig.getInstance(); 1733 mGlobalGids = systemConfig.getGlobalGids(); 1734 mSystemPermissions = systemConfig.getSystemPermissions(); 1735 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1736 1737 synchronized (mInstallLock) { 1738 // writer 1739 synchronized (mPackages) { 1740 mHandlerThread = new ServiceThread(TAG, 1741 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1742 mHandlerThread.start(); 1743 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1744 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1745 1746 File dataDir = Environment.getDataDirectory(); 1747 mAppDataDir = new File(dataDir, "data"); 1748 mAppInstallDir = new File(dataDir, "app"); 1749 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1750 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1751 mUserAppDataDir = new File(dataDir, "user"); 1752 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1753 1754 sUserManager = new UserManagerService(context, this, 1755 mInstallLock, mPackages); 1756 1757 // Propagate permission configuration in to package manager. 1758 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1759 = systemConfig.getPermissions(); 1760 for (int i=0; i<permConfig.size(); i++) { 1761 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1762 BasePermission bp = mSettings.mPermissions.get(perm.name); 1763 if (bp == null) { 1764 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1765 mSettings.mPermissions.put(perm.name, bp); 1766 } 1767 if (perm.gids != null) { 1768 bp.setGids(perm.gids, perm.perUser); 1769 } 1770 } 1771 1772 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1773 for (int i=0; i<libConfig.size(); i++) { 1774 mSharedLibraries.put(libConfig.keyAt(i), 1775 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1776 } 1777 1778 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1779 1780 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1781 mSdkVersion, mOnlyCore); 1782 1783 String customResolverActivity = Resources.getSystem().getString( 1784 R.string.config_customResolverActivity); 1785 if (TextUtils.isEmpty(customResolverActivity)) { 1786 customResolverActivity = null; 1787 } else { 1788 mCustomResolverComponentName = ComponentName.unflattenFromString( 1789 customResolverActivity); 1790 } 1791 1792 long startTime = SystemClock.uptimeMillis(); 1793 1794 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1795 startTime); 1796 1797 // Set flag to monitor and not change apk file paths when 1798 // scanning install directories. 1799 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1800 1801 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1802 1803 /** 1804 * Add everything in the in the boot class path to the 1805 * list of process files because dexopt will have been run 1806 * if necessary during zygote startup. 1807 */ 1808 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1809 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1810 1811 if (bootClassPath != null) { 1812 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1813 for (String element : bootClassPathElements) { 1814 alreadyDexOpted.add(element); 1815 } 1816 } else { 1817 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1818 } 1819 1820 if (systemServerClassPath != null) { 1821 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1822 for (String element : systemServerClassPathElements) { 1823 alreadyDexOpted.add(element); 1824 } 1825 } else { 1826 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1827 } 1828 1829 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1830 final String[] dexCodeInstructionSets = 1831 getDexCodeInstructionSets( 1832 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1833 1834 /** 1835 * Ensure all external libraries have had dexopt run on them. 1836 */ 1837 if (mSharedLibraries.size() > 0) { 1838 // NOTE: For now, we're compiling these system "shared libraries" 1839 // (and framework jars) into all available architectures. It's possible 1840 // to compile them only when we come across an app that uses them (there's 1841 // already logic for that in scanPackageLI) but that adds some complexity. 1842 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1843 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1844 final String lib = libEntry.path; 1845 if (lib == null) { 1846 continue; 1847 } 1848 1849 try { 1850 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1851 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1852 alreadyDexOpted.add(lib); 1853 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1854 } 1855 } catch (FileNotFoundException e) { 1856 Slog.w(TAG, "Library not found: " + lib); 1857 } catch (IOException e) { 1858 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1859 + e.getMessage()); 1860 } 1861 } 1862 } 1863 } 1864 1865 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1866 1867 // Gross hack for now: we know this file doesn't contain any 1868 // code, so don't dexopt it to avoid the resulting log spew. 1869 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1870 1871 // Gross hack for now: we know this file is only part of 1872 // the boot class path for art, so don't dexopt it to 1873 // avoid the resulting log spew. 1874 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1875 1876 /** 1877 * And there are a number of commands implemented in Java, which 1878 * we currently need to do the dexopt on so that they can be 1879 * run from a non-root shell. 1880 */ 1881 String[] frameworkFiles = frameworkDir.list(); 1882 if (frameworkFiles != null) { 1883 // TODO: We could compile these only for the most preferred ABI. We should 1884 // first double check that the dex files for these commands are not referenced 1885 // by other system apps. 1886 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1887 for (int i=0; i<frameworkFiles.length; i++) { 1888 File libPath = new File(frameworkDir, frameworkFiles[i]); 1889 String path = libPath.getPath(); 1890 // Skip the file if we already did it. 1891 if (alreadyDexOpted.contains(path)) { 1892 continue; 1893 } 1894 // Skip the file if it is not a type we want to dexopt. 1895 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1896 continue; 1897 } 1898 try { 1899 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1900 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1901 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1902 } 1903 } catch (FileNotFoundException e) { 1904 Slog.w(TAG, "Jar not found: " + path); 1905 } catch (IOException e) { 1906 Slog.w(TAG, "Exception reading jar: " + path, e); 1907 } 1908 } 1909 } 1910 } 1911 1912 // Collect vendor overlay packages. 1913 // (Do this before scanning any apps.) 1914 // For security and version matching reason, only consider 1915 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1916 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1917 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1918 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1919 1920 // Find base frameworks (resource packages without code). 1921 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1922 | PackageParser.PARSE_IS_SYSTEM_DIR 1923 | PackageParser.PARSE_IS_PRIVILEGED, 1924 scanFlags | SCAN_NO_DEX, 0); 1925 1926 // Collected privileged system packages. 1927 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1928 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR 1930 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1931 1932 // Collect ordinary system packages. 1933 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1934 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1935 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1936 1937 // Collect all vendor packages. 1938 File vendorAppDir = new File("/vendor/app"); 1939 try { 1940 vendorAppDir = vendorAppDir.getCanonicalFile(); 1941 } catch (IOException e) { 1942 // failed to look up canonical path, continue with original one 1943 } 1944 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1945 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1946 1947 // Collect all OEM packages. 1948 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1949 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1950 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1951 1952 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1953 mInstaller.moveFiles(); 1954 1955 // Prune any system packages that no longer exist. 1956 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1957 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1958 if (!mOnlyCore) { 1959 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1960 while (psit.hasNext()) { 1961 PackageSetting ps = psit.next(); 1962 1963 /* 1964 * If this is not a system app, it can't be a 1965 * disable system app. 1966 */ 1967 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1968 continue; 1969 } 1970 1971 /* 1972 * If the package is scanned, it's not erased. 1973 */ 1974 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1975 if (scannedPkg != null) { 1976 /* 1977 * If the system app is both scanned and in the 1978 * disabled packages list, then it must have been 1979 * added via OTA. Remove it from the currently 1980 * scanned package so the previously user-installed 1981 * application can be scanned. 1982 */ 1983 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1984 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1985 + ps.name + "; removing system app. Last known codePath=" 1986 + ps.codePathString + ", installStatus=" + ps.installStatus 1987 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1988 + scannedPkg.mVersionCode); 1989 removePackageLI(ps, true); 1990 expectingBetter.put(ps.name, ps.codePath); 1991 } 1992 1993 continue; 1994 } 1995 1996 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1997 psit.remove(); 1998 logCriticalInfo(Log.WARN, "System package " + ps.name 1999 + " no longer exists; wiping its data"); 2000 removeDataDirsLI(ps.name); 2001 } else { 2002 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2003 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2004 possiblyDeletedUpdatedSystemApps.add(ps.name); 2005 } 2006 } 2007 } 2008 } 2009 2010 //look for any incomplete package installations 2011 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2012 //clean up list 2013 for(int i = 0; i < deletePkgsList.size(); i++) { 2014 //clean up here 2015 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2016 } 2017 //delete tmp files 2018 deleteTempPackageFiles(); 2019 2020 // Remove any shared userIDs that have no associated packages 2021 mSettings.pruneSharedUsersLPw(); 2022 2023 if (!mOnlyCore) { 2024 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2025 SystemClock.uptimeMillis()); 2026 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2027 2028 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2029 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2030 2031 /** 2032 * Remove disable package settings for any updated system 2033 * apps that were removed via an OTA. If they're not a 2034 * previously-updated app, remove them completely. 2035 * Otherwise, just revoke their system-level permissions. 2036 */ 2037 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2038 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2039 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2040 2041 String msg; 2042 if (deletedPkg == null) { 2043 msg = "Updated system package " + deletedAppName 2044 + " no longer exists; wiping its data"; 2045 removeDataDirsLI(deletedAppName); 2046 } else { 2047 msg = "Updated system app + " + deletedAppName 2048 + " no longer present; removing system privileges for " 2049 + deletedAppName; 2050 2051 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2052 2053 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2054 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2055 } 2056 logCriticalInfo(Log.WARN, msg); 2057 } 2058 2059 /** 2060 * Make sure all system apps that we expected to appear on 2061 * the userdata partition actually showed up. If they never 2062 * appeared, crawl back and revive the system version. 2063 */ 2064 for (int i = 0; i < expectingBetter.size(); i++) { 2065 final String packageName = expectingBetter.keyAt(i); 2066 if (!mPackages.containsKey(packageName)) { 2067 final File scanFile = expectingBetter.valueAt(i); 2068 2069 logCriticalInfo(Log.WARN, "Expected better " + packageName 2070 + " but never showed up; reverting to system"); 2071 2072 final int reparseFlags; 2073 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2074 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2075 | PackageParser.PARSE_IS_SYSTEM_DIR 2076 | PackageParser.PARSE_IS_PRIVILEGED; 2077 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR; 2083 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2084 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2085 | PackageParser.PARSE_IS_SYSTEM_DIR; 2086 } else { 2087 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2088 continue; 2089 } 2090 2091 mSettings.enableSystemPackageLPw(packageName); 2092 2093 try { 2094 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2095 } catch (PackageManagerException e) { 2096 Slog.e(TAG, "Failed to parse original system package: " 2097 + e.getMessage()); 2098 } 2099 } 2100 } 2101 } 2102 2103 // Now that we know all of the shared libraries, update all clients to have 2104 // the correct library paths. 2105 updateAllSharedLibrariesLPw(); 2106 2107 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2108 // NOTE: We ignore potential failures here during a system scan (like 2109 // the rest of the commands above) because there's precious little we 2110 // can do about it. A settings error is reported, though. 2111 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2112 false /* force dexopt */, false /* defer dexopt */); 2113 } 2114 2115 // Now that we know all the packages we are keeping, 2116 // read and update their last usage times. 2117 mPackageUsage.readLP(); 2118 2119 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2120 SystemClock.uptimeMillis()); 2121 Slog.i(TAG, "Time to scan packages: " 2122 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2123 + " seconds"); 2124 2125 // If the platform SDK has changed since the last time we booted, 2126 // we need to re-grant app permission to catch any new ones that 2127 // appear. This is really a hack, and means that apps can in some 2128 // cases get permissions that the user didn't initially explicitly 2129 // allow... it would be nice to have some better way to handle 2130 // this situation. 2131 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2132 != mSdkVersion; 2133 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2134 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2135 + "; regranting permissions for internal storage"); 2136 mSettings.mInternalSdkPlatform = mSdkVersion; 2137 2138 // For now runtime permissions are toggled via a system property. 2139 if (!RUNTIME_PERMISSIONS_ENABLED) { 2140 // Remove the runtime permissions state if the feature 2141 // was disabled by flipping the system property. 2142 mSettings.deleteRuntimePermissionsFiles(); 2143 } 2144 2145 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2146 | (regrantPermissions 2147 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2148 : 0)); 2149 2150 // If this is the first boot, and it is a normal boot, then 2151 // we need to initialize the default preferred apps. 2152 if (!mRestoredSettings && !onlyCore) { 2153 mSettings.readDefaultPreferredAppsLPw(this, 0); 2154 } 2155 2156 // If this is first boot after an OTA, and a normal boot, then 2157 // we need to clear code cache directories. 2158 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2159 if (mIsUpgrade && !onlyCore) { 2160 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2161 for (String pkgName : mSettings.mPackages.keySet()) { 2162 deleteCodeCacheDirsLI(pkgName); 2163 } 2164 mSettings.mFingerprint = Build.FINGERPRINT; 2165 } 2166 2167 // All the changes are done during package scanning. 2168 mSettings.updateInternalDatabaseVersion(); 2169 2170 // can downgrade to reader 2171 mSettings.writeLPr(); 2172 2173 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2174 SystemClock.uptimeMillis()); 2175 2176 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2177 2178 mInstallerService = new PackageInstallerService(context, this); 2179 2180 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2181 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2182 mIntentFilterVerifierComponent); 2183 2184 primeDomainVerificationsLPw(false); 2185 2186 } // synchronized (mPackages) 2187 } // synchronized (mInstallLock) 2188 2189 // Now after opening every single application zip, make sure they 2190 // are all flushed. Not really needed, but keeps things nice and 2191 // tidy. 2192 Runtime.getRuntime().gc(); 2193 } 2194 2195 @Override 2196 public boolean isFirstBoot() { 2197 return !mRestoredSettings; 2198 } 2199 2200 @Override 2201 public boolean isOnlyCoreApps() { 2202 return mOnlyCore; 2203 } 2204 2205 @Override 2206 public boolean isUpgrade() { 2207 return mIsUpgrade; 2208 } 2209 2210 private String getRequiredVerifierLPr() { 2211 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2212 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2213 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2214 2215 String requiredVerifier = null; 2216 2217 final int N = receivers.size(); 2218 for (int i = 0; i < N; i++) { 2219 final ResolveInfo info = receivers.get(i); 2220 2221 if (info.activityInfo == null) { 2222 continue; 2223 } 2224 2225 final String packageName = info.activityInfo.packageName; 2226 2227 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2228 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2229 continue; 2230 } 2231 2232 if (requiredVerifier != null) { 2233 throw new RuntimeException("There can be only one required verifier"); 2234 } 2235 2236 requiredVerifier = packageName; 2237 } 2238 2239 return requiredVerifier; 2240 } 2241 2242 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2243 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2244 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2245 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2246 2247 ComponentName verifierComponentName = null; 2248 2249 int priority = -1000; 2250 final int N = receivers.size(); 2251 for (int i = 0; i < N; i++) { 2252 final ResolveInfo info = receivers.get(i); 2253 2254 if (info.activityInfo == null) { 2255 continue; 2256 } 2257 2258 final String packageName = info.activityInfo.packageName; 2259 2260 final PackageSetting ps = mSettings.mPackages.get(packageName); 2261 if (ps == null) { 2262 continue; 2263 } 2264 2265 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2266 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2267 continue; 2268 } 2269 2270 // Select the IntentFilterVerifier with the highest priority 2271 if (priority < info.priority) { 2272 priority = info.priority; 2273 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2274 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2275 " with priority: " + info.priority); 2276 } 2277 } 2278 2279 return verifierComponentName; 2280 } 2281 2282 private void primeDomainVerificationsLPw(boolean logging) { 2283 Slog.d(TAG, "Start priming domain verification"); 2284 boolean updated = false; 2285 ArrayList<String> allHosts = new ArrayList<>(); 2286 for (PackageParser.Package pkg : mPackages.values()) { 2287 final String packageName = pkg.packageName; 2288 if (!hasDomainURLs(pkg)) { 2289 if (logging) { 2290 Slog.d(TAG, "No priming domain verifications for " + 2291 "package with no domain URLs: " + packageName); 2292 } 2293 continue; 2294 } 2295 for (PackageParser.Activity a : pkg.activities) { 2296 for (ActivityIntentInfo filter : a.intents) { 2297 if (hasValidDomains(filter, false)) { 2298 allHosts.addAll(filter.getHostsList()); 2299 } 2300 } 2301 } 2302 if (allHosts.size() > 0) { 2303 allHosts.add("*"); 2304 } 2305 IntentFilterVerificationInfo ivi = 2306 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2307 if (ivi != null) { 2308 // We will always log this 2309 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2310 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2311 updated = true; 2312 } 2313 else { 2314 if (logging) { 2315 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2316 } 2317 } 2318 allHosts.clear(); 2319 } 2320 if (updated) { 2321 scheduleWriteSettingsLocked(); 2322 } 2323 Slog.d(TAG, "End priming domain verification"); 2324 } 2325 2326 @Override 2327 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2328 throws RemoteException { 2329 try { 2330 return super.onTransact(code, data, reply, flags); 2331 } catch (RuntimeException e) { 2332 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2333 Slog.wtf(TAG, "Package Manager Crash", e); 2334 } 2335 throw e; 2336 } 2337 } 2338 2339 void cleanupInstallFailedPackage(PackageSetting ps) { 2340 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2341 2342 removeDataDirsLI(ps.name); 2343 if (ps.codePath != null) { 2344 if (ps.codePath.isDirectory()) { 2345 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2346 } else { 2347 ps.codePath.delete(); 2348 } 2349 } 2350 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2351 if (ps.resourcePath.isDirectory()) { 2352 FileUtils.deleteContents(ps.resourcePath); 2353 } 2354 ps.resourcePath.delete(); 2355 } 2356 mSettings.removePackageLPw(ps.name); 2357 } 2358 2359 static int[] appendInts(int[] cur, int[] add) { 2360 if (add == null) return cur; 2361 if (cur == null) return add; 2362 final int N = add.length; 2363 for (int i=0; i<N; i++) { 2364 cur = appendInt(cur, add[i]); 2365 } 2366 return cur; 2367 } 2368 2369 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2370 if (!sUserManager.exists(userId)) return null; 2371 final PackageSetting ps = (PackageSetting) p.mExtras; 2372 if (ps == null) { 2373 return null; 2374 } 2375 2376 final PermissionsState permissionsState = ps.getPermissionsState(); 2377 2378 final int[] gids = permissionsState.computeGids(userId); 2379 final Set<String> permissions = permissionsState.getPermissions(userId); 2380 final PackageUserState state = ps.readUserState(userId); 2381 2382 return PackageParser.generatePackageInfo(p, gids, flags, 2383 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2384 } 2385 2386 @Override 2387 public boolean isPackageAvailable(String packageName, int userId) { 2388 if (!sUserManager.exists(userId)) return false; 2389 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2390 synchronized (mPackages) { 2391 PackageParser.Package p = mPackages.get(packageName); 2392 if (p != null) { 2393 final PackageSetting ps = (PackageSetting) p.mExtras; 2394 if (ps != null) { 2395 final PackageUserState state = ps.readUserState(userId); 2396 if (state != null) { 2397 return PackageParser.isAvailable(state); 2398 } 2399 } 2400 } 2401 } 2402 return false; 2403 } 2404 2405 @Override 2406 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2407 if (!sUserManager.exists(userId)) return null; 2408 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2409 // reader 2410 synchronized (mPackages) { 2411 PackageParser.Package p = mPackages.get(packageName); 2412 if (DEBUG_PACKAGE_INFO) 2413 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2414 if (p != null) { 2415 return generatePackageInfo(p, flags, userId); 2416 } 2417 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2418 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2419 } 2420 } 2421 return null; 2422 } 2423 2424 @Override 2425 public String[] currentToCanonicalPackageNames(String[] names) { 2426 String[] out = new String[names.length]; 2427 // reader 2428 synchronized (mPackages) { 2429 for (int i=names.length-1; i>=0; i--) { 2430 PackageSetting ps = mSettings.mPackages.get(names[i]); 2431 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2432 } 2433 } 2434 return out; 2435 } 2436 2437 @Override 2438 public String[] canonicalToCurrentPackageNames(String[] names) { 2439 String[] out = new String[names.length]; 2440 // reader 2441 synchronized (mPackages) { 2442 for (int i=names.length-1; i>=0; i--) { 2443 String cur = mSettings.mRenamedPackages.get(names[i]); 2444 out[i] = cur != null ? cur : names[i]; 2445 } 2446 } 2447 return out; 2448 } 2449 2450 @Override 2451 public int getPackageUid(String packageName, int userId) { 2452 if (!sUserManager.exists(userId)) return -1; 2453 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2454 2455 // reader 2456 synchronized (mPackages) { 2457 PackageParser.Package p = mPackages.get(packageName); 2458 if(p != null) { 2459 return UserHandle.getUid(userId, p.applicationInfo.uid); 2460 } 2461 PackageSetting ps = mSettings.mPackages.get(packageName); 2462 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2463 return -1; 2464 } 2465 p = ps.pkg; 2466 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2467 } 2468 } 2469 2470 @Override 2471 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2472 if (!sUserManager.exists(userId)) { 2473 return null; 2474 } 2475 2476 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2477 "getPackageGids"); 2478 2479 // reader 2480 synchronized (mPackages) { 2481 PackageParser.Package p = mPackages.get(packageName); 2482 if (DEBUG_PACKAGE_INFO) { 2483 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2484 } 2485 if (p != null) { 2486 PackageSetting ps = (PackageSetting) p.mExtras; 2487 return ps.getPermissionsState().computeGids(userId); 2488 } 2489 } 2490 2491 return null; 2492 } 2493 2494 static PermissionInfo generatePermissionInfo( 2495 BasePermission bp, int flags) { 2496 if (bp.perm != null) { 2497 return PackageParser.generatePermissionInfo(bp.perm, flags); 2498 } 2499 PermissionInfo pi = new PermissionInfo(); 2500 pi.name = bp.name; 2501 pi.packageName = bp.sourcePackage; 2502 pi.nonLocalizedLabel = bp.name; 2503 pi.protectionLevel = bp.protectionLevel; 2504 return pi; 2505 } 2506 2507 @Override 2508 public PermissionInfo getPermissionInfo(String name, int flags) { 2509 // reader 2510 synchronized (mPackages) { 2511 final BasePermission p = mSettings.mPermissions.get(name); 2512 if (p != null) { 2513 return generatePermissionInfo(p, flags); 2514 } 2515 return null; 2516 } 2517 } 2518 2519 @Override 2520 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2521 // reader 2522 synchronized (mPackages) { 2523 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2524 for (BasePermission p : mSettings.mPermissions.values()) { 2525 if (group == null) { 2526 if (p.perm == null || p.perm.info.group == null) { 2527 out.add(generatePermissionInfo(p, flags)); 2528 } 2529 } else { 2530 if (p.perm != null && group.equals(p.perm.info.group)) { 2531 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2532 } 2533 } 2534 } 2535 2536 if (out.size() > 0) { 2537 return out; 2538 } 2539 return mPermissionGroups.containsKey(group) ? out : null; 2540 } 2541 } 2542 2543 @Override 2544 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2545 // reader 2546 synchronized (mPackages) { 2547 return PackageParser.generatePermissionGroupInfo( 2548 mPermissionGroups.get(name), flags); 2549 } 2550 } 2551 2552 @Override 2553 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2554 // reader 2555 synchronized (mPackages) { 2556 final int N = mPermissionGroups.size(); 2557 ArrayList<PermissionGroupInfo> out 2558 = new ArrayList<PermissionGroupInfo>(N); 2559 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2560 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2561 } 2562 return out; 2563 } 2564 } 2565 2566 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2567 int userId) { 2568 if (!sUserManager.exists(userId)) return null; 2569 PackageSetting ps = mSettings.mPackages.get(packageName); 2570 if (ps != null) { 2571 if (ps.pkg == null) { 2572 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2573 flags, userId); 2574 if (pInfo != null) { 2575 return pInfo.applicationInfo; 2576 } 2577 return null; 2578 } 2579 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2580 ps.readUserState(userId), userId); 2581 } 2582 return null; 2583 } 2584 2585 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2586 int userId) { 2587 if (!sUserManager.exists(userId)) return null; 2588 PackageSetting ps = mSettings.mPackages.get(packageName); 2589 if (ps != null) { 2590 PackageParser.Package pkg = ps.pkg; 2591 if (pkg == null) { 2592 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2593 return null; 2594 } 2595 // Only data remains, so we aren't worried about code paths 2596 pkg = new PackageParser.Package(packageName); 2597 pkg.applicationInfo.packageName = packageName; 2598 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2599 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2600 pkg.applicationInfo.dataDir = 2601 getDataPathForPackage(packageName, 0).getPath(); 2602 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2603 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2604 } 2605 return generatePackageInfo(pkg, flags, userId); 2606 } 2607 return null; 2608 } 2609 2610 @Override 2611 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2612 if (!sUserManager.exists(userId)) return null; 2613 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2614 // writer 2615 synchronized (mPackages) { 2616 PackageParser.Package p = mPackages.get(packageName); 2617 if (DEBUG_PACKAGE_INFO) Log.v( 2618 TAG, "getApplicationInfo " + packageName 2619 + ": " + p); 2620 if (p != null) { 2621 PackageSetting ps = mSettings.mPackages.get(packageName); 2622 if (ps == null) return null; 2623 // Note: isEnabledLP() does not apply here - always return info 2624 return PackageParser.generateApplicationInfo( 2625 p, flags, ps.readUserState(userId), userId); 2626 } 2627 if ("android".equals(packageName)||"system".equals(packageName)) { 2628 return mAndroidApplication; 2629 } 2630 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2631 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2632 } 2633 } 2634 return null; 2635 } 2636 2637 2638 @Override 2639 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2640 mContext.enforceCallingOrSelfPermission( 2641 android.Manifest.permission.CLEAR_APP_CACHE, null); 2642 // Queue up an async operation since clearing cache may take a little while. 2643 mHandler.post(new Runnable() { 2644 public void run() { 2645 mHandler.removeCallbacks(this); 2646 int retCode = -1; 2647 synchronized (mInstallLock) { 2648 retCode = mInstaller.freeCache(freeStorageSize); 2649 if (retCode < 0) { 2650 Slog.w(TAG, "Couldn't clear application caches"); 2651 } 2652 } 2653 if (observer != null) { 2654 try { 2655 observer.onRemoveCompleted(null, (retCode >= 0)); 2656 } catch (RemoteException e) { 2657 Slog.w(TAG, "RemoveException when invoking call back"); 2658 } 2659 } 2660 } 2661 }); 2662 } 2663 2664 @Override 2665 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2666 mContext.enforceCallingOrSelfPermission( 2667 android.Manifest.permission.CLEAR_APP_CACHE, null); 2668 // Queue up an async operation since clearing cache may take a little while. 2669 mHandler.post(new Runnable() { 2670 public void run() { 2671 mHandler.removeCallbacks(this); 2672 int retCode = -1; 2673 synchronized (mInstallLock) { 2674 retCode = mInstaller.freeCache(freeStorageSize); 2675 if (retCode < 0) { 2676 Slog.w(TAG, "Couldn't clear application caches"); 2677 } 2678 } 2679 if(pi != null) { 2680 try { 2681 // Callback via pending intent 2682 int code = (retCode >= 0) ? 1 : 0; 2683 pi.sendIntent(null, code, null, 2684 null, null); 2685 } catch (SendIntentException e1) { 2686 Slog.i(TAG, "Failed to send pending intent"); 2687 } 2688 } 2689 } 2690 }); 2691 } 2692 2693 void freeStorage(long freeStorageSize) throws IOException { 2694 synchronized (mInstallLock) { 2695 if (mInstaller.freeCache(freeStorageSize) < 0) { 2696 throw new IOException("Failed to free enough space"); 2697 } 2698 } 2699 } 2700 2701 @Override 2702 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2703 if (!sUserManager.exists(userId)) return null; 2704 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2705 synchronized (mPackages) { 2706 PackageParser.Activity a = mActivities.mActivities.get(component); 2707 2708 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2709 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2710 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2711 if (ps == null) return null; 2712 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2713 userId); 2714 } 2715 if (mResolveComponentName.equals(component)) { 2716 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2717 new PackageUserState(), userId); 2718 } 2719 } 2720 return null; 2721 } 2722 2723 @Override 2724 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2725 String resolvedType) { 2726 synchronized (mPackages) { 2727 PackageParser.Activity a = mActivities.mActivities.get(component); 2728 if (a == null) { 2729 return false; 2730 } 2731 for (int i=0; i<a.intents.size(); i++) { 2732 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2733 intent.getData(), intent.getCategories(), TAG) >= 0) { 2734 return true; 2735 } 2736 } 2737 return false; 2738 } 2739 } 2740 2741 @Override 2742 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2743 if (!sUserManager.exists(userId)) return null; 2744 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2745 synchronized (mPackages) { 2746 PackageParser.Activity a = mReceivers.mActivities.get(component); 2747 if (DEBUG_PACKAGE_INFO) Log.v( 2748 TAG, "getReceiverInfo " + component + ": " + a); 2749 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2750 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2751 if (ps == null) return null; 2752 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2753 userId); 2754 } 2755 } 2756 return null; 2757 } 2758 2759 @Override 2760 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2761 if (!sUserManager.exists(userId)) return null; 2762 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2763 synchronized (mPackages) { 2764 PackageParser.Service s = mServices.mServices.get(component); 2765 if (DEBUG_PACKAGE_INFO) Log.v( 2766 TAG, "getServiceInfo " + component + ": " + s); 2767 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2768 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2769 if (ps == null) return null; 2770 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2771 userId); 2772 } 2773 } 2774 return null; 2775 } 2776 2777 @Override 2778 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2779 if (!sUserManager.exists(userId)) return null; 2780 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2781 synchronized (mPackages) { 2782 PackageParser.Provider p = mProviders.mProviders.get(component); 2783 if (DEBUG_PACKAGE_INFO) Log.v( 2784 TAG, "getProviderInfo " + component + ": " + p); 2785 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2786 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2787 if (ps == null) return null; 2788 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2789 userId); 2790 } 2791 } 2792 return null; 2793 } 2794 2795 @Override 2796 public String[] getSystemSharedLibraryNames() { 2797 Set<String> libSet; 2798 synchronized (mPackages) { 2799 libSet = mSharedLibraries.keySet(); 2800 int size = libSet.size(); 2801 if (size > 0) { 2802 String[] libs = new String[size]; 2803 libSet.toArray(libs); 2804 return libs; 2805 } 2806 } 2807 return null; 2808 } 2809 2810 /** 2811 * @hide 2812 */ 2813 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2814 synchronized (mPackages) { 2815 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2816 if (lib != null && lib.apk != null) { 2817 return mPackages.get(lib.apk); 2818 } 2819 } 2820 return null; 2821 } 2822 2823 @Override 2824 public FeatureInfo[] getSystemAvailableFeatures() { 2825 Collection<FeatureInfo> featSet; 2826 synchronized (mPackages) { 2827 featSet = mAvailableFeatures.values(); 2828 int size = featSet.size(); 2829 if (size > 0) { 2830 FeatureInfo[] features = new FeatureInfo[size+1]; 2831 featSet.toArray(features); 2832 FeatureInfo fi = new FeatureInfo(); 2833 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2834 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2835 features[size] = fi; 2836 return features; 2837 } 2838 } 2839 return null; 2840 } 2841 2842 @Override 2843 public boolean hasSystemFeature(String name) { 2844 synchronized (mPackages) { 2845 return mAvailableFeatures.containsKey(name); 2846 } 2847 } 2848 2849 private void checkValidCaller(int uid, int userId) { 2850 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2851 return; 2852 2853 throw new SecurityException("Caller uid=" + uid 2854 + " is not privileged to communicate with user=" + userId); 2855 } 2856 2857 @Override 2858 public int checkPermission(String permName, String pkgName, int userId) { 2859 if (!sUserManager.exists(userId)) { 2860 return PackageManager.PERMISSION_DENIED; 2861 } 2862 2863 synchronized (mPackages) { 2864 final PackageParser.Package p = mPackages.get(pkgName); 2865 if (p != null && p.mExtras != null) { 2866 final PackageSetting ps = (PackageSetting) p.mExtras; 2867 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2868 return PackageManager.PERMISSION_GRANTED; 2869 } 2870 } 2871 } 2872 2873 return PackageManager.PERMISSION_DENIED; 2874 } 2875 2876 @Override 2877 public int checkUidPermission(String permName, int uid) { 2878 final int userId = UserHandle.getUserId(uid); 2879 2880 if (!sUserManager.exists(userId)) { 2881 return PackageManager.PERMISSION_DENIED; 2882 } 2883 2884 synchronized (mPackages) { 2885 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2886 if (obj != null) { 2887 final SettingBase ps = (SettingBase) obj; 2888 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2889 return PackageManager.PERMISSION_GRANTED; 2890 } 2891 } else { 2892 ArraySet<String> perms = mSystemPermissions.get(uid); 2893 if (perms != null && perms.contains(permName)) { 2894 return PackageManager.PERMISSION_GRANTED; 2895 } 2896 } 2897 } 2898 2899 return PackageManager.PERMISSION_DENIED; 2900 } 2901 2902 /** 2903 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2904 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2905 * @param checkShell TODO(yamasani): 2906 * @param message the message to log on security exception 2907 */ 2908 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2909 boolean checkShell, String message) { 2910 if (userId < 0) { 2911 throw new IllegalArgumentException("Invalid userId " + userId); 2912 } 2913 if (checkShell) { 2914 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2915 } 2916 if (userId == UserHandle.getUserId(callingUid)) return; 2917 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2918 if (requireFullPermission) { 2919 mContext.enforceCallingOrSelfPermission( 2920 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2921 } else { 2922 try { 2923 mContext.enforceCallingOrSelfPermission( 2924 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2925 } catch (SecurityException se) { 2926 mContext.enforceCallingOrSelfPermission( 2927 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2928 } 2929 } 2930 } 2931 } 2932 2933 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2934 if (callingUid == Process.SHELL_UID) { 2935 if (userHandle >= 0 2936 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2937 throw new SecurityException("Shell does not have permission to access user " 2938 + userHandle); 2939 } else if (userHandle < 0) { 2940 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2941 + Debug.getCallers(3)); 2942 } 2943 } 2944 } 2945 2946 private BasePermission findPermissionTreeLP(String permName) { 2947 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2948 if (permName.startsWith(bp.name) && 2949 permName.length() > bp.name.length() && 2950 permName.charAt(bp.name.length()) == '.') { 2951 return bp; 2952 } 2953 } 2954 return null; 2955 } 2956 2957 private BasePermission checkPermissionTreeLP(String permName) { 2958 if (permName != null) { 2959 BasePermission bp = findPermissionTreeLP(permName); 2960 if (bp != null) { 2961 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2962 return bp; 2963 } 2964 throw new SecurityException("Calling uid " 2965 + Binder.getCallingUid() 2966 + " is not allowed to add to permission tree " 2967 + bp.name + " owned by uid " + bp.uid); 2968 } 2969 } 2970 throw new SecurityException("No permission tree found for " + permName); 2971 } 2972 2973 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2974 if (s1 == null) { 2975 return s2 == null; 2976 } 2977 if (s2 == null) { 2978 return false; 2979 } 2980 if (s1.getClass() != s2.getClass()) { 2981 return false; 2982 } 2983 return s1.equals(s2); 2984 } 2985 2986 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2987 if (pi1.icon != pi2.icon) return false; 2988 if (pi1.logo != pi2.logo) return false; 2989 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2990 if (!compareStrings(pi1.name, pi2.name)) return false; 2991 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2992 // We'll take care of setting this one. 2993 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2994 // These are not currently stored in settings. 2995 //if (!compareStrings(pi1.group, pi2.group)) return false; 2996 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2997 //if (pi1.labelRes != pi2.labelRes) return false; 2998 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2999 return true; 3000 } 3001 3002 int permissionInfoFootprint(PermissionInfo info) { 3003 int size = info.name.length(); 3004 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3005 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3006 return size; 3007 } 3008 3009 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3010 int size = 0; 3011 for (BasePermission perm : mSettings.mPermissions.values()) { 3012 if (perm.uid == tree.uid) { 3013 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3014 } 3015 } 3016 return size; 3017 } 3018 3019 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3020 // We calculate the max size of permissions defined by this uid and throw 3021 // if that plus the size of 'info' would exceed our stated maximum. 3022 if (tree.uid != Process.SYSTEM_UID) { 3023 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3024 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3025 throw new SecurityException("Permission tree size cap exceeded"); 3026 } 3027 } 3028 } 3029 3030 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3031 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3032 throw new SecurityException("Label must be specified in permission"); 3033 } 3034 BasePermission tree = checkPermissionTreeLP(info.name); 3035 BasePermission bp = mSettings.mPermissions.get(info.name); 3036 boolean added = bp == null; 3037 boolean changed = true; 3038 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3039 if (added) { 3040 enforcePermissionCapLocked(info, tree); 3041 bp = new BasePermission(info.name, tree.sourcePackage, 3042 BasePermission.TYPE_DYNAMIC); 3043 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3044 throw new SecurityException( 3045 "Not allowed to modify non-dynamic permission " 3046 + info.name); 3047 } else { 3048 if (bp.protectionLevel == fixedLevel 3049 && bp.perm.owner.equals(tree.perm.owner) 3050 && bp.uid == tree.uid 3051 && comparePermissionInfos(bp.perm.info, info)) { 3052 changed = false; 3053 } 3054 } 3055 bp.protectionLevel = fixedLevel; 3056 info = new PermissionInfo(info); 3057 info.protectionLevel = fixedLevel; 3058 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3059 bp.perm.info.packageName = tree.perm.info.packageName; 3060 bp.uid = tree.uid; 3061 if (added) { 3062 mSettings.mPermissions.put(info.name, bp); 3063 } 3064 if (changed) { 3065 if (!async) { 3066 mSettings.writeLPr(); 3067 } else { 3068 scheduleWriteSettingsLocked(); 3069 } 3070 } 3071 return added; 3072 } 3073 3074 @Override 3075 public boolean addPermission(PermissionInfo info) { 3076 synchronized (mPackages) { 3077 return addPermissionLocked(info, false); 3078 } 3079 } 3080 3081 @Override 3082 public boolean addPermissionAsync(PermissionInfo info) { 3083 synchronized (mPackages) { 3084 return addPermissionLocked(info, true); 3085 } 3086 } 3087 3088 @Override 3089 public void removePermission(String name) { 3090 synchronized (mPackages) { 3091 checkPermissionTreeLP(name); 3092 BasePermission bp = mSettings.mPermissions.get(name); 3093 if (bp != null) { 3094 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3095 throw new SecurityException( 3096 "Not allowed to modify non-dynamic permission " 3097 + name); 3098 } 3099 mSettings.mPermissions.remove(name); 3100 mSettings.writeLPr(); 3101 } 3102 } 3103 } 3104 3105 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3106 BasePermission bp) { 3107 int index = pkg.requestedPermissions.indexOf(bp.name); 3108 if (index == -1) { 3109 throw new SecurityException("Package " + pkg.packageName 3110 + " has not requested permission " + bp.name); 3111 } 3112 if (!bp.isRuntime()) { 3113 throw new SecurityException("Permission " + bp.name 3114 + " is not a changeable permission type"); 3115 } 3116 } 3117 3118 @Override 3119 public boolean grantPermission(String packageName, String name, int userId) { 3120 if (!RUNTIME_PERMISSIONS_ENABLED) { 3121 return false; 3122 } 3123 3124 if (!sUserManager.exists(userId)) { 3125 return false; 3126 } 3127 3128 mContext.enforceCallingOrSelfPermission( 3129 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3130 "grantPermission"); 3131 3132 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3133 "grantPermission"); 3134 3135 boolean gidsChanged = false; 3136 final SettingBase sb; 3137 3138 synchronized (mPackages) { 3139 final PackageParser.Package pkg = mPackages.get(packageName); 3140 if (pkg == null) { 3141 throw new IllegalArgumentException("Unknown package: " + packageName); 3142 } 3143 3144 final BasePermission bp = mSettings.mPermissions.get(name); 3145 if (bp == null) { 3146 throw new IllegalArgumentException("Unknown permission: " + name); 3147 } 3148 3149 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3150 3151 sb = (SettingBase) pkg.mExtras; 3152 if (sb == null) { 3153 throw new IllegalArgumentException("Unknown package: " + packageName); 3154 } 3155 3156 final PermissionsState permissionsState = sb.getPermissionsState(); 3157 3158 final int result = permissionsState.grantRuntimePermission(bp, userId); 3159 switch (result) { 3160 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3161 return false; 3162 } 3163 3164 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3165 gidsChanged = true; 3166 } break; 3167 } 3168 3169 // Not critical if that is lost - app has to request again. 3170 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3171 } 3172 3173 if (gidsChanged) { 3174 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3175 } 3176 3177 return true; 3178 } 3179 3180 @Override 3181 public boolean revokePermission(String packageName, String name, int userId) { 3182 if (!RUNTIME_PERMISSIONS_ENABLED) { 3183 return false; 3184 } 3185 3186 if (!sUserManager.exists(userId)) { 3187 return false; 3188 } 3189 3190 mContext.enforceCallingOrSelfPermission( 3191 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3192 "revokePermission"); 3193 3194 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3195 "revokePermission"); 3196 3197 final SettingBase sb; 3198 3199 synchronized (mPackages) { 3200 final PackageParser.Package pkg = mPackages.get(packageName); 3201 if (pkg == null) { 3202 throw new IllegalArgumentException("Unknown package: " + packageName); 3203 } 3204 3205 final BasePermission bp = mSettings.mPermissions.get(name); 3206 if (bp == null) { 3207 throw new IllegalArgumentException("Unknown permission: " + name); 3208 } 3209 3210 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3211 3212 sb = (SettingBase) pkg.mExtras; 3213 if (sb == null) { 3214 throw new IllegalArgumentException("Unknown package: " + packageName); 3215 } 3216 3217 final PermissionsState permissionsState = sb.getPermissionsState(); 3218 3219 if (permissionsState.revokeRuntimePermission(bp, userId) == 3220 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3221 return false; 3222 } 3223 3224 // Critical, after this call all should never have the permission. 3225 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3226 } 3227 3228 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3229 3230 return true; 3231 } 3232 3233 @Override 3234 public boolean isProtectedBroadcast(String actionName) { 3235 synchronized (mPackages) { 3236 return mProtectedBroadcasts.contains(actionName); 3237 } 3238 } 3239 3240 @Override 3241 public int checkSignatures(String pkg1, String pkg2) { 3242 synchronized (mPackages) { 3243 final PackageParser.Package p1 = mPackages.get(pkg1); 3244 final PackageParser.Package p2 = mPackages.get(pkg2); 3245 if (p1 == null || p1.mExtras == null 3246 || p2 == null || p2.mExtras == null) { 3247 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3248 } 3249 return compareSignatures(p1.mSignatures, p2.mSignatures); 3250 } 3251 } 3252 3253 @Override 3254 public int checkUidSignatures(int uid1, int uid2) { 3255 // Map to base uids. 3256 uid1 = UserHandle.getAppId(uid1); 3257 uid2 = UserHandle.getAppId(uid2); 3258 // reader 3259 synchronized (mPackages) { 3260 Signature[] s1; 3261 Signature[] s2; 3262 Object obj = mSettings.getUserIdLPr(uid1); 3263 if (obj != null) { 3264 if (obj instanceof SharedUserSetting) { 3265 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3266 } else if (obj instanceof PackageSetting) { 3267 s1 = ((PackageSetting)obj).signatures.mSignatures; 3268 } else { 3269 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3270 } 3271 } else { 3272 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3273 } 3274 obj = mSettings.getUserIdLPr(uid2); 3275 if (obj != null) { 3276 if (obj instanceof SharedUserSetting) { 3277 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3278 } else if (obj instanceof PackageSetting) { 3279 s2 = ((PackageSetting)obj).signatures.mSignatures; 3280 } else { 3281 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3282 } 3283 } else { 3284 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3285 } 3286 return compareSignatures(s1, s2); 3287 } 3288 } 3289 3290 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3291 final long identity = Binder.clearCallingIdentity(); 3292 try { 3293 if (sb instanceof SharedUserSetting) { 3294 SharedUserSetting sus = (SharedUserSetting) sb; 3295 final int packageCount = sus.packages.size(); 3296 for (int i = 0; i < packageCount; i++) { 3297 PackageSetting susPs = sus.packages.valueAt(i); 3298 if (userId == UserHandle.USER_ALL) { 3299 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3300 } else { 3301 final int uid = UserHandle.getUid(userId, susPs.appId); 3302 killUid(uid, reason); 3303 } 3304 } 3305 } else if (sb instanceof PackageSetting) { 3306 PackageSetting ps = (PackageSetting) sb; 3307 if (userId == UserHandle.USER_ALL) { 3308 killApplication(ps.pkg.packageName, ps.appId, reason); 3309 } else { 3310 final int uid = UserHandle.getUid(userId, ps.appId); 3311 killUid(uid, reason); 3312 } 3313 } 3314 } finally { 3315 Binder.restoreCallingIdentity(identity); 3316 } 3317 } 3318 3319 private static void killUid(int uid, String reason) { 3320 IActivityManager am = ActivityManagerNative.getDefault(); 3321 if (am != null) { 3322 try { 3323 am.killUid(uid, reason); 3324 } catch (RemoteException e) { 3325 /* ignore - same process */ 3326 } 3327 } 3328 } 3329 3330 /** 3331 * Compares two sets of signatures. Returns: 3332 * <br /> 3333 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3334 * <br /> 3335 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3336 * <br /> 3337 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3338 * <br /> 3339 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3340 * <br /> 3341 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3342 */ 3343 static int compareSignatures(Signature[] s1, Signature[] s2) { 3344 if (s1 == null) { 3345 return s2 == null 3346 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3347 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3348 } 3349 3350 if (s2 == null) { 3351 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3352 } 3353 3354 if (s1.length != s2.length) { 3355 return PackageManager.SIGNATURE_NO_MATCH; 3356 } 3357 3358 // Since both signature sets are of size 1, we can compare without HashSets. 3359 if (s1.length == 1) { 3360 return s1[0].equals(s2[0]) ? 3361 PackageManager.SIGNATURE_MATCH : 3362 PackageManager.SIGNATURE_NO_MATCH; 3363 } 3364 3365 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3366 for (Signature sig : s1) { 3367 set1.add(sig); 3368 } 3369 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3370 for (Signature sig : s2) { 3371 set2.add(sig); 3372 } 3373 // Make sure s2 contains all signatures in s1. 3374 if (set1.equals(set2)) { 3375 return PackageManager.SIGNATURE_MATCH; 3376 } 3377 return PackageManager.SIGNATURE_NO_MATCH; 3378 } 3379 3380 /** 3381 * If the database version for this type of package (internal storage or 3382 * external storage) is less than the version where package signatures 3383 * were updated, return true. 3384 */ 3385 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3386 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3387 DatabaseVersion.SIGNATURE_END_ENTITY)) 3388 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3389 DatabaseVersion.SIGNATURE_END_ENTITY)); 3390 } 3391 3392 /** 3393 * Used for backward compatibility to make sure any packages with 3394 * certificate chains get upgraded to the new style. {@code existingSigs} 3395 * will be in the old format (since they were stored on disk from before the 3396 * system upgrade) and {@code scannedSigs} will be in the newer format. 3397 */ 3398 private int compareSignaturesCompat(PackageSignatures existingSigs, 3399 PackageParser.Package scannedPkg) { 3400 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3401 return PackageManager.SIGNATURE_NO_MATCH; 3402 } 3403 3404 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3405 for (Signature sig : existingSigs.mSignatures) { 3406 existingSet.add(sig); 3407 } 3408 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3409 for (Signature sig : scannedPkg.mSignatures) { 3410 try { 3411 Signature[] chainSignatures = sig.getChainSignatures(); 3412 for (Signature chainSig : chainSignatures) { 3413 scannedCompatSet.add(chainSig); 3414 } 3415 } catch (CertificateEncodingException e) { 3416 scannedCompatSet.add(sig); 3417 } 3418 } 3419 /* 3420 * Make sure the expanded scanned set contains all signatures in the 3421 * existing one. 3422 */ 3423 if (scannedCompatSet.equals(existingSet)) { 3424 // Migrate the old signatures to the new scheme. 3425 existingSigs.assignSignatures(scannedPkg.mSignatures); 3426 // The new KeySets will be re-added later in the scanning process. 3427 synchronized (mPackages) { 3428 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3429 } 3430 return PackageManager.SIGNATURE_MATCH; 3431 } 3432 return PackageManager.SIGNATURE_NO_MATCH; 3433 } 3434 3435 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3436 if (isExternal(scannedPkg)) { 3437 return mSettings.isExternalDatabaseVersionOlderThan( 3438 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3439 } else { 3440 return mSettings.isInternalDatabaseVersionOlderThan( 3441 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3442 } 3443 } 3444 3445 private int compareSignaturesRecover(PackageSignatures existingSigs, 3446 PackageParser.Package scannedPkg) { 3447 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3448 return PackageManager.SIGNATURE_NO_MATCH; 3449 } 3450 3451 String msg = null; 3452 try { 3453 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3454 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3455 + scannedPkg.packageName); 3456 return PackageManager.SIGNATURE_MATCH; 3457 } 3458 } catch (CertificateException e) { 3459 msg = e.getMessage(); 3460 } 3461 3462 logCriticalInfo(Log.INFO, 3463 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3464 return PackageManager.SIGNATURE_NO_MATCH; 3465 } 3466 3467 @Override 3468 public String[] getPackagesForUid(int uid) { 3469 uid = UserHandle.getAppId(uid); 3470 // reader 3471 synchronized (mPackages) { 3472 Object obj = mSettings.getUserIdLPr(uid); 3473 if (obj instanceof SharedUserSetting) { 3474 final SharedUserSetting sus = (SharedUserSetting) obj; 3475 final int N = sus.packages.size(); 3476 final String[] res = new String[N]; 3477 final Iterator<PackageSetting> it = sus.packages.iterator(); 3478 int i = 0; 3479 while (it.hasNext()) { 3480 res[i++] = it.next().name; 3481 } 3482 return res; 3483 } else if (obj instanceof PackageSetting) { 3484 final PackageSetting ps = (PackageSetting) obj; 3485 return new String[] { ps.name }; 3486 } 3487 } 3488 return null; 3489 } 3490 3491 @Override 3492 public String getNameForUid(int uid) { 3493 // reader 3494 synchronized (mPackages) { 3495 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3496 if (obj instanceof SharedUserSetting) { 3497 final SharedUserSetting sus = (SharedUserSetting) obj; 3498 return sus.name + ":" + sus.userId; 3499 } else if (obj instanceof PackageSetting) { 3500 final PackageSetting ps = (PackageSetting) obj; 3501 return ps.name; 3502 } 3503 } 3504 return null; 3505 } 3506 3507 @Override 3508 public int getUidForSharedUser(String sharedUserName) { 3509 if(sharedUserName == null) { 3510 return -1; 3511 } 3512 // reader 3513 synchronized (mPackages) { 3514 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3515 if (suid == null) { 3516 return -1; 3517 } 3518 return suid.userId; 3519 } 3520 } 3521 3522 @Override 3523 public int getFlagsForUid(int uid) { 3524 synchronized (mPackages) { 3525 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3526 if (obj instanceof SharedUserSetting) { 3527 final SharedUserSetting sus = (SharedUserSetting) obj; 3528 return sus.pkgFlags; 3529 } else if (obj instanceof PackageSetting) { 3530 final PackageSetting ps = (PackageSetting) obj; 3531 return ps.pkgFlags; 3532 } 3533 } 3534 return 0; 3535 } 3536 3537 @Override 3538 public int getPrivateFlagsForUid(int uid) { 3539 synchronized (mPackages) { 3540 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3541 if (obj instanceof SharedUserSetting) { 3542 final SharedUserSetting sus = (SharedUserSetting) obj; 3543 return sus.pkgPrivateFlags; 3544 } else if (obj instanceof PackageSetting) { 3545 final PackageSetting ps = (PackageSetting) obj; 3546 return ps.pkgPrivateFlags; 3547 } 3548 } 3549 return 0; 3550 } 3551 3552 @Override 3553 public boolean isUidPrivileged(int uid) { 3554 uid = UserHandle.getAppId(uid); 3555 // reader 3556 synchronized (mPackages) { 3557 Object obj = mSettings.getUserIdLPr(uid); 3558 if (obj instanceof SharedUserSetting) { 3559 final SharedUserSetting sus = (SharedUserSetting) obj; 3560 final Iterator<PackageSetting> it = sus.packages.iterator(); 3561 while (it.hasNext()) { 3562 if (it.next().isPrivileged()) { 3563 return true; 3564 } 3565 } 3566 } else if (obj instanceof PackageSetting) { 3567 final PackageSetting ps = (PackageSetting) obj; 3568 return ps.isPrivileged(); 3569 } 3570 } 3571 return false; 3572 } 3573 3574 @Override 3575 public String[] getAppOpPermissionPackages(String permissionName) { 3576 synchronized (mPackages) { 3577 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3578 if (pkgs == null) { 3579 return null; 3580 } 3581 return pkgs.toArray(new String[pkgs.size()]); 3582 } 3583 } 3584 3585 @Override 3586 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3587 int flags, int userId) { 3588 if (!sUserManager.exists(userId)) return null; 3589 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3590 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3591 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3592 } 3593 3594 @Override 3595 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3596 IntentFilter filter, int match, ComponentName activity) { 3597 final int userId = UserHandle.getCallingUserId(); 3598 if (DEBUG_PREFERRED) { 3599 Log.v(TAG, "setLastChosenActivity intent=" + intent 3600 + " resolvedType=" + resolvedType 3601 + " flags=" + flags 3602 + " filter=" + filter 3603 + " match=" + match 3604 + " activity=" + activity); 3605 filter.dump(new PrintStreamPrinter(System.out), " "); 3606 } 3607 intent.setComponent(null); 3608 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3609 // Find any earlier preferred or last chosen entries and nuke them 3610 findPreferredActivity(intent, resolvedType, 3611 flags, query, 0, false, true, false, userId); 3612 // Add the new activity as the last chosen for this filter 3613 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3614 "Setting last chosen"); 3615 } 3616 3617 @Override 3618 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3619 final int userId = UserHandle.getCallingUserId(); 3620 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3621 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3622 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3623 false, false, false, userId); 3624 } 3625 3626 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3627 int flags, List<ResolveInfo> query, int userId) { 3628 if (query != null) { 3629 final int N = query.size(); 3630 if (N == 1) { 3631 return query.get(0); 3632 } else if (N > 1) { 3633 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3634 // If there is more than one activity with the same priority, 3635 // then let the user decide between them. 3636 ResolveInfo r0 = query.get(0); 3637 ResolveInfo r1 = query.get(1); 3638 if (DEBUG_INTENT_MATCHING || debug) { 3639 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3640 + r1.activityInfo.name + "=" + r1.priority); 3641 } 3642 // If the first activity has a higher priority, or a different 3643 // default, then it is always desireable to pick it. 3644 if (r0.priority != r1.priority 3645 || r0.preferredOrder != r1.preferredOrder 3646 || r0.isDefault != r1.isDefault) { 3647 return query.get(0); 3648 } 3649 // If we have saved a preference for a preferred activity for 3650 // this Intent, use that. 3651 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3652 flags, query, r0.priority, true, false, debug, userId); 3653 if (ri != null) { 3654 return ri; 3655 } 3656 if (userId != 0) { 3657 ri = new ResolveInfo(mResolveInfo); 3658 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3659 ri.activityInfo.applicationInfo = new ApplicationInfo( 3660 ri.activityInfo.applicationInfo); 3661 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3662 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3663 return ri; 3664 } 3665 return mResolveInfo; 3666 } 3667 } 3668 return null; 3669 } 3670 3671 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3672 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3673 final int N = query.size(); 3674 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3675 .get(userId); 3676 // Get the list of persistent preferred activities that handle the intent 3677 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3678 List<PersistentPreferredActivity> pprefs = ppir != null 3679 ? ppir.queryIntent(intent, resolvedType, 3680 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3681 : null; 3682 if (pprefs != null && pprefs.size() > 0) { 3683 final int M = pprefs.size(); 3684 for (int i=0; i<M; i++) { 3685 final PersistentPreferredActivity ppa = pprefs.get(i); 3686 if (DEBUG_PREFERRED || debug) { 3687 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3688 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3689 + "\n component=" + ppa.mComponent); 3690 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3691 } 3692 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3693 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3694 if (DEBUG_PREFERRED || debug) { 3695 Slog.v(TAG, "Found persistent preferred activity:"); 3696 if (ai != null) { 3697 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3698 } else { 3699 Slog.v(TAG, " null"); 3700 } 3701 } 3702 if (ai == null) { 3703 // This previously registered persistent preferred activity 3704 // component is no longer known. Ignore it and do NOT remove it. 3705 continue; 3706 } 3707 for (int j=0; j<N; j++) { 3708 final ResolveInfo ri = query.get(j); 3709 if (!ri.activityInfo.applicationInfo.packageName 3710 .equals(ai.applicationInfo.packageName)) { 3711 continue; 3712 } 3713 if (!ri.activityInfo.name.equals(ai.name)) { 3714 continue; 3715 } 3716 // Found a persistent preference that can handle the intent. 3717 if (DEBUG_PREFERRED || debug) { 3718 Slog.v(TAG, "Returning persistent preferred activity: " + 3719 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3720 } 3721 return ri; 3722 } 3723 } 3724 } 3725 return null; 3726 } 3727 3728 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3729 List<ResolveInfo> query, int priority, boolean always, 3730 boolean removeMatches, boolean debug, int userId) { 3731 if (!sUserManager.exists(userId)) return null; 3732 // writer 3733 synchronized (mPackages) { 3734 if (intent.getSelector() != null) { 3735 intent = intent.getSelector(); 3736 } 3737 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3738 3739 // Try to find a matching persistent preferred activity. 3740 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3741 debug, userId); 3742 3743 // If a persistent preferred activity matched, use it. 3744 if (pri != null) { 3745 return pri; 3746 } 3747 3748 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3749 // Get the list of preferred activities that handle the intent 3750 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3751 List<PreferredActivity> prefs = pir != null 3752 ? pir.queryIntent(intent, resolvedType, 3753 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3754 : null; 3755 if (prefs != null && prefs.size() > 0) { 3756 boolean changed = false; 3757 try { 3758 // First figure out how good the original match set is. 3759 // We will only allow preferred activities that came 3760 // from the same match quality. 3761 int match = 0; 3762 3763 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3764 3765 final int N = query.size(); 3766 for (int j=0; j<N; j++) { 3767 final ResolveInfo ri = query.get(j); 3768 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3769 + ": 0x" + Integer.toHexString(match)); 3770 if (ri.match > match) { 3771 match = ri.match; 3772 } 3773 } 3774 3775 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3776 + Integer.toHexString(match)); 3777 3778 match &= IntentFilter.MATCH_CATEGORY_MASK; 3779 final int M = prefs.size(); 3780 for (int i=0; i<M; i++) { 3781 final PreferredActivity pa = prefs.get(i); 3782 if (DEBUG_PREFERRED || debug) { 3783 Slog.v(TAG, "Checking PreferredActivity ds=" 3784 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3785 + "\n component=" + pa.mPref.mComponent); 3786 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3787 } 3788 if (pa.mPref.mMatch != match) { 3789 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3790 + Integer.toHexString(pa.mPref.mMatch)); 3791 continue; 3792 } 3793 // If it's not an "always" type preferred activity and that's what we're 3794 // looking for, skip it. 3795 if (always && !pa.mPref.mAlways) { 3796 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3797 continue; 3798 } 3799 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3800 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3801 if (DEBUG_PREFERRED || debug) { 3802 Slog.v(TAG, "Found preferred activity:"); 3803 if (ai != null) { 3804 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3805 } else { 3806 Slog.v(TAG, " null"); 3807 } 3808 } 3809 if (ai == null) { 3810 // This previously registered preferred activity 3811 // component is no longer known. Most likely an update 3812 // to the app was installed and in the new version this 3813 // component no longer exists. Clean it up by removing 3814 // it from the preferred activities list, and skip it. 3815 Slog.w(TAG, "Removing dangling preferred activity: " 3816 + pa.mPref.mComponent); 3817 pir.removeFilter(pa); 3818 changed = true; 3819 continue; 3820 } 3821 for (int j=0; j<N; j++) { 3822 final ResolveInfo ri = query.get(j); 3823 if (!ri.activityInfo.applicationInfo.packageName 3824 .equals(ai.applicationInfo.packageName)) { 3825 continue; 3826 } 3827 if (!ri.activityInfo.name.equals(ai.name)) { 3828 continue; 3829 } 3830 3831 if (removeMatches) { 3832 pir.removeFilter(pa); 3833 changed = true; 3834 if (DEBUG_PREFERRED) { 3835 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3836 } 3837 break; 3838 } 3839 3840 // Okay we found a previously set preferred or last chosen app. 3841 // If the result set is different from when this 3842 // was created, we need to clear it and re-ask the 3843 // user their preference, if we're looking for an "always" type entry. 3844 if (always && !pa.mPref.sameSet(query)) { 3845 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3846 + intent + " type " + resolvedType); 3847 if (DEBUG_PREFERRED) { 3848 Slog.v(TAG, "Removing preferred activity since set changed " 3849 + pa.mPref.mComponent); 3850 } 3851 pir.removeFilter(pa); 3852 // Re-add the filter as a "last chosen" entry (!always) 3853 PreferredActivity lastChosen = new PreferredActivity( 3854 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3855 pir.addFilter(lastChosen); 3856 changed = true; 3857 return null; 3858 } 3859 3860 // Yay! Either the set matched or we're looking for the last chosen 3861 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3862 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3863 return ri; 3864 } 3865 } 3866 } finally { 3867 if (changed) { 3868 if (DEBUG_PREFERRED) { 3869 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3870 } 3871 scheduleWritePackageRestrictionsLocked(userId); 3872 } 3873 } 3874 } 3875 } 3876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3877 return null; 3878 } 3879 3880 /* 3881 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3882 */ 3883 @Override 3884 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3885 int targetUserId) { 3886 mContext.enforceCallingOrSelfPermission( 3887 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3888 List<CrossProfileIntentFilter> matches = 3889 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3890 if (matches != null) { 3891 int size = matches.size(); 3892 for (int i = 0; i < size; i++) { 3893 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3894 } 3895 } 3896 return false; 3897 } 3898 3899 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3900 String resolvedType, int userId) { 3901 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3902 if (resolver != null) { 3903 return resolver.queryIntent(intent, resolvedType, false, userId); 3904 } 3905 return null; 3906 } 3907 3908 @Override 3909 public List<ResolveInfo> queryIntentActivities(Intent intent, 3910 String resolvedType, int flags, int userId) { 3911 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3913 ComponentName comp = intent.getComponent(); 3914 if (comp == null) { 3915 if (intent.getSelector() != null) { 3916 intent = intent.getSelector(); 3917 comp = intent.getComponent(); 3918 } 3919 } 3920 3921 if (comp != null) { 3922 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3923 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3924 if (ai != null) { 3925 final ResolveInfo ri = new ResolveInfo(); 3926 ri.activityInfo = ai; 3927 list.add(ri); 3928 } 3929 return list; 3930 } 3931 3932 // reader 3933 synchronized (mPackages) { 3934 final String pkgName = intent.getPackage(); 3935 if (pkgName == null) { 3936 List<CrossProfileIntentFilter> matchingFilters = 3937 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3938 // Check for results that need to skip the current profile. 3939 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3940 resolvedType, flags, userId); 3941 if (resolveInfo != null) { 3942 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3943 result.add(resolveInfo); 3944 return filterIfNotPrimaryUser(result, userId); 3945 } 3946 // Check for cross profile results. 3947 resolveInfo = queryCrossProfileIntents( 3948 matchingFilters, intent, resolvedType, flags, userId); 3949 3950 // Check for results in the current profile. 3951 List<ResolveInfo> result = mActivities.queryIntent( 3952 intent, resolvedType, flags, userId); 3953 if (resolveInfo != null) { 3954 result.add(resolveInfo); 3955 Collections.sort(result, mResolvePrioritySorter); 3956 } 3957 result = filterIfNotPrimaryUser(result, userId); 3958 if (result.size() > 1) { 3959 return filterCandidatesWithDomainPreferedActivitiesLPr(result); 3960 } 3961 3962 return result; 3963 } 3964 final PackageParser.Package pkg = mPackages.get(pkgName); 3965 if (pkg != null) { 3966 return filterIfNotPrimaryUser( 3967 mActivities.queryIntentForPackage( 3968 intent, resolvedType, flags, pkg.activities, userId), 3969 userId); 3970 } 3971 return new ArrayList<ResolveInfo>(); 3972 } 3973 } 3974 3975 /** 3976 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3977 * 3978 * @return filtered list 3979 */ 3980 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3981 if (userId == UserHandle.USER_OWNER) { 3982 return resolveInfos; 3983 } 3984 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3985 ResolveInfo info = resolveInfos.get(i); 3986 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3987 resolveInfos.remove(i); 3988 } 3989 } 3990 return resolveInfos; 3991 } 3992 3993 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 3994 List<ResolveInfo> candidates) { 3995 if (DEBUG_PREFERRED) { 3996 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3997 candidates.size()); 3998 } 3999 final int userId = UserHandle.getCallingUserId(); 4000 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4001 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4002 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4003 synchronized (mPackages) { 4004 final int count = candidates.size(); 4005 // First, try to use the domain prefered App 4006 for (int n=0; n<count; n++) { 4007 ResolveInfo info = candidates.get(n); 4008 String packageName = info.activityInfo.packageName; 4009 PackageSetting ps = mSettings.mPackages.get(packageName); 4010 if (ps != null) { 4011 // Try to get the status from User settings first 4012 int status = getDomainVerificationStatusLPr(ps, userId); 4013 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS || 4014 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4015 result.add(info); 4016 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4017 neverList.add(info); 4018 } 4019 // Add to the special match all list (Browser use case) 4020 if (info.handleAllWebDataURI) { 4021 matchAllList.add(info); 4022 } 4023 } 4024 } 4025 // If there is nothing selected, add all candidates and remove the ones that the User 4026 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4027 // also remove any . 4028 // If there is still none after this pass, add all Browser Apps and let the User decide 4029 // with the Disambiguation dialog if there are several ones. 4030 if (result.size() == 0) { 4031 result.addAll(candidates); 4032 } 4033 result.removeAll(neverList); 4034 result.removeAll(matchAllList); 4035 if (result.size() == 0) { 4036 result.addAll(matchAllList); 4037 } 4038 } 4039 if (DEBUG_PREFERRED) { 4040 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4041 result.size()); 4042 } 4043 return result; 4044 } 4045 4046 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4047 int status = ps.getDomainVerificationStatusForUser(userId); 4048 // if none available, get the master status 4049 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4050 if (ps.getIntentFilterVerificationInfo() != null) { 4051 status = ps.getIntentFilterVerificationInfo().getStatus(); 4052 } 4053 } 4054 return status; 4055 } 4056 4057 private ResolveInfo querySkipCurrentProfileIntents( 4058 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4059 int flags, int sourceUserId) { 4060 if (matchingFilters != null) { 4061 int size = matchingFilters.size(); 4062 for (int i = 0; i < size; i ++) { 4063 CrossProfileIntentFilter filter = matchingFilters.get(i); 4064 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4065 // Checking if there are activities in the target user that can handle the 4066 // intent. 4067 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4068 flags, sourceUserId); 4069 if (resolveInfo != null) { 4070 return resolveInfo; 4071 } 4072 } 4073 } 4074 } 4075 return null; 4076 } 4077 4078 // Return matching ResolveInfo if any for skip current profile intent filters. 4079 private ResolveInfo queryCrossProfileIntents( 4080 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4081 int flags, int sourceUserId) { 4082 if (matchingFilters != null) { 4083 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4084 // match the same intent. For performance reasons, it is better not to 4085 // run queryIntent twice for the same userId 4086 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4087 int size = matchingFilters.size(); 4088 for (int i = 0; i < size; i++) { 4089 CrossProfileIntentFilter filter = matchingFilters.get(i); 4090 int targetUserId = filter.getTargetUserId(); 4091 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4092 && !alreadyTriedUserIds.get(targetUserId)) { 4093 // Checking if there are activities in the target user that can handle the 4094 // intent. 4095 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4096 flags, sourceUserId); 4097 if (resolveInfo != null) return resolveInfo; 4098 alreadyTriedUserIds.put(targetUserId, true); 4099 } 4100 } 4101 } 4102 return null; 4103 } 4104 4105 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4106 String resolvedType, int flags, int sourceUserId) { 4107 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4108 resolvedType, flags, filter.getTargetUserId()); 4109 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4110 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4111 } 4112 return null; 4113 } 4114 4115 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4116 int sourceUserId, int targetUserId) { 4117 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4118 String className; 4119 if (targetUserId == UserHandle.USER_OWNER) { 4120 className = FORWARD_INTENT_TO_USER_OWNER; 4121 } else { 4122 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4123 } 4124 ComponentName forwardingActivityComponentName = new ComponentName( 4125 mAndroidApplication.packageName, className); 4126 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4127 sourceUserId); 4128 if (targetUserId == UserHandle.USER_OWNER) { 4129 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4130 forwardingResolveInfo.noResourceId = true; 4131 } 4132 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4133 forwardingResolveInfo.priority = 0; 4134 forwardingResolveInfo.preferredOrder = 0; 4135 forwardingResolveInfo.match = 0; 4136 forwardingResolveInfo.isDefault = true; 4137 forwardingResolveInfo.filter = filter; 4138 forwardingResolveInfo.targetUserId = targetUserId; 4139 return forwardingResolveInfo; 4140 } 4141 4142 @Override 4143 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4144 Intent[] specifics, String[] specificTypes, Intent intent, 4145 String resolvedType, int flags, int userId) { 4146 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4147 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4148 false, "query intent activity options"); 4149 final String resultsAction = intent.getAction(); 4150 4151 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4152 | PackageManager.GET_RESOLVED_FILTER, userId); 4153 4154 if (DEBUG_INTENT_MATCHING) { 4155 Log.v(TAG, "Query " + intent + ": " + results); 4156 } 4157 4158 int specificsPos = 0; 4159 int N; 4160 4161 // todo: note that the algorithm used here is O(N^2). This 4162 // isn't a problem in our current environment, but if we start running 4163 // into situations where we have more than 5 or 10 matches then this 4164 // should probably be changed to something smarter... 4165 4166 // First we go through and resolve each of the specific items 4167 // that were supplied, taking care of removing any corresponding 4168 // duplicate items in the generic resolve list. 4169 if (specifics != null) { 4170 for (int i=0; i<specifics.length; i++) { 4171 final Intent sintent = specifics[i]; 4172 if (sintent == null) { 4173 continue; 4174 } 4175 4176 if (DEBUG_INTENT_MATCHING) { 4177 Log.v(TAG, "Specific #" + i + ": " + sintent); 4178 } 4179 4180 String action = sintent.getAction(); 4181 if (resultsAction != null && resultsAction.equals(action)) { 4182 // If this action was explicitly requested, then don't 4183 // remove things that have it. 4184 action = null; 4185 } 4186 4187 ResolveInfo ri = null; 4188 ActivityInfo ai = null; 4189 4190 ComponentName comp = sintent.getComponent(); 4191 if (comp == null) { 4192 ri = resolveIntent( 4193 sintent, 4194 specificTypes != null ? specificTypes[i] : null, 4195 flags, userId); 4196 if (ri == null) { 4197 continue; 4198 } 4199 if (ri == mResolveInfo) { 4200 // ACK! Must do something better with this. 4201 } 4202 ai = ri.activityInfo; 4203 comp = new ComponentName(ai.applicationInfo.packageName, 4204 ai.name); 4205 } else { 4206 ai = getActivityInfo(comp, flags, userId); 4207 if (ai == null) { 4208 continue; 4209 } 4210 } 4211 4212 // Look for any generic query activities that are duplicates 4213 // of this specific one, and remove them from the results. 4214 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4215 N = results.size(); 4216 int j; 4217 for (j=specificsPos; j<N; j++) { 4218 ResolveInfo sri = results.get(j); 4219 if ((sri.activityInfo.name.equals(comp.getClassName()) 4220 && sri.activityInfo.applicationInfo.packageName.equals( 4221 comp.getPackageName())) 4222 || (action != null && sri.filter.matchAction(action))) { 4223 results.remove(j); 4224 if (DEBUG_INTENT_MATCHING) Log.v( 4225 TAG, "Removing duplicate item from " + j 4226 + " due to specific " + specificsPos); 4227 if (ri == null) { 4228 ri = sri; 4229 } 4230 j--; 4231 N--; 4232 } 4233 } 4234 4235 // Add this specific item to its proper place. 4236 if (ri == null) { 4237 ri = new ResolveInfo(); 4238 ri.activityInfo = ai; 4239 } 4240 results.add(specificsPos, ri); 4241 ri.specificIndex = i; 4242 specificsPos++; 4243 } 4244 } 4245 4246 // Now we go through the remaining generic results and remove any 4247 // duplicate actions that are found here. 4248 N = results.size(); 4249 for (int i=specificsPos; i<N-1; i++) { 4250 final ResolveInfo rii = results.get(i); 4251 if (rii.filter == null) { 4252 continue; 4253 } 4254 4255 // Iterate over all of the actions of this result's intent 4256 // filter... typically this should be just one. 4257 final Iterator<String> it = rii.filter.actionsIterator(); 4258 if (it == null) { 4259 continue; 4260 } 4261 while (it.hasNext()) { 4262 final String action = it.next(); 4263 if (resultsAction != null && resultsAction.equals(action)) { 4264 // If this action was explicitly requested, then don't 4265 // remove things that have it. 4266 continue; 4267 } 4268 for (int j=i+1; j<N; j++) { 4269 final ResolveInfo rij = results.get(j); 4270 if (rij.filter != null && rij.filter.hasAction(action)) { 4271 results.remove(j); 4272 if (DEBUG_INTENT_MATCHING) Log.v( 4273 TAG, "Removing duplicate item from " + j 4274 + " due to action " + action + " at " + i); 4275 j--; 4276 N--; 4277 } 4278 } 4279 } 4280 4281 // If the caller didn't request filter information, drop it now 4282 // so we don't have to marshall/unmarshall it. 4283 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4284 rii.filter = null; 4285 } 4286 } 4287 4288 // Filter out the caller activity if so requested. 4289 if (caller != null) { 4290 N = results.size(); 4291 for (int i=0; i<N; i++) { 4292 ActivityInfo ainfo = results.get(i).activityInfo; 4293 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4294 && caller.getClassName().equals(ainfo.name)) { 4295 results.remove(i); 4296 break; 4297 } 4298 } 4299 } 4300 4301 // If the caller didn't request filter information, 4302 // drop them now so we don't have to 4303 // marshall/unmarshall it. 4304 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4305 N = results.size(); 4306 for (int i=0; i<N; i++) { 4307 results.get(i).filter = null; 4308 } 4309 } 4310 4311 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4312 return results; 4313 } 4314 4315 @Override 4316 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4317 int userId) { 4318 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4319 ComponentName comp = intent.getComponent(); 4320 if (comp == null) { 4321 if (intent.getSelector() != null) { 4322 intent = intent.getSelector(); 4323 comp = intent.getComponent(); 4324 } 4325 } 4326 if (comp != null) { 4327 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4328 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4329 if (ai != null) { 4330 ResolveInfo ri = new ResolveInfo(); 4331 ri.activityInfo = ai; 4332 list.add(ri); 4333 } 4334 return list; 4335 } 4336 4337 // reader 4338 synchronized (mPackages) { 4339 String pkgName = intent.getPackage(); 4340 if (pkgName == null) { 4341 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4342 } 4343 final PackageParser.Package pkg = mPackages.get(pkgName); 4344 if (pkg != null) { 4345 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4346 userId); 4347 } 4348 return null; 4349 } 4350 } 4351 4352 @Override 4353 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4354 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4355 if (!sUserManager.exists(userId)) return null; 4356 if (query != null) { 4357 if (query.size() >= 1) { 4358 // If there is more than one service with the same priority, 4359 // just arbitrarily pick the first one. 4360 return query.get(0); 4361 } 4362 } 4363 return null; 4364 } 4365 4366 @Override 4367 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4368 int userId) { 4369 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4370 ComponentName comp = intent.getComponent(); 4371 if (comp == null) { 4372 if (intent.getSelector() != null) { 4373 intent = intent.getSelector(); 4374 comp = intent.getComponent(); 4375 } 4376 } 4377 if (comp != null) { 4378 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4379 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4380 if (si != null) { 4381 final ResolveInfo ri = new ResolveInfo(); 4382 ri.serviceInfo = si; 4383 list.add(ri); 4384 } 4385 return list; 4386 } 4387 4388 // reader 4389 synchronized (mPackages) { 4390 String pkgName = intent.getPackage(); 4391 if (pkgName == null) { 4392 return mServices.queryIntent(intent, resolvedType, flags, userId); 4393 } 4394 final PackageParser.Package pkg = mPackages.get(pkgName); 4395 if (pkg != null) { 4396 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4397 userId); 4398 } 4399 return null; 4400 } 4401 } 4402 4403 @Override 4404 public List<ResolveInfo> queryIntentContentProviders( 4405 Intent intent, String resolvedType, int flags, int userId) { 4406 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4407 ComponentName comp = intent.getComponent(); 4408 if (comp == null) { 4409 if (intent.getSelector() != null) { 4410 intent = intent.getSelector(); 4411 comp = intent.getComponent(); 4412 } 4413 } 4414 if (comp != null) { 4415 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4416 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4417 if (pi != null) { 4418 final ResolveInfo ri = new ResolveInfo(); 4419 ri.providerInfo = pi; 4420 list.add(ri); 4421 } 4422 return list; 4423 } 4424 4425 // reader 4426 synchronized (mPackages) { 4427 String pkgName = intent.getPackage(); 4428 if (pkgName == null) { 4429 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4430 } 4431 final PackageParser.Package pkg = mPackages.get(pkgName); 4432 if (pkg != null) { 4433 return mProviders.queryIntentForPackage( 4434 intent, resolvedType, flags, pkg.providers, userId); 4435 } 4436 return null; 4437 } 4438 } 4439 4440 @Override 4441 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4442 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4443 4444 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4445 4446 // writer 4447 synchronized (mPackages) { 4448 ArrayList<PackageInfo> list; 4449 if (listUninstalled) { 4450 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4451 for (PackageSetting ps : mSettings.mPackages.values()) { 4452 PackageInfo pi; 4453 if (ps.pkg != null) { 4454 pi = generatePackageInfo(ps.pkg, flags, userId); 4455 } else { 4456 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4457 } 4458 if (pi != null) { 4459 list.add(pi); 4460 } 4461 } 4462 } else { 4463 list = new ArrayList<PackageInfo>(mPackages.size()); 4464 for (PackageParser.Package p : mPackages.values()) { 4465 PackageInfo pi = generatePackageInfo(p, flags, userId); 4466 if (pi != null) { 4467 list.add(pi); 4468 } 4469 } 4470 } 4471 4472 return new ParceledListSlice<PackageInfo>(list); 4473 } 4474 } 4475 4476 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4477 String[] permissions, boolean[] tmp, int flags, int userId) { 4478 int numMatch = 0; 4479 final PermissionsState permissionsState = ps.getPermissionsState(); 4480 for (int i=0; i<permissions.length; i++) { 4481 final String permission = permissions[i]; 4482 if (permissionsState.hasPermission(permission, userId)) { 4483 tmp[i] = true; 4484 numMatch++; 4485 } else { 4486 tmp[i] = false; 4487 } 4488 } 4489 if (numMatch == 0) { 4490 return; 4491 } 4492 PackageInfo pi; 4493 if (ps.pkg != null) { 4494 pi = generatePackageInfo(ps.pkg, flags, userId); 4495 } else { 4496 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4497 } 4498 // The above might return null in cases of uninstalled apps or install-state 4499 // skew across users/profiles. 4500 if (pi != null) { 4501 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4502 if (numMatch == permissions.length) { 4503 pi.requestedPermissions = permissions; 4504 } else { 4505 pi.requestedPermissions = new String[numMatch]; 4506 numMatch = 0; 4507 for (int i=0; i<permissions.length; i++) { 4508 if (tmp[i]) { 4509 pi.requestedPermissions[numMatch] = permissions[i]; 4510 numMatch++; 4511 } 4512 } 4513 } 4514 } 4515 list.add(pi); 4516 } 4517 } 4518 4519 @Override 4520 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4521 String[] permissions, int flags, int userId) { 4522 if (!sUserManager.exists(userId)) return null; 4523 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4524 4525 // writer 4526 synchronized (mPackages) { 4527 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4528 boolean[] tmpBools = new boolean[permissions.length]; 4529 if (listUninstalled) { 4530 for (PackageSetting ps : mSettings.mPackages.values()) { 4531 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4532 } 4533 } else { 4534 for (PackageParser.Package pkg : mPackages.values()) { 4535 PackageSetting ps = (PackageSetting)pkg.mExtras; 4536 if (ps != null) { 4537 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4538 userId); 4539 } 4540 } 4541 } 4542 4543 return new ParceledListSlice<PackageInfo>(list); 4544 } 4545 } 4546 4547 @Override 4548 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4549 if (!sUserManager.exists(userId)) return null; 4550 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4551 4552 // writer 4553 synchronized (mPackages) { 4554 ArrayList<ApplicationInfo> list; 4555 if (listUninstalled) { 4556 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4557 for (PackageSetting ps : mSettings.mPackages.values()) { 4558 ApplicationInfo ai; 4559 if (ps.pkg != null) { 4560 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4561 ps.readUserState(userId), userId); 4562 } else { 4563 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4564 } 4565 if (ai != null) { 4566 list.add(ai); 4567 } 4568 } 4569 } else { 4570 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4571 for (PackageParser.Package p : mPackages.values()) { 4572 if (p.mExtras != null) { 4573 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4574 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4575 if (ai != null) { 4576 list.add(ai); 4577 } 4578 } 4579 } 4580 } 4581 4582 return new ParceledListSlice<ApplicationInfo>(list); 4583 } 4584 } 4585 4586 public List<ApplicationInfo> getPersistentApplications(int flags) { 4587 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4588 4589 // reader 4590 synchronized (mPackages) { 4591 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4592 final int userId = UserHandle.getCallingUserId(); 4593 while (i.hasNext()) { 4594 final PackageParser.Package p = i.next(); 4595 if (p.applicationInfo != null 4596 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4597 && (!mSafeMode || isSystemApp(p))) { 4598 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4599 if (ps != null) { 4600 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4601 ps.readUserState(userId), userId); 4602 if (ai != null) { 4603 finalList.add(ai); 4604 } 4605 } 4606 } 4607 } 4608 } 4609 4610 return finalList; 4611 } 4612 4613 @Override 4614 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4615 if (!sUserManager.exists(userId)) return null; 4616 // reader 4617 synchronized (mPackages) { 4618 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4619 PackageSetting ps = provider != null 4620 ? mSettings.mPackages.get(provider.owner.packageName) 4621 : null; 4622 return ps != null 4623 && mSettings.isEnabledLPr(provider.info, flags, userId) 4624 && (!mSafeMode || (provider.info.applicationInfo.flags 4625 &ApplicationInfo.FLAG_SYSTEM) != 0) 4626 ? PackageParser.generateProviderInfo(provider, flags, 4627 ps.readUserState(userId), userId) 4628 : null; 4629 } 4630 } 4631 4632 /** 4633 * @deprecated 4634 */ 4635 @Deprecated 4636 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4637 // reader 4638 synchronized (mPackages) { 4639 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4640 .entrySet().iterator(); 4641 final int userId = UserHandle.getCallingUserId(); 4642 while (i.hasNext()) { 4643 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4644 PackageParser.Provider p = entry.getValue(); 4645 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4646 4647 if (ps != null && p.syncable 4648 && (!mSafeMode || (p.info.applicationInfo.flags 4649 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4650 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4651 ps.readUserState(userId), userId); 4652 if (info != null) { 4653 outNames.add(entry.getKey()); 4654 outInfo.add(info); 4655 } 4656 } 4657 } 4658 } 4659 } 4660 4661 @Override 4662 public List<ProviderInfo> queryContentProviders(String processName, 4663 int uid, int flags) { 4664 ArrayList<ProviderInfo> finalList = null; 4665 // reader 4666 synchronized (mPackages) { 4667 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4668 final int userId = processName != null ? 4669 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4670 while (i.hasNext()) { 4671 final PackageParser.Provider p = i.next(); 4672 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4673 if (ps != null && p.info.authority != null 4674 && (processName == null 4675 || (p.info.processName.equals(processName) 4676 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4677 && mSettings.isEnabledLPr(p.info, flags, userId) 4678 && (!mSafeMode 4679 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4680 if (finalList == null) { 4681 finalList = new ArrayList<ProviderInfo>(3); 4682 } 4683 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4684 ps.readUserState(userId), userId); 4685 if (info != null) { 4686 finalList.add(info); 4687 } 4688 } 4689 } 4690 } 4691 4692 if (finalList != null) { 4693 Collections.sort(finalList, mProviderInitOrderSorter); 4694 } 4695 4696 return finalList; 4697 } 4698 4699 @Override 4700 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4701 int flags) { 4702 // reader 4703 synchronized (mPackages) { 4704 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4705 return PackageParser.generateInstrumentationInfo(i, flags); 4706 } 4707 } 4708 4709 @Override 4710 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4711 int flags) { 4712 ArrayList<InstrumentationInfo> finalList = 4713 new ArrayList<InstrumentationInfo>(); 4714 4715 // reader 4716 synchronized (mPackages) { 4717 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4718 while (i.hasNext()) { 4719 final PackageParser.Instrumentation p = i.next(); 4720 if (targetPackage == null 4721 || targetPackage.equals(p.info.targetPackage)) { 4722 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4723 flags); 4724 if (ii != null) { 4725 finalList.add(ii); 4726 } 4727 } 4728 } 4729 } 4730 4731 return finalList; 4732 } 4733 4734 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4735 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4736 if (overlays == null) { 4737 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4738 return; 4739 } 4740 for (PackageParser.Package opkg : overlays.values()) { 4741 // Not much to do if idmap fails: we already logged the error 4742 // and we certainly don't want to abort installation of pkg simply 4743 // because an overlay didn't fit properly. For these reasons, 4744 // ignore the return value of createIdmapForPackagePairLI. 4745 createIdmapForPackagePairLI(pkg, opkg); 4746 } 4747 } 4748 4749 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4750 PackageParser.Package opkg) { 4751 if (!opkg.mTrustedOverlay) { 4752 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4753 opkg.baseCodePath + ": overlay not trusted"); 4754 return false; 4755 } 4756 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4757 if (overlaySet == null) { 4758 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4759 opkg.baseCodePath + " but target package has no known overlays"); 4760 return false; 4761 } 4762 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4763 // TODO: generate idmap for split APKs 4764 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4765 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4766 + opkg.baseCodePath); 4767 return false; 4768 } 4769 PackageParser.Package[] overlayArray = 4770 overlaySet.values().toArray(new PackageParser.Package[0]); 4771 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4772 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4773 return p1.mOverlayPriority - p2.mOverlayPriority; 4774 } 4775 }; 4776 Arrays.sort(overlayArray, cmp); 4777 4778 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4779 int i = 0; 4780 for (PackageParser.Package p : overlayArray) { 4781 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4782 } 4783 return true; 4784 } 4785 4786 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4787 final File[] files = dir.listFiles(); 4788 if (ArrayUtils.isEmpty(files)) { 4789 Log.d(TAG, "No files in app dir " + dir); 4790 return; 4791 } 4792 4793 if (DEBUG_PACKAGE_SCANNING) { 4794 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4795 + " flags=0x" + Integer.toHexString(parseFlags)); 4796 } 4797 4798 for (File file : files) { 4799 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4800 && !PackageInstallerService.isStageName(file.getName()); 4801 if (!isPackage) { 4802 // Ignore entries which are not packages 4803 continue; 4804 } 4805 try { 4806 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4807 scanFlags, currentTime, null); 4808 } catch (PackageManagerException e) { 4809 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4810 4811 // Delete invalid userdata apps 4812 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4813 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4814 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4815 if (file.isDirectory()) { 4816 mInstaller.rmPackageDir(file.getAbsolutePath()); 4817 } else { 4818 file.delete(); 4819 } 4820 } 4821 } 4822 } 4823 } 4824 4825 private static File getSettingsProblemFile() { 4826 File dataDir = Environment.getDataDirectory(); 4827 File systemDir = new File(dataDir, "system"); 4828 File fname = new File(systemDir, "uiderrors.txt"); 4829 return fname; 4830 } 4831 4832 static void reportSettingsProblem(int priority, String msg) { 4833 logCriticalInfo(priority, msg); 4834 } 4835 4836 static void logCriticalInfo(int priority, String msg) { 4837 Slog.println(priority, TAG, msg); 4838 EventLogTags.writePmCriticalInfo(msg); 4839 try { 4840 File fname = getSettingsProblemFile(); 4841 FileOutputStream out = new FileOutputStream(fname, true); 4842 PrintWriter pw = new FastPrintWriter(out); 4843 SimpleDateFormat formatter = new SimpleDateFormat(); 4844 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4845 pw.println(dateString + ": " + msg); 4846 pw.close(); 4847 FileUtils.setPermissions( 4848 fname.toString(), 4849 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4850 -1, -1); 4851 } catch (java.io.IOException e) { 4852 } 4853 } 4854 4855 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4856 PackageParser.Package pkg, File srcFile, int parseFlags) 4857 throws PackageManagerException { 4858 if (ps != null 4859 && ps.codePath.equals(srcFile) 4860 && ps.timeStamp == srcFile.lastModified() 4861 && !isCompatSignatureUpdateNeeded(pkg) 4862 && !isRecoverSignatureUpdateNeeded(pkg)) { 4863 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4864 if (ps.signatures.mSignatures != null 4865 && ps.signatures.mSignatures.length != 0 4866 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4867 // Optimization: reuse the existing cached certificates 4868 // if the package appears to be unchanged. 4869 pkg.mSignatures = ps.signatures.mSignatures; 4870 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4871 synchronized (mPackages) { 4872 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4873 } 4874 return; 4875 } 4876 4877 Slog.w(TAG, "PackageSetting for " + ps.name 4878 + " is missing signatures. Collecting certs again to recover them."); 4879 } else { 4880 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4881 } 4882 4883 try { 4884 pp.collectCertificates(pkg, parseFlags); 4885 pp.collectManifestDigest(pkg); 4886 } catch (PackageParserException e) { 4887 throw PackageManagerException.from(e); 4888 } 4889 } 4890 4891 /* 4892 * Scan a package and return the newly parsed package. 4893 * Returns null in case of errors and the error code is stored in mLastScanError 4894 */ 4895 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4896 long currentTime, UserHandle user) throws PackageManagerException { 4897 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4898 parseFlags |= mDefParseFlags; 4899 PackageParser pp = new PackageParser(); 4900 pp.setSeparateProcesses(mSeparateProcesses); 4901 pp.setOnlyCoreApps(mOnlyCore); 4902 pp.setDisplayMetrics(mMetrics); 4903 4904 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4905 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4906 } 4907 4908 final PackageParser.Package pkg; 4909 try { 4910 pkg = pp.parsePackage(scanFile, parseFlags); 4911 } catch (PackageParserException e) { 4912 throw PackageManagerException.from(e); 4913 } 4914 4915 PackageSetting ps = null; 4916 PackageSetting updatedPkg; 4917 // reader 4918 synchronized (mPackages) { 4919 // Look to see if we already know about this package. 4920 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4921 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4922 // This package has been renamed to its original name. Let's 4923 // use that. 4924 ps = mSettings.peekPackageLPr(oldName); 4925 } 4926 // If there was no original package, see one for the real package name. 4927 if (ps == null) { 4928 ps = mSettings.peekPackageLPr(pkg.packageName); 4929 } 4930 // Check to see if this package could be hiding/updating a system 4931 // package. Must look for it either under the original or real 4932 // package name depending on our state. 4933 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4934 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4935 } 4936 boolean updatedPkgBetter = false; 4937 // First check if this is a system package that may involve an update 4938 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4939 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4940 // it needs to drop FLAG_PRIVILEGED. 4941 if (locationIsPrivileged(scanFile)) { 4942 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4943 } else { 4944 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4945 } 4946 4947 if (ps != null && !ps.codePath.equals(scanFile)) { 4948 // The path has changed from what was last scanned... check the 4949 // version of the new path against what we have stored to determine 4950 // what to do. 4951 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4952 if (pkg.mVersionCode <= ps.versionCode) { 4953 // The system package has been updated and the code path does not match 4954 // Ignore entry. Skip it. 4955 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4956 + " ignored: updated version " + ps.versionCode 4957 + " better than this " + pkg.mVersionCode); 4958 if (!updatedPkg.codePath.equals(scanFile)) { 4959 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4960 + ps.name + " changing from " + updatedPkg.codePathString 4961 + " to " + scanFile); 4962 updatedPkg.codePath = scanFile; 4963 updatedPkg.codePathString = scanFile.toString(); 4964 updatedPkg.resourcePath = scanFile; 4965 updatedPkg.resourcePathString = scanFile.toString(); 4966 } 4967 updatedPkg.pkg = pkg; 4968 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4969 } else { 4970 // The current app on the system partition is better than 4971 // what we have updated to on the data partition; switch 4972 // back to the system partition version. 4973 // At this point, its safely assumed that package installation for 4974 // apps in system partition will go through. If not there won't be a working 4975 // version of the app 4976 // writer 4977 synchronized (mPackages) { 4978 // Just remove the loaded entries from package lists. 4979 mPackages.remove(ps.name); 4980 } 4981 4982 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4983 + " reverting from " + ps.codePathString 4984 + ": new version " + pkg.mVersionCode 4985 + " better than installed " + ps.versionCode); 4986 4987 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4988 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4989 getAppDexInstructionSets(ps)); 4990 synchronized (mInstallLock) { 4991 args.cleanUpResourcesLI(); 4992 } 4993 synchronized (mPackages) { 4994 mSettings.enableSystemPackageLPw(ps.name); 4995 } 4996 updatedPkgBetter = true; 4997 } 4998 } 4999 } 5000 5001 if (updatedPkg != null) { 5002 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5003 // initially 5004 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5005 5006 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5007 // flag set initially 5008 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5009 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5010 } 5011 } 5012 5013 // Verify certificates against what was last scanned 5014 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5015 5016 /* 5017 * A new system app appeared, but we already had a non-system one of the 5018 * same name installed earlier. 5019 */ 5020 boolean shouldHideSystemApp = false; 5021 if (updatedPkg == null && ps != null 5022 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5023 /* 5024 * Check to make sure the signatures match first. If they don't, 5025 * wipe the installed application and its data. 5026 */ 5027 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5028 != PackageManager.SIGNATURE_MATCH) { 5029 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5030 + " signatures don't match existing userdata copy; removing"); 5031 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5032 ps = null; 5033 } else { 5034 /* 5035 * If the newly-added system app is an older version than the 5036 * already installed version, hide it. It will be scanned later 5037 * and re-added like an update. 5038 */ 5039 if (pkg.mVersionCode <= ps.versionCode) { 5040 shouldHideSystemApp = true; 5041 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5042 + " but new version " + pkg.mVersionCode + " better than installed " 5043 + ps.versionCode + "; hiding system"); 5044 } else { 5045 /* 5046 * The newly found system app is a newer version that the 5047 * one previously installed. Simply remove the 5048 * already-installed application and replace it with our own 5049 * while keeping the application data. 5050 */ 5051 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5052 + " reverting from " + ps.codePathString + ": new version " 5053 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5054 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5055 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5056 getAppDexInstructionSets(ps)); 5057 synchronized (mInstallLock) { 5058 args.cleanUpResourcesLI(); 5059 } 5060 } 5061 } 5062 } 5063 5064 // The apk is forward locked (not public) if its code and resources 5065 // are kept in different files. (except for app in either system or 5066 // vendor path). 5067 // TODO grab this value from PackageSettings 5068 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5069 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5070 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5071 } 5072 } 5073 5074 // TODO: extend to support forward-locked splits 5075 String resourcePath = null; 5076 String baseResourcePath = null; 5077 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5078 if (ps != null && ps.resourcePathString != null) { 5079 resourcePath = ps.resourcePathString; 5080 baseResourcePath = ps.resourcePathString; 5081 } else { 5082 // Should not happen at all. Just log an error. 5083 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5084 } 5085 } else { 5086 resourcePath = pkg.codePath; 5087 baseResourcePath = pkg.baseCodePath; 5088 } 5089 5090 // Set application objects path explicitly. 5091 pkg.applicationInfo.setCodePath(pkg.codePath); 5092 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5093 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5094 pkg.applicationInfo.setResourcePath(resourcePath); 5095 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5096 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5097 5098 // Note that we invoke the following method only if we are about to unpack an application 5099 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5100 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5101 5102 /* 5103 * If the system app should be overridden by a previously installed 5104 * data, hide the system app now and let the /data/app scan pick it up 5105 * again. 5106 */ 5107 if (shouldHideSystemApp) { 5108 synchronized (mPackages) { 5109 /* 5110 * We have to grant systems permissions before we hide, because 5111 * grantPermissions will assume the package update is trying to 5112 * expand its permissions. 5113 */ 5114 grantPermissionsLPw(pkg, true, pkg.packageName); 5115 mSettings.disableSystemPackageLPw(pkg.packageName); 5116 } 5117 } 5118 5119 return scannedPkg; 5120 } 5121 5122 private static String fixProcessName(String defProcessName, 5123 String processName, int uid) { 5124 if (processName == null) { 5125 return defProcessName; 5126 } 5127 return processName; 5128 } 5129 5130 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5131 throws PackageManagerException { 5132 if (pkgSetting.signatures.mSignatures != null) { 5133 // Already existing package. Make sure signatures match 5134 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5135 == PackageManager.SIGNATURE_MATCH; 5136 if (!match) { 5137 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5138 == PackageManager.SIGNATURE_MATCH; 5139 } 5140 if (!match) { 5141 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5142 == PackageManager.SIGNATURE_MATCH; 5143 } 5144 if (!match) { 5145 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5146 + pkg.packageName + " signatures do not match the " 5147 + "previously installed version; ignoring!"); 5148 } 5149 } 5150 5151 // Check for shared user signatures 5152 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5153 // Already existing package. Make sure signatures match 5154 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5155 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5156 if (!match) { 5157 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5158 == PackageManager.SIGNATURE_MATCH; 5159 } 5160 if (!match) { 5161 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5162 == PackageManager.SIGNATURE_MATCH; 5163 } 5164 if (!match) { 5165 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5166 "Package " + pkg.packageName 5167 + " has no signatures that match those in shared user " 5168 + pkgSetting.sharedUser.name + "; ignoring!"); 5169 } 5170 } 5171 } 5172 5173 /** 5174 * Enforces that only the system UID or root's UID can call a method exposed 5175 * via Binder. 5176 * 5177 * @param message used as message if SecurityException is thrown 5178 * @throws SecurityException if the caller is not system or root 5179 */ 5180 private static final void enforceSystemOrRoot(String message) { 5181 final int uid = Binder.getCallingUid(); 5182 if (uid != Process.SYSTEM_UID && uid != 0) { 5183 throw new SecurityException(message); 5184 } 5185 } 5186 5187 @Override 5188 public void performBootDexOpt() { 5189 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5190 5191 // Before everything else, see whether we need to fstrim. 5192 try { 5193 IMountService ms = PackageHelper.getMountService(); 5194 if (ms != null) { 5195 final boolean isUpgrade = isUpgrade(); 5196 boolean doTrim = isUpgrade; 5197 if (doTrim) { 5198 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5199 } else { 5200 final long interval = android.provider.Settings.Global.getLong( 5201 mContext.getContentResolver(), 5202 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5203 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5204 if (interval > 0) { 5205 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5206 if (timeSinceLast > interval) { 5207 doTrim = true; 5208 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5209 + "; running immediately"); 5210 } 5211 } 5212 } 5213 if (doTrim) { 5214 if (!isFirstBoot()) { 5215 try { 5216 ActivityManagerNative.getDefault().showBootMessage( 5217 mContext.getResources().getString( 5218 R.string.android_upgrading_fstrim), true); 5219 } catch (RemoteException e) { 5220 } 5221 } 5222 ms.runMaintenance(); 5223 } 5224 } else { 5225 Slog.e(TAG, "Mount service unavailable!"); 5226 } 5227 } catch (RemoteException e) { 5228 // Can't happen; MountService is local 5229 } 5230 5231 final ArraySet<PackageParser.Package> pkgs; 5232 synchronized (mPackages) { 5233 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5234 } 5235 5236 if (pkgs != null) { 5237 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5238 // in case the device runs out of space. 5239 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5240 // Give priority to core apps. 5241 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5242 PackageParser.Package pkg = it.next(); 5243 if (pkg.coreApp) { 5244 if (DEBUG_DEXOPT) { 5245 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5246 } 5247 sortedPkgs.add(pkg); 5248 it.remove(); 5249 } 5250 } 5251 // Give priority to system apps that listen for pre boot complete. 5252 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5253 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5254 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5255 PackageParser.Package pkg = it.next(); 5256 if (pkgNames.contains(pkg.packageName)) { 5257 if (DEBUG_DEXOPT) { 5258 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5259 } 5260 sortedPkgs.add(pkg); 5261 it.remove(); 5262 } 5263 } 5264 // Give priority to system apps. 5265 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5266 PackageParser.Package pkg = it.next(); 5267 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5268 if (DEBUG_DEXOPT) { 5269 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5270 } 5271 sortedPkgs.add(pkg); 5272 it.remove(); 5273 } 5274 } 5275 // Give priority to updated system apps. 5276 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5277 PackageParser.Package pkg = it.next(); 5278 if (pkg.isUpdatedSystemApp()) { 5279 if (DEBUG_DEXOPT) { 5280 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5281 } 5282 sortedPkgs.add(pkg); 5283 it.remove(); 5284 } 5285 } 5286 // Give priority to apps that listen for boot complete. 5287 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5288 pkgNames = getPackageNamesForIntent(intent); 5289 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5290 PackageParser.Package pkg = it.next(); 5291 if (pkgNames.contains(pkg.packageName)) { 5292 if (DEBUG_DEXOPT) { 5293 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5294 } 5295 sortedPkgs.add(pkg); 5296 it.remove(); 5297 } 5298 } 5299 // Filter out packages that aren't recently used. 5300 filterRecentlyUsedApps(pkgs); 5301 // Add all remaining apps. 5302 for (PackageParser.Package pkg : pkgs) { 5303 if (DEBUG_DEXOPT) { 5304 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5305 } 5306 sortedPkgs.add(pkg); 5307 } 5308 5309 // If we want to be lazy, filter everything that wasn't recently used. 5310 if (mLazyDexOpt) { 5311 filterRecentlyUsedApps(sortedPkgs); 5312 } 5313 5314 int i = 0; 5315 int total = sortedPkgs.size(); 5316 File dataDir = Environment.getDataDirectory(); 5317 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5318 if (lowThreshold == 0) { 5319 throw new IllegalStateException("Invalid low memory threshold"); 5320 } 5321 for (PackageParser.Package pkg : sortedPkgs) { 5322 long usableSpace = dataDir.getUsableSpace(); 5323 if (usableSpace < lowThreshold) { 5324 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5325 break; 5326 } 5327 performBootDexOpt(pkg, ++i, total); 5328 } 5329 } 5330 } 5331 5332 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5333 // Filter out packages that aren't recently used. 5334 // 5335 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5336 // should do a full dexopt. 5337 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5338 int total = pkgs.size(); 5339 int skipped = 0; 5340 long now = System.currentTimeMillis(); 5341 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5342 PackageParser.Package pkg = i.next(); 5343 long then = pkg.mLastPackageUsageTimeInMills; 5344 if (then + mDexOptLRUThresholdInMills < now) { 5345 if (DEBUG_DEXOPT) { 5346 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5347 ((then == 0) ? "never" : new Date(then))); 5348 } 5349 i.remove(); 5350 skipped++; 5351 } 5352 } 5353 if (DEBUG_DEXOPT) { 5354 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5355 } 5356 } 5357 } 5358 5359 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5360 List<ResolveInfo> ris = null; 5361 try { 5362 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5363 intent, null, 0, UserHandle.USER_OWNER); 5364 } catch (RemoteException e) { 5365 } 5366 ArraySet<String> pkgNames = new ArraySet<String>(); 5367 if (ris != null) { 5368 for (ResolveInfo ri : ris) { 5369 pkgNames.add(ri.activityInfo.packageName); 5370 } 5371 } 5372 return pkgNames; 5373 } 5374 5375 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5376 if (DEBUG_DEXOPT) { 5377 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5378 } 5379 if (!isFirstBoot()) { 5380 try { 5381 ActivityManagerNative.getDefault().showBootMessage( 5382 mContext.getResources().getString(R.string.android_upgrading_apk, 5383 curr, total), true); 5384 } catch (RemoteException e) { 5385 } 5386 } 5387 PackageParser.Package p = pkg; 5388 synchronized (mInstallLock) { 5389 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5390 false /* force dex */, false /* defer */, true /* include dependencies */); 5391 } 5392 } 5393 5394 @Override 5395 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5396 return performDexOpt(packageName, instructionSet, false); 5397 } 5398 5399 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5400 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5401 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5402 if (!dexopt && !updateUsage) { 5403 // We aren't going to dexopt or update usage, so bail early. 5404 return false; 5405 } 5406 PackageParser.Package p; 5407 final String targetInstructionSet; 5408 synchronized (mPackages) { 5409 p = mPackages.get(packageName); 5410 if (p == null) { 5411 return false; 5412 } 5413 if (updateUsage) { 5414 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5415 } 5416 mPackageUsage.write(false); 5417 if (!dexopt) { 5418 // We aren't going to dexopt, so bail early. 5419 return false; 5420 } 5421 5422 targetInstructionSet = instructionSet != null ? instructionSet : 5423 getPrimaryInstructionSet(p.applicationInfo); 5424 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5425 return false; 5426 } 5427 } 5428 5429 synchronized (mInstallLock) { 5430 final String[] instructionSets = new String[] { targetInstructionSet }; 5431 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5432 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5433 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5434 } 5435 } 5436 5437 public ArraySet<String> getPackagesThatNeedDexOpt() { 5438 ArraySet<String> pkgs = null; 5439 synchronized (mPackages) { 5440 for (PackageParser.Package p : mPackages.values()) { 5441 if (DEBUG_DEXOPT) { 5442 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5443 } 5444 if (!p.mDexOptPerformed.isEmpty()) { 5445 continue; 5446 } 5447 if (pkgs == null) { 5448 pkgs = new ArraySet<String>(); 5449 } 5450 pkgs.add(p.packageName); 5451 } 5452 } 5453 return pkgs; 5454 } 5455 5456 public void shutdown() { 5457 mPackageUsage.write(true); 5458 } 5459 5460 @Override 5461 public void forceDexOpt(String packageName) { 5462 enforceSystemOrRoot("forceDexOpt"); 5463 5464 PackageParser.Package pkg; 5465 synchronized (mPackages) { 5466 pkg = mPackages.get(packageName); 5467 if (pkg == null) { 5468 throw new IllegalArgumentException("Missing package: " + packageName); 5469 } 5470 } 5471 5472 synchronized (mInstallLock) { 5473 final String[] instructionSets = new String[] { 5474 getPrimaryInstructionSet(pkg.applicationInfo) }; 5475 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5476 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5477 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5478 throw new IllegalStateException("Failed to dexopt: " + res); 5479 } 5480 } 5481 } 5482 5483 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5484 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5485 Slog.w(TAG, "Unable to update from " + oldPkg.name 5486 + " to " + newPkg.packageName 5487 + ": old package not in system partition"); 5488 return false; 5489 } else if (mPackages.get(oldPkg.name) != null) { 5490 Slog.w(TAG, "Unable to update from " + oldPkg.name 5491 + " to " + newPkg.packageName 5492 + ": old package still exists"); 5493 return false; 5494 } 5495 return true; 5496 } 5497 5498 private File getDataPathForPackage(String packageName, int userId) { 5499 /* 5500 * Until we fully support multiple users, return the directory we 5501 * previously would have. The PackageManagerTests will need to be 5502 * revised when this is changed back.. 5503 */ 5504 if (userId == 0) { 5505 return new File(mAppDataDir, packageName); 5506 } else { 5507 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5508 + File.separator + packageName); 5509 } 5510 } 5511 5512 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5513 int[] users = sUserManager.getUserIds(); 5514 int res = mInstaller.install(packageName, uid, uid, seinfo); 5515 if (res < 0) { 5516 return res; 5517 } 5518 for (int user : users) { 5519 if (user != 0) { 5520 res = mInstaller.createUserData(packageName, 5521 UserHandle.getUid(user, uid), user, seinfo); 5522 if (res < 0) { 5523 return res; 5524 } 5525 } 5526 } 5527 return res; 5528 } 5529 5530 private int removeDataDirsLI(String packageName) { 5531 int[] users = sUserManager.getUserIds(); 5532 int res = 0; 5533 for (int user : users) { 5534 int resInner = mInstaller.remove(packageName, user); 5535 if (resInner < 0) { 5536 res = resInner; 5537 } 5538 } 5539 5540 return res; 5541 } 5542 5543 private int deleteCodeCacheDirsLI(String packageName) { 5544 int[] users = sUserManager.getUserIds(); 5545 int res = 0; 5546 for (int user : users) { 5547 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5548 if (resInner < 0) { 5549 res = resInner; 5550 } 5551 } 5552 return res; 5553 } 5554 5555 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5556 PackageParser.Package changingLib) { 5557 if (file.path != null) { 5558 usesLibraryFiles.add(file.path); 5559 return; 5560 } 5561 PackageParser.Package p = mPackages.get(file.apk); 5562 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5563 // If we are doing this while in the middle of updating a library apk, 5564 // then we need to make sure to use that new apk for determining the 5565 // dependencies here. (We haven't yet finished committing the new apk 5566 // to the package manager state.) 5567 if (p == null || p.packageName.equals(changingLib.packageName)) { 5568 p = changingLib; 5569 } 5570 } 5571 if (p != null) { 5572 usesLibraryFiles.addAll(p.getAllCodePaths()); 5573 } 5574 } 5575 5576 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5577 PackageParser.Package changingLib) throws PackageManagerException { 5578 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5579 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5580 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5581 for (int i=0; i<N; i++) { 5582 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5583 if (file == null) { 5584 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5585 "Package " + pkg.packageName + " requires unavailable shared library " 5586 + pkg.usesLibraries.get(i) + "; failing!"); 5587 } 5588 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5589 } 5590 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5591 for (int i=0; i<N; i++) { 5592 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5593 if (file == null) { 5594 Slog.w(TAG, "Package " + pkg.packageName 5595 + " desires unavailable shared library " 5596 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5597 } else { 5598 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5599 } 5600 } 5601 N = usesLibraryFiles.size(); 5602 if (N > 0) { 5603 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5604 } else { 5605 pkg.usesLibraryFiles = null; 5606 } 5607 } 5608 } 5609 5610 private static boolean hasString(List<String> list, List<String> which) { 5611 if (list == null) { 5612 return false; 5613 } 5614 for (int i=list.size()-1; i>=0; i--) { 5615 for (int j=which.size()-1; j>=0; j--) { 5616 if (which.get(j).equals(list.get(i))) { 5617 return true; 5618 } 5619 } 5620 } 5621 return false; 5622 } 5623 5624 private void updateAllSharedLibrariesLPw() { 5625 for (PackageParser.Package pkg : mPackages.values()) { 5626 try { 5627 updateSharedLibrariesLPw(pkg, null); 5628 } catch (PackageManagerException e) { 5629 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5630 } 5631 } 5632 } 5633 5634 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5635 PackageParser.Package changingPkg) { 5636 ArrayList<PackageParser.Package> res = null; 5637 for (PackageParser.Package pkg : mPackages.values()) { 5638 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5639 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5640 if (res == null) { 5641 res = new ArrayList<PackageParser.Package>(); 5642 } 5643 res.add(pkg); 5644 try { 5645 updateSharedLibrariesLPw(pkg, changingPkg); 5646 } catch (PackageManagerException e) { 5647 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5648 } 5649 } 5650 } 5651 return res; 5652 } 5653 5654 /** 5655 * Derive the value of the {@code cpuAbiOverride} based on the provided 5656 * value and an optional stored value from the package settings. 5657 */ 5658 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5659 String cpuAbiOverride = null; 5660 5661 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5662 cpuAbiOverride = null; 5663 } else if (abiOverride != null) { 5664 cpuAbiOverride = abiOverride; 5665 } else if (settings != null) { 5666 cpuAbiOverride = settings.cpuAbiOverrideString; 5667 } 5668 5669 return cpuAbiOverride; 5670 } 5671 5672 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5673 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5674 boolean success = false; 5675 try { 5676 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5677 currentTime, user); 5678 success = true; 5679 return res; 5680 } finally { 5681 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5682 removeDataDirsLI(pkg.packageName); 5683 } 5684 } 5685 } 5686 5687 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5688 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5689 final File scanFile = new File(pkg.codePath); 5690 if (pkg.applicationInfo.getCodePath() == null || 5691 pkg.applicationInfo.getResourcePath() == null) { 5692 // Bail out. The resource and code paths haven't been set. 5693 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5694 "Code and resource paths haven't been set correctly"); 5695 } 5696 5697 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5698 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5699 } else { 5700 // Only allow system apps to be flagged as core apps. 5701 pkg.coreApp = false; 5702 } 5703 5704 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5705 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5706 } 5707 5708 if (mCustomResolverComponentName != null && 5709 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5710 setUpCustomResolverActivity(pkg); 5711 } 5712 5713 if (pkg.packageName.equals("android")) { 5714 synchronized (mPackages) { 5715 if (mAndroidApplication != null) { 5716 Slog.w(TAG, "*************************************************"); 5717 Slog.w(TAG, "Core android package being redefined. Skipping."); 5718 Slog.w(TAG, " file=" + scanFile); 5719 Slog.w(TAG, "*************************************************"); 5720 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5721 "Core android package being redefined. Skipping."); 5722 } 5723 5724 // Set up information for our fall-back user intent resolution activity. 5725 mPlatformPackage = pkg; 5726 pkg.mVersionCode = mSdkVersion; 5727 mAndroidApplication = pkg.applicationInfo; 5728 5729 if (!mResolverReplaced) { 5730 mResolveActivity.applicationInfo = mAndroidApplication; 5731 mResolveActivity.name = ResolverActivity.class.getName(); 5732 mResolveActivity.packageName = mAndroidApplication.packageName; 5733 mResolveActivity.processName = "system:ui"; 5734 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5735 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5736 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5737 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5738 mResolveActivity.exported = true; 5739 mResolveActivity.enabled = true; 5740 mResolveInfo.activityInfo = mResolveActivity; 5741 mResolveInfo.priority = 0; 5742 mResolveInfo.preferredOrder = 0; 5743 mResolveInfo.match = 0; 5744 mResolveComponentName = new ComponentName( 5745 mAndroidApplication.packageName, mResolveActivity.name); 5746 } 5747 } 5748 } 5749 5750 if (DEBUG_PACKAGE_SCANNING) { 5751 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5752 Log.d(TAG, "Scanning package " + pkg.packageName); 5753 } 5754 5755 if (mPackages.containsKey(pkg.packageName) 5756 || mSharedLibraries.containsKey(pkg.packageName)) { 5757 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5758 "Application package " + pkg.packageName 5759 + " already installed. Skipping duplicate."); 5760 } 5761 5762 // If we're only installing presumed-existing packages, require that the 5763 // scanned APK is both already known and at the path previously established 5764 // for it. Previously unknown packages we pick up normally, but if we have an 5765 // a priori expectation about this package's install presence, enforce it. 5766 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5767 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5768 if (known != null) { 5769 if (DEBUG_PACKAGE_SCANNING) { 5770 Log.d(TAG, "Examining " + pkg.codePath 5771 + " and requiring known paths " + known.codePathString 5772 + " & " + known.resourcePathString); 5773 } 5774 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5775 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5776 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5777 "Application package " + pkg.packageName 5778 + " found at " + pkg.applicationInfo.getCodePath() 5779 + " but expected at " + known.codePathString + "; ignoring."); 5780 } 5781 } 5782 } 5783 5784 // Initialize package source and resource directories 5785 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5786 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5787 5788 SharedUserSetting suid = null; 5789 PackageSetting pkgSetting = null; 5790 5791 if (!isSystemApp(pkg)) { 5792 // Only system apps can use these features. 5793 pkg.mOriginalPackages = null; 5794 pkg.mRealPackage = null; 5795 pkg.mAdoptPermissions = null; 5796 } 5797 5798 // writer 5799 synchronized (mPackages) { 5800 if (pkg.mSharedUserId != null) { 5801 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5802 if (suid == null) { 5803 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5804 "Creating application package " + pkg.packageName 5805 + " for shared user failed"); 5806 } 5807 if (DEBUG_PACKAGE_SCANNING) { 5808 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5809 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5810 + "): packages=" + suid.packages); 5811 } 5812 } 5813 5814 // Check if we are renaming from an original package name. 5815 PackageSetting origPackage = null; 5816 String realName = null; 5817 if (pkg.mOriginalPackages != null) { 5818 // This package may need to be renamed to a previously 5819 // installed name. Let's check on that... 5820 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5821 if (pkg.mOriginalPackages.contains(renamed)) { 5822 // This package had originally been installed as the 5823 // original name, and we have already taken care of 5824 // transitioning to the new one. Just update the new 5825 // one to continue using the old name. 5826 realName = pkg.mRealPackage; 5827 if (!pkg.packageName.equals(renamed)) { 5828 // Callers into this function may have already taken 5829 // care of renaming the package; only do it here if 5830 // it is not already done. 5831 pkg.setPackageName(renamed); 5832 } 5833 5834 } else { 5835 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5836 if ((origPackage = mSettings.peekPackageLPr( 5837 pkg.mOriginalPackages.get(i))) != null) { 5838 // We do have the package already installed under its 5839 // original name... should we use it? 5840 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5841 // New package is not compatible with original. 5842 origPackage = null; 5843 continue; 5844 } else if (origPackage.sharedUser != null) { 5845 // Make sure uid is compatible between packages. 5846 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5847 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5848 + " to " + pkg.packageName + ": old uid " 5849 + origPackage.sharedUser.name 5850 + " differs from " + pkg.mSharedUserId); 5851 origPackage = null; 5852 continue; 5853 } 5854 } else { 5855 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5856 + pkg.packageName + " to old name " + origPackage.name); 5857 } 5858 break; 5859 } 5860 } 5861 } 5862 } 5863 5864 if (mTransferedPackages.contains(pkg.packageName)) { 5865 Slog.w(TAG, "Package " + pkg.packageName 5866 + " was transferred to another, but its .apk remains"); 5867 } 5868 5869 // Just create the setting, don't add it yet. For already existing packages 5870 // the PkgSetting exists already and doesn't have to be created. 5871 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5872 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5873 pkg.applicationInfo.primaryCpuAbi, 5874 pkg.applicationInfo.secondaryCpuAbi, 5875 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5876 user, false); 5877 if (pkgSetting == null) { 5878 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5879 "Creating application package " + pkg.packageName + " failed"); 5880 } 5881 5882 if (pkgSetting.origPackage != null) { 5883 // If we are first transitioning from an original package, 5884 // fix up the new package's name now. We need to do this after 5885 // looking up the package under its new name, so getPackageLP 5886 // can take care of fiddling things correctly. 5887 pkg.setPackageName(origPackage.name); 5888 5889 // File a report about this. 5890 String msg = "New package " + pkgSetting.realName 5891 + " renamed to replace old package " + pkgSetting.name; 5892 reportSettingsProblem(Log.WARN, msg); 5893 5894 // Make a note of it. 5895 mTransferedPackages.add(origPackage.name); 5896 5897 // No longer need to retain this. 5898 pkgSetting.origPackage = null; 5899 } 5900 5901 if (realName != null) { 5902 // Make a note of it. 5903 mTransferedPackages.add(pkg.packageName); 5904 } 5905 5906 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5907 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5908 } 5909 5910 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5911 // Check all shared libraries and map to their actual file path. 5912 // We only do this here for apps not on a system dir, because those 5913 // are the only ones that can fail an install due to this. We 5914 // will take care of the system apps by updating all of their 5915 // library paths after the scan is done. 5916 updateSharedLibrariesLPw(pkg, null); 5917 } 5918 5919 if (mFoundPolicyFile) { 5920 SELinuxMMAC.assignSeinfoValue(pkg); 5921 } 5922 5923 pkg.applicationInfo.uid = pkgSetting.appId; 5924 pkg.mExtras = pkgSetting; 5925 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5926 try { 5927 verifySignaturesLP(pkgSetting, pkg); 5928 // We just determined the app is signed correctly, so bring 5929 // over the latest parsed certs. 5930 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5931 } catch (PackageManagerException e) { 5932 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5933 throw e; 5934 } 5935 // The signature has changed, but this package is in the system 5936 // image... let's recover! 5937 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5938 // However... if this package is part of a shared user, but it 5939 // doesn't match the signature of the shared user, let's fail. 5940 // What this means is that you can't change the signatures 5941 // associated with an overall shared user, which doesn't seem all 5942 // that unreasonable. 5943 if (pkgSetting.sharedUser != null) { 5944 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5945 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5946 throw new PackageManagerException( 5947 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5948 "Signature mismatch for shared user : " 5949 + pkgSetting.sharedUser); 5950 } 5951 } 5952 // File a report about this. 5953 String msg = "System package " + pkg.packageName 5954 + " signature changed; retaining data."; 5955 reportSettingsProblem(Log.WARN, msg); 5956 } 5957 } else { 5958 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5959 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5960 + pkg.packageName + " upgrade keys do not match the " 5961 + "previously installed version"); 5962 } else { 5963 // We just determined the app is signed correctly, so bring 5964 // over the latest parsed certs. 5965 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5966 } 5967 } 5968 // Verify that this new package doesn't have any content providers 5969 // that conflict with existing packages. Only do this if the 5970 // package isn't already installed, since we don't want to break 5971 // things that are installed. 5972 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5973 final int N = pkg.providers.size(); 5974 int i; 5975 for (i=0; i<N; i++) { 5976 PackageParser.Provider p = pkg.providers.get(i); 5977 if (p.info.authority != null) { 5978 String names[] = p.info.authority.split(";"); 5979 for (int j = 0; j < names.length; j++) { 5980 if (mProvidersByAuthority.containsKey(names[j])) { 5981 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5982 final String otherPackageName = 5983 ((other != null && other.getComponentName() != null) ? 5984 other.getComponentName().getPackageName() : "?"); 5985 throw new PackageManagerException( 5986 INSTALL_FAILED_CONFLICTING_PROVIDER, 5987 "Can't install because provider name " + names[j] 5988 + " (in package " + pkg.applicationInfo.packageName 5989 + ") is already used by " + otherPackageName); 5990 } 5991 } 5992 } 5993 } 5994 } 5995 5996 if (pkg.mAdoptPermissions != null) { 5997 // This package wants to adopt ownership of permissions from 5998 // another package. 5999 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6000 final String origName = pkg.mAdoptPermissions.get(i); 6001 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6002 if (orig != null) { 6003 if (verifyPackageUpdateLPr(orig, pkg)) { 6004 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6005 + pkg.packageName); 6006 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6007 } 6008 } 6009 } 6010 } 6011 } 6012 6013 final String pkgName = pkg.packageName; 6014 6015 final long scanFileTime = scanFile.lastModified(); 6016 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6017 pkg.applicationInfo.processName = fixProcessName( 6018 pkg.applicationInfo.packageName, 6019 pkg.applicationInfo.processName, 6020 pkg.applicationInfo.uid); 6021 6022 File dataPath; 6023 if (mPlatformPackage == pkg) { 6024 // The system package is special. 6025 dataPath = new File(Environment.getDataDirectory(), "system"); 6026 6027 pkg.applicationInfo.dataDir = dataPath.getPath(); 6028 6029 } else { 6030 // This is a normal package, need to make its data directory. 6031 dataPath = getDataPathForPackage(pkg.packageName, 0); 6032 6033 boolean uidError = false; 6034 if (dataPath.exists()) { 6035 int currentUid = 0; 6036 try { 6037 StructStat stat = Os.stat(dataPath.getPath()); 6038 currentUid = stat.st_uid; 6039 } catch (ErrnoException e) { 6040 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6041 } 6042 6043 // If we have mismatched owners for the data path, we have a problem. 6044 if (currentUid != pkg.applicationInfo.uid) { 6045 boolean recovered = false; 6046 if (currentUid == 0) { 6047 // The directory somehow became owned by root. Wow. 6048 // This is probably because the system was stopped while 6049 // installd was in the middle of messing with its libs 6050 // directory. Ask installd to fix that. 6051 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 6052 pkg.applicationInfo.uid); 6053 if (ret >= 0) { 6054 recovered = true; 6055 String msg = "Package " + pkg.packageName 6056 + " unexpectedly changed to uid 0; recovered to " + 6057 + pkg.applicationInfo.uid; 6058 reportSettingsProblem(Log.WARN, msg); 6059 } 6060 } 6061 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6062 || (scanFlags&SCAN_BOOTING) != 0)) { 6063 // If this is a system app, we can at least delete its 6064 // current data so the application will still work. 6065 int ret = removeDataDirsLI(pkgName); 6066 if (ret >= 0) { 6067 // TODO: Kill the processes first 6068 // Old data gone! 6069 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6070 ? "System package " : "Third party package "; 6071 String msg = prefix + pkg.packageName 6072 + " has changed from uid: " 6073 + currentUid + " to " 6074 + pkg.applicationInfo.uid + "; old data erased"; 6075 reportSettingsProblem(Log.WARN, msg); 6076 recovered = true; 6077 6078 // And now re-install the app. 6079 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6080 pkg.applicationInfo.seinfo); 6081 if (ret == -1) { 6082 // Ack should not happen! 6083 msg = prefix + pkg.packageName 6084 + " could not have data directory re-created after delete."; 6085 reportSettingsProblem(Log.WARN, msg); 6086 throw new PackageManagerException( 6087 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6088 } 6089 } 6090 if (!recovered) { 6091 mHasSystemUidErrors = true; 6092 } 6093 } else if (!recovered) { 6094 // If we allow this install to proceed, we will be broken. 6095 // Abort, abort! 6096 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6097 "scanPackageLI"); 6098 } 6099 if (!recovered) { 6100 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6101 + pkg.applicationInfo.uid + "/fs_" 6102 + currentUid; 6103 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6104 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6105 String msg = "Package " + pkg.packageName 6106 + " has mismatched uid: " 6107 + currentUid + " on disk, " 6108 + pkg.applicationInfo.uid + " in settings"; 6109 // writer 6110 synchronized (mPackages) { 6111 mSettings.mReadMessages.append(msg); 6112 mSettings.mReadMessages.append('\n'); 6113 uidError = true; 6114 if (!pkgSetting.uidError) { 6115 reportSettingsProblem(Log.ERROR, msg); 6116 } 6117 } 6118 } 6119 } 6120 pkg.applicationInfo.dataDir = dataPath.getPath(); 6121 if (mShouldRestoreconData) { 6122 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6123 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6124 pkg.applicationInfo.uid); 6125 } 6126 } else { 6127 if (DEBUG_PACKAGE_SCANNING) { 6128 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6129 Log.v(TAG, "Want this data dir: " + dataPath); 6130 } 6131 //invoke installer to do the actual installation 6132 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6133 pkg.applicationInfo.seinfo); 6134 if (ret < 0) { 6135 // Error from installer 6136 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6137 "Unable to create data dirs [errorCode=" + ret + "]"); 6138 } 6139 6140 if (dataPath.exists()) { 6141 pkg.applicationInfo.dataDir = dataPath.getPath(); 6142 } else { 6143 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6144 pkg.applicationInfo.dataDir = null; 6145 } 6146 } 6147 6148 pkgSetting.uidError = uidError; 6149 } 6150 6151 final String path = scanFile.getPath(); 6152 final String codePath = pkg.applicationInfo.getCodePath(); 6153 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6154 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6155 setBundledAppAbisAndRoots(pkg, pkgSetting); 6156 6157 // If we haven't found any native libraries for the app, check if it has 6158 // renderscript code. We'll need to force the app to 32 bit if it has 6159 // renderscript bitcode. 6160 if (pkg.applicationInfo.primaryCpuAbi == null 6161 && pkg.applicationInfo.secondaryCpuAbi == null 6162 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6163 NativeLibraryHelper.Handle handle = null; 6164 try { 6165 handle = NativeLibraryHelper.Handle.create(scanFile); 6166 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6167 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6168 } 6169 } catch (IOException ioe) { 6170 Slog.w(TAG, "Error scanning system app : " + ioe); 6171 } finally { 6172 IoUtils.closeQuietly(handle); 6173 } 6174 } 6175 6176 setNativeLibraryPaths(pkg); 6177 } else { 6178 // TODO: We can probably be smarter about this stuff. For installed apps, 6179 // we can calculate this information at install time once and for all. For 6180 // system apps, we can probably assume that this information doesn't change 6181 // after the first boot scan. As things stand, we do lots of unnecessary work. 6182 6183 // Give ourselves some initial paths; we'll come back for another 6184 // pass once we've determined ABI below. 6185 setNativeLibraryPaths(pkg); 6186 6187 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6188 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6189 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6190 6191 NativeLibraryHelper.Handle handle = null; 6192 try { 6193 handle = NativeLibraryHelper.Handle.create(scanFile); 6194 // TODO(multiArch): This can be null for apps that didn't go through the 6195 // usual installation process. We can calculate it again, like we 6196 // do during install time. 6197 // 6198 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6199 // unnecessary. 6200 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6201 6202 // Null out the abis so that they can be recalculated. 6203 pkg.applicationInfo.primaryCpuAbi = null; 6204 pkg.applicationInfo.secondaryCpuAbi = null; 6205 if (isMultiArch(pkg.applicationInfo)) { 6206 // Warn if we've set an abiOverride for multi-lib packages.. 6207 // By definition, we need to copy both 32 and 64 bit libraries for 6208 // such packages. 6209 if (pkg.cpuAbiOverride != null 6210 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6211 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6212 } 6213 6214 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6215 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6216 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6217 if (isAsec) { 6218 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6219 } else { 6220 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6221 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6222 useIsaSpecificSubdirs); 6223 } 6224 } 6225 6226 maybeThrowExceptionForMultiArchCopy( 6227 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6228 6229 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6230 if (isAsec) { 6231 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6232 } else { 6233 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6234 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6235 useIsaSpecificSubdirs); 6236 } 6237 } 6238 6239 maybeThrowExceptionForMultiArchCopy( 6240 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6241 6242 if (abi64 >= 0) { 6243 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6244 } 6245 6246 if (abi32 >= 0) { 6247 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6248 if (abi64 >= 0) { 6249 pkg.applicationInfo.secondaryCpuAbi = abi; 6250 } else { 6251 pkg.applicationInfo.primaryCpuAbi = abi; 6252 } 6253 } 6254 } else { 6255 String[] abiList = (cpuAbiOverride != null) ? 6256 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6257 6258 // Enable gross and lame hacks for apps that are built with old 6259 // SDK tools. We must scan their APKs for renderscript bitcode and 6260 // not launch them if it's present. Don't bother checking on devices 6261 // that don't have 64 bit support. 6262 boolean needsRenderScriptOverride = false; 6263 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6264 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6265 abiList = Build.SUPPORTED_32_BIT_ABIS; 6266 needsRenderScriptOverride = true; 6267 } 6268 6269 final int copyRet; 6270 if (isAsec) { 6271 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6272 } else { 6273 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6274 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6275 } 6276 6277 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6278 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6279 "Error unpackaging native libs for app, errorCode=" + copyRet); 6280 } 6281 6282 if (copyRet >= 0) { 6283 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6284 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6285 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6286 } else if (needsRenderScriptOverride) { 6287 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6288 } 6289 } 6290 } catch (IOException ioe) { 6291 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6292 } finally { 6293 IoUtils.closeQuietly(handle); 6294 } 6295 6296 // Now that we've calculated the ABIs and determined if it's an internal app, 6297 // we will go ahead and populate the nativeLibraryPath. 6298 setNativeLibraryPaths(pkg); 6299 6300 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6301 final int[] userIds = sUserManager.getUserIds(); 6302 synchronized (mInstallLock) { 6303 // Create a native library symlink only if we have native libraries 6304 // and if the native libraries are 32 bit libraries. We do not provide 6305 // this symlink for 64 bit libraries. 6306 if (pkg.applicationInfo.primaryCpuAbi != null && 6307 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6308 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6309 for (int userId : userIds) { 6310 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6311 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6312 "Failed linking native library dir (user=" + userId + ")"); 6313 } 6314 } 6315 } 6316 } 6317 } 6318 6319 // This is a special case for the "system" package, where the ABI is 6320 // dictated by the zygote configuration (and init.rc). We should keep track 6321 // of this ABI so that we can deal with "normal" applications that run under 6322 // the same UID correctly. 6323 if (mPlatformPackage == pkg) { 6324 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6325 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6326 } 6327 6328 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6329 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6330 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6331 // Copy the derived override back to the parsed package, so that we can 6332 // update the package settings accordingly. 6333 pkg.cpuAbiOverride = cpuAbiOverride; 6334 6335 if (DEBUG_ABI_SELECTION) { 6336 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6337 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6338 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6339 } 6340 6341 // Push the derived path down into PackageSettings so we know what to 6342 // clean up at uninstall time. 6343 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6344 6345 if (DEBUG_ABI_SELECTION) { 6346 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6347 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6348 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6349 } 6350 6351 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6352 // We don't do this here during boot because we can do it all 6353 // at once after scanning all existing packages. 6354 // 6355 // We also do this *before* we perform dexopt on this package, so that 6356 // we can avoid redundant dexopts, and also to make sure we've got the 6357 // code and package path correct. 6358 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6359 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6360 } 6361 6362 if ((scanFlags & SCAN_NO_DEX) == 0) { 6363 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6364 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6365 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6366 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6367 } 6368 } 6369 if (mFactoryTest && pkg.requestedPermissions.contains( 6370 android.Manifest.permission.FACTORY_TEST)) { 6371 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6372 } 6373 6374 ArrayList<PackageParser.Package> clientLibPkgs = null; 6375 6376 // writer 6377 synchronized (mPackages) { 6378 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6379 // Only system apps can add new shared libraries. 6380 if (pkg.libraryNames != null) { 6381 for (int i=0; i<pkg.libraryNames.size(); i++) { 6382 String name = pkg.libraryNames.get(i); 6383 boolean allowed = false; 6384 if (pkg.isUpdatedSystemApp()) { 6385 // New library entries can only be added through the 6386 // system image. This is important to get rid of a lot 6387 // of nasty edge cases: for example if we allowed a non- 6388 // system update of the app to add a library, then uninstalling 6389 // the update would make the library go away, and assumptions 6390 // we made such as through app install filtering would now 6391 // have allowed apps on the device which aren't compatible 6392 // with it. Better to just have the restriction here, be 6393 // conservative, and create many fewer cases that can negatively 6394 // impact the user experience. 6395 final PackageSetting sysPs = mSettings 6396 .getDisabledSystemPkgLPr(pkg.packageName); 6397 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6398 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6399 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6400 allowed = true; 6401 allowed = true; 6402 break; 6403 } 6404 } 6405 } 6406 } else { 6407 allowed = true; 6408 } 6409 if (allowed) { 6410 if (!mSharedLibraries.containsKey(name)) { 6411 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6412 } else if (!name.equals(pkg.packageName)) { 6413 Slog.w(TAG, "Package " + pkg.packageName + " library " 6414 + name + " already exists; skipping"); 6415 } 6416 } else { 6417 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6418 + name + " that is not declared on system image; skipping"); 6419 } 6420 } 6421 if ((scanFlags&SCAN_BOOTING) == 0) { 6422 // If we are not booting, we need to update any applications 6423 // that are clients of our shared library. If we are booting, 6424 // this will all be done once the scan is complete. 6425 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6426 } 6427 } 6428 } 6429 } 6430 6431 // We also need to dexopt any apps that are dependent on this library. Note that 6432 // if these fail, we should abort the install since installing the library will 6433 // result in some apps being broken. 6434 if (clientLibPkgs != null) { 6435 if ((scanFlags & SCAN_NO_DEX) == 0) { 6436 for (int i = 0; i < clientLibPkgs.size(); i++) { 6437 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6438 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6439 null /* instruction sets */, forceDex, 6440 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6441 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6442 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6443 "scanPackageLI failed to dexopt clientLibPkgs"); 6444 } 6445 } 6446 } 6447 } 6448 6449 // Request the ActivityManager to kill the process(only for existing packages) 6450 // so that we do not end up in a confused state while the user is still using the older 6451 // version of the application while the new one gets installed. 6452 if ((scanFlags & SCAN_REPLACING) != 0) { 6453 killApplication(pkg.applicationInfo.packageName, 6454 pkg.applicationInfo.uid, "update pkg"); 6455 } 6456 6457 // Also need to kill any apps that are dependent on the library. 6458 if (clientLibPkgs != null) { 6459 for (int i=0; i<clientLibPkgs.size(); i++) { 6460 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6461 killApplication(clientPkg.applicationInfo.packageName, 6462 clientPkg.applicationInfo.uid, "update lib"); 6463 } 6464 } 6465 6466 // writer 6467 synchronized (mPackages) { 6468 // We don't expect installation to fail beyond this point 6469 6470 // Add the new setting to mSettings 6471 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6472 // Add the new setting to mPackages 6473 mPackages.put(pkg.applicationInfo.packageName, pkg); 6474 // Make sure we don't accidentally delete its data. 6475 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6476 while (iter.hasNext()) { 6477 PackageCleanItem item = iter.next(); 6478 if (pkgName.equals(item.packageName)) { 6479 iter.remove(); 6480 } 6481 } 6482 6483 // Take care of first install / last update times. 6484 if (currentTime != 0) { 6485 if (pkgSetting.firstInstallTime == 0) { 6486 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6487 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6488 pkgSetting.lastUpdateTime = currentTime; 6489 } 6490 } else if (pkgSetting.firstInstallTime == 0) { 6491 // We need *something*. Take time time stamp of the file. 6492 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6493 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6494 if (scanFileTime != pkgSetting.timeStamp) { 6495 // A package on the system image has changed; consider this 6496 // to be an update. 6497 pkgSetting.lastUpdateTime = scanFileTime; 6498 } 6499 } 6500 6501 // Add the package's KeySets to the global KeySetManagerService 6502 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6503 try { 6504 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6505 if (pkg.mKeySetMapping != null) { 6506 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6507 if (pkg.mUpgradeKeySets != null) { 6508 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6509 } 6510 } 6511 } catch (NullPointerException e) { 6512 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6513 } catch (IllegalArgumentException e) { 6514 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6515 } 6516 6517 int N = pkg.providers.size(); 6518 StringBuilder r = null; 6519 int i; 6520 for (i=0; i<N; i++) { 6521 PackageParser.Provider p = pkg.providers.get(i); 6522 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6523 p.info.processName, pkg.applicationInfo.uid); 6524 mProviders.addProvider(p); 6525 p.syncable = p.info.isSyncable; 6526 if (p.info.authority != null) { 6527 String names[] = p.info.authority.split(";"); 6528 p.info.authority = null; 6529 for (int j = 0; j < names.length; j++) { 6530 if (j == 1 && p.syncable) { 6531 // We only want the first authority for a provider to possibly be 6532 // syncable, so if we already added this provider using a different 6533 // authority clear the syncable flag. We copy the provider before 6534 // changing it because the mProviders object contains a reference 6535 // to a provider that we don't want to change. 6536 // Only do this for the second authority since the resulting provider 6537 // object can be the same for all future authorities for this provider. 6538 p = new PackageParser.Provider(p); 6539 p.syncable = false; 6540 } 6541 if (!mProvidersByAuthority.containsKey(names[j])) { 6542 mProvidersByAuthority.put(names[j], p); 6543 if (p.info.authority == null) { 6544 p.info.authority = names[j]; 6545 } else { 6546 p.info.authority = p.info.authority + ";" + names[j]; 6547 } 6548 if (DEBUG_PACKAGE_SCANNING) { 6549 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6550 Log.d(TAG, "Registered content provider: " + names[j] 6551 + ", className = " + p.info.name + ", isSyncable = " 6552 + p.info.isSyncable); 6553 } 6554 } else { 6555 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6556 Slog.w(TAG, "Skipping provider name " + names[j] + 6557 " (in package " + pkg.applicationInfo.packageName + 6558 "): name already used by " 6559 + ((other != null && other.getComponentName() != null) 6560 ? other.getComponentName().getPackageName() : "?")); 6561 } 6562 } 6563 } 6564 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6565 if (r == null) { 6566 r = new StringBuilder(256); 6567 } else { 6568 r.append(' '); 6569 } 6570 r.append(p.info.name); 6571 } 6572 } 6573 if (r != null) { 6574 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6575 } 6576 6577 N = pkg.services.size(); 6578 r = null; 6579 for (i=0; i<N; i++) { 6580 PackageParser.Service s = pkg.services.get(i); 6581 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6582 s.info.processName, pkg.applicationInfo.uid); 6583 mServices.addService(s); 6584 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6585 if (r == null) { 6586 r = new StringBuilder(256); 6587 } else { 6588 r.append(' '); 6589 } 6590 r.append(s.info.name); 6591 } 6592 } 6593 if (r != null) { 6594 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6595 } 6596 6597 N = pkg.receivers.size(); 6598 r = null; 6599 for (i=0; i<N; i++) { 6600 PackageParser.Activity a = pkg.receivers.get(i); 6601 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6602 a.info.processName, pkg.applicationInfo.uid); 6603 mReceivers.addActivity(a, "receiver"); 6604 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6605 if (r == null) { 6606 r = new StringBuilder(256); 6607 } else { 6608 r.append(' '); 6609 } 6610 r.append(a.info.name); 6611 } 6612 } 6613 if (r != null) { 6614 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6615 } 6616 6617 N = pkg.activities.size(); 6618 r = null; 6619 for (i=0; i<N; i++) { 6620 PackageParser.Activity a = pkg.activities.get(i); 6621 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6622 a.info.processName, pkg.applicationInfo.uid); 6623 mActivities.addActivity(a, "activity"); 6624 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6625 if (r == null) { 6626 r = new StringBuilder(256); 6627 } else { 6628 r.append(' '); 6629 } 6630 r.append(a.info.name); 6631 } 6632 } 6633 if (r != null) { 6634 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6635 } 6636 6637 N = pkg.permissionGroups.size(); 6638 r = null; 6639 for (i=0; i<N; i++) { 6640 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6641 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6642 if (cur == null) { 6643 mPermissionGroups.put(pg.info.name, pg); 6644 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6645 if (r == null) { 6646 r = new StringBuilder(256); 6647 } else { 6648 r.append(' '); 6649 } 6650 r.append(pg.info.name); 6651 } 6652 } else { 6653 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6654 + pg.info.packageName + " ignored: original from " 6655 + cur.info.packageName); 6656 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6657 if (r == null) { 6658 r = new StringBuilder(256); 6659 } else { 6660 r.append(' '); 6661 } 6662 r.append("DUP:"); 6663 r.append(pg.info.name); 6664 } 6665 } 6666 } 6667 if (r != null) { 6668 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6669 } 6670 6671 N = pkg.permissions.size(); 6672 r = null; 6673 for (i=0; i<N; i++) { 6674 PackageParser.Permission p = pkg.permissions.get(i); 6675 ArrayMap<String, BasePermission> permissionMap = 6676 p.tree ? mSettings.mPermissionTrees 6677 : mSettings.mPermissions; 6678 p.group = mPermissionGroups.get(p.info.group); 6679 if (p.info.group == null || p.group != null) { 6680 BasePermission bp = permissionMap.get(p.info.name); 6681 6682 // Allow system apps to redefine non-system permissions 6683 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6684 final boolean currentOwnerIsSystem = (bp.perm != null 6685 && isSystemApp(bp.perm.owner)); 6686 if (isSystemApp(p.owner)) { 6687 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6688 // It's a built-in permission and no owner, take ownership now 6689 bp.packageSetting = pkgSetting; 6690 bp.perm = p; 6691 bp.uid = pkg.applicationInfo.uid; 6692 bp.sourcePackage = p.info.packageName; 6693 } else if (!currentOwnerIsSystem) { 6694 String msg = "New decl " + p.owner + " of permission " 6695 + p.info.name + " is system; overriding " + bp.sourcePackage; 6696 reportSettingsProblem(Log.WARN, msg); 6697 bp = null; 6698 } 6699 } 6700 } 6701 6702 if (bp == null) { 6703 bp = new BasePermission(p.info.name, p.info.packageName, 6704 BasePermission.TYPE_NORMAL); 6705 permissionMap.put(p.info.name, bp); 6706 } 6707 6708 if (bp.perm == null) { 6709 if (bp.sourcePackage == null 6710 || bp.sourcePackage.equals(p.info.packageName)) { 6711 BasePermission tree = findPermissionTreeLP(p.info.name); 6712 if (tree == null 6713 || tree.sourcePackage.equals(p.info.packageName)) { 6714 bp.packageSetting = pkgSetting; 6715 bp.perm = p; 6716 bp.uid = pkg.applicationInfo.uid; 6717 bp.sourcePackage = p.info.packageName; 6718 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6719 if (r == null) { 6720 r = new StringBuilder(256); 6721 } else { 6722 r.append(' '); 6723 } 6724 r.append(p.info.name); 6725 } 6726 } else { 6727 Slog.w(TAG, "Permission " + p.info.name + " from package " 6728 + p.info.packageName + " ignored: base tree " 6729 + tree.name + " is from package " 6730 + tree.sourcePackage); 6731 } 6732 } else { 6733 Slog.w(TAG, "Permission " + p.info.name + " from package " 6734 + p.info.packageName + " ignored: original from " 6735 + bp.sourcePackage); 6736 } 6737 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6738 if (r == null) { 6739 r = new StringBuilder(256); 6740 } else { 6741 r.append(' '); 6742 } 6743 r.append("DUP:"); 6744 r.append(p.info.name); 6745 } 6746 if (bp.perm == p) { 6747 bp.protectionLevel = p.info.protectionLevel; 6748 } 6749 } else { 6750 Slog.w(TAG, "Permission " + p.info.name + " from package " 6751 + p.info.packageName + " ignored: no group " 6752 + p.group); 6753 } 6754 } 6755 if (r != null) { 6756 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6757 } 6758 6759 N = pkg.instrumentation.size(); 6760 r = null; 6761 for (i=0; i<N; i++) { 6762 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6763 a.info.packageName = pkg.applicationInfo.packageName; 6764 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6765 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6766 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6767 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6768 a.info.dataDir = pkg.applicationInfo.dataDir; 6769 6770 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6771 // need other information about the application, like the ABI and what not ? 6772 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6773 mInstrumentation.put(a.getComponentName(), a); 6774 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6775 if (r == null) { 6776 r = new StringBuilder(256); 6777 } else { 6778 r.append(' '); 6779 } 6780 r.append(a.info.name); 6781 } 6782 } 6783 if (r != null) { 6784 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6785 } 6786 6787 if (pkg.protectedBroadcasts != null) { 6788 N = pkg.protectedBroadcasts.size(); 6789 for (i=0; i<N; i++) { 6790 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6791 } 6792 } 6793 6794 pkgSetting.setTimeStamp(scanFileTime); 6795 6796 // Create idmap files for pairs of (packages, overlay packages). 6797 // Note: "android", ie framework-res.apk, is handled by native layers. 6798 if (pkg.mOverlayTarget != null) { 6799 // This is an overlay package. 6800 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6801 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6802 mOverlays.put(pkg.mOverlayTarget, 6803 new ArrayMap<String, PackageParser.Package>()); 6804 } 6805 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6806 map.put(pkg.packageName, pkg); 6807 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6808 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6809 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6810 "scanPackageLI failed to createIdmap"); 6811 } 6812 } 6813 } else if (mOverlays.containsKey(pkg.packageName) && 6814 !pkg.packageName.equals("android")) { 6815 // This is a regular package, with one or more known overlay packages. 6816 createIdmapsForPackageLI(pkg); 6817 } 6818 } 6819 6820 return pkg; 6821 } 6822 6823 /** 6824 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6825 * i.e, so that all packages can be run inside a single process if required. 6826 * 6827 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6828 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6829 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6830 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6831 * updating a package that belongs to a shared user. 6832 * 6833 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6834 * adds unnecessary complexity. 6835 */ 6836 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6837 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6838 String requiredInstructionSet = null; 6839 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6840 requiredInstructionSet = VMRuntime.getInstructionSet( 6841 scannedPackage.applicationInfo.primaryCpuAbi); 6842 } 6843 6844 PackageSetting requirer = null; 6845 for (PackageSetting ps : packagesForUser) { 6846 // If packagesForUser contains scannedPackage, we skip it. This will happen 6847 // when scannedPackage is an update of an existing package. Without this check, 6848 // we will never be able to change the ABI of any package belonging to a shared 6849 // user, even if it's compatible with other packages. 6850 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6851 if (ps.primaryCpuAbiString == null) { 6852 continue; 6853 } 6854 6855 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6856 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6857 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6858 // this but there's not much we can do. 6859 String errorMessage = "Instruction set mismatch, " 6860 + ((requirer == null) ? "[caller]" : requirer) 6861 + " requires " + requiredInstructionSet + " whereas " + ps 6862 + " requires " + instructionSet; 6863 Slog.w(TAG, errorMessage); 6864 } 6865 6866 if (requiredInstructionSet == null) { 6867 requiredInstructionSet = instructionSet; 6868 requirer = ps; 6869 } 6870 } 6871 } 6872 6873 if (requiredInstructionSet != null) { 6874 String adjustedAbi; 6875 if (requirer != null) { 6876 // requirer != null implies that either scannedPackage was null or that scannedPackage 6877 // did not require an ABI, in which case we have to adjust scannedPackage to match 6878 // the ABI of the set (which is the same as requirer's ABI) 6879 adjustedAbi = requirer.primaryCpuAbiString; 6880 if (scannedPackage != null) { 6881 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6882 } 6883 } else { 6884 // requirer == null implies that we're updating all ABIs in the set to 6885 // match scannedPackage. 6886 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6887 } 6888 6889 for (PackageSetting ps : packagesForUser) { 6890 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6891 if (ps.primaryCpuAbiString != null) { 6892 continue; 6893 } 6894 6895 ps.primaryCpuAbiString = adjustedAbi; 6896 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6897 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6898 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6899 6900 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6901 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6902 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6903 ps.primaryCpuAbiString = null; 6904 ps.pkg.applicationInfo.primaryCpuAbi = null; 6905 return; 6906 } else { 6907 mInstaller.rmdex(ps.codePathString, 6908 getDexCodeInstructionSet(getPreferredInstructionSet())); 6909 } 6910 } 6911 } 6912 } 6913 } 6914 } 6915 6916 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6917 synchronized (mPackages) { 6918 mResolverReplaced = true; 6919 // Set up information for custom user intent resolution activity. 6920 mResolveActivity.applicationInfo = pkg.applicationInfo; 6921 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6922 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6923 mResolveActivity.processName = pkg.applicationInfo.packageName; 6924 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6925 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6926 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6927 mResolveActivity.theme = 0; 6928 mResolveActivity.exported = true; 6929 mResolveActivity.enabled = true; 6930 mResolveInfo.activityInfo = mResolveActivity; 6931 mResolveInfo.priority = 0; 6932 mResolveInfo.preferredOrder = 0; 6933 mResolveInfo.match = 0; 6934 mResolveComponentName = mCustomResolverComponentName; 6935 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6936 mResolveComponentName); 6937 } 6938 } 6939 6940 private static String calculateBundledApkRoot(final String codePathString) { 6941 final File codePath = new File(codePathString); 6942 final File codeRoot; 6943 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6944 codeRoot = Environment.getRootDirectory(); 6945 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6946 codeRoot = Environment.getOemDirectory(); 6947 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6948 codeRoot = Environment.getVendorDirectory(); 6949 } else { 6950 // Unrecognized code path; take its top real segment as the apk root: 6951 // e.g. /something/app/blah.apk => /something 6952 try { 6953 File f = codePath.getCanonicalFile(); 6954 File parent = f.getParentFile(); // non-null because codePath is a file 6955 File tmp; 6956 while ((tmp = parent.getParentFile()) != null) { 6957 f = parent; 6958 parent = tmp; 6959 } 6960 codeRoot = f; 6961 Slog.w(TAG, "Unrecognized code path " 6962 + codePath + " - using " + codeRoot); 6963 } catch (IOException e) { 6964 // Can't canonicalize the code path -- shenanigans? 6965 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6966 return Environment.getRootDirectory().getPath(); 6967 } 6968 } 6969 return codeRoot.getPath(); 6970 } 6971 6972 /** 6973 * Derive and set the location of native libraries for the given package, 6974 * which varies depending on where and how the package was installed. 6975 */ 6976 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6977 final ApplicationInfo info = pkg.applicationInfo; 6978 final String codePath = pkg.codePath; 6979 final File codeFile = new File(codePath); 6980 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6981 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6982 6983 info.nativeLibraryRootDir = null; 6984 info.nativeLibraryRootRequiresIsa = false; 6985 info.nativeLibraryDir = null; 6986 info.secondaryNativeLibraryDir = null; 6987 6988 if (isApkFile(codeFile)) { 6989 // Monolithic install 6990 if (bundledApp) { 6991 // If "/system/lib64/apkname" exists, assume that is the per-package 6992 // native library directory to use; otherwise use "/system/lib/apkname". 6993 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6994 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6995 getPrimaryInstructionSet(info)); 6996 6997 // This is a bundled system app so choose the path based on the ABI. 6998 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6999 // is just the default path. 7000 final String apkName = deriveCodePathName(codePath); 7001 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7002 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7003 apkName).getAbsolutePath(); 7004 7005 if (info.secondaryCpuAbi != null) { 7006 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7007 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7008 secondaryLibDir, apkName).getAbsolutePath(); 7009 } 7010 } else if (asecApp) { 7011 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7012 .getAbsolutePath(); 7013 } else { 7014 final String apkName = deriveCodePathName(codePath); 7015 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7016 .getAbsolutePath(); 7017 } 7018 7019 info.nativeLibraryRootRequiresIsa = false; 7020 info.nativeLibraryDir = info.nativeLibraryRootDir; 7021 } else { 7022 // Cluster install 7023 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7024 info.nativeLibraryRootRequiresIsa = true; 7025 7026 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7027 getPrimaryInstructionSet(info)).getAbsolutePath(); 7028 7029 if (info.secondaryCpuAbi != null) { 7030 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7031 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7032 } 7033 } 7034 } 7035 7036 /** 7037 * Calculate the abis and roots for a bundled app. These can uniquely 7038 * be determined from the contents of the system partition, i.e whether 7039 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7040 * of this information, and instead assume that the system was built 7041 * sensibly. 7042 */ 7043 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7044 PackageSetting pkgSetting) { 7045 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7046 7047 // If "/system/lib64/apkname" exists, assume that is the per-package 7048 // native library directory to use; otherwise use "/system/lib/apkname". 7049 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7050 setBundledAppAbi(pkg, apkRoot, apkName); 7051 // pkgSetting might be null during rescan following uninstall of updates 7052 // to a bundled app, so accommodate that possibility. The settings in 7053 // that case will be established later from the parsed package. 7054 // 7055 // If the settings aren't null, sync them up with what we've just derived. 7056 // note that apkRoot isn't stored in the package settings. 7057 if (pkgSetting != null) { 7058 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7059 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7060 } 7061 } 7062 7063 /** 7064 * Deduces the ABI of a bundled app and sets the relevant fields on the 7065 * parsed pkg object. 7066 * 7067 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7068 * under which system libraries are installed. 7069 * @param apkName the name of the installed package. 7070 */ 7071 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7072 final File codeFile = new File(pkg.codePath); 7073 7074 final boolean has64BitLibs; 7075 final boolean has32BitLibs; 7076 if (isApkFile(codeFile)) { 7077 // Monolithic install 7078 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7079 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7080 } else { 7081 // Cluster install 7082 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7083 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7084 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7085 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7086 has64BitLibs = (new File(rootDir, isa)).exists(); 7087 } else { 7088 has64BitLibs = false; 7089 } 7090 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7091 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7092 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7093 has32BitLibs = (new File(rootDir, isa)).exists(); 7094 } else { 7095 has32BitLibs = false; 7096 } 7097 } 7098 7099 if (has64BitLibs && !has32BitLibs) { 7100 // The package has 64 bit libs, but not 32 bit libs. Its primary 7101 // ABI should be 64 bit. We can safely assume here that the bundled 7102 // native libraries correspond to the most preferred ABI in the list. 7103 7104 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7105 pkg.applicationInfo.secondaryCpuAbi = null; 7106 } else if (has32BitLibs && !has64BitLibs) { 7107 // The package has 32 bit libs but not 64 bit libs. Its primary 7108 // ABI should be 32 bit. 7109 7110 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7111 pkg.applicationInfo.secondaryCpuAbi = null; 7112 } else if (has32BitLibs && has64BitLibs) { 7113 // The application has both 64 and 32 bit bundled libraries. We check 7114 // here that the app declares multiArch support, and warn if it doesn't. 7115 // 7116 // We will be lenient here and record both ABIs. The primary will be the 7117 // ABI that's higher on the list, i.e, a device that's configured to prefer 7118 // 64 bit apps will see a 64 bit primary ABI, 7119 7120 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7121 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7122 } 7123 7124 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7125 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7126 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7127 } else { 7128 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7129 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7130 } 7131 } else { 7132 pkg.applicationInfo.primaryCpuAbi = null; 7133 pkg.applicationInfo.secondaryCpuAbi = null; 7134 } 7135 } 7136 7137 private void killApplication(String pkgName, int appId, String reason) { 7138 // Request the ActivityManager to kill the process(only for existing packages) 7139 // so that we do not end up in a confused state while the user is still using the older 7140 // version of the application while the new one gets installed. 7141 IActivityManager am = ActivityManagerNative.getDefault(); 7142 if (am != null) { 7143 try { 7144 am.killApplicationWithAppId(pkgName, appId, reason); 7145 } catch (RemoteException e) { 7146 } 7147 } 7148 } 7149 7150 void removePackageLI(PackageSetting ps, boolean chatty) { 7151 if (DEBUG_INSTALL) { 7152 if (chatty) 7153 Log.d(TAG, "Removing package " + ps.name); 7154 } 7155 7156 // writer 7157 synchronized (mPackages) { 7158 mPackages.remove(ps.name); 7159 final PackageParser.Package pkg = ps.pkg; 7160 if (pkg != null) { 7161 cleanPackageDataStructuresLILPw(pkg, chatty); 7162 } 7163 } 7164 } 7165 7166 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7167 if (DEBUG_INSTALL) { 7168 if (chatty) 7169 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7170 } 7171 7172 // writer 7173 synchronized (mPackages) { 7174 mPackages.remove(pkg.applicationInfo.packageName); 7175 cleanPackageDataStructuresLILPw(pkg, chatty); 7176 } 7177 } 7178 7179 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7180 int N = pkg.providers.size(); 7181 StringBuilder r = null; 7182 int i; 7183 for (i=0; i<N; i++) { 7184 PackageParser.Provider p = pkg.providers.get(i); 7185 mProviders.removeProvider(p); 7186 if (p.info.authority == null) { 7187 7188 /* There was another ContentProvider with this authority when 7189 * this app was installed so this authority is null, 7190 * Ignore it as we don't have to unregister the provider. 7191 */ 7192 continue; 7193 } 7194 String names[] = p.info.authority.split(";"); 7195 for (int j = 0; j < names.length; j++) { 7196 if (mProvidersByAuthority.get(names[j]) == p) { 7197 mProvidersByAuthority.remove(names[j]); 7198 if (DEBUG_REMOVE) { 7199 if (chatty) 7200 Log.d(TAG, "Unregistered content provider: " + names[j] 7201 + ", className = " + p.info.name + ", isSyncable = " 7202 + p.info.isSyncable); 7203 } 7204 } 7205 } 7206 if (DEBUG_REMOVE && chatty) { 7207 if (r == null) { 7208 r = new StringBuilder(256); 7209 } else { 7210 r.append(' '); 7211 } 7212 r.append(p.info.name); 7213 } 7214 } 7215 if (r != null) { 7216 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7217 } 7218 7219 N = pkg.services.size(); 7220 r = null; 7221 for (i=0; i<N; i++) { 7222 PackageParser.Service s = pkg.services.get(i); 7223 mServices.removeService(s); 7224 if (chatty) { 7225 if (r == null) { 7226 r = new StringBuilder(256); 7227 } else { 7228 r.append(' '); 7229 } 7230 r.append(s.info.name); 7231 } 7232 } 7233 if (r != null) { 7234 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7235 } 7236 7237 N = pkg.receivers.size(); 7238 r = null; 7239 for (i=0; i<N; i++) { 7240 PackageParser.Activity a = pkg.receivers.get(i); 7241 mReceivers.removeActivity(a, "receiver"); 7242 if (DEBUG_REMOVE && chatty) { 7243 if (r == null) { 7244 r = new StringBuilder(256); 7245 } else { 7246 r.append(' '); 7247 } 7248 r.append(a.info.name); 7249 } 7250 } 7251 if (r != null) { 7252 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7253 } 7254 7255 N = pkg.activities.size(); 7256 r = null; 7257 for (i=0; i<N; i++) { 7258 PackageParser.Activity a = pkg.activities.get(i); 7259 mActivities.removeActivity(a, "activity"); 7260 if (DEBUG_REMOVE && chatty) { 7261 if (r == null) { 7262 r = new StringBuilder(256); 7263 } else { 7264 r.append(' '); 7265 } 7266 r.append(a.info.name); 7267 } 7268 } 7269 if (r != null) { 7270 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7271 } 7272 7273 N = pkg.permissions.size(); 7274 r = null; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Permission p = pkg.permissions.get(i); 7277 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7278 if (bp == null) { 7279 bp = mSettings.mPermissionTrees.get(p.info.name); 7280 } 7281 if (bp != null && bp.perm == p) { 7282 bp.perm = null; 7283 if (DEBUG_REMOVE && chatty) { 7284 if (r == null) { 7285 r = new StringBuilder(256); 7286 } else { 7287 r.append(' '); 7288 } 7289 r.append(p.info.name); 7290 } 7291 } 7292 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7293 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7294 if (appOpPerms != null) { 7295 appOpPerms.remove(pkg.packageName); 7296 } 7297 } 7298 } 7299 if (r != null) { 7300 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7301 } 7302 7303 N = pkg.requestedPermissions.size(); 7304 r = null; 7305 for (i=0; i<N; i++) { 7306 String perm = pkg.requestedPermissions.get(i); 7307 BasePermission bp = mSettings.mPermissions.get(perm); 7308 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7309 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7310 if (appOpPerms != null) { 7311 appOpPerms.remove(pkg.packageName); 7312 if (appOpPerms.isEmpty()) { 7313 mAppOpPermissionPackages.remove(perm); 7314 } 7315 } 7316 } 7317 } 7318 if (r != null) { 7319 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7320 } 7321 7322 N = pkg.instrumentation.size(); 7323 r = null; 7324 for (i=0; i<N; i++) { 7325 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7326 mInstrumentation.remove(a.getComponentName()); 7327 if (DEBUG_REMOVE && chatty) { 7328 if (r == null) { 7329 r = new StringBuilder(256); 7330 } else { 7331 r.append(' '); 7332 } 7333 r.append(a.info.name); 7334 } 7335 } 7336 if (r != null) { 7337 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7338 } 7339 7340 r = null; 7341 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7342 // Only system apps can hold shared libraries. 7343 if (pkg.libraryNames != null) { 7344 for (i=0; i<pkg.libraryNames.size(); i++) { 7345 String name = pkg.libraryNames.get(i); 7346 SharedLibraryEntry cur = mSharedLibraries.get(name); 7347 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7348 mSharedLibraries.remove(name); 7349 if (DEBUG_REMOVE && chatty) { 7350 if (r == null) { 7351 r = new StringBuilder(256); 7352 } else { 7353 r.append(' '); 7354 } 7355 r.append(name); 7356 } 7357 } 7358 } 7359 } 7360 } 7361 if (r != null) { 7362 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7363 } 7364 } 7365 7366 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7367 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7368 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7369 return true; 7370 } 7371 } 7372 return false; 7373 } 7374 7375 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7376 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7377 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7378 7379 private void updatePermissionsLPw(String changingPkg, 7380 PackageParser.Package pkgInfo, int flags) { 7381 // Make sure there are no dangling permission trees. 7382 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7383 while (it.hasNext()) { 7384 final BasePermission bp = it.next(); 7385 if (bp.packageSetting == null) { 7386 // We may not yet have parsed the package, so just see if 7387 // we still know about its settings. 7388 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7389 } 7390 if (bp.packageSetting == null) { 7391 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7392 + " from package " + bp.sourcePackage); 7393 it.remove(); 7394 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7395 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7396 Slog.i(TAG, "Removing old permission tree: " + bp.name 7397 + " from package " + bp.sourcePackage); 7398 flags |= UPDATE_PERMISSIONS_ALL; 7399 it.remove(); 7400 } 7401 } 7402 } 7403 7404 // Make sure all dynamic permissions have been assigned to a package, 7405 // and make sure there are no dangling permissions. 7406 it = mSettings.mPermissions.values().iterator(); 7407 while (it.hasNext()) { 7408 final BasePermission bp = it.next(); 7409 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7410 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7411 + bp.name + " pkg=" + bp.sourcePackage 7412 + " info=" + bp.pendingInfo); 7413 if (bp.packageSetting == null && bp.pendingInfo != null) { 7414 final BasePermission tree = findPermissionTreeLP(bp.name); 7415 if (tree != null && tree.perm != null) { 7416 bp.packageSetting = tree.packageSetting; 7417 bp.perm = new PackageParser.Permission(tree.perm.owner, 7418 new PermissionInfo(bp.pendingInfo)); 7419 bp.perm.info.packageName = tree.perm.info.packageName; 7420 bp.perm.info.name = bp.name; 7421 bp.uid = tree.uid; 7422 } 7423 } 7424 } 7425 if (bp.packageSetting == null) { 7426 // We may not yet have parsed the package, so just see if 7427 // we still know about its settings. 7428 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7429 } 7430 if (bp.packageSetting == null) { 7431 Slog.w(TAG, "Removing dangling permission: " + bp.name 7432 + " from package " + bp.sourcePackage); 7433 it.remove(); 7434 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7435 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7436 Slog.i(TAG, "Removing old permission: " + bp.name 7437 + " from package " + bp.sourcePackage); 7438 flags |= UPDATE_PERMISSIONS_ALL; 7439 it.remove(); 7440 } 7441 } 7442 } 7443 7444 // Now update the permissions for all packages, in particular 7445 // replace the granted permissions of the system packages. 7446 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7447 for (PackageParser.Package pkg : mPackages.values()) { 7448 if (pkg != pkgInfo) { 7449 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7450 changingPkg); 7451 } 7452 } 7453 } 7454 7455 if (pkgInfo != null) { 7456 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7457 } 7458 } 7459 7460 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7461 String packageOfInterest) { 7462 // IMPORTANT: There are two types of permissions: install and runtime. 7463 // Install time permissions are granted when the app is installed to 7464 // all device users and users added in the future. Runtime permissions 7465 // are granted at runtime explicitly to specific users. Normal and signature 7466 // protected permissions are install time permissions. Dangerous permissions 7467 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7468 // otherwise they are runtime permissions. This function does not manage 7469 // runtime permissions except for the case an app targeting Lollipop MR1 7470 // being upgraded to target a newer SDK, in which case dangerous permissions 7471 // are transformed from install time to runtime ones. 7472 7473 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7474 if (ps == null) { 7475 return; 7476 } 7477 7478 PermissionsState permissionsState = ps.getPermissionsState(); 7479 PermissionsState origPermissions = permissionsState; 7480 7481 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7482 7483 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7484 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7485 7486 boolean changedInstallPermission = false; 7487 7488 if (replace) { 7489 ps.installPermissionsFixed = false; 7490 if (!ps.isSharedUser()) { 7491 origPermissions = new PermissionsState(permissionsState); 7492 permissionsState.reset(); 7493 } 7494 } 7495 7496 permissionsState.setGlobalGids(mGlobalGids); 7497 7498 final int N = pkg.requestedPermissions.size(); 7499 for (int i=0; i<N; i++) { 7500 final String name = pkg.requestedPermissions.get(i); 7501 final BasePermission bp = mSettings.mPermissions.get(name); 7502 7503 if (DEBUG_INSTALL) { 7504 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7505 } 7506 7507 if (bp == null || bp.packageSetting == null) { 7508 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7509 Slog.w(TAG, "Unknown permission " + name 7510 + " in package " + pkg.packageName); 7511 } 7512 continue; 7513 } 7514 7515 final String perm = bp.name; 7516 boolean allowedSig = false; 7517 int grant = GRANT_DENIED; 7518 7519 // Keep track of app op permissions. 7520 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7521 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7522 if (pkgs == null) { 7523 pkgs = new ArraySet<>(); 7524 mAppOpPermissionPackages.put(bp.name, pkgs); 7525 } 7526 pkgs.add(pkg.packageName); 7527 } 7528 7529 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7530 switch (level) { 7531 case PermissionInfo.PROTECTION_NORMAL: { 7532 // For all apps normal permissions are install time ones. 7533 grant = GRANT_INSTALL; 7534 } break; 7535 7536 case PermissionInfo.PROTECTION_DANGEROUS: { 7537 if (!RUNTIME_PERMISSIONS_ENABLED 7538 || pkg.applicationInfo.targetSdkVersion 7539 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7540 // For legacy apps dangerous permissions are install time ones. 7541 grant = GRANT_INSTALL; 7542 } else if (ps.isSystem()) { 7543 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7544 if (origPermissions.hasInstallPermission(bp.name)) { 7545 // If a system app had an install permission, then the app was 7546 // upgraded and we grant the permissions as runtime to all users. 7547 grant = GRANT_UPGRADE; 7548 upgradeUserIds = currentUserIds; 7549 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7550 // If users changed since the last permissions update for a 7551 // system app, we grant the permission as runtime to the new users. 7552 grant = GRANT_UPGRADE; 7553 upgradeUserIds = currentUserIds; 7554 for (int userId : updatedUserIds) { 7555 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7556 } 7557 } else { 7558 // Otherwise, we grant the permission as runtime if the app 7559 // already had it, i.e. we preserve runtime permissions. 7560 grant = GRANT_RUNTIME; 7561 } 7562 } else if (origPermissions.hasInstallPermission(bp.name)) { 7563 // For legacy apps that became modern, install becomes runtime. 7564 grant = GRANT_UPGRADE; 7565 upgradeUserIds = currentUserIds; 7566 } else if (replace) { 7567 // For upgraded modern apps keep runtime permissions unchanged. 7568 grant = GRANT_RUNTIME; 7569 } 7570 } break; 7571 7572 case PermissionInfo.PROTECTION_SIGNATURE: { 7573 // For all apps signature permissions are install time ones. 7574 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7575 if (allowedSig) { 7576 grant = GRANT_INSTALL; 7577 } 7578 } break; 7579 } 7580 7581 if (DEBUG_INSTALL) { 7582 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7583 } 7584 7585 if (grant != GRANT_DENIED) { 7586 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7587 // If this is an existing, non-system package, then 7588 // we can't add any new permissions to it. 7589 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7590 // Except... if this is a permission that was added 7591 // to the platform (note: need to only do this when 7592 // updating the platform). 7593 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7594 grant = GRANT_DENIED; 7595 } 7596 } 7597 } 7598 7599 switch (grant) { 7600 case GRANT_INSTALL: { 7601 // Grant an install permission. 7602 if (permissionsState.grantInstallPermission(bp) != 7603 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7604 changedInstallPermission = true; 7605 } 7606 } break; 7607 7608 case GRANT_RUNTIME: { 7609 // Grant previously granted runtime permissions. 7610 for (int userId : UserManagerService.getInstance().getUserIds()) { 7611 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7612 if (permissionsState.grantRuntimePermission(bp, userId) == 7613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7614 // If we cannot put the permission as it was, we have to write. 7615 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7616 changedRuntimePermissionUserIds, userId); 7617 } 7618 } 7619 } 7620 } break; 7621 7622 case GRANT_UPGRADE: { 7623 // Grant runtime permissions for a previously held install permission. 7624 permissionsState.revokeInstallPermission(bp); 7625 for (int userId : upgradeUserIds) { 7626 if (permissionsState.grantRuntimePermission(bp, userId) != 7627 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7628 // If we granted the permission, we have to write. 7629 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7630 changedRuntimePermissionUserIds, userId); 7631 } 7632 } 7633 } break; 7634 7635 default: { 7636 if (packageOfInterest == null 7637 || packageOfInterest.equals(pkg.packageName)) { 7638 Slog.w(TAG, "Not granting permission " + perm 7639 + " to package " + pkg.packageName 7640 + " because it was previously installed without"); 7641 } 7642 } break; 7643 } 7644 } else { 7645 if (permissionsState.revokeInstallPermission(bp) != 7646 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7647 changedInstallPermission = true; 7648 Slog.i(TAG, "Un-granting permission " + perm 7649 + " from package " + pkg.packageName 7650 + " (protectionLevel=" + bp.protectionLevel 7651 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7652 + ")"); 7653 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7654 // Don't print warning for app op permissions, since it is fine for them 7655 // not to be granted, there is a UI for the user to decide. 7656 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7657 Slog.w(TAG, "Not granting permission " + perm 7658 + " to package " + pkg.packageName 7659 + " (protectionLevel=" + bp.protectionLevel 7660 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7661 + ")"); 7662 } 7663 } 7664 } 7665 } 7666 7667 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7668 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7669 // This is the first that we have heard about this package, so the 7670 // permissions we have now selected are fixed until explicitly 7671 // changed. 7672 ps.installPermissionsFixed = true; 7673 } 7674 7675 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7676 7677 // Persist the runtime permissions state for users with changes. 7678 if (RUNTIME_PERMISSIONS_ENABLED) { 7679 for (int userId : changedRuntimePermissionUserIds) { 7680 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7681 } 7682 } 7683 } 7684 7685 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7686 boolean allowed = false; 7687 final int NP = PackageParser.NEW_PERMISSIONS.length; 7688 for (int ip=0; ip<NP; ip++) { 7689 final PackageParser.NewPermissionInfo npi 7690 = PackageParser.NEW_PERMISSIONS[ip]; 7691 if (npi.name.equals(perm) 7692 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7693 allowed = true; 7694 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7695 + pkg.packageName); 7696 break; 7697 } 7698 } 7699 return allowed; 7700 } 7701 7702 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7703 BasePermission bp, PermissionsState origPermissions) { 7704 boolean allowed; 7705 allowed = (compareSignatures( 7706 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7707 == PackageManager.SIGNATURE_MATCH) 7708 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7709 == PackageManager.SIGNATURE_MATCH); 7710 if (!allowed && (bp.protectionLevel 7711 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7712 if (isSystemApp(pkg)) { 7713 // For updated system applications, a system permission 7714 // is granted only if it had been defined by the original application. 7715 if (pkg.isUpdatedSystemApp()) { 7716 final PackageSetting sysPs = mSettings 7717 .getDisabledSystemPkgLPr(pkg.packageName); 7718 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7719 // If the original was granted this permission, we take 7720 // that grant decision as read and propagate it to the 7721 // update. 7722 if (sysPs.isPrivileged()) { 7723 allowed = true; 7724 } 7725 } else { 7726 // The system apk may have been updated with an older 7727 // version of the one on the data partition, but which 7728 // granted a new system permission that it didn't have 7729 // before. In this case we do want to allow the app to 7730 // now get the new permission if the ancestral apk is 7731 // privileged to get it. 7732 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7733 for (int j=0; 7734 j<sysPs.pkg.requestedPermissions.size(); j++) { 7735 if (perm.equals( 7736 sysPs.pkg.requestedPermissions.get(j))) { 7737 allowed = true; 7738 break; 7739 } 7740 } 7741 } 7742 } 7743 } else { 7744 allowed = isPrivilegedApp(pkg); 7745 } 7746 } 7747 } 7748 if (!allowed && (bp.protectionLevel 7749 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7750 // For development permissions, a development permission 7751 // is granted only if it was already granted. 7752 allowed = origPermissions.hasInstallPermission(perm); 7753 } 7754 return allowed; 7755 } 7756 7757 final class ActivityIntentResolver 7758 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7759 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7760 boolean defaultOnly, int userId) { 7761 if (!sUserManager.exists(userId)) return null; 7762 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7763 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7764 } 7765 7766 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7767 int userId) { 7768 if (!sUserManager.exists(userId)) return null; 7769 mFlags = flags; 7770 return super.queryIntent(intent, resolvedType, 7771 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7772 } 7773 7774 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7775 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7776 if (!sUserManager.exists(userId)) return null; 7777 if (packageActivities == null) { 7778 return null; 7779 } 7780 mFlags = flags; 7781 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7782 final int N = packageActivities.size(); 7783 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7784 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7785 7786 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7787 for (int i = 0; i < N; ++i) { 7788 intentFilters = packageActivities.get(i).intents; 7789 if (intentFilters != null && intentFilters.size() > 0) { 7790 PackageParser.ActivityIntentInfo[] array = 7791 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7792 intentFilters.toArray(array); 7793 listCut.add(array); 7794 } 7795 } 7796 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7797 } 7798 7799 public final void addActivity(PackageParser.Activity a, String type) { 7800 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7801 mActivities.put(a.getComponentName(), a); 7802 if (DEBUG_SHOW_INFO) 7803 Log.v( 7804 TAG, " " + type + " " + 7805 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7806 if (DEBUG_SHOW_INFO) 7807 Log.v(TAG, " Class=" + a.info.name); 7808 final int NI = a.intents.size(); 7809 for (int j=0; j<NI; j++) { 7810 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7811 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7812 intent.setPriority(0); 7813 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7814 + a.className + " with priority > 0, forcing to 0"); 7815 } 7816 if (DEBUG_SHOW_INFO) { 7817 Log.v(TAG, " IntentFilter:"); 7818 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7819 } 7820 if (!intent.debugCheck()) { 7821 Log.w(TAG, "==> For Activity " + a.info.name); 7822 } 7823 addFilter(intent); 7824 } 7825 } 7826 7827 public final void removeActivity(PackageParser.Activity a, String type) { 7828 mActivities.remove(a.getComponentName()); 7829 if (DEBUG_SHOW_INFO) { 7830 Log.v(TAG, " " + type + " " 7831 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7832 : a.info.name) + ":"); 7833 Log.v(TAG, " Class=" + a.info.name); 7834 } 7835 final int NI = a.intents.size(); 7836 for (int j=0; j<NI; j++) { 7837 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7838 if (DEBUG_SHOW_INFO) { 7839 Log.v(TAG, " IntentFilter:"); 7840 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7841 } 7842 removeFilter(intent); 7843 } 7844 } 7845 7846 @Override 7847 protected boolean allowFilterResult( 7848 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7849 ActivityInfo filterAi = filter.activity.info; 7850 for (int i=dest.size()-1; i>=0; i--) { 7851 ActivityInfo destAi = dest.get(i).activityInfo; 7852 if (destAi.name == filterAi.name 7853 && destAi.packageName == filterAi.packageName) { 7854 return false; 7855 } 7856 } 7857 return true; 7858 } 7859 7860 @Override 7861 protected ActivityIntentInfo[] newArray(int size) { 7862 return new ActivityIntentInfo[size]; 7863 } 7864 7865 @Override 7866 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7867 if (!sUserManager.exists(userId)) return true; 7868 PackageParser.Package p = filter.activity.owner; 7869 if (p != null) { 7870 PackageSetting ps = (PackageSetting)p.mExtras; 7871 if (ps != null) { 7872 // System apps are never considered stopped for purposes of 7873 // filtering, because there may be no way for the user to 7874 // actually re-launch them. 7875 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7876 && ps.getStopped(userId); 7877 } 7878 } 7879 return false; 7880 } 7881 7882 @Override 7883 protected boolean isPackageForFilter(String packageName, 7884 PackageParser.ActivityIntentInfo info) { 7885 return packageName.equals(info.activity.owner.packageName); 7886 } 7887 7888 @Override 7889 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7890 int match, int userId) { 7891 if (!sUserManager.exists(userId)) return null; 7892 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7893 return null; 7894 } 7895 final PackageParser.Activity activity = info.activity; 7896 if (mSafeMode && (activity.info.applicationInfo.flags 7897 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7898 return null; 7899 } 7900 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7901 if (ps == null) { 7902 return null; 7903 } 7904 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7905 ps.readUserState(userId), userId); 7906 if (ai == null) { 7907 return null; 7908 } 7909 final ResolveInfo res = new ResolveInfo(); 7910 res.activityInfo = ai; 7911 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7912 res.filter = info; 7913 } 7914 if (info != null) { 7915 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7916 } 7917 res.priority = info.getPriority(); 7918 res.preferredOrder = activity.owner.mPreferredOrder; 7919 //System.out.println("Result: " + res.activityInfo.className + 7920 // " = " + res.priority); 7921 res.match = match; 7922 res.isDefault = info.hasDefault; 7923 res.labelRes = info.labelRes; 7924 res.nonLocalizedLabel = info.nonLocalizedLabel; 7925 if (userNeedsBadging(userId)) { 7926 res.noResourceId = true; 7927 } else { 7928 res.icon = info.icon; 7929 } 7930 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7931 return res; 7932 } 7933 7934 @Override 7935 protected void sortResults(List<ResolveInfo> results) { 7936 Collections.sort(results, mResolvePrioritySorter); 7937 } 7938 7939 @Override 7940 protected void dumpFilter(PrintWriter out, String prefix, 7941 PackageParser.ActivityIntentInfo filter) { 7942 out.print(prefix); out.print( 7943 Integer.toHexString(System.identityHashCode(filter.activity))); 7944 out.print(' '); 7945 filter.activity.printComponentShortName(out); 7946 out.print(" filter "); 7947 out.println(Integer.toHexString(System.identityHashCode(filter))); 7948 } 7949 7950 @Override 7951 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7952 return filter.activity; 7953 } 7954 7955 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7956 PackageParser.Activity activity = (PackageParser.Activity)label; 7957 out.print(prefix); out.print( 7958 Integer.toHexString(System.identityHashCode(activity))); 7959 out.print(' '); 7960 activity.printComponentShortName(out); 7961 if (count > 1) { 7962 out.print(" ("); out.print(count); out.print(" filters)"); 7963 } 7964 out.println(); 7965 } 7966 7967// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7968// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7969// final List<ResolveInfo> retList = Lists.newArrayList(); 7970// while (i.hasNext()) { 7971// final ResolveInfo resolveInfo = i.next(); 7972// if (isEnabledLP(resolveInfo.activityInfo)) { 7973// retList.add(resolveInfo); 7974// } 7975// } 7976// return retList; 7977// } 7978 7979 // Keys are String (activity class name), values are Activity. 7980 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7981 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7982 private int mFlags; 7983 } 7984 7985 private final class ServiceIntentResolver 7986 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7987 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7988 boolean defaultOnly, int userId) { 7989 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7990 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7991 } 7992 7993 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7994 int userId) { 7995 if (!sUserManager.exists(userId)) return null; 7996 mFlags = flags; 7997 return super.queryIntent(intent, resolvedType, 7998 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7999 } 8000 8001 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8002 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8003 if (!sUserManager.exists(userId)) return null; 8004 if (packageServices == null) { 8005 return null; 8006 } 8007 mFlags = flags; 8008 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8009 final int N = packageServices.size(); 8010 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8011 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8012 8013 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8014 for (int i = 0; i < N; ++i) { 8015 intentFilters = packageServices.get(i).intents; 8016 if (intentFilters != null && intentFilters.size() > 0) { 8017 PackageParser.ServiceIntentInfo[] array = 8018 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8019 intentFilters.toArray(array); 8020 listCut.add(array); 8021 } 8022 } 8023 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8024 } 8025 8026 public final void addService(PackageParser.Service s) { 8027 mServices.put(s.getComponentName(), s); 8028 if (DEBUG_SHOW_INFO) { 8029 Log.v(TAG, " " 8030 + (s.info.nonLocalizedLabel != null 8031 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8032 Log.v(TAG, " Class=" + s.info.name); 8033 } 8034 final int NI = s.intents.size(); 8035 int j; 8036 for (j=0; j<NI; j++) { 8037 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8038 if (DEBUG_SHOW_INFO) { 8039 Log.v(TAG, " IntentFilter:"); 8040 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8041 } 8042 if (!intent.debugCheck()) { 8043 Log.w(TAG, "==> For Service " + s.info.name); 8044 } 8045 addFilter(intent); 8046 } 8047 } 8048 8049 public final void removeService(PackageParser.Service s) { 8050 mServices.remove(s.getComponentName()); 8051 if (DEBUG_SHOW_INFO) { 8052 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8053 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8054 Log.v(TAG, " Class=" + s.info.name); 8055 } 8056 final int NI = s.intents.size(); 8057 int j; 8058 for (j=0; j<NI; j++) { 8059 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8060 if (DEBUG_SHOW_INFO) { 8061 Log.v(TAG, " IntentFilter:"); 8062 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8063 } 8064 removeFilter(intent); 8065 } 8066 } 8067 8068 @Override 8069 protected boolean allowFilterResult( 8070 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8071 ServiceInfo filterSi = filter.service.info; 8072 for (int i=dest.size()-1; i>=0; i--) { 8073 ServiceInfo destAi = dest.get(i).serviceInfo; 8074 if (destAi.name == filterSi.name 8075 && destAi.packageName == filterSi.packageName) { 8076 return false; 8077 } 8078 } 8079 return true; 8080 } 8081 8082 @Override 8083 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8084 return new PackageParser.ServiceIntentInfo[size]; 8085 } 8086 8087 @Override 8088 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8089 if (!sUserManager.exists(userId)) return true; 8090 PackageParser.Package p = filter.service.owner; 8091 if (p != null) { 8092 PackageSetting ps = (PackageSetting)p.mExtras; 8093 if (ps != null) { 8094 // System apps are never considered stopped for purposes of 8095 // filtering, because there may be no way for the user to 8096 // actually re-launch them. 8097 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8098 && ps.getStopped(userId); 8099 } 8100 } 8101 return false; 8102 } 8103 8104 @Override 8105 protected boolean isPackageForFilter(String packageName, 8106 PackageParser.ServiceIntentInfo info) { 8107 return packageName.equals(info.service.owner.packageName); 8108 } 8109 8110 @Override 8111 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8112 int match, int userId) { 8113 if (!sUserManager.exists(userId)) return null; 8114 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8115 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8116 return null; 8117 } 8118 final PackageParser.Service service = info.service; 8119 if (mSafeMode && (service.info.applicationInfo.flags 8120 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8121 return null; 8122 } 8123 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8124 if (ps == null) { 8125 return null; 8126 } 8127 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8128 ps.readUserState(userId), userId); 8129 if (si == null) { 8130 return null; 8131 } 8132 final ResolveInfo res = new ResolveInfo(); 8133 res.serviceInfo = si; 8134 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8135 res.filter = filter; 8136 } 8137 res.priority = info.getPriority(); 8138 res.preferredOrder = service.owner.mPreferredOrder; 8139 res.match = match; 8140 res.isDefault = info.hasDefault; 8141 res.labelRes = info.labelRes; 8142 res.nonLocalizedLabel = info.nonLocalizedLabel; 8143 res.icon = info.icon; 8144 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8145 return res; 8146 } 8147 8148 @Override 8149 protected void sortResults(List<ResolveInfo> results) { 8150 Collections.sort(results, mResolvePrioritySorter); 8151 } 8152 8153 @Override 8154 protected void dumpFilter(PrintWriter out, String prefix, 8155 PackageParser.ServiceIntentInfo filter) { 8156 out.print(prefix); out.print( 8157 Integer.toHexString(System.identityHashCode(filter.service))); 8158 out.print(' '); 8159 filter.service.printComponentShortName(out); 8160 out.print(" filter "); 8161 out.println(Integer.toHexString(System.identityHashCode(filter))); 8162 } 8163 8164 @Override 8165 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8166 return filter.service; 8167 } 8168 8169 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8170 PackageParser.Service service = (PackageParser.Service)label; 8171 out.print(prefix); out.print( 8172 Integer.toHexString(System.identityHashCode(service))); 8173 out.print(' '); 8174 service.printComponentShortName(out); 8175 if (count > 1) { 8176 out.print(" ("); out.print(count); out.print(" filters)"); 8177 } 8178 out.println(); 8179 } 8180 8181// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8182// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8183// final List<ResolveInfo> retList = Lists.newArrayList(); 8184// while (i.hasNext()) { 8185// final ResolveInfo resolveInfo = (ResolveInfo) i; 8186// if (isEnabledLP(resolveInfo.serviceInfo)) { 8187// retList.add(resolveInfo); 8188// } 8189// } 8190// return retList; 8191// } 8192 8193 // Keys are String (activity class name), values are Activity. 8194 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8195 = new ArrayMap<ComponentName, PackageParser.Service>(); 8196 private int mFlags; 8197 }; 8198 8199 private final class ProviderIntentResolver 8200 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8201 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8202 boolean defaultOnly, int userId) { 8203 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8204 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8205 } 8206 8207 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8208 int userId) { 8209 if (!sUserManager.exists(userId)) 8210 return null; 8211 mFlags = flags; 8212 return super.queryIntent(intent, resolvedType, 8213 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8214 } 8215 8216 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8217 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8218 if (!sUserManager.exists(userId)) 8219 return null; 8220 if (packageProviders == null) { 8221 return null; 8222 } 8223 mFlags = flags; 8224 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8225 final int N = packageProviders.size(); 8226 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8227 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8228 8229 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8230 for (int i = 0; i < N; ++i) { 8231 intentFilters = packageProviders.get(i).intents; 8232 if (intentFilters != null && intentFilters.size() > 0) { 8233 PackageParser.ProviderIntentInfo[] array = 8234 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8235 intentFilters.toArray(array); 8236 listCut.add(array); 8237 } 8238 } 8239 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8240 } 8241 8242 public final void addProvider(PackageParser.Provider p) { 8243 if (mProviders.containsKey(p.getComponentName())) { 8244 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8245 return; 8246 } 8247 8248 mProviders.put(p.getComponentName(), p); 8249 if (DEBUG_SHOW_INFO) { 8250 Log.v(TAG, " " 8251 + (p.info.nonLocalizedLabel != null 8252 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8253 Log.v(TAG, " Class=" + p.info.name); 8254 } 8255 final int NI = p.intents.size(); 8256 int j; 8257 for (j = 0; j < NI; j++) { 8258 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8259 if (DEBUG_SHOW_INFO) { 8260 Log.v(TAG, " IntentFilter:"); 8261 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8262 } 8263 if (!intent.debugCheck()) { 8264 Log.w(TAG, "==> For Provider " + p.info.name); 8265 } 8266 addFilter(intent); 8267 } 8268 } 8269 8270 public final void removeProvider(PackageParser.Provider p) { 8271 mProviders.remove(p.getComponentName()); 8272 if (DEBUG_SHOW_INFO) { 8273 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8274 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8275 Log.v(TAG, " Class=" + p.info.name); 8276 } 8277 final int NI = p.intents.size(); 8278 int j; 8279 for (j = 0; j < NI; j++) { 8280 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8281 if (DEBUG_SHOW_INFO) { 8282 Log.v(TAG, " IntentFilter:"); 8283 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8284 } 8285 removeFilter(intent); 8286 } 8287 } 8288 8289 @Override 8290 protected boolean allowFilterResult( 8291 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8292 ProviderInfo filterPi = filter.provider.info; 8293 for (int i = dest.size() - 1; i >= 0; i--) { 8294 ProviderInfo destPi = dest.get(i).providerInfo; 8295 if (destPi.name == filterPi.name 8296 && destPi.packageName == filterPi.packageName) { 8297 return false; 8298 } 8299 } 8300 return true; 8301 } 8302 8303 @Override 8304 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8305 return new PackageParser.ProviderIntentInfo[size]; 8306 } 8307 8308 @Override 8309 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8310 if (!sUserManager.exists(userId)) 8311 return true; 8312 PackageParser.Package p = filter.provider.owner; 8313 if (p != null) { 8314 PackageSetting ps = (PackageSetting) p.mExtras; 8315 if (ps != null) { 8316 // System apps are never considered stopped for purposes of 8317 // filtering, because there may be no way for the user to 8318 // actually re-launch them. 8319 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8320 && ps.getStopped(userId); 8321 } 8322 } 8323 return false; 8324 } 8325 8326 @Override 8327 protected boolean isPackageForFilter(String packageName, 8328 PackageParser.ProviderIntentInfo info) { 8329 return packageName.equals(info.provider.owner.packageName); 8330 } 8331 8332 @Override 8333 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8334 int match, int userId) { 8335 if (!sUserManager.exists(userId)) 8336 return null; 8337 final PackageParser.ProviderIntentInfo info = filter; 8338 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8339 return null; 8340 } 8341 final PackageParser.Provider provider = info.provider; 8342 if (mSafeMode && (provider.info.applicationInfo.flags 8343 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8344 return null; 8345 } 8346 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8347 if (ps == null) { 8348 return null; 8349 } 8350 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8351 ps.readUserState(userId), userId); 8352 if (pi == null) { 8353 return null; 8354 } 8355 final ResolveInfo res = new ResolveInfo(); 8356 res.providerInfo = pi; 8357 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8358 res.filter = filter; 8359 } 8360 res.priority = info.getPriority(); 8361 res.preferredOrder = provider.owner.mPreferredOrder; 8362 res.match = match; 8363 res.isDefault = info.hasDefault; 8364 res.labelRes = info.labelRes; 8365 res.nonLocalizedLabel = info.nonLocalizedLabel; 8366 res.icon = info.icon; 8367 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8368 return res; 8369 } 8370 8371 @Override 8372 protected void sortResults(List<ResolveInfo> results) { 8373 Collections.sort(results, mResolvePrioritySorter); 8374 } 8375 8376 @Override 8377 protected void dumpFilter(PrintWriter out, String prefix, 8378 PackageParser.ProviderIntentInfo filter) { 8379 out.print(prefix); 8380 out.print( 8381 Integer.toHexString(System.identityHashCode(filter.provider))); 8382 out.print(' '); 8383 filter.provider.printComponentShortName(out); 8384 out.print(" filter "); 8385 out.println(Integer.toHexString(System.identityHashCode(filter))); 8386 } 8387 8388 @Override 8389 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8390 return filter.provider; 8391 } 8392 8393 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8394 PackageParser.Provider provider = (PackageParser.Provider)label; 8395 out.print(prefix); out.print( 8396 Integer.toHexString(System.identityHashCode(provider))); 8397 out.print(' '); 8398 provider.printComponentShortName(out); 8399 if (count > 1) { 8400 out.print(" ("); out.print(count); out.print(" filters)"); 8401 } 8402 out.println(); 8403 } 8404 8405 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8406 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8407 private int mFlags; 8408 }; 8409 8410 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8411 new Comparator<ResolveInfo>() { 8412 public int compare(ResolveInfo r1, ResolveInfo r2) { 8413 int v1 = r1.priority; 8414 int v2 = r2.priority; 8415 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8416 if (v1 != v2) { 8417 return (v1 > v2) ? -1 : 1; 8418 } 8419 v1 = r1.preferredOrder; 8420 v2 = r2.preferredOrder; 8421 if (v1 != v2) { 8422 return (v1 > v2) ? -1 : 1; 8423 } 8424 if (r1.isDefault != r2.isDefault) { 8425 return r1.isDefault ? -1 : 1; 8426 } 8427 v1 = r1.match; 8428 v2 = r2.match; 8429 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8430 if (v1 != v2) { 8431 return (v1 > v2) ? -1 : 1; 8432 } 8433 if (r1.system != r2.system) { 8434 return r1.system ? -1 : 1; 8435 } 8436 return 0; 8437 } 8438 }; 8439 8440 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8441 new Comparator<ProviderInfo>() { 8442 public int compare(ProviderInfo p1, ProviderInfo p2) { 8443 final int v1 = p1.initOrder; 8444 final int v2 = p2.initOrder; 8445 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8446 } 8447 }; 8448 8449 static final void sendPackageBroadcast(String action, String pkg, 8450 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8451 int[] userIds) { 8452 IActivityManager am = ActivityManagerNative.getDefault(); 8453 if (am != null) { 8454 try { 8455 if (userIds == null) { 8456 userIds = am.getRunningUserIds(); 8457 } 8458 for (int id : userIds) { 8459 final Intent intent = new Intent(action, 8460 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8461 if (extras != null) { 8462 intent.putExtras(extras); 8463 } 8464 if (targetPkg != null) { 8465 intent.setPackage(targetPkg); 8466 } 8467 // Modify the UID when posting to other users 8468 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8469 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8470 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8471 intent.putExtra(Intent.EXTRA_UID, uid); 8472 } 8473 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8475 if (DEBUG_BROADCASTS) { 8476 RuntimeException here = new RuntimeException("here"); 8477 here.fillInStackTrace(); 8478 Slog.d(TAG, "Sending to user " + id + ": " 8479 + intent.toShortString(false, true, false, false) 8480 + " " + intent.getExtras(), here); 8481 } 8482 am.broadcastIntent(null, intent, null, finishedReceiver, 8483 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8484 finishedReceiver != null, false, id); 8485 } 8486 } catch (RemoteException ex) { 8487 } 8488 } 8489 } 8490 8491 /** 8492 * Check if the external storage media is available. This is true if there 8493 * is a mounted external storage medium or if the external storage is 8494 * emulated. 8495 */ 8496 private boolean isExternalMediaAvailable() { 8497 return mMediaMounted || Environment.isExternalStorageEmulated(); 8498 } 8499 8500 @Override 8501 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8502 // writer 8503 synchronized (mPackages) { 8504 if (!isExternalMediaAvailable()) { 8505 // If the external storage is no longer mounted at this point, 8506 // the caller may not have been able to delete all of this 8507 // packages files and can not delete any more. Bail. 8508 return null; 8509 } 8510 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8511 if (lastPackage != null) { 8512 pkgs.remove(lastPackage); 8513 } 8514 if (pkgs.size() > 0) { 8515 return pkgs.get(0); 8516 } 8517 } 8518 return null; 8519 } 8520 8521 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8522 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8523 userId, andCode ? 1 : 0, packageName); 8524 if (mSystemReady) { 8525 msg.sendToTarget(); 8526 } else { 8527 if (mPostSystemReadyMessages == null) { 8528 mPostSystemReadyMessages = new ArrayList<>(); 8529 } 8530 mPostSystemReadyMessages.add(msg); 8531 } 8532 } 8533 8534 void startCleaningPackages() { 8535 // reader 8536 synchronized (mPackages) { 8537 if (!isExternalMediaAvailable()) { 8538 return; 8539 } 8540 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8541 return; 8542 } 8543 } 8544 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8545 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8546 IActivityManager am = ActivityManagerNative.getDefault(); 8547 if (am != null) { 8548 try { 8549 am.startService(null, intent, null, UserHandle.USER_OWNER); 8550 } catch (RemoteException e) { 8551 } 8552 } 8553 } 8554 8555 @Override 8556 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8557 int installFlags, String installerPackageName, VerificationParams verificationParams, 8558 String packageAbiOverride) { 8559 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8560 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8561 } 8562 8563 @Override 8564 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8565 int installFlags, String installerPackageName, VerificationParams verificationParams, 8566 String packageAbiOverride, int userId) { 8567 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8568 8569 final int callingUid = Binder.getCallingUid(); 8570 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8571 8572 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8573 try { 8574 if (observer != null) { 8575 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8576 } 8577 } catch (RemoteException re) { 8578 } 8579 return; 8580 } 8581 8582 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8583 installFlags |= PackageManager.INSTALL_FROM_ADB; 8584 8585 } else { 8586 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8587 // about installerPackageName. 8588 8589 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8590 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8591 } 8592 8593 UserHandle user; 8594 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8595 user = UserHandle.ALL; 8596 } else { 8597 user = new UserHandle(userId); 8598 } 8599 8600 verificationParams.setInstallerUid(callingUid); 8601 8602 final File originFile = new File(originPath); 8603 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8604 8605 final Message msg = mHandler.obtainMessage(INIT_COPY); 8606 msg.obj = new InstallParams(origin, observer, installFlags, 8607 installerPackageName, null, verificationParams, user, packageAbiOverride); 8608 mHandler.sendMessage(msg); 8609 } 8610 8611 void installStage(String packageName, File stagedDir, String stagedCid, 8612 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8613 String installerPackageName, int installerUid, UserHandle user) { 8614 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8615 params.referrerUri, installerUid, null); 8616 8617 final OriginInfo origin; 8618 if (stagedDir != null) { 8619 origin = OriginInfo.fromStagedFile(stagedDir); 8620 } else { 8621 origin = OriginInfo.fromStagedContainer(stagedCid); 8622 } 8623 8624 final Message msg = mHandler.obtainMessage(INIT_COPY); 8625 msg.obj = new InstallParams(origin, observer, params.installFlags, 8626 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8627 mHandler.sendMessage(msg); 8628 } 8629 8630 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8631 Bundle extras = new Bundle(1); 8632 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8633 8634 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8635 packageName, extras, null, null, new int[] {userId}); 8636 try { 8637 IActivityManager am = ActivityManagerNative.getDefault(); 8638 final boolean isSystem = 8639 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8640 if (isSystem && am.isUserRunning(userId, false)) { 8641 // The just-installed/enabled app is bundled on the system, so presumed 8642 // to be able to run automatically without needing an explicit launch. 8643 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8644 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8645 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8646 .setPackage(packageName); 8647 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8648 android.app.AppOpsManager.OP_NONE, false, false, userId); 8649 } 8650 } catch (RemoteException e) { 8651 // shouldn't happen 8652 Slog.w(TAG, "Unable to bootstrap installed package", e); 8653 } 8654 } 8655 8656 @Override 8657 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8658 int userId) { 8659 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8660 PackageSetting pkgSetting; 8661 final int uid = Binder.getCallingUid(); 8662 enforceCrossUserPermission(uid, userId, true, true, 8663 "setApplicationHiddenSetting for user " + userId); 8664 8665 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8666 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8667 return false; 8668 } 8669 8670 long callingId = Binder.clearCallingIdentity(); 8671 try { 8672 boolean sendAdded = false; 8673 boolean sendRemoved = false; 8674 // writer 8675 synchronized (mPackages) { 8676 pkgSetting = mSettings.mPackages.get(packageName); 8677 if (pkgSetting == null) { 8678 return false; 8679 } 8680 if (pkgSetting.getHidden(userId) != hidden) { 8681 pkgSetting.setHidden(hidden, userId); 8682 mSettings.writePackageRestrictionsLPr(userId); 8683 if (hidden) { 8684 sendRemoved = true; 8685 } else { 8686 sendAdded = true; 8687 } 8688 } 8689 } 8690 if (sendAdded) { 8691 sendPackageAddedForUser(packageName, pkgSetting, userId); 8692 return true; 8693 } 8694 if (sendRemoved) { 8695 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8696 "hiding pkg"); 8697 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8698 } 8699 } finally { 8700 Binder.restoreCallingIdentity(callingId); 8701 } 8702 return false; 8703 } 8704 8705 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8706 int userId) { 8707 final PackageRemovedInfo info = new PackageRemovedInfo(); 8708 info.removedPackage = packageName; 8709 info.removedUsers = new int[] {userId}; 8710 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8711 info.sendBroadcast(false, false, false); 8712 } 8713 8714 /** 8715 * Returns true if application is not found or there was an error. Otherwise it returns 8716 * the hidden state of the package for the given user. 8717 */ 8718 @Override 8719 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8720 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8721 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8722 false, "getApplicationHidden for user " + userId); 8723 PackageSetting pkgSetting; 8724 long callingId = Binder.clearCallingIdentity(); 8725 try { 8726 // writer 8727 synchronized (mPackages) { 8728 pkgSetting = mSettings.mPackages.get(packageName); 8729 if (pkgSetting == null) { 8730 return true; 8731 } 8732 return pkgSetting.getHidden(userId); 8733 } 8734 } finally { 8735 Binder.restoreCallingIdentity(callingId); 8736 } 8737 } 8738 8739 /** 8740 * @hide 8741 */ 8742 @Override 8743 public int installExistingPackageAsUser(String packageName, int userId) { 8744 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8745 null); 8746 PackageSetting pkgSetting; 8747 final int uid = Binder.getCallingUid(); 8748 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8749 + userId); 8750 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8751 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8752 } 8753 8754 long callingId = Binder.clearCallingIdentity(); 8755 try { 8756 boolean sendAdded = false; 8757 Bundle extras = new Bundle(1); 8758 8759 // writer 8760 synchronized (mPackages) { 8761 pkgSetting = mSettings.mPackages.get(packageName); 8762 if (pkgSetting == null) { 8763 return PackageManager.INSTALL_FAILED_INVALID_URI; 8764 } 8765 if (!pkgSetting.getInstalled(userId)) { 8766 pkgSetting.setInstalled(true, userId); 8767 pkgSetting.setHidden(false, userId); 8768 mSettings.writePackageRestrictionsLPr(userId); 8769 sendAdded = true; 8770 } 8771 } 8772 8773 if (sendAdded) { 8774 sendPackageAddedForUser(packageName, pkgSetting, userId); 8775 } 8776 } finally { 8777 Binder.restoreCallingIdentity(callingId); 8778 } 8779 8780 return PackageManager.INSTALL_SUCCEEDED; 8781 } 8782 8783 boolean isUserRestricted(int userId, String restrictionKey) { 8784 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8785 if (restrictions.getBoolean(restrictionKey, false)) { 8786 Log.w(TAG, "User is restricted: " + restrictionKey); 8787 return true; 8788 } 8789 return false; 8790 } 8791 8792 @Override 8793 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8794 mContext.enforceCallingOrSelfPermission( 8795 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8796 "Only package verification agents can verify applications"); 8797 8798 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8799 final PackageVerificationResponse response = new PackageVerificationResponse( 8800 verificationCode, Binder.getCallingUid()); 8801 msg.arg1 = id; 8802 msg.obj = response; 8803 mHandler.sendMessage(msg); 8804 } 8805 8806 @Override 8807 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8808 long millisecondsToDelay) { 8809 mContext.enforceCallingOrSelfPermission( 8810 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8811 "Only package verification agents can extend verification timeouts"); 8812 8813 final PackageVerificationState state = mPendingVerification.get(id); 8814 final PackageVerificationResponse response = new PackageVerificationResponse( 8815 verificationCodeAtTimeout, Binder.getCallingUid()); 8816 8817 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8818 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8819 } 8820 if (millisecondsToDelay < 0) { 8821 millisecondsToDelay = 0; 8822 } 8823 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8824 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8825 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8826 } 8827 8828 if ((state != null) && !state.timeoutExtended()) { 8829 state.extendTimeout(); 8830 8831 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8832 msg.arg1 = id; 8833 msg.obj = response; 8834 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8835 } 8836 } 8837 8838 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8839 int verificationCode, UserHandle user) { 8840 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8841 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8842 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8843 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8844 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8845 8846 mContext.sendBroadcastAsUser(intent, user, 8847 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8848 } 8849 8850 private ComponentName matchComponentForVerifier(String packageName, 8851 List<ResolveInfo> receivers) { 8852 ActivityInfo targetReceiver = null; 8853 8854 final int NR = receivers.size(); 8855 for (int i = 0; i < NR; i++) { 8856 final ResolveInfo info = receivers.get(i); 8857 if (info.activityInfo == null) { 8858 continue; 8859 } 8860 8861 if (packageName.equals(info.activityInfo.packageName)) { 8862 targetReceiver = info.activityInfo; 8863 break; 8864 } 8865 } 8866 8867 if (targetReceiver == null) { 8868 return null; 8869 } 8870 8871 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8872 } 8873 8874 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8875 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8876 if (pkgInfo.verifiers.length == 0) { 8877 return null; 8878 } 8879 8880 final int N = pkgInfo.verifiers.length; 8881 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8882 for (int i = 0; i < N; i++) { 8883 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8884 8885 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8886 receivers); 8887 if (comp == null) { 8888 continue; 8889 } 8890 8891 final int verifierUid = getUidForVerifier(verifierInfo); 8892 if (verifierUid == -1) { 8893 continue; 8894 } 8895 8896 if (DEBUG_VERIFY) { 8897 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8898 + " with the correct signature"); 8899 } 8900 sufficientVerifiers.add(comp); 8901 verificationState.addSufficientVerifier(verifierUid); 8902 } 8903 8904 return sufficientVerifiers; 8905 } 8906 8907 private int getUidForVerifier(VerifierInfo verifierInfo) { 8908 synchronized (mPackages) { 8909 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8910 if (pkg == null) { 8911 return -1; 8912 } else if (pkg.mSignatures.length != 1) { 8913 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8914 + " has more than one signature; ignoring"); 8915 return -1; 8916 } 8917 8918 /* 8919 * If the public key of the package's signature does not match 8920 * our expected public key, then this is a different package and 8921 * we should skip. 8922 */ 8923 8924 final byte[] expectedPublicKey; 8925 try { 8926 final Signature verifierSig = pkg.mSignatures[0]; 8927 final PublicKey publicKey = verifierSig.getPublicKey(); 8928 expectedPublicKey = publicKey.getEncoded(); 8929 } catch (CertificateException e) { 8930 return -1; 8931 } 8932 8933 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8934 8935 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8936 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8937 + " does not have the expected public key; ignoring"); 8938 return -1; 8939 } 8940 8941 return pkg.applicationInfo.uid; 8942 } 8943 } 8944 8945 @Override 8946 public void finishPackageInstall(int token) { 8947 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8948 8949 if (DEBUG_INSTALL) { 8950 Slog.v(TAG, "BM finishing package install for " + token); 8951 } 8952 8953 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8954 mHandler.sendMessage(msg); 8955 } 8956 8957 /** 8958 * Get the verification agent timeout. 8959 * 8960 * @return verification timeout in milliseconds 8961 */ 8962 private long getVerificationTimeout() { 8963 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8964 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8965 DEFAULT_VERIFICATION_TIMEOUT); 8966 } 8967 8968 /** 8969 * Get the default verification agent response code. 8970 * 8971 * @return default verification response code 8972 */ 8973 private int getDefaultVerificationResponse() { 8974 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8975 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8976 DEFAULT_VERIFICATION_RESPONSE); 8977 } 8978 8979 /** 8980 * Check whether or not package verification has been enabled. 8981 * 8982 * @return true if verification should be performed 8983 */ 8984 private boolean isVerificationEnabled(int userId, int installFlags) { 8985 if (!DEFAULT_VERIFY_ENABLE) { 8986 return false; 8987 } 8988 8989 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8990 8991 // Check if installing from ADB 8992 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8993 // Do not run verification in a test harness environment 8994 if (ActivityManager.isRunningInTestHarness()) { 8995 return false; 8996 } 8997 if (ensureVerifyAppsEnabled) { 8998 return true; 8999 } 9000 // Check if the developer does not want package verification for ADB installs 9001 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9002 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9003 return false; 9004 } 9005 } 9006 9007 if (ensureVerifyAppsEnabled) { 9008 return true; 9009 } 9010 9011 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9012 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9013 } 9014 9015 @Override 9016 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9017 throws RemoteException { 9018 mContext.enforceCallingOrSelfPermission( 9019 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9020 "Only intentfilter verification agents can verify applications"); 9021 9022 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9023 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9024 Binder.getCallingUid(), verificationCode, failedDomains); 9025 msg.arg1 = id; 9026 msg.obj = response; 9027 mHandler.sendMessage(msg); 9028 } 9029 9030 @Override 9031 public int getIntentVerificationStatus(String packageName, int userId) { 9032 synchronized (mPackages) { 9033 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9034 } 9035 } 9036 9037 @Override 9038 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9039 boolean result = false; 9040 synchronized (mPackages) { 9041 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9042 } 9043 scheduleWritePackageRestrictionsLocked(userId); 9044 return result; 9045 } 9046 9047 @Override 9048 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9049 synchronized (mPackages) { 9050 return mSettings.getIntentFilterVerificationsLPr(packageName); 9051 } 9052 } 9053 9054 @Override 9055 public List<IntentFilter> getAllIntentFilters(String packageName) { 9056 if (TextUtils.isEmpty(packageName)) { 9057 return Collections.<IntentFilter>emptyList(); 9058 } 9059 synchronized (mPackages) { 9060 PackageParser.Package pkg = mPackages.get(packageName); 9061 if (pkg == null || pkg.activities == null) { 9062 return Collections.<IntentFilter>emptyList(); 9063 } 9064 final int count = pkg.activities.size(); 9065 ArrayList<IntentFilter> result = new ArrayList<>(); 9066 for (int n=0; n<count; n++) { 9067 PackageParser.Activity activity = pkg.activities.get(n); 9068 if (activity.intents != null || activity.intents.size() > 0) { 9069 result.addAll(activity.intents); 9070 } 9071 } 9072 return result; 9073 } 9074 } 9075 9076 /** 9077 * Get the "allow unknown sources" setting. 9078 * 9079 * @return the current "allow unknown sources" setting 9080 */ 9081 private int getUnknownSourcesSettings() { 9082 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9083 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9084 -1); 9085 } 9086 9087 @Override 9088 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9089 final int uid = Binder.getCallingUid(); 9090 // writer 9091 synchronized (mPackages) { 9092 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9093 if (targetPackageSetting == null) { 9094 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9095 } 9096 9097 PackageSetting installerPackageSetting; 9098 if (installerPackageName != null) { 9099 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9100 if (installerPackageSetting == null) { 9101 throw new IllegalArgumentException("Unknown installer package: " 9102 + installerPackageName); 9103 } 9104 } else { 9105 installerPackageSetting = null; 9106 } 9107 9108 Signature[] callerSignature; 9109 Object obj = mSettings.getUserIdLPr(uid); 9110 if (obj != null) { 9111 if (obj instanceof SharedUserSetting) { 9112 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9113 } else if (obj instanceof PackageSetting) { 9114 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9115 } else { 9116 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9117 } 9118 } else { 9119 throw new SecurityException("Unknown calling uid " + uid); 9120 } 9121 9122 // Verify: can't set installerPackageName to a package that is 9123 // not signed with the same cert as the caller. 9124 if (installerPackageSetting != null) { 9125 if (compareSignatures(callerSignature, 9126 installerPackageSetting.signatures.mSignatures) 9127 != PackageManager.SIGNATURE_MATCH) { 9128 throw new SecurityException( 9129 "Caller does not have same cert as new installer package " 9130 + installerPackageName); 9131 } 9132 } 9133 9134 // Verify: if target already has an installer package, it must 9135 // be signed with the same cert as the caller. 9136 if (targetPackageSetting.installerPackageName != null) { 9137 PackageSetting setting = mSettings.mPackages.get( 9138 targetPackageSetting.installerPackageName); 9139 // If the currently set package isn't valid, then it's always 9140 // okay to change it. 9141 if (setting != null) { 9142 if (compareSignatures(callerSignature, 9143 setting.signatures.mSignatures) 9144 != PackageManager.SIGNATURE_MATCH) { 9145 throw new SecurityException( 9146 "Caller does not have same cert as old installer package " 9147 + targetPackageSetting.installerPackageName); 9148 } 9149 } 9150 } 9151 9152 // Okay! 9153 targetPackageSetting.installerPackageName = installerPackageName; 9154 scheduleWriteSettingsLocked(); 9155 } 9156 } 9157 9158 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9159 // Queue up an async operation since the package installation may take a little while. 9160 mHandler.post(new Runnable() { 9161 public void run() { 9162 mHandler.removeCallbacks(this); 9163 // Result object to be returned 9164 PackageInstalledInfo res = new PackageInstalledInfo(); 9165 res.returnCode = currentStatus; 9166 res.uid = -1; 9167 res.pkg = null; 9168 res.removedInfo = new PackageRemovedInfo(); 9169 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9170 args.doPreInstall(res.returnCode); 9171 synchronized (mInstallLock) { 9172 installPackageLI(args, res); 9173 } 9174 args.doPostInstall(res.returnCode, res.uid); 9175 } 9176 9177 // A restore should be performed at this point if (a) the install 9178 // succeeded, (b) the operation is not an update, and (c) the new 9179 // package has not opted out of backup participation. 9180 final boolean update = res.removedInfo.removedPackage != null; 9181 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9182 boolean doRestore = !update 9183 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9184 9185 // Set up the post-install work request bookkeeping. This will be used 9186 // and cleaned up by the post-install event handling regardless of whether 9187 // there's a restore pass performed. Token values are >= 1. 9188 int token; 9189 if (mNextInstallToken < 0) mNextInstallToken = 1; 9190 token = mNextInstallToken++; 9191 9192 PostInstallData data = new PostInstallData(args, res); 9193 mRunningInstalls.put(token, data); 9194 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9195 9196 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9197 // Pass responsibility to the Backup Manager. It will perform a 9198 // restore if appropriate, then pass responsibility back to the 9199 // Package Manager to run the post-install observer callbacks 9200 // and broadcasts. 9201 IBackupManager bm = IBackupManager.Stub.asInterface( 9202 ServiceManager.getService(Context.BACKUP_SERVICE)); 9203 if (bm != null) { 9204 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9205 + " to BM for possible restore"); 9206 try { 9207 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9208 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9209 } else { 9210 doRestore = false; 9211 } 9212 } catch (RemoteException e) { 9213 // can't happen; the backup manager is local 9214 } catch (Exception e) { 9215 Slog.e(TAG, "Exception trying to enqueue restore", e); 9216 doRestore = false; 9217 } 9218 } else { 9219 Slog.e(TAG, "Backup Manager not found!"); 9220 doRestore = false; 9221 } 9222 } 9223 9224 if (!doRestore) { 9225 // No restore possible, or the Backup Manager was mysteriously not 9226 // available -- just fire the post-install work request directly. 9227 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9228 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9229 mHandler.sendMessage(msg); 9230 } 9231 } 9232 }); 9233 } 9234 9235 private abstract class HandlerParams { 9236 private static final int MAX_RETRIES = 4; 9237 9238 /** 9239 * Number of times startCopy() has been attempted and had a non-fatal 9240 * error. 9241 */ 9242 private int mRetries = 0; 9243 9244 /** User handle for the user requesting the information or installation. */ 9245 private final UserHandle mUser; 9246 9247 HandlerParams(UserHandle user) { 9248 mUser = user; 9249 } 9250 9251 UserHandle getUser() { 9252 return mUser; 9253 } 9254 9255 final boolean startCopy() { 9256 boolean res; 9257 try { 9258 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9259 9260 if (++mRetries > MAX_RETRIES) { 9261 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9262 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9263 handleServiceError(); 9264 return false; 9265 } else { 9266 handleStartCopy(); 9267 res = true; 9268 } 9269 } catch (RemoteException e) { 9270 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9271 mHandler.sendEmptyMessage(MCS_RECONNECT); 9272 res = false; 9273 } 9274 handleReturnCode(); 9275 return res; 9276 } 9277 9278 final void serviceError() { 9279 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9280 handleServiceError(); 9281 handleReturnCode(); 9282 } 9283 9284 abstract void handleStartCopy() throws RemoteException; 9285 abstract void handleServiceError(); 9286 abstract void handleReturnCode(); 9287 } 9288 9289 class MeasureParams extends HandlerParams { 9290 private final PackageStats mStats; 9291 private boolean mSuccess; 9292 9293 private final IPackageStatsObserver mObserver; 9294 9295 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9296 super(new UserHandle(stats.userHandle)); 9297 mObserver = observer; 9298 mStats = stats; 9299 } 9300 9301 @Override 9302 public String toString() { 9303 return "MeasureParams{" 9304 + Integer.toHexString(System.identityHashCode(this)) 9305 + " " + mStats.packageName + "}"; 9306 } 9307 9308 @Override 9309 void handleStartCopy() throws RemoteException { 9310 synchronized (mInstallLock) { 9311 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9312 } 9313 9314 if (mSuccess) { 9315 final boolean mounted; 9316 if (Environment.isExternalStorageEmulated()) { 9317 mounted = true; 9318 } else { 9319 final String status = Environment.getExternalStorageState(); 9320 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9321 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9322 } 9323 9324 if (mounted) { 9325 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9326 9327 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9328 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9329 9330 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9331 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9332 9333 // Always subtract cache size, since it's a subdirectory 9334 mStats.externalDataSize -= mStats.externalCacheSize; 9335 9336 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9337 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9338 9339 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9340 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9341 } 9342 } 9343 } 9344 9345 @Override 9346 void handleReturnCode() { 9347 if (mObserver != null) { 9348 try { 9349 mObserver.onGetStatsCompleted(mStats, mSuccess); 9350 } catch (RemoteException e) { 9351 Slog.i(TAG, "Observer no longer exists."); 9352 } 9353 } 9354 } 9355 9356 @Override 9357 void handleServiceError() { 9358 Slog.e(TAG, "Could not measure application " + mStats.packageName 9359 + " external storage"); 9360 } 9361 } 9362 9363 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9364 throws RemoteException { 9365 long result = 0; 9366 for (File path : paths) { 9367 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9368 } 9369 return result; 9370 } 9371 9372 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9373 for (File path : paths) { 9374 try { 9375 mcs.clearDirectory(path.getAbsolutePath()); 9376 } catch (RemoteException e) { 9377 } 9378 } 9379 } 9380 9381 static class OriginInfo { 9382 /** 9383 * Location where install is coming from, before it has been 9384 * copied/renamed into place. This could be a single monolithic APK 9385 * file, or a cluster directory. This location may be untrusted. 9386 */ 9387 final File file; 9388 final String cid; 9389 9390 /** 9391 * Flag indicating that {@link #file} or {@link #cid} has already been 9392 * staged, meaning downstream users don't need to defensively copy the 9393 * contents. 9394 */ 9395 final boolean staged; 9396 9397 /** 9398 * Flag indicating that {@link #file} or {@link #cid} is an already 9399 * installed app that is being moved. 9400 */ 9401 final boolean existing; 9402 9403 final String resolvedPath; 9404 final File resolvedFile; 9405 9406 static OriginInfo fromNothing() { 9407 return new OriginInfo(null, null, false, false); 9408 } 9409 9410 static OriginInfo fromUntrustedFile(File file) { 9411 return new OriginInfo(file, null, false, false); 9412 } 9413 9414 static OriginInfo fromExistingFile(File file) { 9415 return new OriginInfo(file, null, false, true); 9416 } 9417 9418 static OriginInfo fromStagedFile(File file) { 9419 return new OriginInfo(file, null, true, false); 9420 } 9421 9422 static OriginInfo fromStagedContainer(String cid) { 9423 return new OriginInfo(null, cid, true, false); 9424 } 9425 9426 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9427 this.file = file; 9428 this.cid = cid; 9429 this.staged = staged; 9430 this.existing = existing; 9431 9432 if (cid != null) { 9433 resolvedPath = PackageHelper.getSdDir(cid); 9434 resolvedFile = new File(resolvedPath); 9435 } else if (file != null) { 9436 resolvedPath = file.getAbsolutePath(); 9437 resolvedFile = file; 9438 } else { 9439 resolvedPath = null; 9440 resolvedFile = null; 9441 } 9442 } 9443 } 9444 9445 class InstallParams extends HandlerParams { 9446 final OriginInfo origin; 9447 final IPackageInstallObserver2 observer; 9448 int installFlags; 9449 final String installerPackageName; 9450 final String volumeUuid; 9451 final VerificationParams verificationParams; 9452 private InstallArgs mArgs; 9453 private int mRet; 9454 final String packageAbiOverride; 9455 9456 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9457 String installerPackageName, String volumeUuid, 9458 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9459 super(user); 9460 this.origin = origin; 9461 this.observer = observer; 9462 this.installFlags = installFlags; 9463 this.installerPackageName = installerPackageName; 9464 this.volumeUuid = volumeUuid; 9465 this.verificationParams = verificationParams; 9466 this.packageAbiOverride = packageAbiOverride; 9467 } 9468 9469 @Override 9470 public String toString() { 9471 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9472 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9473 } 9474 9475 public ManifestDigest getManifestDigest() { 9476 if (verificationParams == null) { 9477 return null; 9478 } 9479 return verificationParams.getManifestDigest(); 9480 } 9481 9482 private int installLocationPolicy(PackageInfoLite pkgLite) { 9483 String packageName = pkgLite.packageName; 9484 int installLocation = pkgLite.installLocation; 9485 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9486 // reader 9487 synchronized (mPackages) { 9488 PackageParser.Package pkg = mPackages.get(packageName); 9489 if (pkg != null) { 9490 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9491 // Check for downgrading. 9492 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9493 try { 9494 checkDowngrade(pkg, pkgLite); 9495 } catch (PackageManagerException e) { 9496 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9497 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9498 } 9499 } 9500 // Check for updated system application. 9501 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9502 if (onSd) { 9503 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9504 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9505 } 9506 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9507 } else { 9508 if (onSd) { 9509 // Install flag overrides everything. 9510 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9511 } 9512 // If current upgrade specifies particular preference 9513 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9514 // Application explicitly specified internal. 9515 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9516 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9517 // App explictly prefers external. Let policy decide 9518 } else { 9519 // Prefer previous location 9520 if (isExternal(pkg)) { 9521 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9522 } 9523 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9524 } 9525 } 9526 } else { 9527 // Invalid install. Return error code 9528 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9529 } 9530 } 9531 } 9532 // All the special cases have been taken care of. 9533 // Return result based on recommended install location. 9534 if (onSd) { 9535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9536 } 9537 return pkgLite.recommendedInstallLocation; 9538 } 9539 9540 /* 9541 * Invoke remote method to get package information and install 9542 * location values. Override install location based on default 9543 * policy if needed and then create install arguments based 9544 * on the install location. 9545 */ 9546 public void handleStartCopy() throws RemoteException { 9547 int ret = PackageManager.INSTALL_SUCCEEDED; 9548 9549 // If we're already staged, we've firmly committed to an install location 9550 if (origin.staged) { 9551 if (origin.file != null) { 9552 installFlags |= PackageManager.INSTALL_INTERNAL; 9553 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9554 } else if (origin.cid != null) { 9555 installFlags |= PackageManager.INSTALL_EXTERNAL; 9556 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9557 } else { 9558 throw new IllegalStateException("Invalid stage location"); 9559 } 9560 } 9561 9562 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9563 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9564 9565 PackageInfoLite pkgLite = null; 9566 9567 if (onInt && onSd) { 9568 // Check if both bits are set. 9569 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9570 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9571 } else { 9572 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9573 packageAbiOverride); 9574 9575 /* 9576 * If we have too little free space, try to free cache 9577 * before giving up. 9578 */ 9579 if (!origin.staged && pkgLite.recommendedInstallLocation 9580 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9581 // TODO: focus freeing disk space on the target device 9582 final StorageManager storage = StorageManager.from(mContext); 9583 final long lowThreshold = storage.getStorageLowBytes( 9584 Environment.getDataDirectory()); 9585 9586 final long sizeBytes = mContainerService.calculateInstalledSize( 9587 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9588 9589 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9590 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9591 installFlags, packageAbiOverride); 9592 } 9593 9594 /* 9595 * The cache free must have deleted the file we 9596 * downloaded to install. 9597 * 9598 * TODO: fix the "freeCache" call to not delete 9599 * the file we care about. 9600 */ 9601 if (pkgLite.recommendedInstallLocation 9602 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9603 pkgLite.recommendedInstallLocation 9604 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9605 } 9606 } 9607 } 9608 9609 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9610 int loc = pkgLite.recommendedInstallLocation; 9611 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9612 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9613 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9614 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9615 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9616 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9617 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9618 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9620 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9621 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9622 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9623 } else { 9624 // Override with defaults if needed. 9625 loc = installLocationPolicy(pkgLite); 9626 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9627 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9628 } else if (!onSd && !onInt) { 9629 // Override install location with flags 9630 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9631 // Set the flag to install on external media. 9632 installFlags |= PackageManager.INSTALL_EXTERNAL; 9633 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9634 } else { 9635 // Make sure the flag for installing on external 9636 // media is unset 9637 installFlags |= PackageManager.INSTALL_INTERNAL; 9638 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9639 } 9640 } 9641 } 9642 } 9643 9644 final InstallArgs args = createInstallArgs(this); 9645 mArgs = args; 9646 9647 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9648 /* 9649 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9650 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9651 */ 9652 int userIdentifier = getUser().getIdentifier(); 9653 if (userIdentifier == UserHandle.USER_ALL 9654 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9655 userIdentifier = UserHandle.USER_OWNER; 9656 } 9657 9658 /* 9659 * Determine if we have any installed package verifiers. If we 9660 * do, then we'll defer to them to verify the packages. 9661 */ 9662 final int requiredUid = mRequiredVerifierPackage == null ? -1 9663 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9664 if (!origin.existing && requiredUid != -1 9665 && isVerificationEnabled(userIdentifier, installFlags)) { 9666 final Intent verification = new Intent( 9667 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9668 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9669 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9670 PACKAGE_MIME_TYPE); 9671 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9672 9673 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9674 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9675 0 /* TODO: Which userId? */); 9676 9677 if (DEBUG_VERIFY) { 9678 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9679 + verification.toString() + " with " + pkgLite.verifiers.length 9680 + " optional verifiers"); 9681 } 9682 9683 final int verificationId = mPendingVerificationToken++; 9684 9685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9686 9687 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9688 installerPackageName); 9689 9690 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9691 installFlags); 9692 9693 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9694 pkgLite.packageName); 9695 9696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9697 pkgLite.versionCode); 9698 9699 if (verificationParams != null) { 9700 if (verificationParams.getVerificationURI() != null) { 9701 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9702 verificationParams.getVerificationURI()); 9703 } 9704 if (verificationParams.getOriginatingURI() != null) { 9705 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9706 verificationParams.getOriginatingURI()); 9707 } 9708 if (verificationParams.getReferrer() != null) { 9709 verification.putExtra(Intent.EXTRA_REFERRER, 9710 verificationParams.getReferrer()); 9711 } 9712 if (verificationParams.getOriginatingUid() >= 0) { 9713 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9714 verificationParams.getOriginatingUid()); 9715 } 9716 if (verificationParams.getInstallerUid() >= 0) { 9717 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9718 verificationParams.getInstallerUid()); 9719 } 9720 } 9721 9722 final PackageVerificationState verificationState = new PackageVerificationState( 9723 requiredUid, args); 9724 9725 mPendingVerification.append(verificationId, verificationState); 9726 9727 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9728 receivers, verificationState); 9729 9730 /* 9731 * If any sufficient verifiers were listed in the package 9732 * manifest, attempt to ask them. 9733 */ 9734 if (sufficientVerifiers != null) { 9735 final int N = sufficientVerifiers.size(); 9736 if (N == 0) { 9737 Slog.i(TAG, "Additional verifiers required, but none installed."); 9738 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9739 } else { 9740 for (int i = 0; i < N; i++) { 9741 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9742 9743 final Intent sufficientIntent = new Intent(verification); 9744 sufficientIntent.setComponent(verifierComponent); 9745 9746 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9747 } 9748 } 9749 } 9750 9751 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9752 mRequiredVerifierPackage, receivers); 9753 if (ret == PackageManager.INSTALL_SUCCEEDED 9754 && mRequiredVerifierPackage != null) { 9755 /* 9756 * Send the intent to the required verification agent, 9757 * but only start the verification timeout after the 9758 * target BroadcastReceivers have run. 9759 */ 9760 verification.setComponent(requiredVerifierComponent); 9761 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9762 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9763 new BroadcastReceiver() { 9764 @Override 9765 public void onReceive(Context context, Intent intent) { 9766 final Message msg = mHandler 9767 .obtainMessage(CHECK_PENDING_VERIFICATION); 9768 msg.arg1 = verificationId; 9769 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9770 } 9771 }, null, 0, null, null); 9772 9773 /* 9774 * We don't want the copy to proceed until verification 9775 * succeeds, so null out this field. 9776 */ 9777 mArgs = null; 9778 } 9779 } else { 9780 /* 9781 * No package verification is enabled, so immediately start 9782 * the remote call to initiate copy using temporary file. 9783 */ 9784 ret = args.copyApk(mContainerService, true); 9785 } 9786 } 9787 9788 mRet = ret; 9789 } 9790 9791 @Override 9792 void handleReturnCode() { 9793 // If mArgs is null, then MCS couldn't be reached. When it 9794 // reconnects, it will try again to install. At that point, this 9795 // will succeed. 9796 if (mArgs != null) { 9797 processPendingInstall(mArgs, mRet); 9798 } 9799 } 9800 9801 @Override 9802 void handleServiceError() { 9803 mArgs = createInstallArgs(this); 9804 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9805 } 9806 9807 public boolean isForwardLocked() { 9808 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9809 } 9810 } 9811 9812 /** 9813 * Used during creation of InstallArgs 9814 * 9815 * @param installFlags package installation flags 9816 * @return true if should be installed on external storage 9817 */ 9818 private static boolean installOnExternalAsec(int installFlags) { 9819 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9820 return false; 9821 } 9822 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9823 return true; 9824 } 9825 return false; 9826 } 9827 9828 /** 9829 * Used during creation of InstallArgs 9830 * 9831 * @param installFlags package installation flags 9832 * @return true if should be installed as forward locked 9833 */ 9834 private static boolean installForwardLocked(int installFlags) { 9835 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9836 } 9837 9838 private InstallArgs createInstallArgs(InstallParams params) { 9839 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9840 return new AsecInstallArgs(params); 9841 } else { 9842 return new FileInstallArgs(params); 9843 } 9844 } 9845 9846 /** 9847 * Create args that describe an existing installed package. Typically used 9848 * when cleaning up old installs, or used as a move source. 9849 */ 9850 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9851 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9852 final boolean isInAsec; 9853 if (installOnExternalAsec(installFlags)) { 9854 /* Apps on SD card are always in ASEC containers. */ 9855 isInAsec = true; 9856 } else if (installForwardLocked(installFlags) 9857 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9858 /* 9859 * Forward-locked apps are only in ASEC containers if they're the 9860 * new style 9861 */ 9862 isInAsec = true; 9863 } else { 9864 isInAsec = false; 9865 } 9866 9867 if (isInAsec) { 9868 return new AsecInstallArgs(codePath, instructionSets, 9869 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9870 } else { 9871 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9872 instructionSets); 9873 } 9874 } 9875 9876 static abstract class InstallArgs { 9877 /** @see InstallParams#origin */ 9878 final OriginInfo origin; 9879 9880 final IPackageInstallObserver2 observer; 9881 // Always refers to PackageManager flags only 9882 final int installFlags; 9883 final String installerPackageName; 9884 final String volumeUuid; 9885 final ManifestDigest manifestDigest; 9886 final UserHandle user; 9887 final String abiOverride; 9888 9889 // The list of instruction sets supported by this app. This is currently 9890 // only used during the rmdex() phase to clean up resources. We can get rid of this 9891 // if we move dex files under the common app path. 9892 /* nullable */ String[] instructionSets; 9893 9894 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9895 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9896 UserHandle user, String[] instructionSets, String abiOverride) { 9897 this.origin = origin; 9898 this.installFlags = installFlags; 9899 this.observer = observer; 9900 this.installerPackageName = installerPackageName; 9901 this.volumeUuid = volumeUuid; 9902 this.manifestDigest = manifestDigest; 9903 this.user = user; 9904 this.instructionSets = instructionSets; 9905 this.abiOverride = abiOverride; 9906 } 9907 9908 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9909 abstract int doPreInstall(int status); 9910 9911 /** 9912 * Rename package into final resting place. All paths on the given 9913 * scanned package should be updated to reflect the rename. 9914 */ 9915 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9916 abstract int doPostInstall(int status, int uid); 9917 9918 /** @see PackageSettingBase#codePathString */ 9919 abstract String getCodePath(); 9920 /** @see PackageSettingBase#resourcePathString */ 9921 abstract String getResourcePath(); 9922 abstract String getLegacyNativeLibraryPath(); 9923 9924 // Need installer lock especially for dex file removal. 9925 abstract void cleanUpResourcesLI(); 9926 abstract boolean doPostDeleteLI(boolean delete); 9927 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9928 9929 /** 9930 * Called before the source arguments are copied. This is used mostly 9931 * for MoveParams when it needs to read the source file to put it in the 9932 * destination. 9933 */ 9934 int doPreCopy() { 9935 return PackageManager.INSTALL_SUCCEEDED; 9936 } 9937 9938 /** 9939 * Called after the source arguments are copied. This is used mostly for 9940 * MoveParams when it needs to read the source file to put it in the 9941 * destination. 9942 * 9943 * @return 9944 */ 9945 int doPostCopy(int uid) { 9946 return PackageManager.INSTALL_SUCCEEDED; 9947 } 9948 9949 protected boolean isFwdLocked() { 9950 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9951 } 9952 9953 protected boolean isExternalAsec() { 9954 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9955 } 9956 9957 UserHandle getUser() { 9958 return user; 9959 } 9960 } 9961 9962 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9963 if (!allCodePaths.isEmpty()) { 9964 if (instructionSets == null) { 9965 throw new IllegalStateException("instructionSet == null"); 9966 } 9967 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9968 for (String codePath : allCodePaths) { 9969 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9970 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9971 if (retCode < 0) { 9972 Slog.w(TAG, "Couldn't remove dex file for package: " 9973 + " at location " + codePath + ", retcode=" + retCode); 9974 // we don't consider this to be a failure of the core package deletion 9975 } 9976 } 9977 } 9978 } 9979 } 9980 9981 /** 9982 * Logic to handle installation of non-ASEC applications, including copying 9983 * and renaming logic. 9984 */ 9985 class FileInstallArgs extends InstallArgs { 9986 private File codeFile; 9987 private File resourceFile; 9988 private File legacyNativeLibraryPath; 9989 9990 // Example topology: 9991 // /data/app/com.example/base.apk 9992 // /data/app/com.example/split_foo.apk 9993 // /data/app/com.example/lib/arm/libfoo.so 9994 // /data/app/com.example/lib/arm64/libfoo.so 9995 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9996 9997 /** New install */ 9998 FileInstallArgs(InstallParams params) { 9999 super(params.origin, params.observer, params.installFlags, 10000 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10001 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10002 if (isFwdLocked()) { 10003 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10004 } 10005 } 10006 10007 /** Existing install */ 10008 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10009 String[] instructionSets) { 10010 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10011 this.codeFile = (codePath != null) ? new File(codePath) : null; 10012 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10013 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10014 new File(legacyNativeLibraryPath) : null; 10015 } 10016 10017 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10018 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10019 isFwdLocked(), abiOverride); 10020 10021 final StorageManager storage = StorageManager.from(mContext); 10022 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10023 } 10024 10025 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10026 if (origin.staged) { 10027 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10028 codeFile = origin.file; 10029 resourceFile = origin.file; 10030 return PackageManager.INSTALL_SUCCEEDED; 10031 } 10032 10033 try { 10034 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10035 codeFile = tempDir; 10036 resourceFile = tempDir; 10037 } catch (IOException e) { 10038 Slog.w(TAG, "Failed to create copy file: " + e); 10039 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10040 } 10041 10042 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10043 @Override 10044 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10045 if (!FileUtils.isValidExtFilename(name)) { 10046 throw new IllegalArgumentException("Invalid filename: " + name); 10047 } 10048 try { 10049 final File file = new File(codeFile, name); 10050 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10051 O_RDWR | O_CREAT, 0644); 10052 Os.chmod(file.getAbsolutePath(), 0644); 10053 return new ParcelFileDescriptor(fd); 10054 } catch (ErrnoException e) { 10055 throw new RemoteException("Failed to open: " + e.getMessage()); 10056 } 10057 } 10058 }; 10059 10060 int ret = PackageManager.INSTALL_SUCCEEDED; 10061 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10062 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10063 Slog.e(TAG, "Failed to copy package"); 10064 return ret; 10065 } 10066 10067 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10068 NativeLibraryHelper.Handle handle = null; 10069 try { 10070 handle = NativeLibraryHelper.Handle.create(codeFile); 10071 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10072 abiOverride); 10073 } catch (IOException e) { 10074 Slog.e(TAG, "Copying native libraries failed", e); 10075 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10076 } finally { 10077 IoUtils.closeQuietly(handle); 10078 } 10079 10080 return ret; 10081 } 10082 10083 int doPreInstall(int status) { 10084 if (status != PackageManager.INSTALL_SUCCEEDED) { 10085 cleanUp(); 10086 } 10087 return status; 10088 } 10089 10090 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10091 if (status != PackageManager.INSTALL_SUCCEEDED) { 10092 cleanUp(); 10093 return false; 10094 } else { 10095 final File targetDir = codeFile.getParentFile(); 10096 final File beforeCodeFile = codeFile; 10097 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10098 10099 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10100 try { 10101 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10102 } catch (ErrnoException e) { 10103 Slog.d(TAG, "Failed to rename", e); 10104 return false; 10105 } 10106 10107 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10108 Slog.d(TAG, "Failed to restorecon"); 10109 return false; 10110 } 10111 10112 // Reflect the rename internally 10113 codeFile = afterCodeFile; 10114 resourceFile = afterCodeFile; 10115 10116 // Reflect the rename in scanned details 10117 pkg.codePath = afterCodeFile.getAbsolutePath(); 10118 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10119 pkg.baseCodePath); 10120 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10121 pkg.splitCodePaths); 10122 10123 // Reflect the rename in app info 10124 pkg.applicationInfo.setCodePath(pkg.codePath); 10125 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10126 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10127 pkg.applicationInfo.setResourcePath(pkg.codePath); 10128 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10129 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10130 10131 return true; 10132 } 10133 } 10134 10135 int doPostInstall(int status, int uid) { 10136 if (status != PackageManager.INSTALL_SUCCEEDED) { 10137 cleanUp(); 10138 } 10139 return status; 10140 } 10141 10142 @Override 10143 String getCodePath() { 10144 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10145 } 10146 10147 @Override 10148 String getResourcePath() { 10149 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10150 } 10151 10152 @Override 10153 String getLegacyNativeLibraryPath() { 10154 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10155 } 10156 10157 private boolean cleanUp() { 10158 if (codeFile == null || !codeFile.exists()) { 10159 return false; 10160 } 10161 10162 if (codeFile.isDirectory()) { 10163 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10164 } else { 10165 codeFile.delete(); 10166 } 10167 10168 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10169 resourceFile.delete(); 10170 } 10171 10172 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10173 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10174 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10175 } 10176 legacyNativeLibraryPath.delete(); 10177 } 10178 10179 return true; 10180 } 10181 10182 void cleanUpResourcesLI() { 10183 // Try enumerating all code paths before deleting 10184 List<String> allCodePaths = Collections.EMPTY_LIST; 10185 if (codeFile != null && codeFile.exists()) { 10186 try { 10187 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10188 allCodePaths = pkg.getAllCodePaths(); 10189 } catch (PackageParserException e) { 10190 // Ignored; we tried our best 10191 } 10192 } 10193 10194 cleanUp(); 10195 removeDexFiles(allCodePaths, instructionSets); 10196 } 10197 10198 boolean doPostDeleteLI(boolean delete) { 10199 // XXX err, shouldn't we respect the delete flag? 10200 cleanUpResourcesLI(); 10201 return true; 10202 } 10203 } 10204 10205 private boolean isAsecExternal(String cid) { 10206 final String asecPath = PackageHelper.getSdFilesystem(cid); 10207 return !asecPath.startsWith(mAsecInternalPath); 10208 } 10209 10210 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10211 PackageManagerException { 10212 if (copyRet < 0) { 10213 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10214 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10215 throw new PackageManagerException(copyRet, message); 10216 } 10217 } 10218 } 10219 10220 /** 10221 * Extract the MountService "container ID" from the full code path of an 10222 * .apk. 10223 */ 10224 static String cidFromCodePath(String fullCodePath) { 10225 int eidx = fullCodePath.lastIndexOf("/"); 10226 String subStr1 = fullCodePath.substring(0, eidx); 10227 int sidx = subStr1.lastIndexOf("/"); 10228 return subStr1.substring(sidx+1, eidx); 10229 } 10230 10231 /** 10232 * Logic to handle installation of ASEC applications, including copying and 10233 * renaming logic. 10234 */ 10235 class AsecInstallArgs extends InstallArgs { 10236 static final String RES_FILE_NAME = "pkg.apk"; 10237 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10238 10239 String cid; 10240 String packagePath; 10241 String resourcePath; 10242 String legacyNativeLibraryDir; 10243 10244 /** New install */ 10245 AsecInstallArgs(InstallParams params) { 10246 super(params.origin, params.observer, params.installFlags, 10247 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10248 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10249 } 10250 10251 /** Existing install */ 10252 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10253 boolean isExternal, boolean isForwardLocked) { 10254 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10255 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10256 instructionSets, null); 10257 // Hackily pretend we're still looking at a full code path 10258 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10259 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10260 } 10261 10262 // Extract cid from fullCodePath 10263 int eidx = fullCodePath.lastIndexOf("/"); 10264 String subStr1 = fullCodePath.substring(0, eidx); 10265 int sidx = subStr1.lastIndexOf("/"); 10266 cid = subStr1.substring(sidx+1, eidx); 10267 setMountPath(subStr1); 10268 } 10269 10270 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10271 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10272 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10273 instructionSets, null); 10274 this.cid = cid; 10275 setMountPath(PackageHelper.getSdDir(cid)); 10276 } 10277 10278 void createCopyFile() { 10279 cid = mInstallerService.allocateExternalStageCidLegacy(); 10280 } 10281 10282 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10283 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10284 abiOverride); 10285 10286 final File target; 10287 if (isExternalAsec()) { 10288 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10289 } else { 10290 target = Environment.getDataDirectory(); 10291 } 10292 10293 final StorageManager storage = StorageManager.from(mContext); 10294 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10295 } 10296 10297 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10298 if (origin.staged) { 10299 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10300 cid = origin.cid; 10301 setMountPath(PackageHelper.getSdDir(cid)); 10302 return PackageManager.INSTALL_SUCCEEDED; 10303 } 10304 10305 if (temp) { 10306 createCopyFile(); 10307 } else { 10308 /* 10309 * Pre-emptively destroy the container since it's destroyed if 10310 * copying fails due to it existing anyway. 10311 */ 10312 PackageHelper.destroySdDir(cid); 10313 } 10314 10315 final String newMountPath = imcs.copyPackageToContainer( 10316 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10317 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10318 10319 if (newMountPath != null) { 10320 setMountPath(newMountPath); 10321 return PackageManager.INSTALL_SUCCEEDED; 10322 } else { 10323 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10324 } 10325 } 10326 10327 @Override 10328 String getCodePath() { 10329 return packagePath; 10330 } 10331 10332 @Override 10333 String getResourcePath() { 10334 return resourcePath; 10335 } 10336 10337 @Override 10338 String getLegacyNativeLibraryPath() { 10339 return legacyNativeLibraryDir; 10340 } 10341 10342 int doPreInstall(int status) { 10343 if (status != PackageManager.INSTALL_SUCCEEDED) { 10344 // Destroy container 10345 PackageHelper.destroySdDir(cid); 10346 } else { 10347 boolean mounted = PackageHelper.isContainerMounted(cid); 10348 if (!mounted) { 10349 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10350 Process.SYSTEM_UID); 10351 if (newMountPath != null) { 10352 setMountPath(newMountPath); 10353 } else { 10354 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10355 } 10356 } 10357 } 10358 return status; 10359 } 10360 10361 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10362 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10363 String newMountPath = null; 10364 if (PackageHelper.isContainerMounted(cid)) { 10365 // Unmount the container 10366 if (!PackageHelper.unMountSdDir(cid)) { 10367 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10368 return false; 10369 } 10370 } 10371 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10372 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10373 " which might be stale. Will try to clean up."); 10374 // Clean up the stale container and proceed to recreate. 10375 if (!PackageHelper.destroySdDir(newCacheId)) { 10376 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10377 return false; 10378 } 10379 // Successfully cleaned up stale container. Try to rename again. 10380 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10381 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10382 + " inspite of cleaning it up."); 10383 return false; 10384 } 10385 } 10386 if (!PackageHelper.isContainerMounted(newCacheId)) { 10387 Slog.w(TAG, "Mounting container " + newCacheId); 10388 newMountPath = PackageHelper.mountSdDir(newCacheId, 10389 getEncryptKey(), Process.SYSTEM_UID); 10390 } else { 10391 newMountPath = PackageHelper.getSdDir(newCacheId); 10392 } 10393 if (newMountPath == null) { 10394 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10395 return false; 10396 } 10397 Log.i(TAG, "Succesfully renamed " + cid + 10398 " to " + newCacheId + 10399 " at new path: " + newMountPath); 10400 cid = newCacheId; 10401 10402 final File beforeCodeFile = new File(packagePath); 10403 setMountPath(newMountPath); 10404 final File afterCodeFile = new File(packagePath); 10405 10406 // Reflect the rename in scanned details 10407 pkg.codePath = afterCodeFile.getAbsolutePath(); 10408 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10409 pkg.baseCodePath); 10410 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10411 pkg.splitCodePaths); 10412 10413 // Reflect the rename in app info 10414 pkg.applicationInfo.setCodePath(pkg.codePath); 10415 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10416 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10417 pkg.applicationInfo.setResourcePath(pkg.codePath); 10418 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10419 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10420 10421 return true; 10422 } 10423 10424 private void setMountPath(String mountPath) { 10425 final File mountFile = new File(mountPath); 10426 10427 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10428 if (monolithicFile.exists()) { 10429 packagePath = monolithicFile.getAbsolutePath(); 10430 if (isFwdLocked()) { 10431 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10432 } else { 10433 resourcePath = packagePath; 10434 } 10435 } else { 10436 packagePath = mountFile.getAbsolutePath(); 10437 resourcePath = packagePath; 10438 } 10439 10440 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10441 } 10442 10443 int doPostInstall(int status, int uid) { 10444 if (status != PackageManager.INSTALL_SUCCEEDED) { 10445 cleanUp(); 10446 } else { 10447 final int groupOwner; 10448 final String protectedFile; 10449 if (isFwdLocked()) { 10450 groupOwner = UserHandle.getSharedAppGid(uid); 10451 protectedFile = RES_FILE_NAME; 10452 } else { 10453 groupOwner = -1; 10454 protectedFile = null; 10455 } 10456 10457 if (uid < Process.FIRST_APPLICATION_UID 10458 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10459 Slog.e(TAG, "Failed to finalize " + cid); 10460 PackageHelper.destroySdDir(cid); 10461 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10462 } 10463 10464 boolean mounted = PackageHelper.isContainerMounted(cid); 10465 if (!mounted) { 10466 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10467 } 10468 } 10469 return status; 10470 } 10471 10472 private void cleanUp() { 10473 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10474 10475 // Destroy secure container 10476 PackageHelper.destroySdDir(cid); 10477 } 10478 10479 private List<String> getAllCodePaths() { 10480 final File codeFile = new File(getCodePath()); 10481 if (codeFile != null && codeFile.exists()) { 10482 try { 10483 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10484 return pkg.getAllCodePaths(); 10485 } catch (PackageParserException e) { 10486 // Ignored; we tried our best 10487 } 10488 } 10489 return Collections.EMPTY_LIST; 10490 } 10491 10492 void cleanUpResourcesLI() { 10493 // Enumerate all code paths before deleting 10494 cleanUpResourcesLI(getAllCodePaths()); 10495 } 10496 10497 private void cleanUpResourcesLI(List<String> allCodePaths) { 10498 cleanUp(); 10499 removeDexFiles(allCodePaths, instructionSets); 10500 } 10501 10502 10503 10504 String getPackageName() { 10505 return getAsecPackageName(cid); 10506 } 10507 10508 boolean doPostDeleteLI(boolean delete) { 10509 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10510 final List<String> allCodePaths = getAllCodePaths(); 10511 boolean mounted = PackageHelper.isContainerMounted(cid); 10512 if (mounted) { 10513 // Unmount first 10514 if (PackageHelper.unMountSdDir(cid)) { 10515 mounted = false; 10516 } 10517 } 10518 if (!mounted && delete) { 10519 cleanUpResourcesLI(allCodePaths); 10520 } 10521 return !mounted; 10522 } 10523 10524 @Override 10525 int doPreCopy() { 10526 if (isFwdLocked()) { 10527 if (!PackageHelper.fixSdPermissions(cid, 10528 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10529 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10530 } 10531 } 10532 10533 return PackageManager.INSTALL_SUCCEEDED; 10534 } 10535 10536 @Override 10537 int doPostCopy(int uid) { 10538 if (isFwdLocked()) { 10539 if (uid < Process.FIRST_APPLICATION_UID 10540 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10541 RES_FILE_NAME)) { 10542 Slog.e(TAG, "Failed to finalize " + cid); 10543 PackageHelper.destroySdDir(cid); 10544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10545 } 10546 } 10547 10548 return PackageManager.INSTALL_SUCCEEDED; 10549 } 10550 } 10551 10552 static String getAsecPackageName(String packageCid) { 10553 int idx = packageCid.lastIndexOf("-"); 10554 if (idx == -1) { 10555 return packageCid; 10556 } 10557 return packageCid.substring(0, idx); 10558 } 10559 10560 // Utility method used to create code paths based on package name and available index. 10561 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10562 String idxStr = ""; 10563 int idx = 1; 10564 // Fall back to default value of idx=1 if prefix is not 10565 // part of oldCodePath 10566 if (oldCodePath != null) { 10567 String subStr = oldCodePath; 10568 // Drop the suffix right away 10569 if (suffix != null && subStr.endsWith(suffix)) { 10570 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10571 } 10572 // If oldCodePath already contains prefix find out the 10573 // ending index to either increment or decrement. 10574 int sidx = subStr.lastIndexOf(prefix); 10575 if (sidx != -1) { 10576 subStr = subStr.substring(sidx + prefix.length()); 10577 if (subStr != null) { 10578 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10579 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10580 } 10581 try { 10582 idx = Integer.parseInt(subStr); 10583 if (idx <= 1) { 10584 idx++; 10585 } else { 10586 idx--; 10587 } 10588 } catch(NumberFormatException e) { 10589 } 10590 } 10591 } 10592 } 10593 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10594 return prefix + idxStr; 10595 } 10596 10597 private File getNextCodePath(File targetDir, String packageName) { 10598 int suffix = 1; 10599 File result; 10600 do { 10601 result = new File(targetDir, packageName + "-" + suffix); 10602 suffix++; 10603 } while (result.exists()); 10604 return result; 10605 } 10606 10607 // Utility method that returns the relative package path with respect 10608 // to the installation directory. Like say for /data/data/com.test-1.apk 10609 // string com.test-1 is returned. 10610 static String deriveCodePathName(String codePath) { 10611 if (codePath == null) { 10612 return null; 10613 } 10614 final File codeFile = new File(codePath); 10615 final String name = codeFile.getName(); 10616 if (codeFile.isDirectory()) { 10617 return name; 10618 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10619 final int lastDot = name.lastIndexOf('.'); 10620 return name.substring(0, lastDot); 10621 } else { 10622 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10623 return null; 10624 } 10625 } 10626 10627 class PackageInstalledInfo { 10628 String name; 10629 int uid; 10630 // The set of users that originally had this package installed. 10631 int[] origUsers; 10632 // The set of users that now have this package installed. 10633 int[] newUsers; 10634 PackageParser.Package pkg; 10635 int returnCode; 10636 String returnMsg; 10637 PackageRemovedInfo removedInfo; 10638 10639 public void setError(int code, String msg) { 10640 returnCode = code; 10641 returnMsg = msg; 10642 Slog.w(TAG, msg); 10643 } 10644 10645 public void setError(String msg, PackageParserException e) { 10646 returnCode = e.error; 10647 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10648 Slog.w(TAG, msg, e); 10649 } 10650 10651 public void setError(String msg, PackageManagerException e) { 10652 returnCode = e.error; 10653 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10654 Slog.w(TAG, msg, e); 10655 } 10656 10657 // In some error cases we want to convey more info back to the observer 10658 String origPackage; 10659 String origPermission; 10660 } 10661 10662 /* 10663 * Install a non-existing package. 10664 */ 10665 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10666 UserHandle user, String installerPackageName, String volumeUuid, 10667 PackageInstalledInfo res) { 10668 // Remember this for later, in case we need to rollback this install 10669 String pkgName = pkg.packageName; 10670 10671 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10672 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10673 synchronized(mPackages) { 10674 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10675 // A package with the same name is already installed, though 10676 // it has been renamed to an older name. The package we 10677 // are trying to install should be installed as an update to 10678 // the existing one, but that has not been requested, so bail. 10679 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10680 + " without first uninstalling package running as " 10681 + mSettings.mRenamedPackages.get(pkgName)); 10682 return; 10683 } 10684 if (mPackages.containsKey(pkgName)) { 10685 // Don't allow installation over an existing package with the same name. 10686 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10687 + " without first uninstalling."); 10688 return; 10689 } 10690 } 10691 10692 try { 10693 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10694 System.currentTimeMillis(), user); 10695 10696 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10697 // delete the partially installed application. the data directory will have to be 10698 // restored if it was already existing 10699 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10700 // remove package from internal structures. Note that we want deletePackageX to 10701 // delete the package data and cache directories that it created in 10702 // scanPackageLocked, unless those directories existed before we even tried to 10703 // install. 10704 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10705 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10706 res.removedInfo, true); 10707 } 10708 10709 } catch (PackageManagerException e) { 10710 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10711 } 10712 } 10713 10714 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10715 // Upgrade keysets are being used. Determine if new package has a superset of the 10716 // required keys. 10717 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10718 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10719 for (int i = 0; i < upgradeKeySets.length; i++) { 10720 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10721 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10722 return true; 10723 } 10724 } 10725 return false; 10726 } 10727 10728 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10729 UserHandle user, String installerPackageName, String volumeUuid, 10730 PackageInstalledInfo res) { 10731 PackageParser.Package oldPackage; 10732 String pkgName = pkg.packageName; 10733 int[] allUsers; 10734 boolean[] perUserInstalled; 10735 10736 // First find the old package info and check signatures 10737 synchronized(mPackages) { 10738 oldPackage = mPackages.get(pkgName); 10739 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10740 PackageSetting ps = mSettings.mPackages.get(pkgName); 10741 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10742 // default to original signature matching 10743 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10744 != PackageManager.SIGNATURE_MATCH) { 10745 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10746 "New package has a different signature: " + pkgName); 10747 return; 10748 } 10749 } else { 10750 if(!checkUpgradeKeySetLP(ps, pkg)) { 10751 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10752 "New package not signed by keys specified by upgrade-keysets: " 10753 + pkgName); 10754 return; 10755 } 10756 } 10757 10758 // In case of rollback, remember per-user/profile install state 10759 allUsers = sUserManager.getUserIds(); 10760 perUserInstalled = new boolean[allUsers.length]; 10761 for (int i = 0; i < allUsers.length; i++) { 10762 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10763 } 10764 } 10765 10766 boolean sysPkg = (isSystemApp(oldPackage)); 10767 if (sysPkg) { 10768 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10769 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10770 } else { 10771 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10772 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10773 } 10774 } 10775 10776 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10777 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10778 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10779 String volumeUuid, PackageInstalledInfo res) { 10780 String pkgName = deletedPackage.packageName; 10781 boolean deletedPkg = true; 10782 boolean updatedSettings = false; 10783 10784 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10785 + deletedPackage); 10786 long origUpdateTime; 10787 if (pkg.mExtras != null) { 10788 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10789 } else { 10790 origUpdateTime = 0; 10791 } 10792 10793 // First delete the existing package while retaining the data directory 10794 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10795 res.removedInfo, true)) { 10796 // If the existing package wasn't successfully deleted 10797 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10798 deletedPkg = false; 10799 } else { 10800 // Successfully deleted the old package; proceed with replace. 10801 10802 // If deleted package lived in a container, give users a chance to 10803 // relinquish resources before killing. 10804 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10805 if (DEBUG_INSTALL) { 10806 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10807 } 10808 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10809 final ArrayList<String> pkgList = new ArrayList<String>(1); 10810 pkgList.add(deletedPackage.applicationInfo.packageName); 10811 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10812 } 10813 10814 deleteCodeCacheDirsLI(pkgName); 10815 try { 10816 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10817 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10818 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10819 perUserInstalled, res, user); 10820 updatedSettings = true; 10821 } catch (PackageManagerException e) { 10822 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10823 } 10824 } 10825 10826 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10827 // remove package from internal structures. Note that we want deletePackageX to 10828 // delete the package data and cache directories that it created in 10829 // scanPackageLocked, unless those directories existed before we even tried to 10830 // install. 10831 if(updatedSettings) { 10832 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10833 deletePackageLI( 10834 pkgName, null, true, allUsers, perUserInstalled, 10835 PackageManager.DELETE_KEEP_DATA, 10836 res.removedInfo, true); 10837 } 10838 // Since we failed to install the new package we need to restore the old 10839 // package that we deleted. 10840 if (deletedPkg) { 10841 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10842 File restoreFile = new File(deletedPackage.codePath); 10843 // Parse old package 10844 boolean oldExternal = isExternal(deletedPackage); 10845 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10846 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10847 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10848 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10849 try { 10850 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10851 } catch (PackageManagerException e) { 10852 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10853 + e.getMessage()); 10854 return; 10855 } 10856 // Restore of old package succeeded. Update permissions. 10857 // writer 10858 synchronized (mPackages) { 10859 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10860 UPDATE_PERMISSIONS_ALL); 10861 // can downgrade to reader 10862 mSettings.writeLPr(); 10863 } 10864 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10865 } 10866 } 10867 } 10868 10869 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10870 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10871 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10872 String volumeUuid, PackageInstalledInfo res) { 10873 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10874 + ", old=" + deletedPackage); 10875 boolean disabledSystem = false; 10876 boolean updatedSettings = false; 10877 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10878 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10879 != 0) { 10880 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10881 } 10882 String packageName = deletedPackage.packageName; 10883 if (packageName == null) { 10884 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10885 "Attempt to delete null packageName."); 10886 return; 10887 } 10888 PackageParser.Package oldPkg; 10889 PackageSetting oldPkgSetting; 10890 // reader 10891 synchronized (mPackages) { 10892 oldPkg = mPackages.get(packageName); 10893 oldPkgSetting = mSettings.mPackages.get(packageName); 10894 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10895 (oldPkgSetting == null)) { 10896 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10897 "Couldn't find package:" + packageName + " information"); 10898 return; 10899 } 10900 } 10901 10902 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10903 10904 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10905 res.removedInfo.removedPackage = packageName; 10906 // Remove existing system package 10907 removePackageLI(oldPkgSetting, true); 10908 // writer 10909 synchronized (mPackages) { 10910 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10911 if (!disabledSystem && deletedPackage != null) { 10912 // We didn't need to disable the .apk as a current system package, 10913 // which means we are replacing another update that is already 10914 // installed. We need to make sure to delete the older one's .apk. 10915 res.removedInfo.args = createInstallArgsForExisting(0, 10916 deletedPackage.applicationInfo.getCodePath(), 10917 deletedPackage.applicationInfo.getResourcePath(), 10918 deletedPackage.applicationInfo.nativeLibraryRootDir, 10919 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10920 } else { 10921 res.removedInfo.args = null; 10922 } 10923 } 10924 10925 // Successfully disabled the old package. Now proceed with re-installation 10926 deleteCodeCacheDirsLI(packageName); 10927 10928 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10929 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10930 10931 PackageParser.Package newPackage = null; 10932 try { 10933 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10934 if (newPackage.mExtras != null) { 10935 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10936 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10937 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10938 10939 // is the update attempting to change shared user? that isn't going to work... 10940 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10941 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10942 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10943 + " to " + newPkgSetting.sharedUser); 10944 updatedSettings = true; 10945 } 10946 } 10947 10948 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10949 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10950 perUserInstalled, res, user); 10951 updatedSettings = true; 10952 } 10953 10954 } catch (PackageManagerException e) { 10955 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10956 } 10957 10958 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10959 // Re installation failed. Restore old information 10960 // Remove new pkg information 10961 if (newPackage != null) { 10962 removeInstalledPackageLI(newPackage, true); 10963 } 10964 // Add back the old system package 10965 try { 10966 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10967 } catch (PackageManagerException e) { 10968 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10969 } 10970 // Restore the old system information in Settings 10971 synchronized (mPackages) { 10972 if (disabledSystem) { 10973 mSettings.enableSystemPackageLPw(packageName); 10974 } 10975 if (updatedSettings) { 10976 mSettings.setInstallerPackageName(packageName, 10977 oldPkgSetting.installerPackageName); 10978 } 10979 mSettings.writeLPr(); 10980 } 10981 } 10982 } 10983 10984 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10985 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10986 UserHandle user) { 10987 String pkgName = newPackage.packageName; 10988 synchronized (mPackages) { 10989 //write settings. the installStatus will be incomplete at this stage. 10990 //note that the new package setting would have already been 10991 //added to mPackages. It hasn't been persisted yet. 10992 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10993 mSettings.writeLPr(); 10994 } 10995 10996 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10997 10998 synchronized (mPackages) { 10999 updatePermissionsLPw(newPackage.packageName, newPackage, 11000 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11001 ? UPDATE_PERMISSIONS_ALL : 0)); 11002 // For system-bundled packages, we assume that installing an upgraded version 11003 // of the package implies that the user actually wants to run that new code, 11004 // so we enable the package. 11005 PackageSetting ps = mSettings.mPackages.get(pkgName); 11006 if (ps != null) { 11007 if (isSystemApp(newPackage)) { 11008 // NB: implicit assumption that system package upgrades apply to all users 11009 if (DEBUG_INSTALL) { 11010 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11011 } 11012 if (res.origUsers != null) { 11013 for (int userHandle : res.origUsers) { 11014 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11015 userHandle, installerPackageName); 11016 } 11017 } 11018 // Also convey the prior install/uninstall state 11019 if (allUsers != null && perUserInstalled != null) { 11020 for (int i = 0; i < allUsers.length; i++) { 11021 if (DEBUG_INSTALL) { 11022 Slog.d(TAG, " user " + allUsers[i] 11023 + " => " + perUserInstalled[i]); 11024 } 11025 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11026 } 11027 // these install state changes will be persisted in the 11028 // upcoming call to mSettings.writeLPr(). 11029 } 11030 } 11031 // It's implied that when a user requests installation, they want the app to be 11032 // installed and enabled. 11033 int userId = user.getIdentifier(); 11034 if (userId != UserHandle.USER_ALL) { 11035 ps.setInstalled(true, userId); 11036 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11037 } 11038 } 11039 res.name = pkgName; 11040 res.uid = newPackage.applicationInfo.uid; 11041 res.pkg = newPackage; 11042 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11043 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11044 mSettings.setVolumeUuid(pkgName, volumeUuid); 11045 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11046 //to update install status 11047 mSettings.writeLPr(); 11048 } 11049 } 11050 11051 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11052 final int installFlags = args.installFlags; 11053 final String installerPackageName = args.installerPackageName; 11054 final String volumeUuid = args.volumeUuid; 11055 final File tmpPackageFile = new File(args.getCodePath()); 11056 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11057 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11058 || (args.volumeUuid != null)); 11059 boolean replace = false; 11060 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11061 // Result object to be returned 11062 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11063 11064 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11065 // Retrieve PackageSettings and parse package 11066 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11067 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11068 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11069 PackageParser pp = new PackageParser(); 11070 pp.setSeparateProcesses(mSeparateProcesses); 11071 pp.setDisplayMetrics(mMetrics); 11072 11073 final PackageParser.Package pkg; 11074 try { 11075 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11076 } catch (PackageParserException e) { 11077 res.setError("Failed parse during installPackageLI", e); 11078 return; 11079 } 11080 11081 // Mark that we have an install time CPU ABI override. 11082 pkg.cpuAbiOverride = args.abiOverride; 11083 11084 String pkgName = res.name = pkg.packageName; 11085 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11086 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11087 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11088 return; 11089 } 11090 } 11091 11092 try { 11093 pp.collectCertificates(pkg, parseFlags); 11094 pp.collectManifestDigest(pkg); 11095 } catch (PackageParserException e) { 11096 res.setError("Failed collect during installPackageLI", e); 11097 return; 11098 } 11099 11100 /* If the installer passed in a manifest digest, compare it now. */ 11101 if (args.manifestDigest != null) { 11102 if (DEBUG_INSTALL) { 11103 final String parsedManifest = pkg.manifestDigest == null ? "null" 11104 : pkg.manifestDigest.toString(); 11105 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11106 + parsedManifest); 11107 } 11108 11109 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11110 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11111 return; 11112 } 11113 } else if (DEBUG_INSTALL) { 11114 final String parsedManifest = pkg.manifestDigest == null 11115 ? "null" : pkg.manifestDigest.toString(); 11116 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11117 } 11118 11119 // Get rid of all references to package scan path via parser. 11120 pp = null; 11121 String oldCodePath = null; 11122 boolean systemApp = false; 11123 synchronized (mPackages) { 11124 // Check if installing already existing package 11125 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11126 String oldName = mSettings.mRenamedPackages.get(pkgName); 11127 if (pkg.mOriginalPackages != null 11128 && pkg.mOriginalPackages.contains(oldName) 11129 && mPackages.containsKey(oldName)) { 11130 // This package is derived from an original package, 11131 // and this device has been updating from that original 11132 // name. We must continue using the original name, so 11133 // rename the new package here. 11134 pkg.setPackageName(oldName); 11135 pkgName = pkg.packageName; 11136 replace = true; 11137 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11138 + oldName + " pkgName=" + pkgName); 11139 } else if (mPackages.containsKey(pkgName)) { 11140 // This package, under its official name, already exists 11141 // on the device; we should replace it. 11142 replace = true; 11143 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11144 } 11145 } 11146 11147 PackageSetting ps = mSettings.mPackages.get(pkgName); 11148 if (ps != null) { 11149 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11150 11151 // Quick sanity check that we're signed correctly if updating; 11152 // we'll check this again later when scanning, but we want to 11153 // bail early here before tripping over redefined permissions. 11154 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11155 try { 11156 verifySignaturesLP(ps, pkg); 11157 } catch (PackageManagerException e) { 11158 res.setError(e.error, e.getMessage()); 11159 return; 11160 } 11161 } else { 11162 if (!checkUpgradeKeySetLP(ps, pkg)) { 11163 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11164 + pkg.packageName + " upgrade keys do not match the " 11165 + "previously installed version"); 11166 return; 11167 } 11168 } 11169 11170 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11171 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11172 systemApp = (ps.pkg.applicationInfo.flags & 11173 ApplicationInfo.FLAG_SYSTEM) != 0; 11174 } 11175 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11176 } 11177 11178 // Check whether the newly-scanned package wants to define an already-defined perm 11179 int N = pkg.permissions.size(); 11180 for (int i = N-1; i >= 0; i--) { 11181 PackageParser.Permission perm = pkg.permissions.get(i); 11182 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11183 if (bp != null) { 11184 // If the defining package is signed with our cert, it's okay. This 11185 // also includes the "updating the same package" case, of course. 11186 // "updating same package" could also involve key-rotation. 11187 final boolean sigsOk; 11188 if (!bp.sourcePackage.equals(pkg.packageName) 11189 || !(bp.packageSetting instanceof PackageSetting) 11190 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11191 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11192 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11193 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11194 } else { 11195 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11196 } 11197 if (!sigsOk) { 11198 // If the owning package is the system itself, we log but allow 11199 // install to proceed; we fail the install on all other permission 11200 // redefinitions. 11201 if (!bp.sourcePackage.equals("android")) { 11202 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11203 + pkg.packageName + " attempting to redeclare permission " 11204 + perm.info.name + " already owned by " + bp.sourcePackage); 11205 res.origPermission = perm.info.name; 11206 res.origPackage = bp.sourcePackage; 11207 return; 11208 } else { 11209 Slog.w(TAG, "Package " + pkg.packageName 11210 + " attempting to redeclare system permission " 11211 + perm.info.name + "; ignoring new declaration"); 11212 pkg.permissions.remove(i); 11213 } 11214 } 11215 } 11216 } 11217 11218 } 11219 11220 if (systemApp && onExternal) { 11221 // Disable updates to system apps on sdcard 11222 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11223 "Cannot install updates to system apps on sdcard"); 11224 return; 11225 } 11226 11227 // Run dexopt before old package gets removed, to minimize time when app is not available 11228 int result = mPackageDexOptimizer 11229 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11230 false /* defer */, false /* inclDependencies */); 11231 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11232 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11233 return; 11234 } 11235 11236 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11237 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11238 return; 11239 } 11240 11241 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11242 11243 // Call with SCAN_NO_DEX, since dexopt has already been made 11244 if (replace) { 11245 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11246 installerPackageName, volumeUuid, res); 11247 } else { 11248 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES 11249 | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res); 11250 } 11251 synchronized (mPackages) { 11252 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11253 if (ps != null) { 11254 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11255 } 11256 } 11257 } 11258 11259 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11260 if (mIntentFilterVerifierComponent == null) { 11261 Slog.d(TAG, "No IntentFilter verification will not be done as " 11262 + "there is no IntentFilterVerifier available!"); 11263 return; 11264 } 11265 11266 final int verifierUid = getPackageUid( 11267 mIntentFilterVerifierComponent.getPackageName(), 11268 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11269 11270 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11271 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11272 msg.obj = pkg; 11273 msg.arg1 = userId; 11274 msg.arg2 = verifierUid; 11275 11276 mHandler.sendMessage(msg); 11277 } 11278 11279 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11280 PackageParser.Package pkg) { 11281 int size = pkg.activities.size(); 11282 if (size == 0) { 11283 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11284 return; 11285 } 11286 11287 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11288 + " Activities needs verification ..."); 11289 11290 final int verificationId = mIntentFilterVerificationToken++; 11291 int count = 0; 11292 final String packageName = pkg.packageName; 11293 ArrayList<String> allHosts = new ArrayList<>(); 11294 synchronized (mPackages) { 11295 for (PackageParser.Activity a : pkg.activities) { 11296 for (ActivityIntentInfo filter : a.intents) { 11297 boolean needFilterVerification = filter.needsVerification() && 11298 !filter.isVerified(); 11299 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11300 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11301 mIntentFilterVerifier.addOneIntentFilterVerification( 11302 verifierUid, userId, verificationId, filter, packageName); 11303 count++; 11304 } else { 11305 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11306 if (hasValidDomains(filter)) { 11307 allHosts.addAll(filter.getHostsList()); 11308 } 11309 } 11310 } 11311 } 11312 } 11313 11314 if (count > 0) { 11315 mIntentFilterVerifier.startVerifications(userId); 11316 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11317 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11318 } else { 11319 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11320 if (allHosts.size() > 0 && hasDomainURLs(pkg) && 11321 mSettings.createIntentFilterVerificationIfNeededLPw( 11322 packageName, allHosts) != null) { 11323 scheduleWriteSettingsLocked(); 11324 } 11325 } 11326 } 11327 11328 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11329 final ComponentName cn = filter.activity.getComponentName(); 11330 final String packageName = cn.getPackageName(); 11331 11332 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11333 packageName); 11334 if (ivi == null) { 11335 return true; 11336 } 11337 int status = ivi.getStatus(); 11338 switch (status) { 11339 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11340 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11341 return true; 11342 11343 default: 11344 // Nothing to do 11345 return false; 11346 } 11347 } 11348 11349 private static boolean isMultiArch(PackageSetting ps) { 11350 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11351 } 11352 11353 private static boolean isMultiArch(ApplicationInfo info) { 11354 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11355 } 11356 11357 private static boolean isExternal(PackageParser.Package pkg) { 11358 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11359 } 11360 11361 private static boolean isExternal(PackageSetting ps) { 11362 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11363 } 11364 11365 private static boolean isExternal(ApplicationInfo info) { 11366 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11367 } 11368 11369 private static boolean isSystemApp(PackageParser.Package pkg) { 11370 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11371 } 11372 11373 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11374 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11375 } 11376 11377 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11378 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11379 } 11380 11381 private static boolean isSystemApp(PackageSetting ps) { 11382 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11383 } 11384 11385 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11386 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11387 } 11388 11389 private int packageFlagsToInstallFlags(PackageSetting ps) { 11390 int installFlags = 0; 11391 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11392 // This existing package was an external ASEC install when we have 11393 // the external flag without a UUID 11394 installFlags |= PackageManager.INSTALL_EXTERNAL; 11395 } 11396 if (ps.isForwardLocked()) { 11397 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11398 } 11399 return installFlags; 11400 } 11401 11402 private void deleteTempPackageFiles() { 11403 final FilenameFilter filter = new FilenameFilter() { 11404 public boolean accept(File dir, String name) { 11405 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11406 } 11407 }; 11408 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11409 file.delete(); 11410 } 11411 } 11412 11413 @Override 11414 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11415 int flags) { 11416 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11417 flags); 11418 } 11419 11420 @Override 11421 public void deletePackage(final String packageName, 11422 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11423 mContext.enforceCallingOrSelfPermission( 11424 android.Manifest.permission.DELETE_PACKAGES, null); 11425 final int uid = Binder.getCallingUid(); 11426 if (UserHandle.getUserId(uid) != userId) { 11427 mContext.enforceCallingPermission( 11428 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11429 "deletePackage for user " + userId); 11430 } 11431 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11432 try { 11433 observer.onPackageDeleted(packageName, 11434 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11435 } catch (RemoteException re) { 11436 } 11437 return; 11438 } 11439 11440 boolean uninstallBlocked = false; 11441 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11442 int[] users = sUserManager.getUserIds(); 11443 for (int i = 0; i < users.length; ++i) { 11444 if (getBlockUninstallForUser(packageName, users[i])) { 11445 uninstallBlocked = true; 11446 break; 11447 } 11448 } 11449 } else { 11450 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11451 } 11452 if (uninstallBlocked) { 11453 try { 11454 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11455 null); 11456 } catch (RemoteException re) { 11457 } 11458 return; 11459 } 11460 11461 if (DEBUG_REMOVE) { 11462 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11463 } 11464 // Queue up an async operation since the package deletion may take a little while. 11465 mHandler.post(new Runnable() { 11466 public void run() { 11467 mHandler.removeCallbacks(this); 11468 final int returnCode = deletePackageX(packageName, userId, flags); 11469 if (observer != null) { 11470 try { 11471 observer.onPackageDeleted(packageName, returnCode, null); 11472 } catch (RemoteException e) { 11473 Log.i(TAG, "Observer no longer exists."); 11474 } //end catch 11475 } //end if 11476 } //end run 11477 }); 11478 } 11479 11480 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11481 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11482 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11483 try { 11484 if (dpm != null) { 11485 if (dpm.isDeviceOwner(packageName)) { 11486 return true; 11487 } 11488 int[] users; 11489 if (userId == UserHandle.USER_ALL) { 11490 users = sUserManager.getUserIds(); 11491 } else { 11492 users = new int[]{userId}; 11493 } 11494 for (int i = 0; i < users.length; ++i) { 11495 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11496 return true; 11497 } 11498 } 11499 } 11500 } catch (RemoteException e) { 11501 } 11502 return false; 11503 } 11504 11505 /** 11506 * This method is an internal method that could be get invoked either 11507 * to delete an installed package or to clean up a failed installation. 11508 * After deleting an installed package, a broadcast is sent to notify any 11509 * listeners that the package has been installed. For cleaning up a failed 11510 * installation, the broadcast is not necessary since the package's 11511 * installation wouldn't have sent the initial broadcast either 11512 * The key steps in deleting a package are 11513 * deleting the package information in internal structures like mPackages, 11514 * deleting the packages base directories through installd 11515 * updating mSettings to reflect current status 11516 * persisting settings for later use 11517 * sending a broadcast if necessary 11518 */ 11519 private int deletePackageX(String packageName, int userId, int flags) { 11520 final PackageRemovedInfo info = new PackageRemovedInfo(); 11521 final boolean res; 11522 11523 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11524 ? UserHandle.ALL : new UserHandle(userId); 11525 11526 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11527 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11528 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11529 } 11530 11531 boolean removedForAllUsers = false; 11532 boolean systemUpdate = false; 11533 11534 // for the uninstall-updates case and restricted profiles, remember the per- 11535 // userhandle installed state 11536 int[] allUsers; 11537 boolean[] perUserInstalled; 11538 synchronized (mPackages) { 11539 PackageSetting ps = mSettings.mPackages.get(packageName); 11540 allUsers = sUserManager.getUserIds(); 11541 perUserInstalled = new boolean[allUsers.length]; 11542 for (int i = 0; i < allUsers.length; i++) { 11543 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11544 } 11545 } 11546 11547 synchronized (mInstallLock) { 11548 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11549 res = deletePackageLI(packageName, removeForUser, 11550 true, allUsers, perUserInstalled, 11551 flags | REMOVE_CHATTY, info, true); 11552 systemUpdate = info.isRemovedPackageSystemUpdate; 11553 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11554 removedForAllUsers = true; 11555 } 11556 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11557 + " removedForAllUsers=" + removedForAllUsers); 11558 } 11559 11560 if (res) { 11561 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11562 11563 // If the removed package was a system update, the old system package 11564 // was re-enabled; we need to broadcast this information 11565 if (systemUpdate) { 11566 Bundle extras = new Bundle(1); 11567 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11568 ? info.removedAppId : info.uid); 11569 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11570 11571 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11572 extras, null, null, null); 11573 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11574 extras, null, null, null); 11575 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11576 null, packageName, null, null); 11577 } 11578 } 11579 // Force a gc here. 11580 Runtime.getRuntime().gc(); 11581 // Delete the resources here after sending the broadcast to let 11582 // other processes clean up before deleting resources. 11583 if (info.args != null) { 11584 synchronized (mInstallLock) { 11585 info.args.doPostDeleteLI(true); 11586 } 11587 } 11588 11589 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11590 } 11591 11592 static class PackageRemovedInfo { 11593 String removedPackage; 11594 int uid = -1; 11595 int removedAppId = -1; 11596 int[] removedUsers = null; 11597 boolean isRemovedPackageSystemUpdate = false; 11598 // Clean up resources deleted packages. 11599 InstallArgs args = null; 11600 11601 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11602 Bundle extras = new Bundle(1); 11603 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11604 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11605 if (replacing) { 11606 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11607 } 11608 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11609 if (removedPackage != null) { 11610 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11611 extras, null, null, removedUsers); 11612 if (fullRemove && !replacing) { 11613 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11614 extras, null, null, removedUsers); 11615 } 11616 } 11617 if (removedAppId >= 0) { 11618 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11619 removedUsers); 11620 } 11621 } 11622 } 11623 11624 /* 11625 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11626 * flag is not set, the data directory is removed as well. 11627 * make sure this flag is set for partially installed apps. If not its meaningless to 11628 * delete a partially installed application. 11629 */ 11630 private void removePackageDataLI(PackageSetting ps, 11631 int[] allUserHandles, boolean[] perUserInstalled, 11632 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11633 String packageName = ps.name; 11634 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11635 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11636 // Retrieve object to delete permissions for shared user later on 11637 final PackageSetting deletedPs; 11638 // reader 11639 synchronized (mPackages) { 11640 deletedPs = mSettings.mPackages.get(packageName); 11641 if (outInfo != null) { 11642 outInfo.removedPackage = packageName; 11643 outInfo.removedUsers = deletedPs != null 11644 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11645 : null; 11646 } 11647 } 11648 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11649 removeDataDirsLI(packageName); 11650 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11651 } 11652 // writer 11653 synchronized (mPackages) { 11654 if (deletedPs != null) { 11655 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11656 if (outInfo != null) { 11657 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11658 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11659 } 11660 updatePermissionsLPw(deletedPs.name, null, 0); 11661 if (deletedPs.sharedUser != null) { 11662 // Remove permissions associated with package. Since runtime 11663 // permissions are per user we have to kill the removed package 11664 // or packages running under the shared user of the removed 11665 // package if revoking the permissions requested only by the removed 11666 // package is successful and this causes a change in gids. 11667 for (int userId : UserManagerService.getInstance().getUserIds()) { 11668 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11669 userId); 11670 if (userIdToKill == UserHandle.USER_ALL 11671 || userIdToKill >= UserHandle.USER_OWNER) { 11672 // If gids changed for this user, kill all affected packages. 11673 mHandler.post(new Runnable() { 11674 @Override 11675 public void run() { 11676 // This has to happen with no lock held. 11677 killSettingPackagesForUser(deletedPs, userIdToKill, 11678 KILL_APP_REASON_GIDS_CHANGED); 11679 } 11680 }); 11681 break; 11682 } 11683 } 11684 } 11685 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11686 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11687 } 11688 // make sure to preserve per-user disabled state if this removal was just 11689 // a downgrade of a system app to the factory package 11690 if (allUserHandles != null && perUserInstalled != null) { 11691 if (DEBUG_REMOVE) { 11692 Slog.d(TAG, "Propagating install state across downgrade"); 11693 } 11694 for (int i = 0; i < allUserHandles.length; i++) { 11695 if (DEBUG_REMOVE) { 11696 Slog.d(TAG, " user " + allUserHandles[i] 11697 + " => " + perUserInstalled[i]); 11698 } 11699 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11700 } 11701 } 11702 } 11703 // can downgrade to reader 11704 if (writeSettings) { 11705 // Save settings now 11706 mSettings.writeLPr(); 11707 } 11708 } 11709 if (outInfo != null) { 11710 // A user ID was deleted here. Go through all users and remove it 11711 // from KeyStore. 11712 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11713 } 11714 } 11715 11716 static boolean locationIsPrivileged(File path) { 11717 try { 11718 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11719 .getCanonicalPath(); 11720 return path.getCanonicalPath().startsWith(privilegedAppDir); 11721 } catch (IOException e) { 11722 Slog.e(TAG, "Unable to access code path " + path); 11723 } 11724 return false; 11725 } 11726 11727 /* 11728 * Tries to delete system package. 11729 */ 11730 private boolean deleteSystemPackageLI(PackageSetting newPs, 11731 int[] allUserHandles, boolean[] perUserInstalled, 11732 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11733 final boolean applyUserRestrictions 11734 = (allUserHandles != null) && (perUserInstalled != null); 11735 PackageSetting disabledPs = null; 11736 // Confirm if the system package has been updated 11737 // An updated system app can be deleted. This will also have to restore 11738 // the system pkg from system partition 11739 // reader 11740 synchronized (mPackages) { 11741 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11742 } 11743 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11744 + " disabledPs=" + disabledPs); 11745 if (disabledPs == null) { 11746 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11747 return false; 11748 } else if (DEBUG_REMOVE) { 11749 Slog.d(TAG, "Deleting system pkg from data partition"); 11750 } 11751 if (DEBUG_REMOVE) { 11752 if (applyUserRestrictions) { 11753 Slog.d(TAG, "Remembering install states:"); 11754 for (int i = 0; i < allUserHandles.length; i++) { 11755 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11756 } 11757 } 11758 } 11759 // Delete the updated package 11760 outInfo.isRemovedPackageSystemUpdate = true; 11761 if (disabledPs.versionCode < newPs.versionCode) { 11762 // Delete data for downgrades 11763 flags &= ~PackageManager.DELETE_KEEP_DATA; 11764 } else { 11765 // Preserve data by setting flag 11766 flags |= PackageManager.DELETE_KEEP_DATA; 11767 } 11768 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11769 allUserHandles, perUserInstalled, outInfo, writeSettings); 11770 if (!ret) { 11771 return false; 11772 } 11773 // writer 11774 synchronized (mPackages) { 11775 // Reinstate the old system package 11776 mSettings.enableSystemPackageLPw(newPs.name); 11777 // Remove any native libraries from the upgraded package. 11778 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11779 } 11780 // Install the system package 11781 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11782 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11783 if (locationIsPrivileged(disabledPs.codePath)) { 11784 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11785 } 11786 11787 final PackageParser.Package newPkg; 11788 try { 11789 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11790 } catch (PackageManagerException e) { 11791 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11792 return false; 11793 } 11794 11795 // writer 11796 synchronized (mPackages) { 11797 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11798 updatePermissionsLPw(newPkg.packageName, newPkg, 11799 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11800 if (applyUserRestrictions) { 11801 if (DEBUG_REMOVE) { 11802 Slog.d(TAG, "Propagating install state across reinstall"); 11803 } 11804 for (int i = 0; i < allUserHandles.length; i++) { 11805 if (DEBUG_REMOVE) { 11806 Slog.d(TAG, " user " + allUserHandles[i] 11807 + " => " + perUserInstalled[i]); 11808 } 11809 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11810 } 11811 // Regardless of writeSettings we need to ensure that this restriction 11812 // state propagation is persisted 11813 mSettings.writeAllUsersPackageRestrictionsLPr(); 11814 } 11815 // can downgrade to reader here 11816 if (writeSettings) { 11817 mSettings.writeLPr(); 11818 } 11819 } 11820 return true; 11821 } 11822 11823 private boolean deleteInstalledPackageLI(PackageSetting ps, 11824 boolean deleteCodeAndResources, int flags, 11825 int[] allUserHandles, boolean[] perUserInstalled, 11826 PackageRemovedInfo outInfo, boolean writeSettings) { 11827 if (outInfo != null) { 11828 outInfo.uid = ps.appId; 11829 } 11830 11831 // Delete package data from internal structures and also remove data if flag is set 11832 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11833 11834 // Delete application code and resources 11835 if (deleteCodeAndResources && (outInfo != null)) { 11836 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11837 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11838 getAppDexInstructionSets(ps)); 11839 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11840 } 11841 return true; 11842 } 11843 11844 @Override 11845 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11846 int userId) { 11847 mContext.enforceCallingOrSelfPermission( 11848 android.Manifest.permission.DELETE_PACKAGES, null); 11849 synchronized (mPackages) { 11850 PackageSetting ps = mSettings.mPackages.get(packageName); 11851 if (ps == null) { 11852 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11853 return false; 11854 } 11855 if (!ps.getInstalled(userId)) { 11856 // Can't block uninstall for an app that is not installed or enabled. 11857 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11858 return false; 11859 } 11860 ps.setBlockUninstall(blockUninstall, userId); 11861 mSettings.writePackageRestrictionsLPr(userId); 11862 } 11863 return true; 11864 } 11865 11866 @Override 11867 public boolean getBlockUninstallForUser(String packageName, int userId) { 11868 synchronized (mPackages) { 11869 PackageSetting ps = mSettings.mPackages.get(packageName); 11870 if (ps == null) { 11871 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11872 return false; 11873 } 11874 return ps.getBlockUninstall(userId); 11875 } 11876 } 11877 11878 /* 11879 * This method handles package deletion in general 11880 */ 11881 private boolean deletePackageLI(String packageName, UserHandle user, 11882 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11883 int flags, PackageRemovedInfo outInfo, 11884 boolean writeSettings) { 11885 if (packageName == null) { 11886 Slog.w(TAG, "Attempt to delete null packageName."); 11887 return false; 11888 } 11889 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11890 PackageSetting ps; 11891 boolean dataOnly = false; 11892 int removeUser = -1; 11893 int appId = -1; 11894 synchronized (mPackages) { 11895 ps = mSettings.mPackages.get(packageName); 11896 if (ps == null) { 11897 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11898 return false; 11899 } 11900 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11901 && user.getIdentifier() != UserHandle.USER_ALL) { 11902 // The caller is asking that the package only be deleted for a single 11903 // user. To do this, we just mark its uninstalled state and delete 11904 // its data. If this is a system app, we only allow this to happen if 11905 // they have set the special DELETE_SYSTEM_APP which requests different 11906 // semantics than normal for uninstalling system apps. 11907 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11908 ps.setUserState(user.getIdentifier(), 11909 COMPONENT_ENABLED_STATE_DEFAULT, 11910 false, //installed 11911 true, //stopped 11912 true, //notLaunched 11913 false, //hidden 11914 null, null, null, 11915 false, // blockUninstall 11916 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11917 if (!isSystemApp(ps)) { 11918 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11919 // Other user still have this package installed, so all 11920 // we need to do is clear this user's data and save that 11921 // it is uninstalled. 11922 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11923 removeUser = user.getIdentifier(); 11924 appId = ps.appId; 11925 mSettings.writePackageRestrictionsLPr(removeUser); 11926 } else { 11927 // We need to set it back to 'installed' so the uninstall 11928 // broadcasts will be sent correctly. 11929 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11930 ps.setInstalled(true, user.getIdentifier()); 11931 } 11932 } else { 11933 // This is a system app, so we assume that the 11934 // other users still have this package installed, so all 11935 // we need to do is clear this user's data and save that 11936 // it is uninstalled. 11937 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11938 removeUser = user.getIdentifier(); 11939 appId = ps.appId; 11940 mSettings.writePackageRestrictionsLPr(removeUser); 11941 } 11942 } 11943 } 11944 11945 if (removeUser >= 0) { 11946 // From above, we determined that we are deleting this only 11947 // for a single user. Continue the work here. 11948 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11949 if (outInfo != null) { 11950 outInfo.removedPackage = packageName; 11951 outInfo.removedAppId = appId; 11952 outInfo.removedUsers = new int[] {removeUser}; 11953 } 11954 mInstaller.clearUserData(packageName, removeUser); 11955 removeKeystoreDataIfNeeded(removeUser, appId); 11956 schedulePackageCleaning(packageName, removeUser, false); 11957 return true; 11958 } 11959 11960 if (dataOnly) { 11961 // Delete application data first 11962 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11963 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11964 return true; 11965 } 11966 11967 boolean ret = false; 11968 if (isSystemApp(ps)) { 11969 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11970 // When an updated system application is deleted we delete the existing resources as well and 11971 // fall back to existing code in system partition 11972 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11973 flags, outInfo, writeSettings); 11974 } else { 11975 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11976 // Kill application pre-emptively especially for apps on sd. 11977 killApplication(packageName, ps.appId, "uninstall pkg"); 11978 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11979 allUserHandles, perUserInstalled, 11980 outInfo, writeSettings); 11981 } 11982 11983 return ret; 11984 } 11985 11986 private final class ClearStorageConnection implements ServiceConnection { 11987 IMediaContainerService mContainerService; 11988 11989 @Override 11990 public void onServiceConnected(ComponentName name, IBinder service) { 11991 synchronized (this) { 11992 mContainerService = IMediaContainerService.Stub.asInterface(service); 11993 notifyAll(); 11994 } 11995 } 11996 11997 @Override 11998 public void onServiceDisconnected(ComponentName name) { 11999 } 12000 } 12001 12002 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12003 final boolean mounted; 12004 if (Environment.isExternalStorageEmulated()) { 12005 mounted = true; 12006 } else { 12007 final String status = Environment.getExternalStorageState(); 12008 12009 mounted = status.equals(Environment.MEDIA_MOUNTED) 12010 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12011 } 12012 12013 if (!mounted) { 12014 return; 12015 } 12016 12017 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12018 int[] users; 12019 if (userId == UserHandle.USER_ALL) { 12020 users = sUserManager.getUserIds(); 12021 } else { 12022 users = new int[] { userId }; 12023 } 12024 final ClearStorageConnection conn = new ClearStorageConnection(); 12025 if (mContext.bindServiceAsUser( 12026 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12027 try { 12028 for (int curUser : users) { 12029 long timeout = SystemClock.uptimeMillis() + 5000; 12030 synchronized (conn) { 12031 long now = SystemClock.uptimeMillis(); 12032 while (conn.mContainerService == null && now < timeout) { 12033 try { 12034 conn.wait(timeout - now); 12035 } catch (InterruptedException e) { 12036 } 12037 } 12038 } 12039 if (conn.mContainerService == null) { 12040 return; 12041 } 12042 12043 final UserEnvironment userEnv = new UserEnvironment(curUser); 12044 clearDirectory(conn.mContainerService, 12045 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12046 if (allData) { 12047 clearDirectory(conn.mContainerService, 12048 userEnv.buildExternalStorageAppDataDirs(packageName)); 12049 clearDirectory(conn.mContainerService, 12050 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12051 } 12052 } 12053 } finally { 12054 mContext.unbindService(conn); 12055 } 12056 } 12057 } 12058 12059 @Override 12060 public void clearApplicationUserData(final String packageName, 12061 final IPackageDataObserver observer, final int userId) { 12062 mContext.enforceCallingOrSelfPermission( 12063 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12064 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12065 // Queue up an async operation since the package deletion may take a little while. 12066 mHandler.post(new Runnable() { 12067 public void run() { 12068 mHandler.removeCallbacks(this); 12069 final boolean succeeded; 12070 synchronized (mInstallLock) { 12071 succeeded = clearApplicationUserDataLI(packageName, userId); 12072 } 12073 clearExternalStorageDataSync(packageName, userId, true); 12074 if (succeeded) { 12075 // invoke DeviceStorageMonitor's update method to clear any notifications 12076 DeviceStorageMonitorInternal 12077 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12078 if (dsm != null) { 12079 dsm.checkMemory(); 12080 } 12081 } 12082 if(observer != null) { 12083 try { 12084 observer.onRemoveCompleted(packageName, succeeded); 12085 } catch (RemoteException e) { 12086 Log.i(TAG, "Observer no longer exists."); 12087 } 12088 } //end if observer 12089 } //end run 12090 }); 12091 } 12092 12093 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12094 if (packageName == null) { 12095 Slog.w(TAG, "Attempt to delete null packageName."); 12096 return false; 12097 } 12098 12099 // Try finding details about the requested package 12100 PackageParser.Package pkg; 12101 synchronized (mPackages) { 12102 pkg = mPackages.get(packageName); 12103 if (pkg == null) { 12104 final PackageSetting ps = mSettings.mPackages.get(packageName); 12105 if (ps != null) { 12106 pkg = ps.pkg; 12107 } 12108 } 12109 } 12110 12111 if (pkg == null) { 12112 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12113 } 12114 12115 // Always delete data directories for package, even if we found no other 12116 // record of app. This helps users recover from UID mismatches without 12117 // resorting to a full data wipe. 12118 int retCode = mInstaller.clearUserData(packageName, userId); 12119 if (retCode < 0) { 12120 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12121 return false; 12122 } 12123 12124 if (pkg == null) { 12125 return false; 12126 } 12127 12128 if (pkg != null && pkg.applicationInfo != null) { 12129 final int appId = pkg.applicationInfo.uid; 12130 removeKeystoreDataIfNeeded(userId, appId); 12131 } 12132 12133 // Create a native library symlink only if we have native libraries 12134 // and if the native libraries are 32 bit libraries. We do not provide 12135 // this symlink for 64 bit libraries. 12136 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12137 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12138 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12139 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12140 Slog.w(TAG, "Failed linking native library dir"); 12141 return false; 12142 } 12143 } 12144 12145 return true; 12146 } 12147 12148 /** 12149 * Remove entries from the keystore daemon. Will only remove it if the 12150 * {@code appId} is valid. 12151 */ 12152 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12153 if (appId < 0) { 12154 return; 12155 } 12156 12157 final KeyStore keyStore = KeyStore.getInstance(); 12158 if (keyStore != null) { 12159 if (userId == UserHandle.USER_ALL) { 12160 for (final int individual : sUserManager.getUserIds()) { 12161 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12162 } 12163 } else { 12164 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12165 } 12166 } else { 12167 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12168 } 12169 } 12170 12171 @Override 12172 public void deleteApplicationCacheFiles(final String packageName, 12173 final IPackageDataObserver observer) { 12174 mContext.enforceCallingOrSelfPermission( 12175 android.Manifest.permission.DELETE_CACHE_FILES, null); 12176 // Queue up an async operation since the package deletion may take a little while. 12177 final int userId = UserHandle.getCallingUserId(); 12178 mHandler.post(new Runnable() { 12179 public void run() { 12180 mHandler.removeCallbacks(this); 12181 final boolean succeded; 12182 synchronized (mInstallLock) { 12183 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12184 } 12185 clearExternalStorageDataSync(packageName, userId, false); 12186 if(observer != null) { 12187 try { 12188 observer.onRemoveCompleted(packageName, succeded); 12189 } catch (RemoteException e) { 12190 Log.i(TAG, "Observer no longer exists."); 12191 } 12192 } //end if observer 12193 } //end run 12194 }); 12195 } 12196 12197 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12198 if (packageName == null) { 12199 Slog.w(TAG, "Attempt to delete null packageName."); 12200 return false; 12201 } 12202 PackageParser.Package p; 12203 synchronized (mPackages) { 12204 p = mPackages.get(packageName); 12205 } 12206 if (p == null) { 12207 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12208 return false; 12209 } 12210 final ApplicationInfo applicationInfo = p.applicationInfo; 12211 if (applicationInfo == null) { 12212 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12213 return false; 12214 } 12215 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12216 if (retCode < 0) { 12217 Slog.w(TAG, "Couldn't remove cache files for package: " 12218 + packageName + " u" + userId); 12219 return false; 12220 } 12221 return true; 12222 } 12223 12224 @Override 12225 public void getPackageSizeInfo(final String packageName, int userHandle, 12226 final IPackageStatsObserver observer) { 12227 mContext.enforceCallingOrSelfPermission( 12228 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12229 if (packageName == null) { 12230 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12231 } 12232 12233 PackageStats stats = new PackageStats(packageName, userHandle); 12234 12235 /* 12236 * Queue up an async operation since the package measurement may take a 12237 * little while. 12238 */ 12239 Message msg = mHandler.obtainMessage(INIT_COPY); 12240 msg.obj = new MeasureParams(stats, observer); 12241 mHandler.sendMessage(msg); 12242 } 12243 12244 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12245 PackageStats pStats) { 12246 if (packageName == null) { 12247 Slog.w(TAG, "Attempt to get size of null packageName."); 12248 return false; 12249 } 12250 PackageParser.Package p; 12251 boolean dataOnly = false; 12252 String libDirRoot = null; 12253 String asecPath = null; 12254 PackageSetting ps = null; 12255 synchronized (mPackages) { 12256 p = mPackages.get(packageName); 12257 ps = mSettings.mPackages.get(packageName); 12258 if(p == null) { 12259 dataOnly = true; 12260 if((ps == null) || (ps.pkg == null)) { 12261 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12262 return false; 12263 } 12264 p = ps.pkg; 12265 } 12266 if (ps != null) { 12267 libDirRoot = ps.legacyNativeLibraryPathString; 12268 } 12269 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12270 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12271 if (secureContainerId != null) { 12272 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12273 } 12274 } 12275 } 12276 String publicSrcDir = null; 12277 if(!dataOnly) { 12278 final ApplicationInfo applicationInfo = p.applicationInfo; 12279 if (applicationInfo == null) { 12280 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12281 return false; 12282 } 12283 if (p.isForwardLocked()) { 12284 publicSrcDir = applicationInfo.getBaseResourcePath(); 12285 } 12286 } 12287 // TODO: extend to measure size of split APKs 12288 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12289 // not just the first level. 12290 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12291 // just the primary. 12292 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12293 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12294 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12295 if (res < 0) { 12296 return false; 12297 } 12298 12299 // Fix-up for forward-locked applications in ASEC containers. 12300 if (!isExternal(p)) { 12301 pStats.codeSize += pStats.externalCodeSize; 12302 pStats.externalCodeSize = 0L; 12303 } 12304 12305 return true; 12306 } 12307 12308 12309 @Override 12310 public void addPackageToPreferred(String packageName) { 12311 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12312 } 12313 12314 @Override 12315 public void removePackageFromPreferred(String packageName) { 12316 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12317 } 12318 12319 @Override 12320 public List<PackageInfo> getPreferredPackages(int flags) { 12321 return new ArrayList<PackageInfo>(); 12322 } 12323 12324 private int getUidTargetSdkVersionLockedLPr(int uid) { 12325 Object obj = mSettings.getUserIdLPr(uid); 12326 if (obj instanceof SharedUserSetting) { 12327 final SharedUserSetting sus = (SharedUserSetting) obj; 12328 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12329 final Iterator<PackageSetting> it = sus.packages.iterator(); 12330 while (it.hasNext()) { 12331 final PackageSetting ps = it.next(); 12332 if (ps.pkg != null) { 12333 int v = ps.pkg.applicationInfo.targetSdkVersion; 12334 if (v < vers) vers = v; 12335 } 12336 } 12337 return vers; 12338 } else if (obj instanceof PackageSetting) { 12339 final PackageSetting ps = (PackageSetting) obj; 12340 if (ps.pkg != null) { 12341 return ps.pkg.applicationInfo.targetSdkVersion; 12342 } 12343 } 12344 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12345 } 12346 12347 @Override 12348 public void addPreferredActivity(IntentFilter filter, int match, 12349 ComponentName[] set, ComponentName activity, int userId) { 12350 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12351 "Adding preferred"); 12352 } 12353 12354 private void addPreferredActivityInternal(IntentFilter filter, int match, 12355 ComponentName[] set, ComponentName activity, boolean always, int userId, 12356 String opname) { 12357 // writer 12358 int callingUid = Binder.getCallingUid(); 12359 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12360 if (filter.countActions() == 0) { 12361 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12362 return; 12363 } 12364 synchronized (mPackages) { 12365 if (mContext.checkCallingOrSelfPermission( 12366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12367 != PackageManager.PERMISSION_GRANTED) { 12368 if (getUidTargetSdkVersionLockedLPr(callingUid) 12369 < Build.VERSION_CODES.FROYO) { 12370 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12371 + callingUid); 12372 return; 12373 } 12374 mContext.enforceCallingOrSelfPermission( 12375 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12376 } 12377 12378 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12379 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12380 + userId + ":"); 12381 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12382 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12383 scheduleWritePackageRestrictionsLocked(userId); 12384 } 12385 } 12386 12387 @Override 12388 public void replacePreferredActivity(IntentFilter filter, int match, 12389 ComponentName[] set, ComponentName activity, int userId) { 12390 if (filter.countActions() != 1) { 12391 throw new IllegalArgumentException( 12392 "replacePreferredActivity expects filter to have only 1 action."); 12393 } 12394 if (filter.countDataAuthorities() != 0 12395 || filter.countDataPaths() != 0 12396 || filter.countDataSchemes() > 1 12397 || filter.countDataTypes() != 0) { 12398 throw new IllegalArgumentException( 12399 "replacePreferredActivity expects filter to have no data authorities, " + 12400 "paths, or types; and at most one scheme."); 12401 } 12402 12403 final int callingUid = Binder.getCallingUid(); 12404 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12405 synchronized (mPackages) { 12406 if (mContext.checkCallingOrSelfPermission( 12407 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12408 != PackageManager.PERMISSION_GRANTED) { 12409 if (getUidTargetSdkVersionLockedLPr(callingUid) 12410 < Build.VERSION_CODES.FROYO) { 12411 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12412 + Binder.getCallingUid()); 12413 return; 12414 } 12415 mContext.enforceCallingOrSelfPermission( 12416 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12417 } 12418 12419 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12420 if (pir != null) { 12421 // Get all of the existing entries that exactly match this filter. 12422 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12423 if (existing != null && existing.size() == 1) { 12424 PreferredActivity cur = existing.get(0); 12425 if (DEBUG_PREFERRED) { 12426 Slog.i(TAG, "Checking replace of preferred:"); 12427 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12428 if (!cur.mPref.mAlways) { 12429 Slog.i(TAG, " -- CUR; not mAlways!"); 12430 } else { 12431 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12432 Slog.i(TAG, " -- CUR: mSet=" 12433 + Arrays.toString(cur.mPref.mSetComponents)); 12434 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12435 Slog.i(TAG, " -- NEW: mMatch=" 12436 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12437 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12438 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12439 } 12440 } 12441 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12442 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12443 && cur.mPref.sameSet(set)) { 12444 // Setting the preferred activity to what it happens to be already 12445 if (DEBUG_PREFERRED) { 12446 Slog.i(TAG, "Replacing with same preferred activity " 12447 + cur.mPref.mShortComponent + " for user " 12448 + userId + ":"); 12449 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12450 } 12451 return; 12452 } 12453 } 12454 12455 if (existing != null) { 12456 if (DEBUG_PREFERRED) { 12457 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12458 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12459 } 12460 for (int i = 0; i < existing.size(); i++) { 12461 PreferredActivity pa = existing.get(i); 12462 if (DEBUG_PREFERRED) { 12463 Slog.i(TAG, "Removing existing preferred activity " 12464 + pa.mPref.mComponent + ":"); 12465 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12466 } 12467 pir.removeFilter(pa); 12468 } 12469 } 12470 } 12471 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12472 "Replacing preferred"); 12473 } 12474 } 12475 12476 @Override 12477 public void clearPackagePreferredActivities(String packageName) { 12478 final int uid = Binder.getCallingUid(); 12479 // writer 12480 synchronized (mPackages) { 12481 PackageParser.Package pkg = mPackages.get(packageName); 12482 if (pkg == null || pkg.applicationInfo.uid != uid) { 12483 if (mContext.checkCallingOrSelfPermission( 12484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12485 != PackageManager.PERMISSION_GRANTED) { 12486 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12487 < Build.VERSION_CODES.FROYO) { 12488 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12489 + Binder.getCallingUid()); 12490 return; 12491 } 12492 mContext.enforceCallingOrSelfPermission( 12493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12494 } 12495 } 12496 12497 int user = UserHandle.getCallingUserId(); 12498 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12499 scheduleWritePackageRestrictionsLocked(user); 12500 } 12501 } 12502 } 12503 12504 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12505 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12506 ArrayList<PreferredActivity> removed = null; 12507 boolean changed = false; 12508 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12509 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12510 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12511 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12512 continue; 12513 } 12514 Iterator<PreferredActivity> it = pir.filterIterator(); 12515 while (it.hasNext()) { 12516 PreferredActivity pa = it.next(); 12517 // Mark entry for removal only if it matches the package name 12518 // and the entry is of type "always". 12519 if (packageName == null || 12520 (pa.mPref.mComponent.getPackageName().equals(packageName) 12521 && pa.mPref.mAlways)) { 12522 if (removed == null) { 12523 removed = new ArrayList<PreferredActivity>(); 12524 } 12525 removed.add(pa); 12526 } 12527 } 12528 if (removed != null) { 12529 for (int j=0; j<removed.size(); j++) { 12530 PreferredActivity pa = removed.get(j); 12531 pir.removeFilter(pa); 12532 } 12533 changed = true; 12534 } 12535 } 12536 return changed; 12537 } 12538 12539 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12540 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12541 if (userId == UserHandle.USER_ALL) { 12542 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12543 for (int oneUserId : sUserManager.getUserIds()) { 12544 scheduleWritePackageRestrictionsLocked(oneUserId); 12545 } 12546 } else { 12547 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12548 scheduleWritePackageRestrictionsLocked(userId); 12549 } 12550 } 12551 12552 @Override 12553 public void resetPreferredActivities(int userId) { 12554 /* TODO: Actually use userId. Why is it being passed in? */ 12555 mContext.enforceCallingOrSelfPermission( 12556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12557 // writer 12558 synchronized (mPackages) { 12559 int user = UserHandle.getCallingUserId(); 12560 clearPackagePreferredActivitiesLPw(null, user); 12561 mSettings.readDefaultPreferredAppsLPw(this, user); 12562 scheduleWritePackageRestrictionsLocked(user); 12563 } 12564 } 12565 12566 @Override 12567 public int getPreferredActivities(List<IntentFilter> outFilters, 12568 List<ComponentName> outActivities, String packageName) { 12569 12570 int num = 0; 12571 final int userId = UserHandle.getCallingUserId(); 12572 // reader 12573 synchronized (mPackages) { 12574 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12575 if (pir != null) { 12576 final Iterator<PreferredActivity> it = pir.filterIterator(); 12577 while (it.hasNext()) { 12578 final PreferredActivity pa = it.next(); 12579 if (packageName == null 12580 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12581 && pa.mPref.mAlways)) { 12582 if (outFilters != null) { 12583 outFilters.add(new IntentFilter(pa)); 12584 } 12585 if (outActivities != null) { 12586 outActivities.add(pa.mPref.mComponent); 12587 } 12588 } 12589 } 12590 } 12591 } 12592 12593 return num; 12594 } 12595 12596 @Override 12597 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12598 int userId) { 12599 int callingUid = Binder.getCallingUid(); 12600 if (callingUid != Process.SYSTEM_UID) { 12601 throw new SecurityException( 12602 "addPersistentPreferredActivity can only be run by the system"); 12603 } 12604 if (filter.countActions() == 0) { 12605 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12606 return; 12607 } 12608 synchronized (mPackages) { 12609 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12610 " :"); 12611 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12612 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12613 new PersistentPreferredActivity(filter, activity)); 12614 scheduleWritePackageRestrictionsLocked(userId); 12615 } 12616 } 12617 12618 @Override 12619 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12620 int callingUid = Binder.getCallingUid(); 12621 if (callingUid != Process.SYSTEM_UID) { 12622 throw new SecurityException( 12623 "clearPackagePersistentPreferredActivities can only be run by the system"); 12624 } 12625 ArrayList<PersistentPreferredActivity> removed = null; 12626 boolean changed = false; 12627 synchronized (mPackages) { 12628 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12629 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12630 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12631 .valueAt(i); 12632 if (userId != thisUserId) { 12633 continue; 12634 } 12635 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12636 while (it.hasNext()) { 12637 PersistentPreferredActivity ppa = it.next(); 12638 // Mark entry for removal only if it matches the package name. 12639 if (ppa.mComponent.getPackageName().equals(packageName)) { 12640 if (removed == null) { 12641 removed = new ArrayList<PersistentPreferredActivity>(); 12642 } 12643 removed.add(ppa); 12644 } 12645 } 12646 if (removed != null) { 12647 for (int j=0; j<removed.size(); j++) { 12648 PersistentPreferredActivity ppa = removed.get(j); 12649 ppir.removeFilter(ppa); 12650 } 12651 changed = true; 12652 } 12653 } 12654 12655 if (changed) { 12656 scheduleWritePackageRestrictionsLocked(userId); 12657 } 12658 } 12659 } 12660 12661 /** 12662 * Non-Binder method, support for the backup/restore mechanism: write the 12663 * full set of preferred activities in its canonical XML format. Returns true 12664 * on success; false otherwise. 12665 */ 12666 @Override 12667 public byte[] getPreferredActivityBackup(int userId) { 12668 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12669 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12670 } 12671 12672 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12673 try { 12674 final XmlSerializer serializer = new FastXmlSerializer(); 12675 serializer.setOutput(dataStream, "utf-8"); 12676 serializer.startDocument(null, true); 12677 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12678 12679 synchronized (mPackages) { 12680 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12681 } 12682 12683 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12684 serializer.endDocument(); 12685 serializer.flush(); 12686 } catch (Exception e) { 12687 if (DEBUG_BACKUP) { 12688 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12689 } 12690 return null; 12691 } 12692 12693 return dataStream.toByteArray(); 12694 } 12695 12696 @Override 12697 public void restorePreferredActivities(byte[] backup, int userId) { 12698 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12699 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12700 } 12701 12702 try { 12703 final XmlPullParser parser = Xml.newPullParser(); 12704 parser.setInput(new ByteArrayInputStream(backup), null); 12705 12706 int type; 12707 while ((type = parser.next()) != XmlPullParser.START_TAG 12708 && type != XmlPullParser.END_DOCUMENT) { 12709 } 12710 if (type != XmlPullParser.START_TAG) { 12711 // oops didn't find a start tag?! 12712 if (DEBUG_BACKUP) { 12713 Slog.e(TAG, "Didn't find start tag during restore"); 12714 } 12715 return; 12716 } 12717 12718 // this is supposed to be TAG_PREFERRED_BACKUP 12719 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12720 if (DEBUG_BACKUP) { 12721 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12722 } 12723 return; 12724 } 12725 12726 // skip interfering stuff, then we're aligned with the backing implementation 12727 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12728 synchronized (mPackages) { 12729 mSettings.readPreferredActivitiesLPw(parser, userId); 12730 } 12731 } catch (Exception e) { 12732 if (DEBUG_BACKUP) { 12733 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12734 } 12735 } 12736 } 12737 12738 @Override 12739 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12740 int sourceUserId, int targetUserId, int flags) { 12741 mContext.enforceCallingOrSelfPermission( 12742 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12743 int callingUid = Binder.getCallingUid(); 12744 enforceOwnerRights(ownerPackage, callingUid); 12745 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12746 if (intentFilter.countActions() == 0) { 12747 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12748 return; 12749 } 12750 synchronized (mPackages) { 12751 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12752 ownerPackage, targetUserId, flags); 12753 CrossProfileIntentResolver resolver = 12754 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12755 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12756 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12757 if (existing != null) { 12758 int size = existing.size(); 12759 for (int i = 0; i < size; i++) { 12760 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12761 return; 12762 } 12763 } 12764 } 12765 resolver.addFilter(newFilter); 12766 scheduleWritePackageRestrictionsLocked(sourceUserId); 12767 } 12768 } 12769 12770 @Override 12771 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12772 mContext.enforceCallingOrSelfPermission( 12773 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12774 int callingUid = Binder.getCallingUid(); 12775 enforceOwnerRights(ownerPackage, callingUid); 12776 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12777 synchronized (mPackages) { 12778 CrossProfileIntentResolver resolver = 12779 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12780 ArraySet<CrossProfileIntentFilter> set = 12781 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12782 for (CrossProfileIntentFilter filter : set) { 12783 if (filter.getOwnerPackage().equals(ownerPackage)) { 12784 resolver.removeFilter(filter); 12785 } 12786 } 12787 scheduleWritePackageRestrictionsLocked(sourceUserId); 12788 } 12789 } 12790 12791 // Enforcing that callingUid is owning pkg on userId 12792 private void enforceOwnerRights(String pkg, int callingUid) { 12793 // The system owns everything. 12794 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12795 return; 12796 } 12797 int callingUserId = UserHandle.getUserId(callingUid); 12798 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12799 if (pi == null) { 12800 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12801 + callingUserId); 12802 } 12803 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12804 throw new SecurityException("Calling uid " + callingUid 12805 + " does not own package " + pkg); 12806 } 12807 } 12808 12809 @Override 12810 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12811 Intent intent = new Intent(Intent.ACTION_MAIN); 12812 intent.addCategory(Intent.CATEGORY_HOME); 12813 12814 final int callingUserId = UserHandle.getCallingUserId(); 12815 List<ResolveInfo> list = queryIntentActivities(intent, null, 12816 PackageManager.GET_META_DATA, callingUserId); 12817 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12818 true, false, false, callingUserId); 12819 12820 allHomeCandidates.clear(); 12821 if (list != null) { 12822 for (ResolveInfo ri : list) { 12823 allHomeCandidates.add(ri); 12824 } 12825 } 12826 return (preferred == null || preferred.activityInfo == null) 12827 ? null 12828 : new ComponentName(preferred.activityInfo.packageName, 12829 preferred.activityInfo.name); 12830 } 12831 12832 @Override 12833 public void setApplicationEnabledSetting(String appPackageName, 12834 int newState, int flags, int userId, String callingPackage) { 12835 if (!sUserManager.exists(userId)) return; 12836 if (callingPackage == null) { 12837 callingPackage = Integer.toString(Binder.getCallingUid()); 12838 } 12839 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12840 } 12841 12842 @Override 12843 public void setComponentEnabledSetting(ComponentName componentName, 12844 int newState, int flags, int userId) { 12845 if (!sUserManager.exists(userId)) return; 12846 setEnabledSetting(componentName.getPackageName(), 12847 componentName.getClassName(), newState, flags, userId, null); 12848 } 12849 12850 private void setEnabledSetting(final String packageName, String className, int newState, 12851 final int flags, int userId, String callingPackage) { 12852 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12853 || newState == COMPONENT_ENABLED_STATE_ENABLED 12854 || newState == COMPONENT_ENABLED_STATE_DISABLED 12855 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12856 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12857 throw new IllegalArgumentException("Invalid new component state: " 12858 + newState); 12859 } 12860 PackageSetting pkgSetting; 12861 final int uid = Binder.getCallingUid(); 12862 final int permission = mContext.checkCallingOrSelfPermission( 12863 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12864 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12865 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12866 boolean sendNow = false; 12867 boolean isApp = (className == null); 12868 String componentName = isApp ? packageName : className; 12869 int packageUid = -1; 12870 ArrayList<String> components; 12871 12872 // writer 12873 synchronized (mPackages) { 12874 pkgSetting = mSettings.mPackages.get(packageName); 12875 if (pkgSetting == null) { 12876 if (className == null) { 12877 throw new IllegalArgumentException( 12878 "Unknown package: " + packageName); 12879 } 12880 throw new IllegalArgumentException( 12881 "Unknown component: " + packageName 12882 + "/" + className); 12883 } 12884 // Allow root and verify that userId is not being specified by a different user 12885 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12886 throw new SecurityException( 12887 "Permission Denial: attempt to change component state from pid=" 12888 + Binder.getCallingPid() 12889 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12890 } 12891 if (className == null) { 12892 // We're dealing with an application/package level state change 12893 if (pkgSetting.getEnabled(userId) == newState) { 12894 // Nothing to do 12895 return; 12896 } 12897 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12898 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12899 // Don't care about who enables an app. 12900 callingPackage = null; 12901 } 12902 pkgSetting.setEnabled(newState, userId, callingPackage); 12903 // pkgSetting.pkg.mSetEnabled = newState; 12904 } else { 12905 // We're dealing with a component level state change 12906 // First, verify that this is a valid class name. 12907 PackageParser.Package pkg = pkgSetting.pkg; 12908 if (pkg == null || !pkg.hasComponentClassName(className)) { 12909 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12910 throw new IllegalArgumentException("Component class " + className 12911 + " does not exist in " + packageName); 12912 } else { 12913 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12914 + className + " does not exist in " + packageName); 12915 } 12916 } 12917 switch (newState) { 12918 case COMPONENT_ENABLED_STATE_ENABLED: 12919 if (!pkgSetting.enableComponentLPw(className, userId)) { 12920 return; 12921 } 12922 break; 12923 case COMPONENT_ENABLED_STATE_DISABLED: 12924 if (!pkgSetting.disableComponentLPw(className, userId)) { 12925 return; 12926 } 12927 break; 12928 case COMPONENT_ENABLED_STATE_DEFAULT: 12929 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12930 return; 12931 } 12932 break; 12933 default: 12934 Slog.e(TAG, "Invalid new component state: " + newState); 12935 return; 12936 } 12937 } 12938 scheduleWritePackageRestrictionsLocked(userId); 12939 components = mPendingBroadcasts.get(userId, packageName); 12940 final boolean newPackage = components == null; 12941 if (newPackage) { 12942 components = new ArrayList<String>(); 12943 } 12944 if (!components.contains(componentName)) { 12945 components.add(componentName); 12946 } 12947 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12948 sendNow = true; 12949 // Purge entry from pending broadcast list if another one exists already 12950 // since we are sending one right away. 12951 mPendingBroadcasts.remove(userId, packageName); 12952 } else { 12953 if (newPackage) { 12954 mPendingBroadcasts.put(userId, packageName, components); 12955 } 12956 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12957 // Schedule a message 12958 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12959 } 12960 } 12961 } 12962 12963 long callingId = Binder.clearCallingIdentity(); 12964 try { 12965 if (sendNow) { 12966 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12967 sendPackageChangedBroadcast(packageName, 12968 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12969 } 12970 } finally { 12971 Binder.restoreCallingIdentity(callingId); 12972 } 12973 } 12974 12975 private void sendPackageChangedBroadcast(String packageName, 12976 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12977 if (DEBUG_INSTALL) 12978 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12979 + componentNames); 12980 Bundle extras = new Bundle(4); 12981 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12982 String nameList[] = new String[componentNames.size()]; 12983 componentNames.toArray(nameList); 12984 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12985 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12986 extras.putInt(Intent.EXTRA_UID, packageUid); 12987 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12988 new int[] {UserHandle.getUserId(packageUid)}); 12989 } 12990 12991 @Override 12992 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12993 if (!sUserManager.exists(userId)) return; 12994 final int uid = Binder.getCallingUid(); 12995 final int permission = mContext.checkCallingOrSelfPermission( 12996 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12997 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12998 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12999 // writer 13000 synchronized (mPackages) { 13001 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13002 uid, userId)) { 13003 scheduleWritePackageRestrictionsLocked(userId); 13004 } 13005 } 13006 } 13007 13008 @Override 13009 public String getInstallerPackageName(String packageName) { 13010 // reader 13011 synchronized (mPackages) { 13012 return mSettings.getInstallerPackageNameLPr(packageName); 13013 } 13014 } 13015 13016 @Override 13017 public int getApplicationEnabledSetting(String packageName, int userId) { 13018 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13019 int uid = Binder.getCallingUid(); 13020 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13021 // reader 13022 synchronized (mPackages) { 13023 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13024 } 13025 } 13026 13027 @Override 13028 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13029 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13030 int uid = Binder.getCallingUid(); 13031 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13032 // reader 13033 synchronized (mPackages) { 13034 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13035 } 13036 } 13037 13038 @Override 13039 public void enterSafeMode() { 13040 enforceSystemOrRoot("Only the system can request entering safe mode"); 13041 13042 if (!mSystemReady) { 13043 mSafeMode = true; 13044 } 13045 } 13046 13047 @Override 13048 public void systemReady() { 13049 mSystemReady = true; 13050 13051 // Read the compatibilty setting when the system is ready. 13052 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13053 mContext.getContentResolver(), 13054 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13055 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13056 if (DEBUG_SETTINGS) { 13057 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13058 } 13059 13060 synchronized (mPackages) { 13061 // Verify that all of the preferred activity components actually 13062 // exist. It is possible for applications to be updated and at 13063 // that point remove a previously declared activity component that 13064 // had been set as a preferred activity. We try to clean this up 13065 // the next time we encounter that preferred activity, but it is 13066 // possible for the user flow to never be able to return to that 13067 // situation so here we do a sanity check to make sure we haven't 13068 // left any junk around. 13069 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13070 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13071 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13072 removed.clear(); 13073 for (PreferredActivity pa : pir.filterSet()) { 13074 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13075 removed.add(pa); 13076 } 13077 } 13078 if (removed.size() > 0) { 13079 for (int r=0; r<removed.size(); r++) { 13080 PreferredActivity pa = removed.get(r); 13081 Slog.w(TAG, "Removing dangling preferred activity: " 13082 + pa.mPref.mComponent); 13083 pir.removeFilter(pa); 13084 } 13085 mSettings.writePackageRestrictionsLPr( 13086 mSettings.mPreferredActivities.keyAt(i)); 13087 } 13088 } 13089 } 13090 sUserManager.systemReady(); 13091 13092 // Kick off any messages waiting for system ready 13093 if (mPostSystemReadyMessages != null) { 13094 for (Message msg : mPostSystemReadyMessages) { 13095 msg.sendToTarget(); 13096 } 13097 mPostSystemReadyMessages = null; 13098 } 13099 13100 // Watch for external volumes that come and go over time 13101 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13102 storage.registerListener(mStorageListener); 13103 13104 mInstallerService.systemReady(); 13105 } 13106 13107 @Override 13108 public boolean isSafeMode() { 13109 return mSafeMode; 13110 } 13111 13112 @Override 13113 public boolean hasSystemUidErrors() { 13114 return mHasSystemUidErrors; 13115 } 13116 13117 static String arrayToString(int[] array) { 13118 StringBuffer buf = new StringBuffer(128); 13119 buf.append('['); 13120 if (array != null) { 13121 for (int i=0; i<array.length; i++) { 13122 if (i > 0) buf.append(", "); 13123 buf.append(array[i]); 13124 } 13125 } 13126 buf.append(']'); 13127 return buf.toString(); 13128 } 13129 13130 static class DumpState { 13131 public static final int DUMP_LIBS = 1 << 0; 13132 public static final int DUMP_FEATURES = 1 << 1; 13133 public static final int DUMP_RESOLVERS = 1 << 2; 13134 public static final int DUMP_PERMISSIONS = 1 << 3; 13135 public static final int DUMP_PACKAGES = 1 << 4; 13136 public static final int DUMP_SHARED_USERS = 1 << 5; 13137 public static final int DUMP_MESSAGES = 1 << 6; 13138 public static final int DUMP_PROVIDERS = 1 << 7; 13139 public static final int DUMP_VERIFIERS = 1 << 8; 13140 public static final int DUMP_PREFERRED = 1 << 9; 13141 public static final int DUMP_PREFERRED_XML = 1 << 10; 13142 public static final int DUMP_KEYSETS = 1 << 11; 13143 public static final int DUMP_VERSION = 1 << 12; 13144 public static final int DUMP_INSTALLS = 1 << 13; 13145 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13146 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13147 13148 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13149 13150 private int mTypes; 13151 13152 private int mOptions; 13153 13154 private boolean mTitlePrinted; 13155 13156 private SharedUserSetting mSharedUser; 13157 13158 public boolean isDumping(int type) { 13159 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13160 return true; 13161 } 13162 13163 return (mTypes & type) != 0; 13164 } 13165 13166 public void setDump(int type) { 13167 mTypes |= type; 13168 } 13169 13170 public boolean isOptionEnabled(int option) { 13171 return (mOptions & option) != 0; 13172 } 13173 13174 public void setOptionEnabled(int option) { 13175 mOptions |= option; 13176 } 13177 13178 public boolean onTitlePrinted() { 13179 final boolean printed = mTitlePrinted; 13180 mTitlePrinted = true; 13181 return printed; 13182 } 13183 13184 public boolean getTitlePrinted() { 13185 return mTitlePrinted; 13186 } 13187 13188 public void setTitlePrinted(boolean enabled) { 13189 mTitlePrinted = enabled; 13190 } 13191 13192 public SharedUserSetting getSharedUser() { 13193 return mSharedUser; 13194 } 13195 13196 public void setSharedUser(SharedUserSetting user) { 13197 mSharedUser = user; 13198 } 13199 } 13200 13201 @Override 13202 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13203 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13204 != PackageManager.PERMISSION_GRANTED) { 13205 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13206 + Binder.getCallingPid() 13207 + ", uid=" + Binder.getCallingUid() 13208 + " without permission " 13209 + android.Manifest.permission.DUMP); 13210 return; 13211 } 13212 13213 DumpState dumpState = new DumpState(); 13214 boolean fullPreferred = false; 13215 boolean checkin = false; 13216 13217 String packageName = null; 13218 13219 int opti = 0; 13220 while (opti < args.length) { 13221 String opt = args[opti]; 13222 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13223 break; 13224 } 13225 opti++; 13226 13227 if ("-a".equals(opt)) { 13228 // Right now we only know how to print all. 13229 } else if ("-h".equals(opt)) { 13230 pw.println("Package manager dump options:"); 13231 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13232 pw.println(" --checkin: dump for a checkin"); 13233 pw.println(" -f: print details of intent filters"); 13234 pw.println(" -h: print this help"); 13235 pw.println(" cmd may be one of:"); 13236 pw.println(" l[ibraries]: list known shared libraries"); 13237 pw.println(" f[ibraries]: list device features"); 13238 pw.println(" k[eysets]: print known keysets"); 13239 pw.println(" r[esolvers]: dump intent resolvers"); 13240 pw.println(" perm[issions]: dump permissions"); 13241 pw.println(" pref[erred]: print preferred package settings"); 13242 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13243 pw.println(" prov[iders]: dump content providers"); 13244 pw.println(" p[ackages]: dump installed packages"); 13245 pw.println(" s[hared-users]: dump shared user IDs"); 13246 pw.println(" m[essages]: print collected runtime messages"); 13247 pw.println(" v[erifiers]: print package verifier info"); 13248 pw.println(" version: print database version info"); 13249 pw.println(" write: write current settings now"); 13250 pw.println(" <package.name>: info about given package"); 13251 pw.println(" installs: details about install sessions"); 13252 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13253 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13254 return; 13255 } else if ("--checkin".equals(opt)) { 13256 checkin = true; 13257 } else if ("-f".equals(opt)) { 13258 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13259 } else { 13260 pw.println("Unknown argument: " + opt + "; use -h for help"); 13261 } 13262 } 13263 13264 // Is the caller requesting to dump a particular piece of data? 13265 if (opti < args.length) { 13266 String cmd = args[opti]; 13267 opti++; 13268 // Is this a package name? 13269 if ("android".equals(cmd) || cmd.contains(".")) { 13270 packageName = cmd; 13271 // When dumping a single package, we always dump all of its 13272 // filter information since the amount of data will be reasonable. 13273 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13274 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13275 dumpState.setDump(DumpState.DUMP_LIBS); 13276 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13277 dumpState.setDump(DumpState.DUMP_FEATURES); 13278 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13279 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13280 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13281 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13282 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13283 dumpState.setDump(DumpState.DUMP_PREFERRED); 13284 } else if ("preferred-xml".equals(cmd)) { 13285 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13286 if (opti < args.length && "--full".equals(args[opti])) { 13287 fullPreferred = true; 13288 opti++; 13289 } 13290 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13291 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13292 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13293 dumpState.setDump(DumpState.DUMP_PACKAGES); 13294 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13295 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13296 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13297 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13298 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13299 dumpState.setDump(DumpState.DUMP_MESSAGES); 13300 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13301 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13302 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13303 || "intent-filter-verifiers".equals(cmd)) { 13304 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13305 } else if ("version".equals(cmd)) { 13306 dumpState.setDump(DumpState.DUMP_VERSION); 13307 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13308 dumpState.setDump(DumpState.DUMP_KEYSETS); 13309 } else if ("installs".equals(cmd)) { 13310 dumpState.setDump(DumpState.DUMP_INSTALLS); 13311 } else if ("write".equals(cmd)) { 13312 synchronized (mPackages) { 13313 mSettings.writeLPr(); 13314 pw.println("Settings written."); 13315 return; 13316 } 13317 } 13318 } 13319 13320 if (checkin) { 13321 pw.println("vers,1"); 13322 } 13323 13324 // reader 13325 synchronized (mPackages) { 13326 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13327 if (!checkin) { 13328 if (dumpState.onTitlePrinted()) 13329 pw.println(); 13330 pw.println("Database versions:"); 13331 pw.print(" SDK Version:"); 13332 pw.print(" internal="); 13333 pw.print(mSettings.mInternalSdkPlatform); 13334 pw.print(" external="); 13335 pw.println(mSettings.mExternalSdkPlatform); 13336 pw.print(" DB Version:"); 13337 pw.print(" internal="); 13338 pw.print(mSettings.mInternalDatabaseVersion); 13339 pw.print(" external="); 13340 pw.println(mSettings.mExternalDatabaseVersion); 13341 } 13342 } 13343 13344 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13345 if (!checkin) { 13346 if (dumpState.onTitlePrinted()) 13347 pw.println(); 13348 pw.println("Verifiers:"); 13349 pw.print(" Required: "); 13350 pw.print(mRequiredVerifierPackage); 13351 pw.print(" (uid="); 13352 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13353 pw.println(")"); 13354 } else if (mRequiredVerifierPackage != null) { 13355 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13356 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13357 } 13358 } 13359 13360 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13361 packageName == null) { 13362 if (mIntentFilterVerifierComponent != null) { 13363 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13364 if (!checkin) { 13365 if (dumpState.onTitlePrinted()) 13366 pw.println(); 13367 pw.println("Intent Filter Verifier:"); 13368 pw.print(" Using: "); 13369 pw.print(verifierPackageName); 13370 pw.print(" (uid="); 13371 pw.print(getPackageUid(verifierPackageName, 0)); 13372 pw.println(")"); 13373 } else if (verifierPackageName != null) { 13374 pw.print("ifv,"); pw.print(verifierPackageName); 13375 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13376 } 13377 } else { 13378 pw.println(); 13379 pw.println("No Intent Filter Verifier available!"); 13380 } 13381 } 13382 13383 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13384 boolean printedHeader = false; 13385 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13386 while (it.hasNext()) { 13387 String name = it.next(); 13388 SharedLibraryEntry ent = mSharedLibraries.get(name); 13389 if (!checkin) { 13390 if (!printedHeader) { 13391 if (dumpState.onTitlePrinted()) 13392 pw.println(); 13393 pw.println("Libraries:"); 13394 printedHeader = true; 13395 } 13396 pw.print(" "); 13397 } else { 13398 pw.print("lib,"); 13399 } 13400 pw.print(name); 13401 if (!checkin) { 13402 pw.print(" -> "); 13403 } 13404 if (ent.path != null) { 13405 if (!checkin) { 13406 pw.print("(jar) "); 13407 pw.print(ent.path); 13408 } else { 13409 pw.print(",jar,"); 13410 pw.print(ent.path); 13411 } 13412 } else { 13413 if (!checkin) { 13414 pw.print("(apk) "); 13415 pw.print(ent.apk); 13416 } else { 13417 pw.print(",apk,"); 13418 pw.print(ent.apk); 13419 } 13420 } 13421 pw.println(); 13422 } 13423 } 13424 13425 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13426 if (dumpState.onTitlePrinted()) 13427 pw.println(); 13428 if (!checkin) { 13429 pw.println("Features:"); 13430 } 13431 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13432 while (it.hasNext()) { 13433 String name = it.next(); 13434 if (!checkin) { 13435 pw.print(" "); 13436 } else { 13437 pw.print("feat,"); 13438 } 13439 pw.println(name); 13440 } 13441 } 13442 13443 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13444 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13445 : "Activity Resolver Table:", " ", packageName, 13446 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13447 dumpState.setTitlePrinted(true); 13448 } 13449 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13450 : "Receiver Resolver Table:", " ", packageName, 13451 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13452 dumpState.setTitlePrinted(true); 13453 } 13454 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13455 : "Service Resolver Table:", " ", packageName, 13456 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13457 dumpState.setTitlePrinted(true); 13458 } 13459 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13460 : "Provider Resolver Table:", " ", packageName, 13461 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13462 dumpState.setTitlePrinted(true); 13463 } 13464 } 13465 13466 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13467 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13468 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13469 int user = mSettings.mPreferredActivities.keyAt(i); 13470 if (pir.dump(pw, 13471 dumpState.getTitlePrinted() 13472 ? "\nPreferred Activities User " + user + ":" 13473 : "Preferred Activities User " + user + ":", " ", 13474 packageName, true, false)) { 13475 dumpState.setTitlePrinted(true); 13476 } 13477 } 13478 } 13479 13480 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13481 pw.flush(); 13482 FileOutputStream fout = new FileOutputStream(fd); 13483 BufferedOutputStream str = new BufferedOutputStream(fout); 13484 XmlSerializer serializer = new FastXmlSerializer(); 13485 try { 13486 serializer.setOutput(str, "utf-8"); 13487 serializer.startDocument(null, true); 13488 serializer.setFeature( 13489 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13490 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13491 serializer.endDocument(); 13492 serializer.flush(); 13493 } catch (IllegalArgumentException e) { 13494 pw.println("Failed writing: " + e); 13495 } catch (IllegalStateException e) { 13496 pw.println("Failed writing: " + e); 13497 } catch (IOException e) { 13498 pw.println("Failed writing: " + e); 13499 } 13500 } 13501 13502 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13503 pw.println(); 13504 int count = mSettings.mPackages.size(); 13505 if (count == 0) { 13506 pw.println("No domain preferred apps!"); 13507 pw.println(); 13508 } else { 13509 final String prefix = " "; 13510 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13511 if (allPackageSettings.size() == 0) { 13512 pw.println("No domain preferred apps!"); 13513 pw.println(); 13514 } else { 13515 pw.println("Domain preferred apps status:"); 13516 pw.println(); 13517 count = 0; 13518 for (PackageSetting ps : allPackageSettings) { 13519 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13520 if (ivi == null || ivi.getPackageName() == null) continue; 13521 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13522 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13523 pw.println(prefix + "Status: " + ivi.getStatusString()); 13524 pw.println(); 13525 count++; 13526 } 13527 if (count == 0) { 13528 pw.println(prefix + "No domain preferred app status!"); 13529 pw.println(); 13530 } 13531 for (int userId : sUserManager.getUserIds()) { 13532 pw.println("Domain preferred apps for User " + userId + ":"); 13533 pw.println(); 13534 count = 0; 13535 for (PackageSetting ps : allPackageSettings) { 13536 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13537 if (ivi == null || ivi.getPackageName() == null) { 13538 continue; 13539 } 13540 final int status = ps.getDomainVerificationStatusForUser(userId); 13541 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13542 continue; 13543 } 13544 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13545 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13546 String statusStr = IntentFilterVerificationInfo. 13547 getStatusStringFromValue(status); 13548 pw.println(prefix + "Status: " + statusStr); 13549 pw.println(); 13550 count++; 13551 } 13552 if (count == 0) { 13553 pw.println(prefix + "No domain preferred apps!"); 13554 pw.println(); 13555 } 13556 } 13557 } 13558 } 13559 } 13560 13561 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13562 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13563 if (packageName == null) { 13564 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13565 if (iperm == 0) { 13566 if (dumpState.onTitlePrinted()) 13567 pw.println(); 13568 pw.println("AppOp Permissions:"); 13569 } 13570 pw.print(" AppOp Permission "); 13571 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13572 pw.println(":"); 13573 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13574 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13575 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13576 } 13577 } 13578 } 13579 } 13580 13581 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13582 boolean printedSomething = false; 13583 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13584 if (packageName != null && !packageName.equals(p.info.packageName)) { 13585 continue; 13586 } 13587 if (!printedSomething) { 13588 if (dumpState.onTitlePrinted()) 13589 pw.println(); 13590 pw.println("Registered ContentProviders:"); 13591 printedSomething = true; 13592 } 13593 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13594 pw.print(" "); pw.println(p.toString()); 13595 } 13596 printedSomething = false; 13597 for (Map.Entry<String, PackageParser.Provider> entry : 13598 mProvidersByAuthority.entrySet()) { 13599 PackageParser.Provider p = entry.getValue(); 13600 if (packageName != null && !packageName.equals(p.info.packageName)) { 13601 continue; 13602 } 13603 if (!printedSomething) { 13604 if (dumpState.onTitlePrinted()) 13605 pw.println(); 13606 pw.println("ContentProvider Authorities:"); 13607 printedSomething = true; 13608 } 13609 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13610 pw.print(" "); pw.println(p.toString()); 13611 if (p.info != null && p.info.applicationInfo != null) { 13612 final String appInfo = p.info.applicationInfo.toString(); 13613 pw.print(" applicationInfo="); pw.println(appInfo); 13614 } 13615 } 13616 } 13617 13618 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13619 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13620 } 13621 13622 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13623 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13624 } 13625 13626 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13627 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13628 } 13629 13630 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13631 // XXX should handle packageName != null by dumping only install data that 13632 // the given package is involved with. 13633 if (dumpState.onTitlePrinted()) pw.println(); 13634 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13635 } 13636 13637 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13638 if (dumpState.onTitlePrinted()) pw.println(); 13639 mSettings.dumpReadMessagesLPr(pw, dumpState); 13640 13641 pw.println(); 13642 pw.println("Package warning messages:"); 13643 BufferedReader in = null; 13644 String line = null; 13645 try { 13646 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13647 while ((line = in.readLine()) != null) { 13648 if (line.contains("ignored: updated version")) continue; 13649 pw.println(line); 13650 } 13651 } catch (IOException ignored) { 13652 } finally { 13653 IoUtils.closeQuietly(in); 13654 } 13655 } 13656 13657 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13658 BufferedReader in = null; 13659 String line = null; 13660 try { 13661 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13662 while ((line = in.readLine()) != null) { 13663 if (line.contains("ignored: updated version")) continue; 13664 pw.print("msg,"); 13665 pw.println(line); 13666 } 13667 } catch (IOException ignored) { 13668 } finally { 13669 IoUtils.closeQuietly(in); 13670 } 13671 } 13672 } 13673 } 13674 13675 // ------- apps on sdcard specific code ------- 13676 static final boolean DEBUG_SD_INSTALL = false; 13677 13678 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13679 13680 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13681 13682 private boolean mMediaMounted = false; 13683 13684 static String getEncryptKey() { 13685 try { 13686 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13687 SD_ENCRYPTION_KEYSTORE_NAME); 13688 if (sdEncKey == null) { 13689 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13690 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13691 if (sdEncKey == null) { 13692 Slog.e(TAG, "Failed to create encryption keys"); 13693 return null; 13694 } 13695 } 13696 return sdEncKey; 13697 } catch (NoSuchAlgorithmException nsae) { 13698 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13699 return null; 13700 } catch (IOException ioe) { 13701 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13702 return null; 13703 } 13704 } 13705 13706 /* 13707 * Update media status on PackageManager. 13708 */ 13709 @Override 13710 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13711 int callingUid = Binder.getCallingUid(); 13712 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13713 throw new SecurityException("Media status can only be updated by the system"); 13714 } 13715 // reader; this apparently protects mMediaMounted, but should probably 13716 // be a different lock in that case. 13717 synchronized (mPackages) { 13718 Log.i(TAG, "Updating external media status from " 13719 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13720 + (mediaStatus ? "mounted" : "unmounted")); 13721 if (DEBUG_SD_INSTALL) 13722 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13723 + ", mMediaMounted=" + mMediaMounted); 13724 if (mediaStatus == mMediaMounted) { 13725 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13726 : 0, -1); 13727 mHandler.sendMessage(msg); 13728 return; 13729 } 13730 mMediaMounted = mediaStatus; 13731 } 13732 // Queue up an async operation since the package installation may take a 13733 // little while. 13734 mHandler.post(new Runnable() { 13735 public void run() { 13736 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13737 } 13738 }); 13739 } 13740 13741 /** 13742 * Called by MountService when the initial ASECs to scan are available. 13743 * Should block until all the ASEC containers are finished being scanned. 13744 */ 13745 public void scanAvailableAsecs() { 13746 updateExternalMediaStatusInner(true, false, false); 13747 if (mShouldRestoreconData) { 13748 SELinuxMMAC.setRestoreconDone(); 13749 mShouldRestoreconData = false; 13750 } 13751 } 13752 13753 /* 13754 * Collect information of applications on external media, map them against 13755 * existing containers and update information based on current mount status. 13756 * Please note that we always have to report status if reportStatus has been 13757 * set to true especially when unloading packages. 13758 */ 13759 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13760 boolean externalStorage) { 13761 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13762 int[] uidArr = EmptyArray.INT; 13763 13764 final String[] list = PackageHelper.getSecureContainerList(); 13765 if (ArrayUtils.isEmpty(list)) { 13766 Log.i(TAG, "No secure containers found"); 13767 } else { 13768 // Process list of secure containers and categorize them 13769 // as active or stale based on their package internal state. 13770 13771 // reader 13772 synchronized (mPackages) { 13773 for (String cid : list) { 13774 // Leave stages untouched for now; installer service owns them 13775 if (PackageInstallerService.isStageName(cid)) continue; 13776 13777 if (DEBUG_SD_INSTALL) 13778 Log.i(TAG, "Processing container " + cid); 13779 String pkgName = getAsecPackageName(cid); 13780 if (pkgName == null) { 13781 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13782 continue; 13783 } 13784 if (DEBUG_SD_INSTALL) 13785 Log.i(TAG, "Looking for pkg : " + pkgName); 13786 13787 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13788 if (ps == null) { 13789 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13790 continue; 13791 } 13792 13793 /* 13794 * Skip packages that are not external if we're unmounting 13795 * external storage. 13796 */ 13797 if (externalStorage && !isMounted && !isExternal(ps)) { 13798 continue; 13799 } 13800 13801 final AsecInstallArgs args = new AsecInstallArgs(cid, 13802 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13803 // The package status is changed only if the code path 13804 // matches between settings and the container id. 13805 if (ps.codePathString != null 13806 && ps.codePathString.startsWith(args.getCodePath())) { 13807 if (DEBUG_SD_INSTALL) { 13808 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13809 + " at code path: " + ps.codePathString); 13810 } 13811 13812 // We do have a valid package installed on sdcard 13813 processCids.put(args, ps.codePathString); 13814 final int uid = ps.appId; 13815 if (uid != -1) { 13816 uidArr = ArrayUtils.appendInt(uidArr, uid); 13817 } 13818 } else { 13819 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13820 + ps.codePathString); 13821 } 13822 } 13823 } 13824 13825 Arrays.sort(uidArr); 13826 } 13827 13828 // Process packages with valid entries. 13829 if (isMounted) { 13830 if (DEBUG_SD_INSTALL) 13831 Log.i(TAG, "Loading packages"); 13832 loadMediaPackages(processCids, uidArr); 13833 startCleaningPackages(); 13834 mInstallerService.onSecureContainersAvailable(); 13835 } else { 13836 if (DEBUG_SD_INSTALL) 13837 Log.i(TAG, "Unloading packages"); 13838 unloadMediaPackages(processCids, uidArr, reportStatus); 13839 } 13840 } 13841 13842 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13843 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13844 final int size = infos.size(); 13845 final String[] packageNames = new String[size]; 13846 final int[] packageUids = new int[size]; 13847 for (int i = 0; i < size; i++) { 13848 final ApplicationInfo info = infos.get(i); 13849 packageNames[i] = info.packageName; 13850 packageUids[i] = info.uid; 13851 } 13852 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13853 finishedReceiver); 13854 } 13855 13856 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13857 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13858 sendResourcesChangedBroadcast(mediaStatus, replacing, 13859 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13860 } 13861 13862 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13863 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13864 int size = pkgList.length; 13865 if (size > 0) { 13866 // Send broadcasts here 13867 Bundle extras = new Bundle(); 13868 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13869 if (uidArr != null) { 13870 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13871 } 13872 if (replacing) { 13873 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13874 } 13875 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13876 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13877 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13878 } 13879 } 13880 13881 /* 13882 * Look at potentially valid container ids from processCids If package 13883 * information doesn't match the one on record or package scanning fails, 13884 * the cid is added to list of removeCids. We currently don't delete stale 13885 * containers. 13886 */ 13887 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13888 ArrayList<String> pkgList = new ArrayList<String>(); 13889 Set<AsecInstallArgs> keys = processCids.keySet(); 13890 13891 for (AsecInstallArgs args : keys) { 13892 String codePath = processCids.get(args); 13893 if (DEBUG_SD_INSTALL) 13894 Log.i(TAG, "Loading container : " + args.cid); 13895 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13896 try { 13897 // Make sure there are no container errors first. 13898 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13899 Slog.e(TAG, "Failed to mount cid : " + args.cid 13900 + " when installing from sdcard"); 13901 continue; 13902 } 13903 // Check code path here. 13904 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13905 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13906 + " does not match one in settings " + codePath); 13907 continue; 13908 } 13909 // Parse package 13910 int parseFlags = mDefParseFlags; 13911 if (args.isExternalAsec()) { 13912 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13913 } 13914 if (args.isFwdLocked()) { 13915 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13916 } 13917 13918 synchronized (mInstallLock) { 13919 PackageParser.Package pkg = null; 13920 try { 13921 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13922 } catch (PackageManagerException e) { 13923 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13924 } 13925 // Scan the package 13926 if (pkg != null) { 13927 /* 13928 * TODO why is the lock being held? doPostInstall is 13929 * called in other places without the lock. This needs 13930 * to be straightened out. 13931 */ 13932 // writer 13933 synchronized (mPackages) { 13934 retCode = PackageManager.INSTALL_SUCCEEDED; 13935 pkgList.add(pkg.packageName); 13936 // Post process args 13937 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13938 pkg.applicationInfo.uid); 13939 } 13940 } else { 13941 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13942 } 13943 } 13944 13945 } finally { 13946 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13947 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13948 } 13949 } 13950 } 13951 // writer 13952 synchronized (mPackages) { 13953 // If the platform SDK has changed since the last time we booted, 13954 // we need to re-grant app permission to catch any new ones that 13955 // appear. This is really a hack, and means that apps can in some 13956 // cases get permissions that the user didn't initially explicitly 13957 // allow... it would be nice to have some better way to handle 13958 // this situation. 13959 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13960 if (regrantPermissions) 13961 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13962 + mSdkVersion + "; regranting permissions for external storage"); 13963 mSettings.mExternalSdkPlatform = mSdkVersion; 13964 13965 // Make sure group IDs have been assigned, and any permission 13966 // changes in other apps are accounted for 13967 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13968 | (regrantPermissions 13969 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13970 : 0)); 13971 13972 mSettings.updateExternalDatabaseVersion(); 13973 13974 // can downgrade to reader 13975 // Persist settings 13976 mSettings.writeLPr(); 13977 } 13978 // Send a broadcast to let everyone know we are done processing 13979 if (pkgList.size() > 0) { 13980 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13981 } 13982 } 13983 13984 /* 13985 * Utility method to unload a list of specified containers 13986 */ 13987 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13988 // Just unmount all valid containers. 13989 for (AsecInstallArgs arg : cidArgs) { 13990 synchronized (mInstallLock) { 13991 arg.doPostDeleteLI(false); 13992 } 13993 } 13994 } 13995 13996 /* 13997 * Unload packages mounted on external media. This involves deleting package 13998 * data from internal structures, sending broadcasts about diabled packages, 13999 * gc'ing to free up references, unmounting all secure containers 14000 * corresponding to packages on external media, and posting a 14001 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14002 * that we always have to post this message if status has been requested no 14003 * matter what. 14004 */ 14005 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14006 final boolean reportStatus) { 14007 if (DEBUG_SD_INSTALL) 14008 Log.i(TAG, "unloading media packages"); 14009 ArrayList<String> pkgList = new ArrayList<String>(); 14010 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14011 final Set<AsecInstallArgs> keys = processCids.keySet(); 14012 for (AsecInstallArgs args : keys) { 14013 String pkgName = args.getPackageName(); 14014 if (DEBUG_SD_INSTALL) 14015 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14016 // Delete package internally 14017 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14018 synchronized (mInstallLock) { 14019 boolean res = deletePackageLI(pkgName, null, false, null, null, 14020 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14021 if (res) { 14022 pkgList.add(pkgName); 14023 } else { 14024 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14025 failedList.add(args); 14026 } 14027 } 14028 } 14029 14030 // reader 14031 synchronized (mPackages) { 14032 // We didn't update the settings after removing each package; 14033 // write them now for all packages. 14034 mSettings.writeLPr(); 14035 } 14036 14037 // We have to absolutely send UPDATED_MEDIA_STATUS only 14038 // after confirming that all the receivers processed the ordered 14039 // broadcast when packages get disabled, force a gc to clean things up. 14040 // and unload all the containers. 14041 if (pkgList.size() > 0) { 14042 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14043 new IIntentReceiver.Stub() { 14044 public void performReceive(Intent intent, int resultCode, String data, 14045 Bundle extras, boolean ordered, boolean sticky, 14046 int sendingUser) throws RemoteException { 14047 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14048 reportStatus ? 1 : 0, 1, keys); 14049 mHandler.sendMessage(msg); 14050 } 14051 }); 14052 } else { 14053 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14054 keys); 14055 mHandler.sendMessage(msg); 14056 } 14057 } 14058 14059 private void loadPrivatePackages(VolumeInfo vol) { 14060 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14061 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14062 synchronized (mPackages) { 14063 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14064 for (PackageSetting ps : packages) { 14065 synchronized (mInstallLock) { 14066 final PackageParser.Package pkg; 14067 try { 14068 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14069 loaded.add(pkg.applicationInfo); 14070 } catch (PackageManagerException e) { 14071 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14072 } 14073 } 14074 } 14075 14076 // TODO: regrant any permissions that changed based since original install 14077 14078 mSettings.writeLPr(); 14079 } 14080 14081 Slog.d(TAG, "Loaded packages " + loaded); 14082 sendResourcesChangedBroadcast(true, false, loaded, null); 14083 } 14084 14085 private void unloadPrivatePackages(VolumeInfo vol) { 14086 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14087 synchronized (mPackages) { 14088 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14089 for (PackageSetting ps : packages) { 14090 if (ps.pkg == null) continue; 14091 synchronized (mInstallLock) { 14092 final ApplicationInfo info = ps.pkg.applicationInfo; 14093 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14094 if (deletePackageLI(ps.name, null, false, null, null, 14095 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14096 unloaded.add(info); 14097 } else { 14098 Slog.w(TAG, "Failed to unload " + ps.codePath); 14099 } 14100 } 14101 } 14102 14103 mSettings.writeLPr(); 14104 } 14105 14106 Slog.d(TAG, "Unloaded packages " + unloaded); 14107 sendResourcesChangedBroadcast(false, false, unloaded, null); 14108 } 14109 14110 @Override 14111 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14112 final int flags) { 14113 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14114 14115 final int installFlags; 14116 if ((flags & MOVE_INTERNAL) != 0) { 14117 installFlags = INSTALL_INTERNAL; 14118 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14119 installFlags = INSTALL_EXTERNAL; 14120 } else { 14121 throw new IllegalArgumentException("Unsupported move flags " + flags); 14122 } 14123 14124 try { 14125 movePackageInternal(packageName, null, installFlags, false, observer); 14126 } catch (PackageManagerException e) { 14127 Slog.d(TAG, "Failed to move " + packageName, e); 14128 try { 14129 observer.packageMoved(packageName, e.error); 14130 } catch (RemoteException ignored) { 14131 } 14132 } 14133 } 14134 14135 @Override 14136 public void movePackageAndData(final String packageName, final String volumeUuid, 14137 final IPackageMoveObserver observer) { 14138 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14139 try { 14140 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14141 } catch (PackageManagerException e) { 14142 Slog.d(TAG, "Failed to move " + packageName, e); 14143 try { 14144 observer.packageMoved(packageName, e.error); 14145 } catch (RemoteException ignored) { 14146 } 14147 } 14148 } 14149 14150 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14151 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14152 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14153 14154 File codeFile = null; 14155 String installerPackageName = null; 14156 String packageAbiOverride = null; 14157 14158 // TOOD: move app private data before installing 14159 14160 // reader 14161 synchronized (mPackages) { 14162 final PackageParser.Package pkg = mPackages.get(packageName); 14163 final PackageSetting ps = mSettings.mPackages.get(packageName); 14164 if (pkg == null || ps == null) { 14165 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14166 } 14167 14168 if (pkg.applicationInfo.isSystemApp()) { 14169 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14170 "Cannot move system application"); 14171 } else if (pkg.mOperationPending) { 14172 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14173 "Attempt to move package which has pending operations"); 14174 } 14175 14176 // TODO: yell if already in desired location 14177 14178 pkg.mOperationPending = true; 14179 14180 codeFile = new File(pkg.codePath); 14181 installerPackageName = ps.installerPackageName; 14182 packageAbiOverride = ps.cpuAbiOverrideString; 14183 } 14184 14185 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14186 @Override 14187 public void onUserActionRequired(Intent intent) throws RemoteException { 14188 throw new IllegalStateException(); 14189 } 14190 14191 @Override 14192 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14193 Bundle extras) throws RemoteException { 14194 Slog.d(TAG, "Install result for move: " 14195 + PackageManager.installStatusToString(returnCode, msg)); 14196 14197 // We usually have a new package now after the install, but if 14198 // we failed we need to clear the pending flag on the original 14199 // package object. 14200 synchronized (mPackages) { 14201 final PackageParser.Package pkg = mPackages.get(packageName); 14202 if (pkg != null) { 14203 pkg.mOperationPending = false; 14204 } 14205 } 14206 14207 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14208 switch (status) { 14209 case PackageInstaller.STATUS_SUCCESS: 14210 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14211 break; 14212 case PackageInstaller.STATUS_FAILURE_STORAGE: 14213 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14214 break; 14215 default: 14216 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14217 break; 14218 } 14219 } 14220 }; 14221 14222 // Treat a move like reinstalling an existing app, which ensures that we 14223 // process everythign uniformly, like unpacking native libraries. 14224 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14225 14226 final Message msg = mHandler.obtainMessage(INIT_COPY); 14227 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14228 msg.obj = new InstallParams(origin, installObserver, installFlags, 14229 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14230 mHandler.sendMessage(msg); 14231 } 14232 14233 @Override 14234 public boolean setInstallLocation(int loc) { 14235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14236 null); 14237 if (getInstallLocation() == loc) { 14238 return true; 14239 } 14240 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14241 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14242 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14243 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14244 return true; 14245 } 14246 return false; 14247 } 14248 14249 @Override 14250 public int getInstallLocation() { 14251 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14252 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14253 PackageHelper.APP_INSTALL_AUTO); 14254 } 14255 14256 /** Called by UserManagerService */ 14257 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14258 mDirtyUsers.remove(userHandle); 14259 mSettings.removeUserLPw(userHandle); 14260 mPendingBroadcasts.remove(userHandle); 14261 if (mInstaller != null) { 14262 // Technically, we shouldn't be doing this with the package lock 14263 // held. However, this is very rare, and there is already so much 14264 // other disk I/O going on, that we'll let it slide for now. 14265 mInstaller.removeUserDataDirs(userHandle); 14266 } 14267 mUserNeedsBadging.delete(userHandle); 14268 removeUnusedPackagesLILPw(userManager, userHandle); 14269 } 14270 14271 /** 14272 * We're removing userHandle and would like to remove any downloaded packages 14273 * that are no longer in use by any other user. 14274 * @param userHandle the user being removed 14275 */ 14276 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14277 final boolean DEBUG_CLEAN_APKS = false; 14278 int [] users = userManager.getUserIdsLPr(); 14279 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14280 while (psit.hasNext()) { 14281 PackageSetting ps = psit.next(); 14282 if (ps.pkg == null) { 14283 continue; 14284 } 14285 final String packageName = ps.pkg.packageName; 14286 // Skip over if system app 14287 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14288 continue; 14289 } 14290 if (DEBUG_CLEAN_APKS) { 14291 Slog.i(TAG, "Checking package " + packageName); 14292 } 14293 boolean keep = false; 14294 for (int i = 0; i < users.length; i++) { 14295 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14296 keep = true; 14297 if (DEBUG_CLEAN_APKS) { 14298 Slog.i(TAG, " Keeping package " + packageName + " for user " 14299 + users[i]); 14300 } 14301 break; 14302 } 14303 } 14304 if (!keep) { 14305 if (DEBUG_CLEAN_APKS) { 14306 Slog.i(TAG, " Removing package " + packageName); 14307 } 14308 mHandler.post(new Runnable() { 14309 public void run() { 14310 deletePackageX(packageName, userHandle, 0); 14311 } //end run 14312 }); 14313 } 14314 } 14315 } 14316 14317 /** Called by UserManagerService */ 14318 void createNewUserLILPw(int userHandle, File path) { 14319 if (mInstaller != null) { 14320 mInstaller.createUserConfig(userHandle); 14321 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14322 } 14323 } 14324 14325 void newUserCreatedLILPw(int userHandle) { 14326 // Adding a user requires updating runtime permissions for system apps. 14327 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14328 } 14329 14330 @Override 14331 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14332 mContext.enforceCallingOrSelfPermission( 14333 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14334 "Only package verification agents can read the verifier device identity"); 14335 14336 synchronized (mPackages) { 14337 return mSettings.getVerifierDeviceIdentityLPw(); 14338 } 14339 } 14340 14341 @Override 14342 public void setPermissionEnforced(String permission, boolean enforced) { 14343 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14344 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14345 synchronized (mPackages) { 14346 if (mSettings.mReadExternalStorageEnforced == null 14347 || mSettings.mReadExternalStorageEnforced != enforced) { 14348 mSettings.mReadExternalStorageEnforced = enforced; 14349 mSettings.writeLPr(); 14350 } 14351 } 14352 // kill any non-foreground processes so we restart them and 14353 // grant/revoke the GID. 14354 final IActivityManager am = ActivityManagerNative.getDefault(); 14355 if (am != null) { 14356 final long token = Binder.clearCallingIdentity(); 14357 try { 14358 am.killProcessesBelowForeground("setPermissionEnforcement"); 14359 } catch (RemoteException e) { 14360 } finally { 14361 Binder.restoreCallingIdentity(token); 14362 } 14363 } 14364 } else { 14365 throw new IllegalArgumentException("No selective enforcement for " + permission); 14366 } 14367 } 14368 14369 @Override 14370 @Deprecated 14371 public boolean isPermissionEnforced(String permission) { 14372 return true; 14373 } 14374 14375 @Override 14376 public boolean isStorageLow() { 14377 final long token = Binder.clearCallingIdentity(); 14378 try { 14379 final DeviceStorageMonitorInternal 14380 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14381 if (dsm != null) { 14382 return dsm.isMemoryLow(); 14383 } else { 14384 return false; 14385 } 14386 } finally { 14387 Binder.restoreCallingIdentity(token); 14388 } 14389 } 14390 14391 @Override 14392 public IPackageInstaller getPackageInstaller() { 14393 return mInstallerService; 14394 } 14395 14396 private boolean userNeedsBadging(int userId) { 14397 int index = mUserNeedsBadging.indexOfKey(userId); 14398 if (index < 0) { 14399 final UserInfo userInfo; 14400 final long token = Binder.clearCallingIdentity(); 14401 try { 14402 userInfo = sUserManager.getUserInfo(userId); 14403 } finally { 14404 Binder.restoreCallingIdentity(token); 14405 } 14406 final boolean b; 14407 if (userInfo != null && userInfo.isManagedProfile()) { 14408 b = true; 14409 } else { 14410 b = false; 14411 } 14412 mUserNeedsBadging.put(userId, b); 14413 return b; 14414 } 14415 return mUserNeedsBadging.valueAt(index); 14416 } 14417 14418 @Override 14419 public KeySet getKeySetByAlias(String packageName, String alias) { 14420 if (packageName == null || alias == null) { 14421 return null; 14422 } 14423 synchronized(mPackages) { 14424 final PackageParser.Package pkg = mPackages.get(packageName); 14425 if (pkg == null) { 14426 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14427 throw new IllegalArgumentException("Unknown package: " + packageName); 14428 } 14429 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14430 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14431 } 14432 } 14433 14434 @Override 14435 public KeySet getSigningKeySet(String packageName) { 14436 if (packageName == null) { 14437 return null; 14438 } 14439 synchronized(mPackages) { 14440 final PackageParser.Package pkg = mPackages.get(packageName); 14441 if (pkg == null) { 14442 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14443 throw new IllegalArgumentException("Unknown package: " + packageName); 14444 } 14445 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14446 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14447 throw new SecurityException("May not access signing KeySet of other apps."); 14448 } 14449 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14450 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14451 } 14452 } 14453 14454 @Override 14455 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14456 if (packageName == null || ks == null) { 14457 return false; 14458 } 14459 synchronized(mPackages) { 14460 final PackageParser.Package pkg = mPackages.get(packageName); 14461 if (pkg == null) { 14462 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14463 throw new IllegalArgumentException("Unknown package: " + packageName); 14464 } 14465 IBinder ksh = ks.getToken(); 14466 if (ksh instanceof KeySetHandle) { 14467 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14468 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14469 } 14470 return false; 14471 } 14472 } 14473 14474 @Override 14475 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14476 if (packageName == null || ks == null) { 14477 return false; 14478 } 14479 synchronized(mPackages) { 14480 final PackageParser.Package pkg = mPackages.get(packageName); 14481 if (pkg == null) { 14482 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14483 throw new IllegalArgumentException("Unknown package: " + packageName); 14484 } 14485 IBinder ksh = ks.getToken(); 14486 if (ksh instanceof KeySetHandle) { 14487 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14488 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14489 } 14490 return false; 14491 } 14492 } 14493 14494 public void getUsageStatsIfNoPackageUsageInfo() { 14495 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14496 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14497 if (usm == null) { 14498 throw new IllegalStateException("UsageStatsManager must be initialized"); 14499 } 14500 long now = System.currentTimeMillis(); 14501 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14502 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14503 String packageName = entry.getKey(); 14504 PackageParser.Package pkg = mPackages.get(packageName); 14505 if (pkg == null) { 14506 continue; 14507 } 14508 UsageStats usage = entry.getValue(); 14509 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14510 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14511 } 14512 } 14513 } 14514 14515 /** 14516 * Check and throw if the given before/after packages would be considered a 14517 * downgrade. 14518 */ 14519 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14520 throws PackageManagerException { 14521 if (after.versionCode < before.mVersionCode) { 14522 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14523 "Update version code " + after.versionCode + " is older than current " 14524 + before.mVersionCode); 14525 } else if (after.versionCode == before.mVersionCode) { 14526 if (after.baseRevisionCode < before.baseRevisionCode) { 14527 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14528 "Update base revision code " + after.baseRevisionCode 14529 + " is older than current " + before.baseRevisionCode); 14530 } 14531 14532 if (!ArrayUtils.isEmpty(after.splitNames)) { 14533 for (int i = 0; i < after.splitNames.length; i++) { 14534 final String splitName = after.splitNames[i]; 14535 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14536 if (j != -1) { 14537 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14538 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14539 "Update split " + splitName + " revision code " 14540 + after.splitRevisionCodes[i] + " is older than current " 14541 + before.splitRevisionCodes[j]); 14542 } 14543 } 14544 } 14545 } 14546 } 14547 } 14548} 14549