PackageManagerService.java revision b9f3674c11ed9c89b80a69f728cbc5f540b2ecde
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_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageManager.MOVE_INTERNAL; 58import static android.content.pm.PackageParser.isApkFile; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 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.XmlPullParser; 206import org.xmlpull.v1.XmlSerializer; 207 208import java.io.BufferedInputStream; 209import java.io.BufferedOutputStream; 210import java.io.BufferedReader; 211import java.io.ByteArrayInputStream; 212import java.io.ByteArrayOutputStream; 213import java.io.File; 214import java.io.FileDescriptor; 215import java.io.FileNotFoundException; 216import java.io.FileOutputStream; 217import java.io.FileReader; 218import java.io.FilenameFilter; 219import java.io.IOException; 220import java.io.InputStream; 221import java.io.PrintWriter; 222import java.nio.charset.StandardCharsets; 223import java.security.NoSuchAlgorithmException; 224import java.security.PublicKey; 225import java.security.cert.CertificateEncodingException; 226import java.security.cert.CertificateException; 227import java.text.SimpleDateFormat; 228import java.util.ArrayList; 229import java.util.Arrays; 230import java.util.Collection; 231import java.util.Collections; 232import java.util.Comparator; 233import java.util.Date; 234import java.util.Iterator; 235import java.util.List; 236import java.util.Map; 237import java.util.Objects; 238import java.util.Set; 239import java.util.concurrent.atomic.AtomicBoolean; 240import java.util.concurrent.atomic.AtomicLong; 241 242/** 243 * Keep track of all those .apks everywhere. 244 * 245 * This is very central to the platform's security; please run the unit 246 * tests whenever making modifications here: 247 * 248mmm frameworks/base/tests/AndroidTests 249adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 250adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 251 * 252 * {@hide} 253 */ 254public class PackageManagerService extends IPackageManager.Stub { 255 static final String TAG = "PackageManager"; 256 static final boolean DEBUG_SETTINGS = false; 257 static final boolean DEBUG_PREFERRED = false; 258 static final boolean DEBUG_UPGRADE = false; 259 private static final boolean DEBUG_BACKUP = true; 260 private static final boolean DEBUG_INSTALL = false; 261 private static final boolean DEBUG_REMOVE = false; 262 private static final boolean DEBUG_BROADCASTS = false; 263 private static final boolean DEBUG_SHOW_INFO = false; 264 private static final boolean DEBUG_PACKAGE_INFO = false; 265 private static final boolean DEBUG_INTENT_MATCHING = false; 266 private static final boolean DEBUG_PACKAGE_SCANNING = false; 267 private static final boolean DEBUG_VERIFY = false; 268 private static final boolean DEBUG_DEXOPT = false; 269 private static final boolean DEBUG_ABI_SELECTION = false; 270 271 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 272 273 private static final int RADIO_UID = Process.PHONE_UID; 274 private static final int LOG_UID = Process.LOG_UID; 275 private static final int NFC_UID = Process.NFC_UID; 276 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 277 private static final int SHELL_UID = Process.SHELL_UID; 278 279 // Cap the size of permission trees that 3rd party apps can define 280 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 281 282 // Suffix used during package installation when copying/moving 283 // package apks to install directory. 284 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 285 286 static final int SCAN_NO_DEX = 1<<1; 287 static final int SCAN_FORCE_DEX = 1<<2; 288 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 289 static final int SCAN_NEW_INSTALL = 1<<4; 290 static final int SCAN_NO_PATHS = 1<<5; 291 static final int SCAN_UPDATE_TIME = 1<<6; 292 static final int SCAN_DEFER_DEX = 1<<7; 293 static final int SCAN_BOOTING = 1<<8; 294 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 295 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 296 static final int SCAN_REPLACING = 1<<11; 297 static final int SCAN_REQUIRE_KNOWN = 1<<12; 298 299 static final int REMOVE_CHATTY = 1<<16; 300 301 /** 302 * Timeout (in milliseconds) after which the watchdog should declare that 303 * our handler thread is wedged. The usual default for such things is one 304 * minute but we sometimes do very lengthy I/O operations on this thread, 305 * such as installing multi-gigabyte applications, so ours needs to be longer. 306 */ 307 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 308 309 /** 310 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 311 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 312 * settings entry if available, otherwise we use the hardcoded default. If it's been 313 * more than this long since the last fstrim, we force one during the boot sequence. 314 * 315 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 316 * one gets run at the next available charging+idle time. This final mandatory 317 * no-fstrim check kicks in only of the other scheduling criteria is never met. 318 */ 319 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 320 321 /** 322 * Whether verification is enabled by default. 323 */ 324 private static final boolean DEFAULT_VERIFY_ENABLE = true; 325 326 /** 327 * The default maximum time to wait for the verification agent to return in 328 * milliseconds. 329 */ 330 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 331 332 /** 333 * The default response for package verification timeout. 334 * 335 * This can be either PackageManager.VERIFICATION_ALLOW or 336 * PackageManager.VERIFICATION_REJECT. 337 */ 338 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 339 340 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 341 342 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 343 DEFAULT_CONTAINER_PACKAGE, 344 "com.android.defcontainer.DefaultContainerService"); 345 346 private static final String KILL_APP_REASON_GIDS_CHANGED = 347 "permission grant or revoke changed gids"; 348 349 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 350 "permissions revoked"; 351 352 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 353 354 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 355 356 /** Permission grant: not grant the permission. */ 357 private static final int GRANT_DENIED = 1; 358 359 /** Permission grant: grant the permission as an install permission. */ 360 private static final int GRANT_INSTALL = 2; 361 362 /** Permission grant: grant the permission as a runtime one. */ 363 private static final int GRANT_RUNTIME = 3; 364 365 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 366 private static final int GRANT_UPGRADE = 4; 367 368 final ServiceThread mHandlerThread; 369 370 final PackageHandler mHandler; 371 372 /** 373 * Messages for {@link #mHandler} that need to wait for system ready before 374 * being dispatched. 375 */ 376 private ArrayList<Message> mPostSystemReadyMessages; 377 378 final int mSdkVersion = Build.VERSION.SDK_INT; 379 380 final Context mContext; 381 final boolean mFactoryTest; 382 final boolean mOnlyCore; 383 final boolean mLazyDexOpt; 384 final long mDexOptLRUThresholdInMills; 385 final DisplayMetrics mMetrics; 386 final int mDefParseFlags; 387 final String[] mSeparateProcesses; 388 final boolean mIsUpgrade; 389 390 // This is where all application persistent data goes. 391 final File mAppDataDir; 392 393 // This is where all application persistent data goes for secondary users. 394 final File mUserAppDataDir; 395 396 /** The location for ASEC container files on internal storage. */ 397 final String mAsecInternalPath; 398 399 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 400 // LOCK HELD. Can be called with mInstallLock held. 401 final Installer mInstaller; 402 403 /** Directory where installed third-party apps stored */ 404 final File mAppInstallDir; 405 406 /** 407 * Directory to which applications installed internally have their 408 * 32 bit native libraries copied. 409 */ 410 private File mAppLib32InstallDir; 411 412 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 413 // apps. 414 final File mDrmAppPrivateInstallDir; 415 416 // ---------------------------------------------------------------- 417 418 // Lock for state used when installing and doing other long running 419 // operations. Methods that must be called with this lock held have 420 // the suffix "LI". 421 final Object mInstallLock = new Object(); 422 423 // ---------------------------------------------------------------- 424 425 // Keys are String (package name), values are Package. This also serves 426 // as the lock for the global state. Methods that must be called with 427 // this lock held have the prefix "LP". 428 final ArrayMap<String, PackageParser.Package> mPackages = 429 new ArrayMap<String, PackageParser.Package>(); 430 431 // Tracks available target package names -> overlay package paths. 432 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 433 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 434 435 final Settings mSettings; 436 boolean mRestoredSettings; 437 438 // System configuration read by SystemConfig. 439 final int[] mGlobalGids; 440 final SparseArray<ArraySet<String>> mSystemPermissions; 441 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 442 443 // If mac_permissions.xml was found for seinfo labeling. 444 boolean mFoundPolicyFile; 445 446 // If a recursive restorecon of /data/data/<pkg> is needed. 447 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 448 449 public static final class SharedLibraryEntry { 450 public final String path; 451 public final String apk; 452 453 SharedLibraryEntry(String _path, String _apk) { 454 path = _path; 455 apk = _apk; 456 } 457 } 458 459 // Currently known shared libraries. 460 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 461 new ArrayMap<String, SharedLibraryEntry>(); 462 463 // All available activities, for your resolving pleasure. 464 final ActivityIntentResolver mActivities = 465 new ActivityIntentResolver(); 466 467 // All available receivers, for your resolving pleasure. 468 final ActivityIntentResolver mReceivers = 469 new ActivityIntentResolver(); 470 471 // All available services, for your resolving pleasure. 472 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 473 474 // All available providers, for your resolving pleasure. 475 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 476 477 // Mapping from provider base names (first directory in content URI codePath) 478 // to the provider information. 479 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 480 new ArrayMap<String, PackageParser.Provider>(); 481 482 // Mapping from instrumentation class names to info about them. 483 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 484 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 485 486 // Mapping from permission names to info about them. 487 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 488 new ArrayMap<String, PackageParser.PermissionGroup>(); 489 490 // Packages whose data we have transfered into another package, thus 491 // should no longer exist. 492 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 493 494 // Broadcast actions that are only available to the system. 495 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 496 497 /** List of packages waiting for verification. */ 498 final SparseArray<PackageVerificationState> mPendingVerification 499 = new SparseArray<PackageVerificationState>(); 500 501 /** Set of packages associated with each app op permission. */ 502 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 503 504 final PackageInstallerService mInstallerService; 505 506 private final PackageDexOptimizer mPackageDexOptimizer; 507 // Cache of users who need badging. 508 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 509 510 /** Token for keys in mPendingVerification. */ 511 private int mPendingVerificationToken = 0; 512 513 volatile boolean mSystemReady; 514 volatile boolean mSafeMode; 515 volatile boolean mHasSystemUidErrors; 516 517 ApplicationInfo mAndroidApplication; 518 final ActivityInfo mResolveActivity = new ActivityInfo(); 519 final ResolveInfo mResolveInfo = new ResolveInfo(); 520 ComponentName mResolveComponentName; 521 PackageParser.Package mPlatformPackage; 522 ComponentName mCustomResolverComponentName; 523 524 boolean mResolverReplaced = false; 525 526 private final ComponentName mIntentFilterVerifierComponent; 527 private int mIntentFilterVerificationToken = 0; 528 529 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 530 = new SparseArray<IntentFilterVerificationState>(); 531 532 private interface IntentFilterVerifier<T extends IntentFilter> { 533 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 534 T filter, String packageName); 535 void startVerifications(int userId); 536 void receiveVerificationResponse(int verificationId); 537 } 538 539 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 540 private Context mContext; 541 private ComponentName mIntentFilterVerifierComponent; 542 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 543 544 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 545 mContext = context; 546 mIntentFilterVerifierComponent = verifierComponent; 547 } 548 549 private String getDefaultScheme() { 550 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 551 return IntentFilter.SCHEME_HTTP; 552 } 553 554 @Override 555 public void startVerifications(int userId) { 556 // Launch verifications requests 557 int count = mCurrentIntentFilterVerifications.size(); 558 for (int n=0; n<count; n++) { 559 int verificationId = mCurrentIntentFilterVerifications.get(n); 560 final IntentFilterVerificationState ivs = 561 mIntentFilterVerificationStates.get(verificationId); 562 563 String packageName = ivs.getPackageName(); 564 565 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 566 final int filterCount = filters.size(); 567 ArraySet<String> domainsSet = new ArraySet<>(); 568 for (int m=0; m<filterCount; m++) { 569 PackageParser.ActivityIntentInfo filter = filters.get(m); 570 domainsSet.addAll(filter.getHostsList()); 571 } 572 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 573 synchronized (mPackages) { 574 if (mSettings.createIntentFilterVerificationIfNeededLPw( 575 packageName, domainsList) != null) { 576 scheduleWriteSettingsLocked(); 577 } 578 } 579 sendVerificationRequest(userId, verificationId, ivs); 580 } 581 mCurrentIntentFilterVerifications.clear(); 582 } 583 584 private void sendVerificationRequest(int userId, int verificationId, 585 IntentFilterVerificationState ivs) { 586 587 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 588 verificationIntent.putExtra( 589 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 590 verificationId); 591 verificationIntent.putExtra( 592 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 593 getDefaultScheme()); 594 verificationIntent.putExtra( 595 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 596 ivs.getHostsString()); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 599 ivs.getPackageName()); 600 verificationIntent.setComponent(mIntentFilterVerifierComponent); 601 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 602 603 UserHandle user = new UserHandle(userId); 604 mContext.sendBroadcastAsUser(verificationIntent, user); 605 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 606 } 607 608 public void receiveVerificationResponse(int verificationId) { 609 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 610 611 final boolean verified = ivs.isVerified(); 612 613 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 614 final int count = filters.size(); 615 for (int n=0; n<count; n++) { 616 PackageParser.ActivityIntentInfo filter = filters.get(n); 617 filter.setVerified(verified); 618 619 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 620 + verified + " and hosts:" + ivs.getHostsString()); 621 } 622 623 mIntentFilterVerificationStates.remove(verificationId); 624 625 final String packageName = ivs.getPackageName(); 626 IntentFilterVerificationInfo ivi = null; 627 628 synchronized (mPackages) { 629 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 630 } 631 if (ivi == null) { 632 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 633 + verificationId + " packageName:" + packageName); 634 return; 635 } 636 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 637 + verificationId); 638 639 synchronized (mPackages) { 640 if (verified) { 641 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 642 } else { 643 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 644 } 645 scheduleWriteSettingsLocked(); 646 647 final int userId = ivs.getUserId(); 648 if (userId != UserHandle.USER_ALL) { 649 final int userStatus = 650 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 651 652 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 653 boolean needUpdate = false; 654 655 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 656 // already been set by the User thru the Disambiguation dialog 657 switch (userStatus) { 658 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 659 if (verified) { 660 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 661 } else { 662 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 663 } 664 needUpdate = true; 665 break; 666 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 needUpdate = true; 671 } 672 break; 673 674 default: 675 // Nothing to do 676 } 677 678 if (needUpdate) { 679 mSettings.updateIntentFilterVerificationStatusLPw( 680 packageName, updatedStatus, userId); 681 scheduleWritePackageRestrictionsLocked(userId); 682 } 683 } 684 } 685 } 686 687 @Override 688 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 689 ActivityIntentInfo filter, String packageName) { 690 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 691 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 692 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 693 return false; 694 } 695 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 696 if (ivs == null) { 697 ivs = createDomainVerificationState(verifierId, userId, verificationId, 698 packageName); 699 } 700 if (!hasValidDomains(filter)) { 701 return false; 702 } 703 ivs.addFilter(filter); 704 return true; 705 } 706 707 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 708 int userId, int verificationId, String packageName) { 709 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 710 verifierId, userId, packageName); 711 ivs.setPendingState(); 712 synchronized (mPackages) { 713 mIntentFilterVerificationStates.append(verificationId, ivs); 714 mCurrentIntentFilterVerifications.add(verificationId); 715 } 716 return ivs; 717 } 718 } 719 720 private static boolean hasValidDomains(ActivityIntentInfo filter) { 721 return hasValidDomains(filter, true); 722 } 723 724 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 725 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 726 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 727 if (!hasHTTPorHTTPS) { 728 if (logging) { 729 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 730 } 731 return false; 732 } 733 ArrayList<String> hosts = filter.getHostsList(); 734 if (hosts.size() == 0) { 735 if (logging) { 736 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 737 } 738 // We still return true as this is the case of any Browser 739 return true; 740 } 741 String hostEndBase = null; 742 for (String host : hosts) { 743 String[] hostParts = host.split("\\."); 744 // Should be at minimum a host like "example.com" 745 if (hostParts.length < 2) { 746 if (logging) { 747 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 748 } 749 return false; 750 } 751 // Verify that we have the same ending domain 752 int length = hostParts.length; 753 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 754 if (hostEndBase == null) { 755 hostEndBase = hostEnd; 756 } 757 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 758 if (logging) { 759 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 760 } 761 return false; 762 } 763 } 764 return true; 765 } 766 767 private IntentFilterVerifier mIntentFilterVerifier; 768 769 // Set of pending broadcasts for aggregating enable/disable of components. 770 static class PendingPackageBroadcasts { 771 // for each user id, a map of <package name -> components within that package> 772 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 773 774 public PendingPackageBroadcasts() { 775 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 776 } 777 778 public ArrayList<String> get(int userId, String packageName) { 779 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 780 return packages.get(packageName); 781 } 782 783 public void put(int userId, String packageName, ArrayList<String> components) { 784 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 785 packages.put(packageName, components); 786 } 787 788 public void remove(int userId, String packageName) { 789 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 790 if (packages != null) { 791 packages.remove(packageName); 792 } 793 } 794 795 public void remove(int userId) { 796 mUidMap.remove(userId); 797 } 798 799 public int userIdCount() { 800 return mUidMap.size(); 801 } 802 803 public int userIdAt(int n) { 804 return mUidMap.keyAt(n); 805 } 806 807 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 808 return mUidMap.get(userId); 809 } 810 811 public int size() { 812 // total number of pending broadcast entries across all userIds 813 int num = 0; 814 for (int i = 0; i< mUidMap.size(); i++) { 815 num += mUidMap.valueAt(i).size(); 816 } 817 return num; 818 } 819 820 public void clear() { 821 mUidMap.clear(); 822 } 823 824 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 825 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 826 if (map == null) { 827 map = new ArrayMap<String, ArrayList<String>>(); 828 mUidMap.put(userId, map); 829 } 830 return map; 831 } 832 } 833 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 834 835 // Service Connection to remote media container service to copy 836 // package uri's from external media onto secure containers 837 // or internal storage. 838 private IMediaContainerService mContainerService = null; 839 840 static final int SEND_PENDING_BROADCAST = 1; 841 static final int MCS_BOUND = 3; 842 static final int END_COPY = 4; 843 static final int INIT_COPY = 5; 844 static final int MCS_UNBIND = 6; 845 static final int START_CLEANING_PACKAGE = 7; 846 static final int FIND_INSTALL_LOC = 8; 847 static final int POST_INSTALL = 9; 848 static final int MCS_RECONNECT = 10; 849 static final int MCS_GIVE_UP = 11; 850 static final int UPDATED_MEDIA_STATUS = 12; 851 static final int WRITE_SETTINGS = 13; 852 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 853 static final int PACKAGE_VERIFIED = 15; 854 static final int CHECK_PENDING_VERIFICATION = 16; 855 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 856 static final int INTENT_FILTER_VERIFIED = 18; 857 858 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 859 860 // Delay time in millisecs 861 static final int BROADCAST_DELAY = 10 * 1000; 862 863 static UserManagerService sUserManager; 864 865 // Stores a list of users whose package restrictions file needs to be updated 866 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 867 868 final private DefaultContainerConnection mDefContainerConn = 869 new DefaultContainerConnection(); 870 class DefaultContainerConnection implements ServiceConnection { 871 public void onServiceConnected(ComponentName name, IBinder service) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 873 IMediaContainerService imcs = 874 IMediaContainerService.Stub.asInterface(service); 875 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 876 } 877 878 public void onServiceDisconnected(ComponentName name) { 879 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 880 } 881 }; 882 883 // Recordkeeping of restore-after-install operations that are currently in flight 884 // between the Package Manager and the Backup Manager 885 class PostInstallData { 886 public InstallArgs args; 887 public PackageInstalledInfo res; 888 889 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 890 args = _a; 891 res = _r; 892 } 893 }; 894 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 895 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 896 897 // backup/restore of preferred activity state 898 private static final String TAG_PREFERRED_BACKUP = "pa"; 899 900 private final String mRequiredVerifierPackage; 901 902 private final PackageUsage mPackageUsage = new PackageUsage(); 903 904 private class PackageUsage { 905 private static final int WRITE_INTERVAL 906 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 907 908 private final Object mFileLock = new Object(); 909 private final AtomicLong mLastWritten = new AtomicLong(0); 910 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 911 912 private boolean mIsHistoricalPackageUsageAvailable = true; 913 914 boolean isHistoricalPackageUsageAvailable() { 915 return mIsHistoricalPackageUsageAvailable; 916 } 917 918 void write(boolean force) { 919 if (force) { 920 writeInternal(); 921 return; 922 } 923 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 924 && !DEBUG_DEXOPT) { 925 return; 926 } 927 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 928 new Thread("PackageUsage_DiskWriter") { 929 @Override 930 public void run() { 931 try { 932 writeInternal(); 933 } finally { 934 mBackgroundWriteRunning.set(false); 935 } 936 } 937 }.start(); 938 } 939 } 940 941 private void writeInternal() { 942 synchronized (mPackages) { 943 synchronized (mFileLock) { 944 AtomicFile file = getFile(); 945 FileOutputStream f = null; 946 try { 947 f = file.startWrite(); 948 BufferedOutputStream out = new BufferedOutputStream(f); 949 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 950 StringBuilder sb = new StringBuilder(); 951 for (PackageParser.Package pkg : mPackages.values()) { 952 if (pkg.mLastPackageUsageTimeInMills == 0) { 953 continue; 954 } 955 sb.setLength(0); 956 sb.append(pkg.packageName); 957 sb.append(' '); 958 sb.append((long)pkg.mLastPackageUsageTimeInMills); 959 sb.append('\n'); 960 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 961 } 962 out.flush(); 963 file.finishWrite(f); 964 } catch (IOException e) { 965 if (f != null) { 966 file.failWrite(f); 967 } 968 Log.e(TAG, "Failed to write package usage times", e); 969 } 970 } 971 } 972 mLastWritten.set(SystemClock.elapsedRealtime()); 973 } 974 975 void readLP() { 976 synchronized (mFileLock) { 977 AtomicFile file = getFile(); 978 BufferedInputStream in = null; 979 try { 980 in = new BufferedInputStream(file.openRead()); 981 StringBuffer sb = new StringBuffer(); 982 while (true) { 983 String packageName = readToken(in, sb, ' '); 984 if (packageName == null) { 985 break; 986 } 987 String timeInMillisString = readToken(in, sb, '\n'); 988 if (timeInMillisString == null) { 989 throw new IOException("Failed to find last usage time for package " 990 + packageName); 991 } 992 PackageParser.Package pkg = mPackages.get(packageName); 993 if (pkg == null) { 994 continue; 995 } 996 long timeInMillis; 997 try { 998 timeInMillis = Long.parseLong(timeInMillisString.toString()); 999 } catch (NumberFormatException e) { 1000 throw new IOException("Failed to parse " + timeInMillisString 1001 + " as a long.", e); 1002 } 1003 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1004 } 1005 } catch (FileNotFoundException expected) { 1006 mIsHistoricalPackageUsageAvailable = false; 1007 } catch (IOException e) { 1008 Log.w(TAG, "Failed to read package usage times", e); 1009 } finally { 1010 IoUtils.closeQuietly(in); 1011 } 1012 } 1013 mLastWritten.set(SystemClock.elapsedRealtime()); 1014 } 1015 1016 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1017 throws IOException { 1018 sb.setLength(0); 1019 while (true) { 1020 int ch = in.read(); 1021 if (ch == -1) { 1022 if (sb.length() == 0) { 1023 return null; 1024 } 1025 throw new IOException("Unexpected EOF"); 1026 } 1027 if (ch == endOfToken) { 1028 return sb.toString(); 1029 } 1030 sb.append((char)ch); 1031 } 1032 } 1033 1034 private AtomicFile getFile() { 1035 File dataDir = Environment.getDataDirectory(); 1036 File systemDir = new File(dataDir, "system"); 1037 File fname = new File(systemDir, "package-usage.list"); 1038 return new AtomicFile(fname); 1039 } 1040 } 1041 1042 class PackageHandler extends Handler { 1043 private boolean mBound = false; 1044 final ArrayList<HandlerParams> mPendingInstalls = 1045 new ArrayList<HandlerParams>(); 1046 1047 private boolean connectToService() { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1049 " DefaultContainerService"); 1050 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1051 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1052 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1053 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1054 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1055 mBound = true; 1056 return true; 1057 } 1058 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1059 return false; 1060 } 1061 1062 private void disconnectService() { 1063 mContainerService = null; 1064 mBound = false; 1065 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1066 mContext.unbindService(mDefContainerConn); 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1068 } 1069 1070 PackageHandler(Looper looper) { 1071 super(looper); 1072 } 1073 1074 public void handleMessage(Message msg) { 1075 try { 1076 doHandleMessage(msg); 1077 } finally { 1078 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1079 } 1080 } 1081 1082 void doHandleMessage(Message msg) { 1083 switch (msg.what) { 1084 case INIT_COPY: { 1085 HandlerParams params = (HandlerParams) msg.obj; 1086 int idx = mPendingInstalls.size(); 1087 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1088 // If a bind was already initiated we dont really 1089 // need to do anything. The pending install 1090 // will be processed later on. 1091 if (!mBound) { 1092 // If this is the only one pending we might 1093 // have to bind to the service again. 1094 if (!connectToService()) { 1095 Slog.e(TAG, "Failed to bind to media container service"); 1096 params.serviceError(); 1097 return; 1098 } else { 1099 // Once we bind to the service, the first 1100 // pending request will be processed. 1101 mPendingInstalls.add(idx, params); 1102 } 1103 } else { 1104 mPendingInstalls.add(idx, params); 1105 // Already bound to the service. Just make 1106 // sure we trigger off processing the first request. 1107 if (idx == 0) { 1108 mHandler.sendEmptyMessage(MCS_BOUND); 1109 } 1110 } 1111 break; 1112 } 1113 case MCS_BOUND: { 1114 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1115 if (msg.obj != null) { 1116 mContainerService = (IMediaContainerService) msg.obj; 1117 } 1118 if (mContainerService == null) { 1119 // Something seriously wrong. Bail out 1120 Slog.e(TAG, "Cannot bind to media container service"); 1121 for (HandlerParams params : mPendingInstalls) { 1122 // Indicate service bind error 1123 params.serviceError(); 1124 } 1125 mPendingInstalls.clear(); 1126 } else if (mPendingInstalls.size() > 0) { 1127 HandlerParams params = mPendingInstalls.get(0); 1128 if (params != null) { 1129 if (params.startCopy()) { 1130 // We are done... look for more work or to 1131 // go idle. 1132 if (DEBUG_SD_INSTALL) Log.i(TAG, 1133 "Checking for more work or unbind..."); 1134 // Delete pending install 1135 if (mPendingInstalls.size() > 0) { 1136 mPendingInstalls.remove(0); 1137 } 1138 if (mPendingInstalls.size() == 0) { 1139 if (mBound) { 1140 if (DEBUG_SD_INSTALL) Log.i(TAG, 1141 "Posting delayed MCS_UNBIND"); 1142 removeMessages(MCS_UNBIND); 1143 Message ubmsg = obtainMessage(MCS_UNBIND); 1144 // Unbind after a little delay, to avoid 1145 // continual thrashing. 1146 sendMessageDelayed(ubmsg, 10000); 1147 } 1148 } else { 1149 // There are more pending requests in queue. 1150 // Just post MCS_BOUND message to trigger processing 1151 // of next pending install. 1152 if (DEBUG_SD_INSTALL) Log.i(TAG, 1153 "Posting MCS_BOUND for next work"); 1154 mHandler.sendEmptyMessage(MCS_BOUND); 1155 } 1156 } 1157 } 1158 } else { 1159 // Should never happen ideally. 1160 Slog.w(TAG, "Empty queue"); 1161 } 1162 break; 1163 } 1164 case MCS_RECONNECT: { 1165 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1166 if (mPendingInstalls.size() > 0) { 1167 if (mBound) { 1168 disconnectService(); 1169 } 1170 if (!connectToService()) { 1171 Slog.e(TAG, "Failed to bind to media container service"); 1172 for (HandlerParams params : mPendingInstalls) { 1173 // Indicate service bind error 1174 params.serviceError(); 1175 } 1176 mPendingInstalls.clear(); 1177 } 1178 } 1179 break; 1180 } 1181 case MCS_UNBIND: { 1182 // If there is no actual work left, then time to unbind. 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1184 1185 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1186 if (mBound) { 1187 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1188 1189 disconnectService(); 1190 } 1191 } else if (mPendingInstalls.size() > 0) { 1192 // There are more pending requests in queue. 1193 // Just post MCS_BOUND message to trigger processing 1194 // of next pending install. 1195 mHandler.sendEmptyMessage(MCS_BOUND); 1196 } 1197 1198 break; 1199 } 1200 case MCS_GIVE_UP: { 1201 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1202 mPendingInstalls.remove(0); 1203 break; 1204 } 1205 case SEND_PENDING_BROADCAST: { 1206 String packages[]; 1207 ArrayList<String> components[]; 1208 int size = 0; 1209 int uids[]; 1210 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1211 synchronized (mPackages) { 1212 if (mPendingBroadcasts == null) { 1213 return; 1214 } 1215 size = mPendingBroadcasts.size(); 1216 if (size <= 0) { 1217 // Nothing to be done. Just return 1218 return; 1219 } 1220 packages = new String[size]; 1221 components = new ArrayList[size]; 1222 uids = new int[size]; 1223 int i = 0; // filling out the above arrays 1224 1225 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1226 int packageUserId = mPendingBroadcasts.userIdAt(n); 1227 Iterator<Map.Entry<String, ArrayList<String>>> it 1228 = mPendingBroadcasts.packagesForUserId(packageUserId) 1229 .entrySet().iterator(); 1230 while (it.hasNext() && i < size) { 1231 Map.Entry<String, ArrayList<String>> ent = it.next(); 1232 packages[i] = ent.getKey(); 1233 components[i] = ent.getValue(); 1234 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1235 uids[i] = (ps != null) 1236 ? UserHandle.getUid(packageUserId, ps.appId) 1237 : -1; 1238 i++; 1239 } 1240 } 1241 size = i; 1242 mPendingBroadcasts.clear(); 1243 } 1244 // Send broadcasts 1245 for (int i = 0; i < size; i++) { 1246 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1247 } 1248 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1249 break; 1250 } 1251 case START_CLEANING_PACKAGE: { 1252 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1253 final String packageName = (String)msg.obj; 1254 final int userId = msg.arg1; 1255 final boolean andCode = msg.arg2 != 0; 1256 synchronized (mPackages) { 1257 if (userId == UserHandle.USER_ALL) { 1258 int[] users = sUserManager.getUserIds(); 1259 for (int user : users) { 1260 mSettings.addPackageToCleanLPw( 1261 new PackageCleanItem(user, packageName, andCode)); 1262 } 1263 } else { 1264 mSettings.addPackageToCleanLPw( 1265 new PackageCleanItem(userId, packageName, andCode)); 1266 } 1267 } 1268 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1269 startCleaningPackages(); 1270 } break; 1271 case POST_INSTALL: { 1272 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1273 PostInstallData data = mRunningInstalls.get(msg.arg1); 1274 mRunningInstalls.delete(msg.arg1); 1275 boolean deleteOld = false; 1276 1277 if (data != null) { 1278 InstallArgs args = data.args; 1279 PackageInstalledInfo res = data.res; 1280 1281 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1282 res.removedInfo.sendBroadcast(false, true, false); 1283 Bundle extras = new Bundle(1); 1284 extras.putInt(Intent.EXTRA_UID, res.uid); 1285 1286 // Now that we successfully installed the package, grant runtime 1287 // permissions if requested before broadcasting the install. 1288 if ((args.installFlags 1289 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1290 grantRequestedRuntimePermissions(res.pkg, 1291 args.user.getIdentifier()); 1292 } 1293 1294 // Determine the set of users who are adding this 1295 // package for the first time vs. those who are seeing 1296 // an update. 1297 int[] firstUsers; 1298 int[] updateUsers = new int[0]; 1299 if (res.origUsers == null || res.origUsers.length == 0) { 1300 firstUsers = res.newUsers; 1301 } else { 1302 firstUsers = new int[0]; 1303 for (int i=0; i<res.newUsers.length; i++) { 1304 int user = res.newUsers[i]; 1305 boolean isNew = true; 1306 for (int j=0; j<res.origUsers.length; j++) { 1307 if (res.origUsers[j] == user) { 1308 isNew = false; 1309 break; 1310 } 1311 } 1312 if (isNew) { 1313 int[] newFirst = new int[firstUsers.length+1]; 1314 System.arraycopy(firstUsers, 0, newFirst, 0, 1315 firstUsers.length); 1316 newFirst[firstUsers.length] = user; 1317 firstUsers = newFirst; 1318 } else { 1319 int[] newUpdate = new int[updateUsers.length+1]; 1320 System.arraycopy(updateUsers, 0, newUpdate, 0, 1321 updateUsers.length); 1322 newUpdate[updateUsers.length] = user; 1323 updateUsers = newUpdate; 1324 } 1325 } 1326 } 1327 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1328 res.pkg.applicationInfo.packageName, 1329 extras, null, null, firstUsers); 1330 final boolean update = res.removedInfo.removedPackage != null; 1331 if (update) { 1332 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1333 } 1334 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1335 res.pkg.applicationInfo.packageName, 1336 extras, null, null, updateUsers); 1337 if (update) { 1338 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1339 res.pkg.applicationInfo.packageName, 1340 extras, null, null, updateUsers); 1341 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1342 null, null, 1343 res.pkg.applicationInfo.packageName, null, updateUsers); 1344 1345 // treat asec-hosted packages like removable media on upgrade 1346 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1347 if (DEBUG_INSTALL) { 1348 Slog.i(TAG, "upgrading pkg " + res.pkg 1349 + " is ASEC-hosted -> AVAILABLE"); 1350 } 1351 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1352 ArrayList<String> pkgList = new ArrayList<String>(1); 1353 pkgList.add(res.pkg.applicationInfo.packageName); 1354 sendResourcesChangedBroadcast(true, true, 1355 pkgList,uidArray, null); 1356 } 1357 } 1358 if (res.removedInfo.args != null) { 1359 // Remove the replaced package's older resources safely now 1360 deleteOld = true; 1361 } 1362 1363 // Log current value of "unknown sources" setting 1364 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1365 getUnknownSourcesSettings()); 1366 } 1367 // Force a gc to clear up things 1368 Runtime.getRuntime().gc(); 1369 // We delete after a gc for applications on sdcard. 1370 if (deleteOld) { 1371 synchronized (mInstallLock) { 1372 res.removedInfo.args.doPostDeleteLI(true); 1373 } 1374 } 1375 if (args.observer != null) { 1376 try { 1377 Bundle extras = extrasForInstallResult(res); 1378 args.observer.onPackageInstalled(res.name, res.returnCode, 1379 res.returnMsg, extras); 1380 } catch (RemoteException e) { 1381 Slog.i(TAG, "Observer no longer exists."); 1382 } 1383 } 1384 } else { 1385 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1386 } 1387 } break; 1388 case UPDATED_MEDIA_STATUS: { 1389 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1390 boolean reportStatus = msg.arg1 == 1; 1391 boolean doGc = msg.arg2 == 1; 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1393 if (doGc) { 1394 // Force a gc to clear up stale containers. 1395 Runtime.getRuntime().gc(); 1396 } 1397 if (msg.obj != null) { 1398 @SuppressWarnings("unchecked") 1399 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1400 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1401 // Unload containers 1402 unloadAllContainers(args); 1403 } 1404 if (reportStatus) { 1405 try { 1406 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1407 PackageHelper.getMountService().finishMediaUpdate(); 1408 } catch (RemoteException e) { 1409 Log.e(TAG, "MountService not running?"); 1410 } 1411 } 1412 } break; 1413 case WRITE_SETTINGS: { 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1415 synchronized (mPackages) { 1416 removeMessages(WRITE_SETTINGS); 1417 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1418 mSettings.writeLPr(); 1419 mDirtyUsers.clear(); 1420 } 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 } break; 1423 case WRITE_PACKAGE_RESTRICTIONS: { 1424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1425 synchronized (mPackages) { 1426 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1427 for (int userId : mDirtyUsers) { 1428 mSettings.writePackageRestrictionsLPr(userId); 1429 } 1430 mDirtyUsers.clear(); 1431 } 1432 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1433 } break; 1434 case CHECK_PENDING_VERIFICATION: { 1435 final int verificationId = msg.arg1; 1436 final PackageVerificationState state = mPendingVerification.get(verificationId); 1437 1438 if ((state != null) && !state.timeoutExtended()) { 1439 final InstallArgs args = state.getInstallArgs(); 1440 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1441 1442 Slog.i(TAG, "Verification timed out for " + originUri); 1443 mPendingVerification.remove(verificationId); 1444 1445 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1446 1447 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1448 Slog.i(TAG, "Continuing with installation of " + originUri); 1449 state.setVerifierResponse(Binder.getCallingUid(), 1450 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1451 broadcastPackageVerified(verificationId, originUri, 1452 PackageManager.VERIFICATION_ALLOW, 1453 state.getInstallArgs().getUser()); 1454 try { 1455 ret = args.copyApk(mContainerService, true); 1456 } catch (RemoteException e) { 1457 Slog.e(TAG, "Could not contact the ContainerService"); 1458 } 1459 } else { 1460 broadcastPackageVerified(verificationId, originUri, 1461 PackageManager.VERIFICATION_REJECT, 1462 state.getInstallArgs().getUser()); 1463 } 1464 1465 processPendingInstall(args, ret); 1466 mHandler.sendEmptyMessage(MCS_UNBIND); 1467 } 1468 break; 1469 } 1470 case PACKAGE_VERIFIED: { 1471 final int verificationId = msg.arg1; 1472 1473 final PackageVerificationState state = mPendingVerification.get(verificationId); 1474 if (state == null) { 1475 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1476 break; 1477 } 1478 1479 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1480 1481 state.setVerifierResponse(response.callerUid, response.code); 1482 1483 if (state.isVerificationComplete()) { 1484 mPendingVerification.remove(verificationId); 1485 1486 final InstallArgs args = state.getInstallArgs(); 1487 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1488 1489 int ret; 1490 if (state.isInstallAllowed()) { 1491 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1492 broadcastPackageVerified(verificationId, originUri, 1493 response.code, state.getInstallArgs().getUser()); 1494 try { 1495 ret = args.copyApk(mContainerService, true); 1496 } catch (RemoteException e) { 1497 Slog.e(TAG, "Could not contact the ContainerService"); 1498 } 1499 } else { 1500 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1501 } 1502 1503 processPendingInstall(args, ret); 1504 1505 mHandler.sendEmptyMessage(MCS_UNBIND); 1506 } 1507 1508 break; 1509 } 1510 case START_INTENT_FILTER_VERIFICATIONS: { 1511 int userId = msg.arg1; 1512 int verifierUid = msg.arg2; 1513 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1514 1515 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1516 break; 1517 } 1518 case INTENT_FILTER_VERIFIED: { 1519 final int verificationId = msg.arg1; 1520 1521 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1522 verificationId); 1523 if (state == null) { 1524 Slog.w(TAG, "Invalid IntentFilter verification token " 1525 + verificationId + " received"); 1526 break; 1527 } 1528 1529 final int userId = state.getUserId(); 1530 1531 Slog.d(TAG, "Processing IntentFilter verification with token:" 1532 + verificationId + " and userId:" + userId); 1533 1534 final IntentFilterVerificationResponse response = 1535 (IntentFilterVerificationResponse) msg.obj; 1536 1537 state.setVerifierResponse(response.callerUid, response.code); 1538 1539 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1540 + " and userId:" + userId 1541 + " is settings verifier response with response code:" 1542 + response.code); 1543 1544 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1545 Slog.d(TAG, "Domains failing verification: " 1546 + response.getFailedDomainsString()); 1547 } 1548 1549 if (state.isVerificationComplete()) { 1550 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1551 } else { 1552 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1553 + " was not said to be complete"); 1554 } 1555 1556 break; 1557 } 1558 } 1559 } 1560 } 1561 1562 private StorageEventListener mStorageListener = new StorageEventListener() { 1563 @Override 1564 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1565 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1566 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1567 loadPrivatePackages(vol); 1568 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1569 unloadPrivatePackages(vol); 1570 } 1571 } 1572 1573 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1574 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1575 updateExternalMediaStatus(true, false); 1576 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1577 updateExternalMediaStatus(false, false); 1578 } 1579 } 1580 } 1581 }; 1582 1583 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1584 if (userId >= UserHandle.USER_OWNER) { 1585 grantRequestedRuntimePermissionsForUser(pkg, userId); 1586 } else if (userId == UserHandle.USER_ALL) { 1587 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1588 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1589 } 1590 } 1591 } 1592 1593 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1594 SettingBase sb = (SettingBase) pkg.mExtras; 1595 if (sb == null) { 1596 return; 1597 } 1598 1599 PermissionsState permissionsState = sb.getPermissionsState(); 1600 1601 for (String permission : pkg.requestedPermissions) { 1602 BasePermission bp = mSettings.mPermissions.get(permission); 1603 if (bp != null && bp.isRuntime()) { 1604 permissionsState.grantRuntimePermission(bp, userId); 1605 } 1606 } 1607 } 1608 1609 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1610 Bundle extras = null; 1611 switch (res.returnCode) { 1612 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1613 extras = new Bundle(); 1614 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1615 res.origPermission); 1616 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1617 res.origPackage); 1618 break; 1619 } 1620 } 1621 return extras; 1622 } 1623 1624 void scheduleWriteSettingsLocked() { 1625 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1626 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1627 } 1628 } 1629 1630 void scheduleWritePackageRestrictionsLocked(int userId) { 1631 if (!sUserManager.exists(userId)) return; 1632 mDirtyUsers.add(userId); 1633 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1634 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1635 } 1636 } 1637 1638 public static PackageManagerService main(Context context, Installer installer, 1639 boolean factoryTest, boolean onlyCore) { 1640 PackageManagerService m = new PackageManagerService(context, installer, 1641 factoryTest, onlyCore); 1642 ServiceManager.addService("package", m); 1643 return m; 1644 } 1645 1646 static String[] splitString(String str, char sep) { 1647 int count = 1; 1648 int i = 0; 1649 while ((i=str.indexOf(sep, i)) >= 0) { 1650 count++; 1651 i++; 1652 } 1653 1654 String[] res = new String[count]; 1655 i=0; 1656 count = 0; 1657 int lastI=0; 1658 while ((i=str.indexOf(sep, i)) >= 0) { 1659 res[count] = str.substring(lastI, i); 1660 count++; 1661 i++; 1662 lastI = i; 1663 } 1664 res[count] = str.substring(lastI, str.length()); 1665 return res; 1666 } 1667 1668 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1669 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1670 Context.DISPLAY_SERVICE); 1671 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1672 } 1673 1674 public PackageManagerService(Context context, Installer installer, 1675 boolean factoryTest, boolean onlyCore) { 1676 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1677 SystemClock.uptimeMillis()); 1678 1679 if (mSdkVersion <= 0) { 1680 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1681 } 1682 1683 mContext = context; 1684 mFactoryTest = factoryTest; 1685 mOnlyCore = onlyCore; 1686 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1687 mMetrics = new DisplayMetrics(); 1688 mSettings = new Settings(mPackages); 1689 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 1702 // TODO: add a property to control this? 1703 long dexOptLRUThresholdInMinutes; 1704 if (mLazyDexOpt) { 1705 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1706 } else { 1707 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1708 } 1709 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1710 1711 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1712 if (separateProcesses != null && separateProcesses.length() > 0) { 1713 if ("*".equals(separateProcesses)) { 1714 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1715 mSeparateProcesses = null; 1716 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1717 } else { 1718 mDefParseFlags = 0; 1719 mSeparateProcesses = separateProcesses.split(","); 1720 Slog.w(TAG, "Running with debug.separate_processes: " 1721 + separateProcesses); 1722 } 1723 } else { 1724 mDefParseFlags = 0; 1725 mSeparateProcesses = null; 1726 } 1727 1728 mInstaller = installer; 1729 mPackageDexOptimizer = new PackageDexOptimizer(this); 1730 1731 getDefaultDisplayMetrics(context, mMetrics); 1732 1733 SystemConfig systemConfig = SystemConfig.getInstance(); 1734 mGlobalGids = systemConfig.getGlobalGids(); 1735 mSystemPermissions = systemConfig.getSystemPermissions(); 1736 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1737 1738 synchronized (mInstallLock) { 1739 // writer 1740 synchronized (mPackages) { 1741 mHandlerThread = new ServiceThread(TAG, 1742 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1743 mHandlerThread.start(); 1744 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1745 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1746 1747 File dataDir = Environment.getDataDirectory(); 1748 mAppDataDir = new File(dataDir, "data"); 1749 mAppInstallDir = new File(dataDir, "app"); 1750 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1751 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1752 mUserAppDataDir = new File(dataDir, "user"); 1753 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1754 1755 sUserManager = new UserManagerService(context, this, 1756 mInstallLock, mPackages); 1757 1758 // Propagate permission configuration in to package manager. 1759 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1760 = systemConfig.getPermissions(); 1761 for (int i=0; i<permConfig.size(); i++) { 1762 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1763 BasePermission bp = mSettings.mPermissions.get(perm.name); 1764 if (bp == null) { 1765 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1766 mSettings.mPermissions.put(perm.name, bp); 1767 } 1768 if (perm.gids != null) { 1769 bp.setGids(perm.gids, perm.perUser); 1770 } 1771 } 1772 1773 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1774 for (int i=0; i<libConfig.size(); i++) { 1775 mSharedLibraries.put(libConfig.keyAt(i), 1776 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1777 } 1778 1779 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1780 1781 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1782 mSdkVersion, mOnlyCore); 1783 1784 String customResolverActivity = Resources.getSystem().getString( 1785 R.string.config_customResolverActivity); 1786 if (TextUtils.isEmpty(customResolverActivity)) { 1787 customResolverActivity = null; 1788 } else { 1789 mCustomResolverComponentName = ComponentName.unflattenFromString( 1790 customResolverActivity); 1791 } 1792 1793 long startTime = SystemClock.uptimeMillis(); 1794 1795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1796 startTime); 1797 1798 // Set flag to monitor and not change apk file paths when 1799 // scanning install directories. 1800 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1801 1802 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1803 1804 /** 1805 * Add everything in the in the boot class path to the 1806 * list of process files because dexopt will have been run 1807 * if necessary during zygote startup. 1808 */ 1809 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1810 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1811 1812 if (bootClassPath != null) { 1813 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1814 for (String element : bootClassPathElements) { 1815 alreadyDexOpted.add(element); 1816 } 1817 } else { 1818 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1819 } 1820 1821 if (systemServerClassPath != null) { 1822 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1823 for (String element : systemServerClassPathElements) { 1824 alreadyDexOpted.add(element); 1825 } 1826 } else { 1827 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1828 } 1829 1830 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1831 final String[] dexCodeInstructionSets = 1832 getDexCodeInstructionSets( 1833 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1834 1835 /** 1836 * Ensure all external libraries have had dexopt run on them. 1837 */ 1838 if (mSharedLibraries.size() > 0) { 1839 // NOTE: For now, we're compiling these system "shared libraries" 1840 // (and framework jars) into all available architectures. It's possible 1841 // to compile them only when we come across an app that uses them (there's 1842 // already logic for that in scanPackageLI) but that adds some complexity. 1843 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1844 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1845 final String lib = libEntry.path; 1846 if (lib == null) { 1847 continue; 1848 } 1849 1850 try { 1851 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1852 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1853 alreadyDexOpted.add(lib); 1854 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1855 } 1856 } catch (FileNotFoundException e) { 1857 Slog.w(TAG, "Library not found: " + lib); 1858 } catch (IOException e) { 1859 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1860 + e.getMessage()); 1861 } 1862 } 1863 } 1864 } 1865 1866 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1867 1868 // Gross hack for now: we know this file doesn't contain any 1869 // code, so don't dexopt it to avoid the resulting log spew. 1870 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1871 1872 // Gross hack for now: we know this file is only part of 1873 // the boot class path for art, so don't dexopt it to 1874 // avoid the resulting log spew. 1875 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1876 1877 /** 1878 * And there are a number of commands implemented in Java, which 1879 * we currently need to do the dexopt on so that they can be 1880 * run from a non-root shell. 1881 */ 1882 String[] frameworkFiles = frameworkDir.list(); 1883 if (frameworkFiles != null) { 1884 // TODO: We could compile these only for the most preferred ABI. We should 1885 // first double check that the dex files for these commands are not referenced 1886 // by other system apps. 1887 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1888 for (int i=0; i<frameworkFiles.length; i++) { 1889 File libPath = new File(frameworkDir, frameworkFiles[i]); 1890 String path = libPath.getPath(); 1891 // Skip the file if we already did it. 1892 if (alreadyDexOpted.contains(path)) { 1893 continue; 1894 } 1895 // Skip the file if it is not a type we want to dexopt. 1896 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1897 continue; 1898 } 1899 try { 1900 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1901 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1902 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1903 } 1904 } catch (FileNotFoundException e) { 1905 Slog.w(TAG, "Jar not found: " + path); 1906 } catch (IOException e) { 1907 Slog.w(TAG, "Exception reading jar: " + path, e); 1908 } 1909 } 1910 } 1911 } 1912 1913 // Collect vendor overlay packages. 1914 // (Do this before scanning any apps.) 1915 // For security and version matching reason, only consider 1916 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1917 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1918 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1919 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1920 1921 // Find base frameworks (resource packages without code). 1922 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1923 | PackageParser.PARSE_IS_SYSTEM_DIR 1924 | PackageParser.PARSE_IS_PRIVILEGED, 1925 scanFlags | SCAN_NO_DEX, 0); 1926 1927 // Collected privileged system packages. 1928 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1929 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR 1931 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1932 1933 // Collect ordinary system packages. 1934 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1935 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1936 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1937 1938 // Collect all vendor packages. 1939 File vendorAppDir = new File("/vendor/app"); 1940 try { 1941 vendorAppDir = vendorAppDir.getCanonicalFile(); 1942 } catch (IOException e) { 1943 // failed to look up canonical path, continue with original one 1944 } 1945 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1946 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1947 1948 // Collect all OEM packages. 1949 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1950 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1951 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1952 1953 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1954 mInstaller.moveFiles(); 1955 1956 // Prune any system packages that no longer exist. 1957 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1958 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1959 if (!mOnlyCore) { 1960 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1961 while (psit.hasNext()) { 1962 PackageSetting ps = psit.next(); 1963 1964 /* 1965 * If this is not a system app, it can't be a 1966 * disable system app. 1967 */ 1968 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1969 continue; 1970 } 1971 1972 /* 1973 * If the package is scanned, it's not erased. 1974 */ 1975 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1976 if (scannedPkg != null) { 1977 /* 1978 * If the system app is both scanned and in the 1979 * disabled packages list, then it must have been 1980 * added via OTA. Remove it from the currently 1981 * scanned package so the previously user-installed 1982 * application can be scanned. 1983 */ 1984 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1985 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1986 + ps.name + "; removing system app. Last known codePath=" 1987 + ps.codePathString + ", installStatus=" + ps.installStatus 1988 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1989 + scannedPkg.mVersionCode); 1990 removePackageLI(ps, true); 1991 expectingBetter.put(ps.name, ps.codePath); 1992 } 1993 1994 continue; 1995 } 1996 1997 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1998 psit.remove(); 1999 logCriticalInfo(Log.WARN, "System package " + ps.name 2000 + " no longer exists; wiping its data"); 2001 removeDataDirsLI(ps.name); 2002 } else { 2003 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2004 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2005 possiblyDeletedUpdatedSystemApps.add(ps.name); 2006 } 2007 } 2008 } 2009 } 2010 2011 //look for any incomplete package installations 2012 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2013 //clean up list 2014 for(int i = 0; i < deletePkgsList.size(); i++) { 2015 //clean up here 2016 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2017 } 2018 //delete tmp files 2019 deleteTempPackageFiles(); 2020 2021 // Remove any shared userIDs that have no associated packages 2022 mSettings.pruneSharedUsersLPw(); 2023 2024 if (!mOnlyCore) { 2025 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2026 SystemClock.uptimeMillis()); 2027 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2028 2029 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2030 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2031 2032 /** 2033 * Remove disable package settings for any updated system 2034 * apps that were removed via an OTA. If they're not a 2035 * previously-updated app, remove them completely. 2036 * Otherwise, just revoke their system-level permissions. 2037 */ 2038 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2039 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2040 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2041 2042 String msg; 2043 if (deletedPkg == null) { 2044 msg = "Updated system package " + deletedAppName 2045 + " no longer exists; wiping its data"; 2046 removeDataDirsLI(deletedAppName); 2047 } else { 2048 msg = "Updated system app + " + deletedAppName 2049 + " no longer present; removing system privileges for " 2050 + deletedAppName; 2051 2052 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2053 2054 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2055 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2056 } 2057 logCriticalInfo(Log.WARN, msg); 2058 } 2059 2060 /** 2061 * Make sure all system apps that we expected to appear on 2062 * the userdata partition actually showed up. If they never 2063 * appeared, crawl back and revive the system version. 2064 */ 2065 for (int i = 0; i < expectingBetter.size(); i++) { 2066 final String packageName = expectingBetter.keyAt(i); 2067 if (!mPackages.containsKey(packageName)) { 2068 final File scanFile = expectingBetter.valueAt(i); 2069 2070 logCriticalInfo(Log.WARN, "Expected better " + packageName 2071 + " but never showed up; reverting to system"); 2072 2073 final int reparseFlags; 2074 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR 2077 | PackageParser.PARSE_IS_PRIVILEGED; 2078 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2079 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR; 2081 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2082 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR; 2084 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2085 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR; 2087 } else { 2088 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2089 continue; 2090 } 2091 2092 mSettings.enableSystemPackageLPw(packageName); 2093 2094 try { 2095 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2096 } catch (PackageManagerException e) { 2097 Slog.e(TAG, "Failed to parse original system package: " 2098 + e.getMessage()); 2099 } 2100 } 2101 } 2102 } 2103 2104 // Now that we know all of the shared libraries, update all clients to have 2105 // the correct library paths. 2106 updateAllSharedLibrariesLPw(); 2107 2108 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2109 // NOTE: We ignore potential failures here during a system scan (like 2110 // the rest of the commands above) because there's precious little we 2111 // can do about it. A settings error is reported, though. 2112 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2113 false /* force dexopt */, false /* defer dexopt */); 2114 } 2115 2116 // Now that we know all the packages we are keeping, 2117 // read and update their last usage times. 2118 mPackageUsage.readLP(); 2119 2120 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2121 SystemClock.uptimeMillis()); 2122 Slog.i(TAG, "Time to scan packages: " 2123 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2124 + " seconds"); 2125 2126 // If the platform SDK has changed since the last time we booted, 2127 // we need to re-grant app permission to catch any new ones that 2128 // appear. This is really a hack, and means that apps can in some 2129 // cases get permissions that the user didn't initially explicitly 2130 // allow... it would be nice to have some better way to handle 2131 // this situation. 2132 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2133 != mSdkVersion; 2134 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2135 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2136 + "; regranting permissions for internal storage"); 2137 mSettings.mInternalSdkPlatform = mSdkVersion; 2138 2139 // For now runtime permissions are toggled via a system property. 2140 if (!RUNTIME_PERMISSIONS_ENABLED) { 2141 // Remove the runtime permissions state if the feature 2142 // was disabled by flipping the system property. 2143 mSettings.deleteRuntimePermissionsFiles(); 2144 } 2145 2146 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2147 | (regrantPermissions 2148 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2149 : 0)); 2150 2151 // If this is the first boot, and it is a normal boot, then 2152 // we need to initialize the default preferred apps. 2153 if (!mRestoredSettings && !onlyCore) { 2154 mSettings.readDefaultPreferredAppsLPw(this, 0); 2155 } 2156 2157 // If this is first boot after an OTA, and a normal boot, then 2158 // we need to clear code cache directories. 2159 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2160 if (mIsUpgrade && !onlyCore) { 2161 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2162 for (String pkgName : mSettings.mPackages.keySet()) { 2163 deleteCodeCacheDirsLI(pkgName); 2164 } 2165 mSettings.mFingerprint = Build.FINGERPRINT; 2166 } 2167 2168 // All the changes are done during package scanning. 2169 mSettings.updateInternalDatabaseVersion(); 2170 2171 // can downgrade to reader 2172 mSettings.writeLPr(); 2173 2174 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2175 SystemClock.uptimeMillis()); 2176 2177 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2178 2179 mInstallerService = new PackageInstallerService(context, this); 2180 2181 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2182 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2183 mIntentFilterVerifierComponent); 2184 2185 primeDomainVerificationsLPw(false); 2186 2187 } // synchronized (mPackages) 2188 } // synchronized (mInstallLock) 2189 2190 // Now after opening every single application zip, make sure they 2191 // are all flushed. Not really needed, but keeps things nice and 2192 // tidy. 2193 Runtime.getRuntime().gc(); 2194 } 2195 2196 @Override 2197 public boolean isFirstBoot() { 2198 return !mRestoredSettings; 2199 } 2200 2201 @Override 2202 public boolean isOnlyCoreApps() { 2203 return mOnlyCore; 2204 } 2205 2206 @Override 2207 public boolean isUpgrade() { 2208 return mIsUpgrade; 2209 } 2210 2211 private String getRequiredVerifierLPr() { 2212 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2213 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2214 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2215 2216 String requiredVerifier = null; 2217 2218 final int N = receivers.size(); 2219 for (int i = 0; i < N; i++) { 2220 final ResolveInfo info = receivers.get(i); 2221 2222 if (info.activityInfo == null) { 2223 continue; 2224 } 2225 2226 final String packageName = info.activityInfo.packageName; 2227 2228 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2229 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2230 continue; 2231 } 2232 2233 if (requiredVerifier != null) { 2234 throw new RuntimeException("There can be only one required verifier"); 2235 } 2236 2237 requiredVerifier = packageName; 2238 } 2239 2240 return requiredVerifier; 2241 } 2242 2243 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2244 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2245 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2246 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2247 2248 ComponentName verifierComponentName = null; 2249 2250 int priority = -1000; 2251 final int N = receivers.size(); 2252 for (int i = 0; i < N; i++) { 2253 final ResolveInfo info = receivers.get(i); 2254 2255 if (info.activityInfo == null) { 2256 continue; 2257 } 2258 2259 final String packageName = info.activityInfo.packageName; 2260 2261 final PackageSetting ps = mSettings.mPackages.get(packageName); 2262 if (ps == null) { 2263 continue; 2264 } 2265 2266 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2267 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2268 continue; 2269 } 2270 2271 // Select the IntentFilterVerifier with the highest priority 2272 if (priority < info.priority) { 2273 priority = info.priority; 2274 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2275 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2276 " with priority: " + info.priority); 2277 } 2278 } 2279 2280 return verifierComponentName; 2281 } 2282 2283 private void primeDomainVerificationsLPw(boolean logging) { 2284 Slog.d(TAG, "Start priming domain verification"); 2285 boolean updated = false; 2286 ArrayList<String> allHosts = new ArrayList<>(); 2287 for (PackageParser.Package pkg : mPackages.values()) { 2288 final String packageName = pkg.packageName; 2289 if (!hasDomainURLs(pkg)) { 2290 if (logging) { 2291 Slog.d(TAG, "No priming domain verifications for " + 2292 "package with no domain URLs: " + packageName); 2293 } 2294 continue; 2295 } 2296 for (PackageParser.Activity a : pkg.activities) { 2297 for (ActivityIntentInfo filter : a.intents) { 2298 if (hasValidDomains(filter, false)) { 2299 allHosts.addAll(filter.getHostsList()); 2300 } 2301 } 2302 } 2303 if (allHosts.size() > 0) { 2304 allHosts.add("*"); 2305 } 2306 IntentFilterVerificationInfo ivi = 2307 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2308 if (ivi != null) { 2309 // We will always log this 2310 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2311 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2312 updated = true; 2313 } 2314 else { 2315 if (logging) { 2316 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2317 } 2318 } 2319 allHosts.clear(); 2320 } 2321 if (updated) { 2322 scheduleWriteSettingsLocked(); 2323 } 2324 Slog.d(TAG, "End priming domain verification"); 2325 } 2326 2327 @Override 2328 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2329 throws RemoteException { 2330 try { 2331 return super.onTransact(code, data, reply, flags); 2332 } catch (RuntimeException e) { 2333 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2334 Slog.wtf(TAG, "Package Manager Crash", e); 2335 } 2336 throw e; 2337 } 2338 } 2339 2340 void cleanupInstallFailedPackage(PackageSetting ps) { 2341 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2342 2343 removeDataDirsLI(ps.name); 2344 if (ps.codePath != null) { 2345 if (ps.codePath.isDirectory()) { 2346 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2347 } else { 2348 ps.codePath.delete(); 2349 } 2350 } 2351 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2352 if (ps.resourcePath.isDirectory()) { 2353 FileUtils.deleteContents(ps.resourcePath); 2354 } 2355 ps.resourcePath.delete(); 2356 } 2357 mSettings.removePackageLPw(ps.name); 2358 } 2359 2360 static int[] appendInts(int[] cur, int[] add) { 2361 if (add == null) return cur; 2362 if (cur == null) return add; 2363 final int N = add.length; 2364 for (int i=0; i<N; i++) { 2365 cur = appendInt(cur, add[i]); 2366 } 2367 return cur; 2368 } 2369 2370 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2371 if (!sUserManager.exists(userId)) return null; 2372 final PackageSetting ps = (PackageSetting) p.mExtras; 2373 if (ps == null) { 2374 return null; 2375 } 2376 2377 final PermissionsState permissionsState = ps.getPermissionsState(); 2378 2379 final int[] gids = permissionsState.computeGids(userId); 2380 final Set<String> permissions = permissionsState.getPermissions(userId); 2381 final PackageUserState state = ps.readUserState(userId); 2382 2383 return PackageParser.generatePackageInfo(p, gids, flags, 2384 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2385 } 2386 2387 @Override 2388 public boolean isPackageAvailable(String packageName, int userId) { 2389 if (!sUserManager.exists(userId)) return false; 2390 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2391 synchronized (mPackages) { 2392 PackageParser.Package p = mPackages.get(packageName); 2393 if (p != null) { 2394 final PackageSetting ps = (PackageSetting) p.mExtras; 2395 if (ps != null) { 2396 final PackageUserState state = ps.readUserState(userId); 2397 if (state != null) { 2398 return PackageParser.isAvailable(state); 2399 } 2400 } 2401 } 2402 } 2403 return false; 2404 } 2405 2406 @Override 2407 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2408 if (!sUserManager.exists(userId)) return null; 2409 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2410 // reader 2411 synchronized (mPackages) { 2412 PackageParser.Package p = mPackages.get(packageName); 2413 if (DEBUG_PACKAGE_INFO) 2414 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2415 if (p != null) { 2416 return generatePackageInfo(p, flags, userId); 2417 } 2418 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2419 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2420 } 2421 } 2422 return null; 2423 } 2424 2425 @Override 2426 public String[] currentToCanonicalPackageNames(String[] names) { 2427 String[] out = new String[names.length]; 2428 // reader 2429 synchronized (mPackages) { 2430 for (int i=names.length-1; i>=0; i--) { 2431 PackageSetting ps = mSettings.mPackages.get(names[i]); 2432 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2433 } 2434 } 2435 return out; 2436 } 2437 2438 @Override 2439 public String[] canonicalToCurrentPackageNames(String[] names) { 2440 String[] out = new String[names.length]; 2441 // reader 2442 synchronized (mPackages) { 2443 for (int i=names.length-1; i>=0; i--) { 2444 String cur = mSettings.mRenamedPackages.get(names[i]); 2445 out[i] = cur != null ? cur : names[i]; 2446 } 2447 } 2448 return out; 2449 } 2450 2451 @Override 2452 public int getPackageUid(String packageName, int userId) { 2453 if (!sUserManager.exists(userId)) return -1; 2454 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2455 2456 // reader 2457 synchronized (mPackages) { 2458 PackageParser.Package p = mPackages.get(packageName); 2459 if(p != null) { 2460 return UserHandle.getUid(userId, p.applicationInfo.uid); 2461 } 2462 PackageSetting ps = mSettings.mPackages.get(packageName); 2463 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2464 return -1; 2465 } 2466 p = ps.pkg; 2467 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2468 } 2469 } 2470 2471 @Override 2472 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2473 if (!sUserManager.exists(userId)) { 2474 return null; 2475 } 2476 2477 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2478 "getPackageGids"); 2479 2480 // reader 2481 synchronized (mPackages) { 2482 PackageParser.Package p = mPackages.get(packageName); 2483 if (DEBUG_PACKAGE_INFO) { 2484 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2485 } 2486 if (p != null) { 2487 PackageSetting ps = (PackageSetting) p.mExtras; 2488 return ps.getPermissionsState().computeGids(userId); 2489 } 2490 } 2491 2492 return null; 2493 } 2494 2495 static PermissionInfo generatePermissionInfo( 2496 BasePermission bp, int flags) { 2497 if (bp.perm != null) { 2498 return PackageParser.generatePermissionInfo(bp.perm, flags); 2499 } 2500 PermissionInfo pi = new PermissionInfo(); 2501 pi.name = bp.name; 2502 pi.packageName = bp.sourcePackage; 2503 pi.nonLocalizedLabel = bp.name; 2504 pi.protectionLevel = bp.protectionLevel; 2505 return pi; 2506 } 2507 2508 @Override 2509 public PermissionInfo getPermissionInfo(String name, int flags) { 2510 // reader 2511 synchronized (mPackages) { 2512 final BasePermission p = mSettings.mPermissions.get(name); 2513 if (p != null) { 2514 return generatePermissionInfo(p, flags); 2515 } 2516 return null; 2517 } 2518 } 2519 2520 @Override 2521 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2522 // reader 2523 synchronized (mPackages) { 2524 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2525 for (BasePermission p : mSettings.mPermissions.values()) { 2526 if (group == null) { 2527 if (p.perm == null || p.perm.info.group == null) { 2528 out.add(generatePermissionInfo(p, flags)); 2529 } 2530 } else { 2531 if (p.perm != null && group.equals(p.perm.info.group)) { 2532 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2533 } 2534 } 2535 } 2536 2537 if (out.size() > 0) { 2538 return out; 2539 } 2540 return mPermissionGroups.containsKey(group) ? out : null; 2541 } 2542 } 2543 2544 @Override 2545 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2546 // reader 2547 synchronized (mPackages) { 2548 return PackageParser.generatePermissionGroupInfo( 2549 mPermissionGroups.get(name), flags); 2550 } 2551 } 2552 2553 @Override 2554 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2555 // reader 2556 synchronized (mPackages) { 2557 final int N = mPermissionGroups.size(); 2558 ArrayList<PermissionGroupInfo> out 2559 = new ArrayList<PermissionGroupInfo>(N); 2560 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2561 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2562 } 2563 return out; 2564 } 2565 } 2566 2567 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2568 int userId) { 2569 if (!sUserManager.exists(userId)) return null; 2570 PackageSetting ps = mSettings.mPackages.get(packageName); 2571 if (ps != null) { 2572 if (ps.pkg == null) { 2573 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2574 flags, userId); 2575 if (pInfo != null) { 2576 return pInfo.applicationInfo; 2577 } 2578 return null; 2579 } 2580 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2581 ps.readUserState(userId), userId); 2582 } 2583 return null; 2584 } 2585 2586 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2587 int userId) { 2588 if (!sUserManager.exists(userId)) return null; 2589 PackageSetting ps = mSettings.mPackages.get(packageName); 2590 if (ps != null) { 2591 PackageParser.Package pkg = ps.pkg; 2592 if (pkg == null) { 2593 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2594 return null; 2595 } 2596 // Only data remains, so we aren't worried about code paths 2597 pkg = new PackageParser.Package(packageName); 2598 pkg.applicationInfo.packageName = packageName; 2599 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2600 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2601 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2602 packageName, userId).getAbsolutePath(); 2603 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2604 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2605 } 2606 return generatePackageInfo(pkg, flags, userId); 2607 } 2608 return null; 2609 } 2610 2611 @Override 2612 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2613 if (!sUserManager.exists(userId)) return null; 2614 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2615 // writer 2616 synchronized (mPackages) { 2617 PackageParser.Package p = mPackages.get(packageName); 2618 if (DEBUG_PACKAGE_INFO) Log.v( 2619 TAG, "getApplicationInfo " + packageName 2620 + ": " + p); 2621 if (p != null) { 2622 PackageSetting ps = mSettings.mPackages.get(packageName); 2623 if (ps == null) return null; 2624 // Note: isEnabledLP() does not apply here - always return info 2625 return PackageParser.generateApplicationInfo( 2626 p, flags, ps.readUserState(userId), userId); 2627 } 2628 if ("android".equals(packageName)||"system".equals(packageName)) { 2629 return mAndroidApplication; 2630 } 2631 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2632 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2633 } 2634 } 2635 return null; 2636 } 2637 2638 2639 @Override 2640 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2641 mContext.enforceCallingOrSelfPermission( 2642 android.Manifest.permission.CLEAR_APP_CACHE, null); 2643 // Queue up an async operation since clearing cache may take a little while. 2644 mHandler.post(new Runnable() { 2645 public void run() { 2646 mHandler.removeCallbacks(this); 2647 int retCode = -1; 2648 synchronized (mInstallLock) { 2649 retCode = mInstaller.freeCache(freeStorageSize); 2650 if (retCode < 0) { 2651 Slog.w(TAG, "Couldn't clear application caches"); 2652 } 2653 } 2654 if (observer != null) { 2655 try { 2656 observer.onRemoveCompleted(null, (retCode >= 0)); 2657 } catch (RemoteException e) { 2658 Slog.w(TAG, "RemoveException when invoking call back"); 2659 } 2660 } 2661 } 2662 }); 2663 } 2664 2665 @Override 2666 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2667 mContext.enforceCallingOrSelfPermission( 2668 android.Manifest.permission.CLEAR_APP_CACHE, null); 2669 // Queue up an async operation since clearing cache may take a little while. 2670 mHandler.post(new Runnable() { 2671 public void run() { 2672 mHandler.removeCallbacks(this); 2673 int retCode = -1; 2674 synchronized (mInstallLock) { 2675 retCode = mInstaller.freeCache(freeStorageSize); 2676 if (retCode < 0) { 2677 Slog.w(TAG, "Couldn't clear application caches"); 2678 } 2679 } 2680 if(pi != null) { 2681 try { 2682 // Callback via pending intent 2683 int code = (retCode >= 0) ? 1 : 0; 2684 pi.sendIntent(null, code, null, 2685 null, null); 2686 } catch (SendIntentException e1) { 2687 Slog.i(TAG, "Failed to send pending intent"); 2688 } 2689 } 2690 } 2691 }); 2692 } 2693 2694 void freeStorage(long freeStorageSize) throws IOException { 2695 synchronized (mInstallLock) { 2696 if (mInstaller.freeCache(freeStorageSize) < 0) { 2697 throw new IOException("Failed to free enough space"); 2698 } 2699 } 2700 } 2701 2702 @Override 2703 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2704 if (!sUserManager.exists(userId)) return null; 2705 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2706 synchronized (mPackages) { 2707 PackageParser.Activity a = mActivities.mActivities.get(component); 2708 2709 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2710 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2711 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2712 if (ps == null) return null; 2713 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2714 userId); 2715 } 2716 if (mResolveComponentName.equals(component)) { 2717 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2718 new PackageUserState(), userId); 2719 } 2720 } 2721 return null; 2722 } 2723 2724 @Override 2725 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2726 String resolvedType) { 2727 synchronized (mPackages) { 2728 PackageParser.Activity a = mActivities.mActivities.get(component); 2729 if (a == null) { 2730 return false; 2731 } 2732 for (int i=0; i<a.intents.size(); i++) { 2733 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2734 intent.getData(), intent.getCategories(), TAG) >= 0) { 2735 return true; 2736 } 2737 } 2738 return false; 2739 } 2740 } 2741 2742 @Override 2743 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2744 if (!sUserManager.exists(userId)) return null; 2745 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2746 synchronized (mPackages) { 2747 PackageParser.Activity a = mReceivers.mActivities.get(component); 2748 if (DEBUG_PACKAGE_INFO) Log.v( 2749 TAG, "getReceiverInfo " + component + ": " + a); 2750 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2751 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2752 if (ps == null) return null; 2753 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2754 userId); 2755 } 2756 } 2757 return null; 2758 } 2759 2760 @Override 2761 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2762 if (!sUserManager.exists(userId)) return null; 2763 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2764 synchronized (mPackages) { 2765 PackageParser.Service s = mServices.mServices.get(component); 2766 if (DEBUG_PACKAGE_INFO) Log.v( 2767 TAG, "getServiceInfo " + component + ": " + s); 2768 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2769 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2770 if (ps == null) return null; 2771 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2772 userId); 2773 } 2774 } 2775 return null; 2776 } 2777 2778 @Override 2779 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2780 if (!sUserManager.exists(userId)) return null; 2781 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2782 synchronized (mPackages) { 2783 PackageParser.Provider p = mProviders.mProviders.get(component); 2784 if (DEBUG_PACKAGE_INFO) Log.v( 2785 TAG, "getProviderInfo " + component + ": " + p); 2786 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2787 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2788 if (ps == null) return null; 2789 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2790 userId); 2791 } 2792 } 2793 return null; 2794 } 2795 2796 @Override 2797 public String[] getSystemSharedLibraryNames() { 2798 Set<String> libSet; 2799 synchronized (mPackages) { 2800 libSet = mSharedLibraries.keySet(); 2801 int size = libSet.size(); 2802 if (size > 0) { 2803 String[] libs = new String[size]; 2804 libSet.toArray(libs); 2805 return libs; 2806 } 2807 } 2808 return null; 2809 } 2810 2811 /** 2812 * @hide 2813 */ 2814 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2815 synchronized (mPackages) { 2816 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2817 if (lib != null && lib.apk != null) { 2818 return mPackages.get(lib.apk); 2819 } 2820 } 2821 return null; 2822 } 2823 2824 @Override 2825 public FeatureInfo[] getSystemAvailableFeatures() { 2826 Collection<FeatureInfo> featSet; 2827 synchronized (mPackages) { 2828 featSet = mAvailableFeatures.values(); 2829 int size = featSet.size(); 2830 if (size > 0) { 2831 FeatureInfo[] features = new FeatureInfo[size+1]; 2832 featSet.toArray(features); 2833 FeatureInfo fi = new FeatureInfo(); 2834 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2835 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2836 features[size] = fi; 2837 return features; 2838 } 2839 } 2840 return null; 2841 } 2842 2843 @Override 2844 public boolean hasSystemFeature(String name) { 2845 synchronized (mPackages) { 2846 return mAvailableFeatures.containsKey(name); 2847 } 2848 } 2849 2850 private void checkValidCaller(int uid, int userId) { 2851 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2852 return; 2853 2854 throw new SecurityException("Caller uid=" + uid 2855 + " is not privileged to communicate with user=" + userId); 2856 } 2857 2858 @Override 2859 public int checkPermission(String permName, String pkgName, int userId) { 2860 if (!sUserManager.exists(userId)) { 2861 return PackageManager.PERMISSION_DENIED; 2862 } 2863 2864 synchronized (mPackages) { 2865 final PackageParser.Package p = mPackages.get(pkgName); 2866 if (p != null && p.mExtras != null) { 2867 final PackageSetting ps = (PackageSetting) p.mExtras; 2868 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2869 return PackageManager.PERMISSION_GRANTED; 2870 } 2871 } 2872 } 2873 2874 return PackageManager.PERMISSION_DENIED; 2875 } 2876 2877 @Override 2878 public int checkUidPermission(String permName, int uid) { 2879 final int userId = UserHandle.getUserId(uid); 2880 2881 if (!sUserManager.exists(userId)) { 2882 return PackageManager.PERMISSION_DENIED; 2883 } 2884 2885 synchronized (mPackages) { 2886 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2887 if (obj != null) { 2888 final SettingBase ps = (SettingBase) obj; 2889 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2890 return PackageManager.PERMISSION_GRANTED; 2891 } 2892 } else { 2893 ArraySet<String> perms = mSystemPermissions.get(uid); 2894 if (perms != null && perms.contains(permName)) { 2895 return PackageManager.PERMISSION_GRANTED; 2896 } 2897 } 2898 } 2899 2900 return PackageManager.PERMISSION_DENIED; 2901 } 2902 2903 /** 2904 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2905 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2906 * @param checkShell TODO(yamasani): 2907 * @param message the message to log on security exception 2908 */ 2909 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2910 boolean checkShell, String message) { 2911 if (userId < 0) { 2912 throw new IllegalArgumentException("Invalid userId " + userId); 2913 } 2914 if (checkShell) { 2915 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2916 } 2917 if (userId == UserHandle.getUserId(callingUid)) return; 2918 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2919 if (requireFullPermission) { 2920 mContext.enforceCallingOrSelfPermission( 2921 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2922 } else { 2923 try { 2924 mContext.enforceCallingOrSelfPermission( 2925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2926 } catch (SecurityException se) { 2927 mContext.enforceCallingOrSelfPermission( 2928 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2929 } 2930 } 2931 } 2932 } 2933 2934 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2935 if (callingUid == Process.SHELL_UID) { 2936 if (userHandle >= 0 2937 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2938 throw new SecurityException("Shell does not have permission to access user " 2939 + userHandle); 2940 } else if (userHandle < 0) { 2941 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2942 + Debug.getCallers(3)); 2943 } 2944 } 2945 } 2946 2947 private BasePermission findPermissionTreeLP(String permName) { 2948 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2949 if (permName.startsWith(bp.name) && 2950 permName.length() > bp.name.length() && 2951 permName.charAt(bp.name.length()) == '.') { 2952 return bp; 2953 } 2954 } 2955 return null; 2956 } 2957 2958 private BasePermission checkPermissionTreeLP(String permName) { 2959 if (permName != null) { 2960 BasePermission bp = findPermissionTreeLP(permName); 2961 if (bp != null) { 2962 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2963 return bp; 2964 } 2965 throw new SecurityException("Calling uid " 2966 + Binder.getCallingUid() 2967 + " is not allowed to add to permission tree " 2968 + bp.name + " owned by uid " + bp.uid); 2969 } 2970 } 2971 throw new SecurityException("No permission tree found for " + permName); 2972 } 2973 2974 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2975 if (s1 == null) { 2976 return s2 == null; 2977 } 2978 if (s2 == null) { 2979 return false; 2980 } 2981 if (s1.getClass() != s2.getClass()) { 2982 return false; 2983 } 2984 return s1.equals(s2); 2985 } 2986 2987 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2988 if (pi1.icon != pi2.icon) return false; 2989 if (pi1.logo != pi2.logo) return false; 2990 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2991 if (!compareStrings(pi1.name, pi2.name)) return false; 2992 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2993 // We'll take care of setting this one. 2994 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2995 // These are not currently stored in settings. 2996 //if (!compareStrings(pi1.group, pi2.group)) return false; 2997 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2998 //if (pi1.labelRes != pi2.labelRes) return false; 2999 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3000 return true; 3001 } 3002 3003 int permissionInfoFootprint(PermissionInfo info) { 3004 int size = info.name.length(); 3005 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3006 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3007 return size; 3008 } 3009 3010 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3011 int size = 0; 3012 for (BasePermission perm : mSettings.mPermissions.values()) { 3013 if (perm.uid == tree.uid) { 3014 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3015 } 3016 } 3017 return size; 3018 } 3019 3020 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3021 // We calculate the max size of permissions defined by this uid and throw 3022 // if that plus the size of 'info' would exceed our stated maximum. 3023 if (tree.uid != Process.SYSTEM_UID) { 3024 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3025 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3026 throw new SecurityException("Permission tree size cap exceeded"); 3027 } 3028 } 3029 } 3030 3031 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3032 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3033 throw new SecurityException("Label must be specified in permission"); 3034 } 3035 BasePermission tree = checkPermissionTreeLP(info.name); 3036 BasePermission bp = mSettings.mPermissions.get(info.name); 3037 boolean added = bp == null; 3038 boolean changed = true; 3039 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3040 if (added) { 3041 enforcePermissionCapLocked(info, tree); 3042 bp = new BasePermission(info.name, tree.sourcePackage, 3043 BasePermission.TYPE_DYNAMIC); 3044 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3045 throw new SecurityException( 3046 "Not allowed to modify non-dynamic permission " 3047 + info.name); 3048 } else { 3049 if (bp.protectionLevel == fixedLevel 3050 && bp.perm.owner.equals(tree.perm.owner) 3051 && bp.uid == tree.uid 3052 && comparePermissionInfos(bp.perm.info, info)) { 3053 changed = false; 3054 } 3055 } 3056 bp.protectionLevel = fixedLevel; 3057 info = new PermissionInfo(info); 3058 info.protectionLevel = fixedLevel; 3059 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3060 bp.perm.info.packageName = tree.perm.info.packageName; 3061 bp.uid = tree.uid; 3062 if (added) { 3063 mSettings.mPermissions.put(info.name, bp); 3064 } 3065 if (changed) { 3066 if (!async) { 3067 mSettings.writeLPr(); 3068 } else { 3069 scheduleWriteSettingsLocked(); 3070 } 3071 } 3072 return added; 3073 } 3074 3075 @Override 3076 public boolean addPermission(PermissionInfo info) { 3077 synchronized (mPackages) { 3078 return addPermissionLocked(info, false); 3079 } 3080 } 3081 3082 @Override 3083 public boolean addPermissionAsync(PermissionInfo info) { 3084 synchronized (mPackages) { 3085 return addPermissionLocked(info, true); 3086 } 3087 } 3088 3089 @Override 3090 public void removePermission(String name) { 3091 synchronized (mPackages) { 3092 checkPermissionTreeLP(name); 3093 BasePermission bp = mSettings.mPermissions.get(name); 3094 if (bp != null) { 3095 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3096 throw new SecurityException( 3097 "Not allowed to modify non-dynamic permission " 3098 + name); 3099 } 3100 mSettings.mPermissions.remove(name); 3101 mSettings.writeLPr(); 3102 } 3103 } 3104 } 3105 3106 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3107 BasePermission bp) { 3108 int index = pkg.requestedPermissions.indexOf(bp.name); 3109 if (index == -1) { 3110 throw new SecurityException("Package " + pkg.packageName 3111 + " has not requested permission " + bp.name); 3112 } 3113 if (!bp.isRuntime()) { 3114 throw new SecurityException("Permission " + bp.name 3115 + " is not a changeable permission type"); 3116 } 3117 } 3118 3119 @Override 3120 public boolean grantPermission(String packageName, String name, int userId) { 3121 if (!RUNTIME_PERMISSIONS_ENABLED) { 3122 return false; 3123 } 3124 3125 if (!sUserManager.exists(userId)) { 3126 return false; 3127 } 3128 3129 mContext.enforceCallingOrSelfPermission( 3130 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3131 "grantPermission"); 3132 3133 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3134 "grantPermission"); 3135 3136 boolean gidsChanged = false; 3137 final SettingBase sb; 3138 3139 synchronized (mPackages) { 3140 final PackageParser.Package pkg = mPackages.get(packageName); 3141 if (pkg == null) { 3142 throw new IllegalArgumentException("Unknown package: " + packageName); 3143 } 3144 3145 final BasePermission bp = mSettings.mPermissions.get(name); 3146 if (bp == null) { 3147 throw new IllegalArgumentException("Unknown permission: " + name); 3148 } 3149 3150 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3151 3152 sb = (SettingBase) pkg.mExtras; 3153 if (sb == null) { 3154 throw new IllegalArgumentException("Unknown package: " + packageName); 3155 } 3156 3157 final PermissionsState permissionsState = sb.getPermissionsState(); 3158 3159 final int result = permissionsState.grantRuntimePermission(bp, userId); 3160 switch (result) { 3161 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3162 return false; 3163 } 3164 3165 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3166 gidsChanged = true; 3167 } break; 3168 } 3169 3170 // Not critical if that is lost - app has to request again. 3171 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3172 } 3173 3174 if (gidsChanged) { 3175 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3176 } 3177 3178 return true; 3179 } 3180 3181 @Override 3182 public boolean revokePermission(String packageName, String name, int userId) { 3183 if (!RUNTIME_PERMISSIONS_ENABLED) { 3184 return false; 3185 } 3186 3187 if (!sUserManager.exists(userId)) { 3188 return false; 3189 } 3190 3191 mContext.enforceCallingOrSelfPermission( 3192 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3193 "revokePermission"); 3194 3195 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3196 "revokePermission"); 3197 3198 final SettingBase sb; 3199 3200 synchronized (mPackages) { 3201 final PackageParser.Package pkg = mPackages.get(packageName); 3202 if (pkg == null) { 3203 throw new IllegalArgumentException("Unknown package: " + packageName); 3204 } 3205 3206 final BasePermission bp = mSettings.mPermissions.get(name); 3207 if (bp == null) { 3208 throw new IllegalArgumentException("Unknown permission: " + name); 3209 } 3210 3211 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3212 3213 sb = (SettingBase) pkg.mExtras; 3214 if (sb == null) { 3215 throw new IllegalArgumentException("Unknown package: " + packageName); 3216 } 3217 3218 final PermissionsState permissionsState = sb.getPermissionsState(); 3219 3220 if (permissionsState.revokeRuntimePermission(bp, userId) == 3221 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3222 return false; 3223 } 3224 3225 // Critical, after this call all should never have the permission. 3226 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3227 } 3228 3229 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3230 3231 return true; 3232 } 3233 3234 @Override 3235 public boolean isProtectedBroadcast(String actionName) { 3236 synchronized (mPackages) { 3237 return mProtectedBroadcasts.contains(actionName); 3238 } 3239 } 3240 3241 @Override 3242 public int checkSignatures(String pkg1, String pkg2) { 3243 synchronized (mPackages) { 3244 final PackageParser.Package p1 = mPackages.get(pkg1); 3245 final PackageParser.Package p2 = mPackages.get(pkg2); 3246 if (p1 == null || p1.mExtras == null 3247 || p2 == null || p2.mExtras == null) { 3248 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3249 } 3250 return compareSignatures(p1.mSignatures, p2.mSignatures); 3251 } 3252 } 3253 3254 @Override 3255 public int checkUidSignatures(int uid1, int uid2) { 3256 // Map to base uids. 3257 uid1 = UserHandle.getAppId(uid1); 3258 uid2 = UserHandle.getAppId(uid2); 3259 // reader 3260 synchronized (mPackages) { 3261 Signature[] s1; 3262 Signature[] s2; 3263 Object obj = mSettings.getUserIdLPr(uid1); 3264 if (obj != null) { 3265 if (obj instanceof SharedUserSetting) { 3266 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3267 } else if (obj instanceof PackageSetting) { 3268 s1 = ((PackageSetting)obj).signatures.mSignatures; 3269 } else { 3270 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3271 } 3272 } else { 3273 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3274 } 3275 obj = mSettings.getUserIdLPr(uid2); 3276 if (obj != null) { 3277 if (obj instanceof SharedUserSetting) { 3278 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3279 } else if (obj instanceof PackageSetting) { 3280 s2 = ((PackageSetting)obj).signatures.mSignatures; 3281 } else { 3282 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3283 } 3284 } else { 3285 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3286 } 3287 return compareSignatures(s1, s2); 3288 } 3289 } 3290 3291 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3292 final long identity = Binder.clearCallingIdentity(); 3293 try { 3294 if (sb instanceof SharedUserSetting) { 3295 SharedUserSetting sus = (SharedUserSetting) sb; 3296 final int packageCount = sus.packages.size(); 3297 for (int i = 0; i < packageCount; i++) { 3298 PackageSetting susPs = sus.packages.valueAt(i); 3299 if (userId == UserHandle.USER_ALL) { 3300 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3301 } else { 3302 final int uid = UserHandle.getUid(userId, susPs.appId); 3303 killUid(uid, reason); 3304 } 3305 } 3306 } else if (sb instanceof PackageSetting) { 3307 PackageSetting ps = (PackageSetting) sb; 3308 if (userId == UserHandle.USER_ALL) { 3309 killApplication(ps.pkg.packageName, ps.appId, reason); 3310 } else { 3311 final int uid = UserHandle.getUid(userId, ps.appId); 3312 killUid(uid, reason); 3313 } 3314 } 3315 } finally { 3316 Binder.restoreCallingIdentity(identity); 3317 } 3318 } 3319 3320 private static void killUid(int uid, String reason) { 3321 IActivityManager am = ActivityManagerNative.getDefault(); 3322 if (am != null) { 3323 try { 3324 am.killUid(uid, reason); 3325 } catch (RemoteException e) { 3326 /* ignore - same process */ 3327 } 3328 } 3329 } 3330 3331 /** 3332 * Compares two sets of signatures. Returns: 3333 * <br /> 3334 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3335 * <br /> 3336 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3337 * <br /> 3338 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3339 * <br /> 3340 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3341 * <br /> 3342 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3343 */ 3344 static int compareSignatures(Signature[] s1, Signature[] s2) { 3345 if (s1 == null) { 3346 return s2 == null 3347 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3348 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3349 } 3350 3351 if (s2 == null) { 3352 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3353 } 3354 3355 if (s1.length != s2.length) { 3356 return PackageManager.SIGNATURE_NO_MATCH; 3357 } 3358 3359 // Since both signature sets are of size 1, we can compare without HashSets. 3360 if (s1.length == 1) { 3361 return s1[0].equals(s2[0]) ? 3362 PackageManager.SIGNATURE_MATCH : 3363 PackageManager.SIGNATURE_NO_MATCH; 3364 } 3365 3366 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3367 for (Signature sig : s1) { 3368 set1.add(sig); 3369 } 3370 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3371 for (Signature sig : s2) { 3372 set2.add(sig); 3373 } 3374 // Make sure s2 contains all signatures in s1. 3375 if (set1.equals(set2)) { 3376 return PackageManager.SIGNATURE_MATCH; 3377 } 3378 return PackageManager.SIGNATURE_NO_MATCH; 3379 } 3380 3381 /** 3382 * If the database version for this type of package (internal storage or 3383 * external storage) is less than the version where package signatures 3384 * were updated, return true. 3385 */ 3386 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3387 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3388 DatabaseVersion.SIGNATURE_END_ENTITY)) 3389 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3390 DatabaseVersion.SIGNATURE_END_ENTITY)); 3391 } 3392 3393 /** 3394 * Used for backward compatibility to make sure any packages with 3395 * certificate chains get upgraded to the new style. {@code existingSigs} 3396 * will be in the old format (since they were stored on disk from before the 3397 * system upgrade) and {@code scannedSigs} will be in the newer format. 3398 */ 3399 private int compareSignaturesCompat(PackageSignatures existingSigs, 3400 PackageParser.Package scannedPkg) { 3401 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3402 return PackageManager.SIGNATURE_NO_MATCH; 3403 } 3404 3405 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3406 for (Signature sig : existingSigs.mSignatures) { 3407 existingSet.add(sig); 3408 } 3409 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3410 for (Signature sig : scannedPkg.mSignatures) { 3411 try { 3412 Signature[] chainSignatures = sig.getChainSignatures(); 3413 for (Signature chainSig : chainSignatures) { 3414 scannedCompatSet.add(chainSig); 3415 } 3416 } catch (CertificateEncodingException e) { 3417 scannedCompatSet.add(sig); 3418 } 3419 } 3420 /* 3421 * Make sure the expanded scanned set contains all signatures in the 3422 * existing one. 3423 */ 3424 if (scannedCompatSet.equals(existingSet)) { 3425 // Migrate the old signatures to the new scheme. 3426 existingSigs.assignSignatures(scannedPkg.mSignatures); 3427 // The new KeySets will be re-added later in the scanning process. 3428 synchronized (mPackages) { 3429 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3430 } 3431 return PackageManager.SIGNATURE_MATCH; 3432 } 3433 return PackageManager.SIGNATURE_NO_MATCH; 3434 } 3435 3436 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3437 if (isExternal(scannedPkg)) { 3438 return mSettings.isExternalDatabaseVersionOlderThan( 3439 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3440 } else { 3441 return mSettings.isInternalDatabaseVersionOlderThan( 3442 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3443 } 3444 } 3445 3446 private int compareSignaturesRecover(PackageSignatures existingSigs, 3447 PackageParser.Package scannedPkg) { 3448 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3449 return PackageManager.SIGNATURE_NO_MATCH; 3450 } 3451 3452 String msg = null; 3453 try { 3454 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3455 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3456 + scannedPkg.packageName); 3457 return PackageManager.SIGNATURE_MATCH; 3458 } 3459 } catch (CertificateException e) { 3460 msg = e.getMessage(); 3461 } 3462 3463 logCriticalInfo(Log.INFO, 3464 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3465 return PackageManager.SIGNATURE_NO_MATCH; 3466 } 3467 3468 @Override 3469 public String[] getPackagesForUid(int uid) { 3470 uid = UserHandle.getAppId(uid); 3471 // reader 3472 synchronized (mPackages) { 3473 Object obj = mSettings.getUserIdLPr(uid); 3474 if (obj instanceof SharedUserSetting) { 3475 final SharedUserSetting sus = (SharedUserSetting) obj; 3476 final int N = sus.packages.size(); 3477 final String[] res = new String[N]; 3478 final Iterator<PackageSetting> it = sus.packages.iterator(); 3479 int i = 0; 3480 while (it.hasNext()) { 3481 res[i++] = it.next().name; 3482 } 3483 return res; 3484 } else if (obj instanceof PackageSetting) { 3485 final PackageSetting ps = (PackageSetting) obj; 3486 return new String[] { ps.name }; 3487 } 3488 } 3489 return null; 3490 } 3491 3492 @Override 3493 public String getNameForUid(int uid) { 3494 // reader 3495 synchronized (mPackages) { 3496 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3497 if (obj instanceof SharedUserSetting) { 3498 final SharedUserSetting sus = (SharedUserSetting) obj; 3499 return sus.name + ":" + sus.userId; 3500 } else if (obj instanceof PackageSetting) { 3501 final PackageSetting ps = (PackageSetting) obj; 3502 return ps.name; 3503 } 3504 } 3505 return null; 3506 } 3507 3508 @Override 3509 public int getUidForSharedUser(String sharedUserName) { 3510 if(sharedUserName == null) { 3511 return -1; 3512 } 3513 // reader 3514 synchronized (mPackages) { 3515 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3516 if (suid == null) { 3517 return -1; 3518 } 3519 return suid.userId; 3520 } 3521 } 3522 3523 @Override 3524 public int getFlagsForUid(int uid) { 3525 synchronized (mPackages) { 3526 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3527 if (obj instanceof SharedUserSetting) { 3528 final SharedUserSetting sus = (SharedUserSetting) obj; 3529 return sus.pkgFlags; 3530 } else if (obj instanceof PackageSetting) { 3531 final PackageSetting ps = (PackageSetting) obj; 3532 return ps.pkgFlags; 3533 } 3534 } 3535 return 0; 3536 } 3537 3538 @Override 3539 public int getPrivateFlagsForUid(int uid) { 3540 synchronized (mPackages) { 3541 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3542 if (obj instanceof SharedUserSetting) { 3543 final SharedUserSetting sus = (SharedUserSetting) obj; 3544 return sus.pkgPrivateFlags; 3545 } else if (obj instanceof PackageSetting) { 3546 final PackageSetting ps = (PackageSetting) obj; 3547 return ps.pkgPrivateFlags; 3548 } 3549 } 3550 return 0; 3551 } 3552 3553 @Override 3554 public boolean isUidPrivileged(int uid) { 3555 uid = UserHandle.getAppId(uid); 3556 // reader 3557 synchronized (mPackages) { 3558 Object obj = mSettings.getUserIdLPr(uid); 3559 if (obj instanceof SharedUserSetting) { 3560 final SharedUserSetting sus = (SharedUserSetting) obj; 3561 final Iterator<PackageSetting> it = sus.packages.iterator(); 3562 while (it.hasNext()) { 3563 if (it.next().isPrivileged()) { 3564 return true; 3565 } 3566 } 3567 } else if (obj instanceof PackageSetting) { 3568 final PackageSetting ps = (PackageSetting) obj; 3569 return ps.isPrivileged(); 3570 } 3571 } 3572 return false; 3573 } 3574 3575 @Override 3576 public String[] getAppOpPermissionPackages(String permissionName) { 3577 synchronized (mPackages) { 3578 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3579 if (pkgs == null) { 3580 return null; 3581 } 3582 return pkgs.toArray(new String[pkgs.size()]); 3583 } 3584 } 3585 3586 @Override 3587 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3588 int flags, int userId) { 3589 if (!sUserManager.exists(userId)) return null; 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3591 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3592 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3593 } 3594 3595 @Override 3596 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3597 IntentFilter filter, int match, ComponentName activity) { 3598 final int userId = UserHandle.getCallingUserId(); 3599 if (DEBUG_PREFERRED) { 3600 Log.v(TAG, "setLastChosenActivity intent=" + intent 3601 + " resolvedType=" + resolvedType 3602 + " flags=" + flags 3603 + " filter=" + filter 3604 + " match=" + match 3605 + " activity=" + activity); 3606 filter.dump(new PrintStreamPrinter(System.out), " "); 3607 } 3608 intent.setComponent(null); 3609 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3610 // Find any earlier preferred or last chosen entries and nuke them 3611 findPreferredActivity(intent, resolvedType, 3612 flags, query, 0, false, true, false, userId); 3613 // Add the new activity as the last chosen for this filter 3614 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3615 "Setting last chosen"); 3616 } 3617 3618 @Override 3619 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3620 final int userId = UserHandle.getCallingUserId(); 3621 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3622 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3623 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3624 false, false, false, userId); 3625 } 3626 3627 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3628 int flags, List<ResolveInfo> query, int userId) { 3629 if (query != null) { 3630 final int N = query.size(); 3631 if (N == 1) { 3632 return query.get(0); 3633 } else if (N > 1) { 3634 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3635 // If there is more than one activity with the same priority, 3636 // then let the user decide between them. 3637 ResolveInfo r0 = query.get(0); 3638 ResolveInfo r1 = query.get(1); 3639 if (DEBUG_INTENT_MATCHING || debug) { 3640 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3641 + r1.activityInfo.name + "=" + r1.priority); 3642 } 3643 // If the first activity has a higher priority, or a different 3644 // default, then it is always desireable to pick it. 3645 if (r0.priority != r1.priority 3646 || r0.preferredOrder != r1.preferredOrder 3647 || r0.isDefault != r1.isDefault) { 3648 return query.get(0); 3649 } 3650 // If we have saved a preference for a preferred activity for 3651 // this Intent, use that. 3652 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3653 flags, query, r0.priority, true, false, debug, userId); 3654 if (ri != null) { 3655 return ri; 3656 } 3657 if (userId != 0) { 3658 ri = new ResolveInfo(mResolveInfo); 3659 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3660 ri.activityInfo.applicationInfo = new ApplicationInfo( 3661 ri.activityInfo.applicationInfo); 3662 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3663 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3664 return ri; 3665 } 3666 return mResolveInfo; 3667 } 3668 } 3669 return null; 3670 } 3671 3672 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3673 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3674 final int N = query.size(); 3675 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3676 .get(userId); 3677 // Get the list of persistent preferred activities that handle the intent 3678 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3679 List<PersistentPreferredActivity> pprefs = ppir != null 3680 ? ppir.queryIntent(intent, resolvedType, 3681 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3682 : null; 3683 if (pprefs != null && pprefs.size() > 0) { 3684 final int M = pprefs.size(); 3685 for (int i=0; i<M; i++) { 3686 final PersistentPreferredActivity ppa = pprefs.get(i); 3687 if (DEBUG_PREFERRED || debug) { 3688 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3689 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3690 + "\n component=" + ppa.mComponent); 3691 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3692 } 3693 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3694 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3695 if (DEBUG_PREFERRED || debug) { 3696 Slog.v(TAG, "Found persistent preferred activity:"); 3697 if (ai != null) { 3698 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3699 } else { 3700 Slog.v(TAG, " null"); 3701 } 3702 } 3703 if (ai == null) { 3704 // This previously registered persistent preferred activity 3705 // component is no longer known. Ignore it and do NOT remove it. 3706 continue; 3707 } 3708 for (int j=0; j<N; j++) { 3709 final ResolveInfo ri = query.get(j); 3710 if (!ri.activityInfo.applicationInfo.packageName 3711 .equals(ai.applicationInfo.packageName)) { 3712 continue; 3713 } 3714 if (!ri.activityInfo.name.equals(ai.name)) { 3715 continue; 3716 } 3717 // Found a persistent preference that can handle the intent. 3718 if (DEBUG_PREFERRED || debug) { 3719 Slog.v(TAG, "Returning persistent preferred activity: " + 3720 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3721 } 3722 return ri; 3723 } 3724 } 3725 } 3726 return null; 3727 } 3728 3729 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3730 List<ResolveInfo> query, int priority, boolean always, 3731 boolean removeMatches, boolean debug, int userId) { 3732 if (!sUserManager.exists(userId)) return null; 3733 // writer 3734 synchronized (mPackages) { 3735 if (intent.getSelector() != null) { 3736 intent = intent.getSelector(); 3737 } 3738 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3739 3740 // Try to find a matching persistent preferred activity. 3741 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3742 debug, userId); 3743 3744 // If a persistent preferred activity matched, use it. 3745 if (pri != null) { 3746 return pri; 3747 } 3748 3749 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3750 // Get the list of preferred activities that handle the intent 3751 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3752 List<PreferredActivity> prefs = pir != null 3753 ? pir.queryIntent(intent, resolvedType, 3754 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3755 : null; 3756 if (prefs != null && prefs.size() > 0) { 3757 boolean changed = false; 3758 try { 3759 // First figure out how good the original match set is. 3760 // We will only allow preferred activities that came 3761 // from the same match quality. 3762 int match = 0; 3763 3764 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3765 3766 final int N = query.size(); 3767 for (int j=0; j<N; j++) { 3768 final ResolveInfo ri = query.get(j); 3769 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3770 + ": 0x" + Integer.toHexString(match)); 3771 if (ri.match > match) { 3772 match = ri.match; 3773 } 3774 } 3775 3776 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3777 + Integer.toHexString(match)); 3778 3779 match &= IntentFilter.MATCH_CATEGORY_MASK; 3780 final int M = prefs.size(); 3781 for (int i=0; i<M; i++) { 3782 final PreferredActivity pa = prefs.get(i); 3783 if (DEBUG_PREFERRED || debug) { 3784 Slog.v(TAG, "Checking PreferredActivity ds=" 3785 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3786 + "\n component=" + pa.mPref.mComponent); 3787 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3788 } 3789 if (pa.mPref.mMatch != match) { 3790 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3791 + Integer.toHexString(pa.mPref.mMatch)); 3792 continue; 3793 } 3794 // If it's not an "always" type preferred activity and that's what we're 3795 // looking for, skip it. 3796 if (always && !pa.mPref.mAlways) { 3797 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3798 continue; 3799 } 3800 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3801 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3802 if (DEBUG_PREFERRED || debug) { 3803 Slog.v(TAG, "Found preferred activity:"); 3804 if (ai != null) { 3805 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3806 } else { 3807 Slog.v(TAG, " null"); 3808 } 3809 } 3810 if (ai == null) { 3811 // This previously registered preferred activity 3812 // component is no longer known. Most likely an update 3813 // to the app was installed and in the new version this 3814 // component no longer exists. Clean it up by removing 3815 // it from the preferred activities list, and skip it. 3816 Slog.w(TAG, "Removing dangling preferred activity: " 3817 + pa.mPref.mComponent); 3818 pir.removeFilter(pa); 3819 changed = true; 3820 continue; 3821 } 3822 for (int j=0; j<N; j++) { 3823 final ResolveInfo ri = query.get(j); 3824 if (!ri.activityInfo.applicationInfo.packageName 3825 .equals(ai.applicationInfo.packageName)) { 3826 continue; 3827 } 3828 if (!ri.activityInfo.name.equals(ai.name)) { 3829 continue; 3830 } 3831 3832 if (removeMatches) { 3833 pir.removeFilter(pa); 3834 changed = true; 3835 if (DEBUG_PREFERRED) { 3836 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3837 } 3838 break; 3839 } 3840 3841 // Okay we found a previously set preferred or last chosen app. 3842 // If the result set is different from when this 3843 // was created, we need to clear it and re-ask the 3844 // user their preference, if we're looking for an "always" type entry. 3845 if (always && !pa.mPref.sameSet(query)) { 3846 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3847 + intent + " type " + resolvedType); 3848 if (DEBUG_PREFERRED) { 3849 Slog.v(TAG, "Removing preferred activity since set changed " 3850 + pa.mPref.mComponent); 3851 } 3852 pir.removeFilter(pa); 3853 // Re-add the filter as a "last chosen" entry (!always) 3854 PreferredActivity lastChosen = new PreferredActivity( 3855 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3856 pir.addFilter(lastChosen); 3857 changed = true; 3858 return null; 3859 } 3860 3861 // Yay! Either the set matched or we're looking for the last chosen 3862 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3863 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3864 return ri; 3865 } 3866 } 3867 } finally { 3868 if (changed) { 3869 if (DEBUG_PREFERRED) { 3870 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3871 } 3872 scheduleWritePackageRestrictionsLocked(userId); 3873 } 3874 } 3875 } 3876 } 3877 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3878 return null; 3879 } 3880 3881 /* 3882 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3883 */ 3884 @Override 3885 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3886 int targetUserId) { 3887 mContext.enforceCallingOrSelfPermission( 3888 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3889 List<CrossProfileIntentFilter> matches = 3890 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3891 if (matches != null) { 3892 int size = matches.size(); 3893 for (int i = 0; i < size; i++) { 3894 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3895 } 3896 } 3897 return false; 3898 } 3899 3900 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3901 String resolvedType, int userId) { 3902 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3903 if (resolver != null) { 3904 return resolver.queryIntent(intent, resolvedType, false, userId); 3905 } 3906 return null; 3907 } 3908 3909 @Override 3910 public List<ResolveInfo> queryIntentActivities(Intent intent, 3911 String resolvedType, int flags, int userId) { 3912 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3913 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3914 ComponentName comp = intent.getComponent(); 3915 if (comp == null) { 3916 if (intent.getSelector() != null) { 3917 intent = intent.getSelector(); 3918 comp = intent.getComponent(); 3919 } 3920 } 3921 3922 if (comp != null) { 3923 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3924 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3925 if (ai != null) { 3926 final ResolveInfo ri = new ResolveInfo(); 3927 ri.activityInfo = ai; 3928 list.add(ri); 3929 } 3930 return list; 3931 } 3932 3933 // reader 3934 synchronized (mPackages) { 3935 final String pkgName = intent.getPackage(); 3936 if (pkgName == null) { 3937 List<CrossProfileIntentFilter> matchingFilters = 3938 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3939 // Check for results that need to skip the current profile. 3940 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3941 resolvedType, flags, userId); 3942 if (resolveInfo != null) { 3943 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3944 result.add(resolveInfo); 3945 return filterIfNotPrimaryUser(result, userId); 3946 } 3947 // Check for cross profile results. 3948 resolveInfo = queryCrossProfileIntents( 3949 matchingFilters, intent, resolvedType, flags, userId); 3950 3951 // Check for results in the current profile. 3952 List<ResolveInfo> result = mActivities.queryIntent( 3953 intent, resolvedType, flags, userId); 3954 if (resolveInfo != null) { 3955 result.add(resolveInfo); 3956 Collections.sort(result, mResolvePrioritySorter); 3957 } 3958 result = filterIfNotPrimaryUser(result, userId); 3959 if (result.size() > 1 && hasWebURI(intent)) { 3960 return filterCandidatesWithDomainPreferedActivitiesLPr(result); 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 static boolean hasWebURI(Intent intent) { 3994 if (intent.getData() == null) { 3995 return false; 3996 } 3997 final String scheme = intent.getScheme(); 3998 if (TextUtils.isEmpty(scheme)) { 3999 return false; 4000 } 4001 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4002 } 4003 4004 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4005 List<ResolveInfo> candidates) { 4006 if (DEBUG_PREFERRED) { 4007 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4008 candidates.size()); 4009 } 4010 4011 final int userId = UserHandle.getCallingUserId(); 4012 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4013 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4014 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4015 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4016 4017 synchronized (mPackages) { 4018 final int count = candidates.size(); 4019 // First, try to use the domain prefered App 4020 for (int n=0; n<count; n++) { 4021 ResolveInfo info = candidates.get(n); 4022 String packageName = info.activityInfo.packageName; 4023 PackageSetting ps = mSettings.mPackages.get(packageName); 4024 if (ps != null) { 4025 // Try to get the status from User settings first 4026 int status = getDomainVerificationStatusLPr(ps, userId); 4027 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4028 result.add(info); 4029 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4030 neverList.add(info); 4031 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4032 undefinedList.add(info); 4033 } 4034 // Add to the special match all list (Browser use case) 4035 if (info.handleAllWebDataURI) { 4036 matchAllList.add(info); 4037 } 4038 } 4039 } 4040 // If there is nothing selected, add all candidates and remove the ones that the User 4041 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4042 // also remove any Browser Apps ones. 4043 // If there is still none after this pass, add all undefined one and Browser Apps and 4044 // let the User decide with the Disambiguation dialog if there are several ones. 4045 if (result.size() == 0) { 4046 result.addAll(candidates); 4047 } 4048 result.removeAll(neverList); 4049 result.removeAll(matchAllList); 4050 if (result.size() == 0) { 4051 result.addAll(undefinedList); 4052 result.addAll(matchAllList); 4053 } 4054 } 4055 if (DEBUG_PREFERRED) { 4056 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4057 result.size()); 4058 } 4059 return result; 4060 } 4061 4062 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4063 int status = ps.getDomainVerificationStatusForUser(userId); 4064 // if none available, get the master status 4065 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4066 if (ps.getIntentFilterVerificationInfo() != null) { 4067 status = ps.getIntentFilterVerificationInfo().getStatus(); 4068 } 4069 } 4070 return status; 4071 } 4072 4073 private ResolveInfo querySkipCurrentProfileIntents( 4074 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4075 int flags, int sourceUserId) { 4076 if (matchingFilters != null) { 4077 int size = matchingFilters.size(); 4078 for (int i = 0; i < size; i ++) { 4079 CrossProfileIntentFilter filter = matchingFilters.get(i); 4080 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4081 // Checking if there are activities in the target user that can handle the 4082 // intent. 4083 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4084 flags, sourceUserId); 4085 if (resolveInfo != null) { 4086 return resolveInfo; 4087 } 4088 } 4089 } 4090 } 4091 return null; 4092 } 4093 4094 // Return matching ResolveInfo if any for skip current profile intent filters. 4095 private ResolveInfo queryCrossProfileIntents( 4096 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4097 int flags, int sourceUserId) { 4098 if (matchingFilters != null) { 4099 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4100 // match the same intent. For performance reasons, it is better not to 4101 // run queryIntent twice for the same userId 4102 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4103 int size = matchingFilters.size(); 4104 for (int i = 0; i < size; i++) { 4105 CrossProfileIntentFilter filter = matchingFilters.get(i); 4106 int targetUserId = filter.getTargetUserId(); 4107 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4108 && !alreadyTriedUserIds.get(targetUserId)) { 4109 // Checking if there are activities in the target user that can handle the 4110 // intent. 4111 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4112 flags, sourceUserId); 4113 if (resolveInfo != null) return resolveInfo; 4114 alreadyTriedUserIds.put(targetUserId, true); 4115 } 4116 } 4117 } 4118 return null; 4119 } 4120 4121 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4122 String resolvedType, int flags, int sourceUserId) { 4123 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4124 resolvedType, flags, filter.getTargetUserId()); 4125 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4126 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4127 } 4128 return null; 4129 } 4130 4131 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4132 int sourceUserId, int targetUserId) { 4133 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4134 String className; 4135 if (targetUserId == UserHandle.USER_OWNER) { 4136 className = FORWARD_INTENT_TO_USER_OWNER; 4137 } else { 4138 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4139 } 4140 ComponentName forwardingActivityComponentName = new ComponentName( 4141 mAndroidApplication.packageName, className); 4142 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4143 sourceUserId); 4144 if (targetUserId == UserHandle.USER_OWNER) { 4145 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4146 forwardingResolveInfo.noResourceId = true; 4147 } 4148 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4149 forwardingResolveInfo.priority = 0; 4150 forwardingResolveInfo.preferredOrder = 0; 4151 forwardingResolveInfo.match = 0; 4152 forwardingResolveInfo.isDefault = true; 4153 forwardingResolveInfo.filter = filter; 4154 forwardingResolveInfo.targetUserId = targetUserId; 4155 return forwardingResolveInfo; 4156 } 4157 4158 @Override 4159 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4160 Intent[] specifics, String[] specificTypes, Intent intent, 4161 String resolvedType, int flags, int userId) { 4162 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4164 false, "query intent activity options"); 4165 final String resultsAction = intent.getAction(); 4166 4167 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4168 | PackageManager.GET_RESOLVED_FILTER, userId); 4169 4170 if (DEBUG_INTENT_MATCHING) { 4171 Log.v(TAG, "Query " + intent + ": " + results); 4172 } 4173 4174 int specificsPos = 0; 4175 int N; 4176 4177 // todo: note that the algorithm used here is O(N^2). This 4178 // isn't a problem in our current environment, but if we start running 4179 // into situations where we have more than 5 or 10 matches then this 4180 // should probably be changed to something smarter... 4181 4182 // First we go through and resolve each of the specific items 4183 // that were supplied, taking care of removing any corresponding 4184 // duplicate items in the generic resolve list. 4185 if (specifics != null) { 4186 for (int i=0; i<specifics.length; i++) { 4187 final Intent sintent = specifics[i]; 4188 if (sintent == null) { 4189 continue; 4190 } 4191 4192 if (DEBUG_INTENT_MATCHING) { 4193 Log.v(TAG, "Specific #" + i + ": " + sintent); 4194 } 4195 4196 String action = sintent.getAction(); 4197 if (resultsAction != null && resultsAction.equals(action)) { 4198 // If this action was explicitly requested, then don't 4199 // remove things that have it. 4200 action = null; 4201 } 4202 4203 ResolveInfo ri = null; 4204 ActivityInfo ai = null; 4205 4206 ComponentName comp = sintent.getComponent(); 4207 if (comp == null) { 4208 ri = resolveIntent( 4209 sintent, 4210 specificTypes != null ? specificTypes[i] : null, 4211 flags, userId); 4212 if (ri == null) { 4213 continue; 4214 } 4215 if (ri == mResolveInfo) { 4216 // ACK! Must do something better with this. 4217 } 4218 ai = ri.activityInfo; 4219 comp = new ComponentName(ai.applicationInfo.packageName, 4220 ai.name); 4221 } else { 4222 ai = getActivityInfo(comp, flags, userId); 4223 if (ai == null) { 4224 continue; 4225 } 4226 } 4227 4228 // Look for any generic query activities that are duplicates 4229 // of this specific one, and remove them from the results. 4230 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4231 N = results.size(); 4232 int j; 4233 for (j=specificsPos; j<N; j++) { 4234 ResolveInfo sri = results.get(j); 4235 if ((sri.activityInfo.name.equals(comp.getClassName()) 4236 && sri.activityInfo.applicationInfo.packageName.equals( 4237 comp.getPackageName())) 4238 || (action != null && sri.filter.matchAction(action))) { 4239 results.remove(j); 4240 if (DEBUG_INTENT_MATCHING) Log.v( 4241 TAG, "Removing duplicate item from " + j 4242 + " due to specific " + specificsPos); 4243 if (ri == null) { 4244 ri = sri; 4245 } 4246 j--; 4247 N--; 4248 } 4249 } 4250 4251 // Add this specific item to its proper place. 4252 if (ri == null) { 4253 ri = new ResolveInfo(); 4254 ri.activityInfo = ai; 4255 } 4256 results.add(specificsPos, ri); 4257 ri.specificIndex = i; 4258 specificsPos++; 4259 } 4260 } 4261 4262 // Now we go through the remaining generic results and remove any 4263 // duplicate actions that are found here. 4264 N = results.size(); 4265 for (int i=specificsPos; i<N-1; i++) { 4266 final ResolveInfo rii = results.get(i); 4267 if (rii.filter == null) { 4268 continue; 4269 } 4270 4271 // Iterate over all of the actions of this result's intent 4272 // filter... typically this should be just one. 4273 final Iterator<String> it = rii.filter.actionsIterator(); 4274 if (it == null) { 4275 continue; 4276 } 4277 while (it.hasNext()) { 4278 final String action = it.next(); 4279 if (resultsAction != null && resultsAction.equals(action)) { 4280 // If this action was explicitly requested, then don't 4281 // remove things that have it. 4282 continue; 4283 } 4284 for (int j=i+1; j<N; j++) { 4285 final ResolveInfo rij = results.get(j); 4286 if (rij.filter != null && rij.filter.hasAction(action)) { 4287 results.remove(j); 4288 if (DEBUG_INTENT_MATCHING) Log.v( 4289 TAG, "Removing duplicate item from " + j 4290 + " due to action " + action + " at " + i); 4291 j--; 4292 N--; 4293 } 4294 } 4295 } 4296 4297 // If the caller didn't request filter information, drop it now 4298 // so we don't have to marshall/unmarshall it. 4299 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4300 rii.filter = null; 4301 } 4302 } 4303 4304 // Filter out the caller activity if so requested. 4305 if (caller != null) { 4306 N = results.size(); 4307 for (int i=0; i<N; i++) { 4308 ActivityInfo ainfo = results.get(i).activityInfo; 4309 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4310 && caller.getClassName().equals(ainfo.name)) { 4311 results.remove(i); 4312 break; 4313 } 4314 } 4315 } 4316 4317 // If the caller didn't request filter information, 4318 // drop them now so we don't have to 4319 // marshall/unmarshall it. 4320 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4321 N = results.size(); 4322 for (int i=0; i<N; i++) { 4323 results.get(i).filter = null; 4324 } 4325 } 4326 4327 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4328 return results; 4329 } 4330 4331 @Override 4332 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4333 int userId) { 4334 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4335 ComponentName comp = intent.getComponent(); 4336 if (comp == null) { 4337 if (intent.getSelector() != null) { 4338 intent = intent.getSelector(); 4339 comp = intent.getComponent(); 4340 } 4341 } 4342 if (comp != null) { 4343 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4344 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4345 if (ai != null) { 4346 ResolveInfo ri = new ResolveInfo(); 4347 ri.activityInfo = ai; 4348 list.add(ri); 4349 } 4350 return list; 4351 } 4352 4353 // reader 4354 synchronized (mPackages) { 4355 String pkgName = intent.getPackage(); 4356 if (pkgName == null) { 4357 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4358 } 4359 final PackageParser.Package pkg = mPackages.get(pkgName); 4360 if (pkg != null) { 4361 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4362 userId); 4363 } 4364 return null; 4365 } 4366 } 4367 4368 @Override 4369 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4370 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4371 if (!sUserManager.exists(userId)) return null; 4372 if (query != null) { 4373 if (query.size() >= 1) { 4374 // If there is more than one service with the same priority, 4375 // just arbitrarily pick the first one. 4376 return query.get(0); 4377 } 4378 } 4379 return null; 4380 } 4381 4382 @Override 4383 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4384 int userId) { 4385 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4386 ComponentName comp = intent.getComponent(); 4387 if (comp == null) { 4388 if (intent.getSelector() != null) { 4389 intent = intent.getSelector(); 4390 comp = intent.getComponent(); 4391 } 4392 } 4393 if (comp != null) { 4394 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4395 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4396 if (si != null) { 4397 final ResolveInfo ri = new ResolveInfo(); 4398 ri.serviceInfo = si; 4399 list.add(ri); 4400 } 4401 return list; 4402 } 4403 4404 // reader 4405 synchronized (mPackages) { 4406 String pkgName = intent.getPackage(); 4407 if (pkgName == null) { 4408 return mServices.queryIntent(intent, resolvedType, flags, userId); 4409 } 4410 final PackageParser.Package pkg = mPackages.get(pkgName); 4411 if (pkg != null) { 4412 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4413 userId); 4414 } 4415 return null; 4416 } 4417 } 4418 4419 @Override 4420 public List<ResolveInfo> queryIntentContentProviders( 4421 Intent intent, String resolvedType, int flags, int userId) { 4422 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4423 ComponentName comp = intent.getComponent(); 4424 if (comp == null) { 4425 if (intent.getSelector() != null) { 4426 intent = intent.getSelector(); 4427 comp = intent.getComponent(); 4428 } 4429 } 4430 if (comp != null) { 4431 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4432 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4433 if (pi != null) { 4434 final ResolveInfo ri = new ResolveInfo(); 4435 ri.providerInfo = pi; 4436 list.add(ri); 4437 } 4438 return list; 4439 } 4440 4441 // reader 4442 synchronized (mPackages) { 4443 String pkgName = intent.getPackage(); 4444 if (pkgName == null) { 4445 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4446 } 4447 final PackageParser.Package pkg = mPackages.get(pkgName); 4448 if (pkg != null) { 4449 return mProviders.queryIntentForPackage( 4450 intent, resolvedType, flags, pkg.providers, userId); 4451 } 4452 return null; 4453 } 4454 } 4455 4456 @Override 4457 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4458 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4459 4460 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4461 4462 // writer 4463 synchronized (mPackages) { 4464 ArrayList<PackageInfo> list; 4465 if (listUninstalled) { 4466 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4467 for (PackageSetting ps : mSettings.mPackages.values()) { 4468 PackageInfo pi; 4469 if (ps.pkg != null) { 4470 pi = generatePackageInfo(ps.pkg, flags, userId); 4471 } else { 4472 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4473 } 4474 if (pi != null) { 4475 list.add(pi); 4476 } 4477 } 4478 } else { 4479 list = new ArrayList<PackageInfo>(mPackages.size()); 4480 for (PackageParser.Package p : mPackages.values()) { 4481 PackageInfo pi = generatePackageInfo(p, flags, userId); 4482 if (pi != null) { 4483 list.add(pi); 4484 } 4485 } 4486 } 4487 4488 return new ParceledListSlice<PackageInfo>(list); 4489 } 4490 } 4491 4492 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4493 String[] permissions, boolean[] tmp, int flags, int userId) { 4494 int numMatch = 0; 4495 final PermissionsState permissionsState = ps.getPermissionsState(); 4496 for (int i=0; i<permissions.length; i++) { 4497 final String permission = permissions[i]; 4498 if (permissionsState.hasPermission(permission, userId)) { 4499 tmp[i] = true; 4500 numMatch++; 4501 } else { 4502 tmp[i] = false; 4503 } 4504 } 4505 if (numMatch == 0) { 4506 return; 4507 } 4508 PackageInfo pi; 4509 if (ps.pkg != null) { 4510 pi = generatePackageInfo(ps.pkg, flags, userId); 4511 } else { 4512 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4513 } 4514 // The above might return null in cases of uninstalled apps or install-state 4515 // skew across users/profiles. 4516 if (pi != null) { 4517 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4518 if (numMatch == permissions.length) { 4519 pi.requestedPermissions = permissions; 4520 } else { 4521 pi.requestedPermissions = new String[numMatch]; 4522 numMatch = 0; 4523 for (int i=0; i<permissions.length; i++) { 4524 if (tmp[i]) { 4525 pi.requestedPermissions[numMatch] = permissions[i]; 4526 numMatch++; 4527 } 4528 } 4529 } 4530 } 4531 list.add(pi); 4532 } 4533 } 4534 4535 @Override 4536 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4537 String[] permissions, int flags, int userId) { 4538 if (!sUserManager.exists(userId)) return null; 4539 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4540 4541 // writer 4542 synchronized (mPackages) { 4543 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4544 boolean[] tmpBools = new boolean[permissions.length]; 4545 if (listUninstalled) { 4546 for (PackageSetting ps : mSettings.mPackages.values()) { 4547 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4548 } 4549 } else { 4550 for (PackageParser.Package pkg : mPackages.values()) { 4551 PackageSetting ps = (PackageSetting)pkg.mExtras; 4552 if (ps != null) { 4553 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4554 userId); 4555 } 4556 } 4557 } 4558 4559 return new ParceledListSlice<PackageInfo>(list); 4560 } 4561 } 4562 4563 @Override 4564 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4565 if (!sUserManager.exists(userId)) return null; 4566 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4567 4568 // writer 4569 synchronized (mPackages) { 4570 ArrayList<ApplicationInfo> list; 4571 if (listUninstalled) { 4572 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4573 for (PackageSetting ps : mSettings.mPackages.values()) { 4574 ApplicationInfo ai; 4575 if (ps.pkg != null) { 4576 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4577 ps.readUserState(userId), userId); 4578 } else { 4579 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4580 } 4581 if (ai != null) { 4582 list.add(ai); 4583 } 4584 } 4585 } else { 4586 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4587 for (PackageParser.Package p : mPackages.values()) { 4588 if (p.mExtras != null) { 4589 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4590 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4591 if (ai != null) { 4592 list.add(ai); 4593 } 4594 } 4595 } 4596 } 4597 4598 return new ParceledListSlice<ApplicationInfo>(list); 4599 } 4600 } 4601 4602 public List<ApplicationInfo> getPersistentApplications(int flags) { 4603 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4604 4605 // reader 4606 synchronized (mPackages) { 4607 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4608 final int userId = UserHandle.getCallingUserId(); 4609 while (i.hasNext()) { 4610 final PackageParser.Package p = i.next(); 4611 if (p.applicationInfo != null 4612 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4613 && (!mSafeMode || isSystemApp(p))) { 4614 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4615 if (ps != null) { 4616 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4617 ps.readUserState(userId), userId); 4618 if (ai != null) { 4619 finalList.add(ai); 4620 } 4621 } 4622 } 4623 } 4624 } 4625 4626 return finalList; 4627 } 4628 4629 @Override 4630 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4631 if (!sUserManager.exists(userId)) return null; 4632 // reader 4633 synchronized (mPackages) { 4634 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4635 PackageSetting ps = provider != null 4636 ? mSettings.mPackages.get(provider.owner.packageName) 4637 : null; 4638 return ps != null 4639 && mSettings.isEnabledLPr(provider.info, flags, userId) 4640 && (!mSafeMode || (provider.info.applicationInfo.flags 4641 &ApplicationInfo.FLAG_SYSTEM) != 0) 4642 ? PackageParser.generateProviderInfo(provider, flags, 4643 ps.readUserState(userId), userId) 4644 : null; 4645 } 4646 } 4647 4648 /** 4649 * @deprecated 4650 */ 4651 @Deprecated 4652 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4653 // reader 4654 synchronized (mPackages) { 4655 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4656 .entrySet().iterator(); 4657 final int userId = UserHandle.getCallingUserId(); 4658 while (i.hasNext()) { 4659 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4660 PackageParser.Provider p = entry.getValue(); 4661 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4662 4663 if (ps != null && p.syncable 4664 && (!mSafeMode || (p.info.applicationInfo.flags 4665 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4666 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4667 ps.readUserState(userId), userId); 4668 if (info != null) { 4669 outNames.add(entry.getKey()); 4670 outInfo.add(info); 4671 } 4672 } 4673 } 4674 } 4675 } 4676 4677 @Override 4678 public List<ProviderInfo> queryContentProviders(String processName, 4679 int uid, int flags) { 4680 ArrayList<ProviderInfo> finalList = null; 4681 // reader 4682 synchronized (mPackages) { 4683 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4684 final int userId = processName != null ? 4685 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4686 while (i.hasNext()) { 4687 final PackageParser.Provider p = i.next(); 4688 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4689 if (ps != null && p.info.authority != null 4690 && (processName == null 4691 || (p.info.processName.equals(processName) 4692 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4693 && mSettings.isEnabledLPr(p.info, flags, userId) 4694 && (!mSafeMode 4695 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4696 if (finalList == null) { 4697 finalList = new ArrayList<ProviderInfo>(3); 4698 } 4699 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4700 ps.readUserState(userId), userId); 4701 if (info != null) { 4702 finalList.add(info); 4703 } 4704 } 4705 } 4706 } 4707 4708 if (finalList != null) { 4709 Collections.sort(finalList, mProviderInitOrderSorter); 4710 } 4711 4712 return finalList; 4713 } 4714 4715 @Override 4716 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4717 int flags) { 4718 // reader 4719 synchronized (mPackages) { 4720 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4721 return PackageParser.generateInstrumentationInfo(i, flags); 4722 } 4723 } 4724 4725 @Override 4726 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4727 int flags) { 4728 ArrayList<InstrumentationInfo> finalList = 4729 new ArrayList<InstrumentationInfo>(); 4730 4731 // reader 4732 synchronized (mPackages) { 4733 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4734 while (i.hasNext()) { 4735 final PackageParser.Instrumentation p = i.next(); 4736 if (targetPackage == null 4737 || targetPackage.equals(p.info.targetPackage)) { 4738 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4739 flags); 4740 if (ii != null) { 4741 finalList.add(ii); 4742 } 4743 } 4744 } 4745 } 4746 4747 return finalList; 4748 } 4749 4750 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4751 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4752 if (overlays == null) { 4753 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4754 return; 4755 } 4756 for (PackageParser.Package opkg : overlays.values()) { 4757 // Not much to do if idmap fails: we already logged the error 4758 // and we certainly don't want to abort installation of pkg simply 4759 // because an overlay didn't fit properly. For these reasons, 4760 // ignore the return value of createIdmapForPackagePairLI. 4761 createIdmapForPackagePairLI(pkg, opkg); 4762 } 4763 } 4764 4765 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4766 PackageParser.Package opkg) { 4767 if (!opkg.mTrustedOverlay) { 4768 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4769 opkg.baseCodePath + ": overlay not trusted"); 4770 return false; 4771 } 4772 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4773 if (overlaySet == null) { 4774 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4775 opkg.baseCodePath + " but target package has no known overlays"); 4776 return false; 4777 } 4778 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4779 // TODO: generate idmap for split APKs 4780 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4781 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4782 + opkg.baseCodePath); 4783 return false; 4784 } 4785 PackageParser.Package[] overlayArray = 4786 overlaySet.values().toArray(new PackageParser.Package[0]); 4787 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4788 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4789 return p1.mOverlayPriority - p2.mOverlayPriority; 4790 } 4791 }; 4792 Arrays.sort(overlayArray, cmp); 4793 4794 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4795 int i = 0; 4796 for (PackageParser.Package p : overlayArray) { 4797 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4798 } 4799 return true; 4800 } 4801 4802 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4803 final File[] files = dir.listFiles(); 4804 if (ArrayUtils.isEmpty(files)) { 4805 Log.d(TAG, "No files in app dir " + dir); 4806 return; 4807 } 4808 4809 if (DEBUG_PACKAGE_SCANNING) { 4810 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4811 + " flags=0x" + Integer.toHexString(parseFlags)); 4812 } 4813 4814 for (File file : files) { 4815 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4816 && !PackageInstallerService.isStageName(file.getName()); 4817 if (!isPackage) { 4818 // Ignore entries which are not packages 4819 continue; 4820 } 4821 try { 4822 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4823 scanFlags, currentTime, null); 4824 } catch (PackageManagerException e) { 4825 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4826 4827 // Delete invalid userdata apps 4828 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4829 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4830 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4831 if (file.isDirectory()) { 4832 mInstaller.rmPackageDir(file.getAbsolutePath()); 4833 } else { 4834 file.delete(); 4835 } 4836 } 4837 } 4838 } 4839 } 4840 4841 private static File getSettingsProblemFile() { 4842 File dataDir = Environment.getDataDirectory(); 4843 File systemDir = new File(dataDir, "system"); 4844 File fname = new File(systemDir, "uiderrors.txt"); 4845 return fname; 4846 } 4847 4848 static void reportSettingsProblem(int priority, String msg) { 4849 logCriticalInfo(priority, msg); 4850 } 4851 4852 static void logCriticalInfo(int priority, String msg) { 4853 Slog.println(priority, TAG, msg); 4854 EventLogTags.writePmCriticalInfo(msg); 4855 try { 4856 File fname = getSettingsProblemFile(); 4857 FileOutputStream out = new FileOutputStream(fname, true); 4858 PrintWriter pw = new FastPrintWriter(out); 4859 SimpleDateFormat formatter = new SimpleDateFormat(); 4860 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4861 pw.println(dateString + ": " + msg); 4862 pw.close(); 4863 FileUtils.setPermissions( 4864 fname.toString(), 4865 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4866 -1, -1); 4867 } catch (java.io.IOException e) { 4868 } 4869 } 4870 4871 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4872 PackageParser.Package pkg, File srcFile, int parseFlags) 4873 throws PackageManagerException { 4874 if (ps != null 4875 && ps.codePath.equals(srcFile) 4876 && ps.timeStamp == srcFile.lastModified() 4877 && !isCompatSignatureUpdateNeeded(pkg) 4878 && !isRecoverSignatureUpdateNeeded(pkg)) { 4879 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4880 if (ps.signatures.mSignatures != null 4881 && ps.signatures.mSignatures.length != 0 4882 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4883 // Optimization: reuse the existing cached certificates 4884 // if the package appears to be unchanged. 4885 pkg.mSignatures = ps.signatures.mSignatures; 4886 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4887 synchronized (mPackages) { 4888 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4889 } 4890 return; 4891 } 4892 4893 Slog.w(TAG, "PackageSetting for " + ps.name 4894 + " is missing signatures. Collecting certs again to recover them."); 4895 } else { 4896 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4897 } 4898 4899 try { 4900 pp.collectCertificates(pkg, parseFlags); 4901 pp.collectManifestDigest(pkg); 4902 } catch (PackageParserException e) { 4903 throw PackageManagerException.from(e); 4904 } 4905 } 4906 4907 /* 4908 * Scan a package and return the newly parsed package. 4909 * Returns null in case of errors and the error code is stored in mLastScanError 4910 */ 4911 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4912 long currentTime, UserHandle user) throws PackageManagerException { 4913 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4914 parseFlags |= mDefParseFlags; 4915 PackageParser pp = new PackageParser(); 4916 pp.setSeparateProcesses(mSeparateProcesses); 4917 pp.setOnlyCoreApps(mOnlyCore); 4918 pp.setDisplayMetrics(mMetrics); 4919 4920 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4921 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4922 } 4923 4924 final PackageParser.Package pkg; 4925 try { 4926 pkg = pp.parsePackage(scanFile, parseFlags); 4927 } catch (PackageParserException e) { 4928 throw PackageManagerException.from(e); 4929 } 4930 4931 PackageSetting ps = null; 4932 PackageSetting updatedPkg; 4933 // reader 4934 synchronized (mPackages) { 4935 // Look to see if we already know about this package. 4936 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4937 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4938 // This package has been renamed to its original name. Let's 4939 // use that. 4940 ps = mSettings.peekPackageLPr(oldName); 4941 } 4942 // If there was no original package, see one for the real package name. 4943 if (ps == null) { 4944 ps = mSettings.peekPackageLPr(pkg.packageName); 4945 } 4946 // Check to see if this package could be hiding/updating a system 4947 // package. Must look for it either under the original or real 4948 // package name depending on our state. 4949 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4950 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4951 } 4952 boolean updatedPkgBetter = false; 4953 // First check if this is a system package that may involve an update 4954 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4955 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4956 // it needs to drop FLAG_PRIVILEGED. 4957 if (locationIsPrivileged(scanFile)) { 4958 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4959 } else { 4960 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4961 } 4962 4963 if (ps != null && !ps.codePath.equals(scanFile)) { 4964 // The path has changed from what was last scanned... check the 4965 // version of the new path against what we have stored to determine 4966 // what to do. 4967 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4968 if (pkg.mVersionCode <= ps.versionCode) { 4969 // The system package has been updated and the code path does not match 4970 // Ignore entry. Skip it. 4971 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4972 + " ignored: updated version " + ps.versionCode 4973 + " better than this " + pkg.mVersionCode); 4974 if (!updatedPkg.codePath.equals(scanFile)) { 4975 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4976 + ps.name + " changing from " + updatedPkg.codePathString 4977 + " to " + scanFile); 4978 updatedPkg.codePath = scanFile; 4979 updatedPkg.codePathString = scanFile.toString(); 4980 updatedPkg.resourcePath = scanFile; 4981 updatedPkg.resourcePathString = scanFile.toString(); 4982 } 4983 updatedPkg.pkg = pkg; 4984 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4985 } else { 4986 // The current app on the system partition is better than 4987 // what we have updated to on the data partition; switch 4988 // back to the system partition version. 4989 // At this point, its safely assumed that package installation for 4990 // apps in system partition will go through. If not there won't be a working 4991 // version of the app 4992 // writer 4993 synchronized (mPackages) { 4994 // Just remove the loaded entries from package lists. 4995 mPackages.remove(ps.name); 4996 } 4997 4998 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4999 + " reverting from " + ps.codePathString 5000 + ": new version " + pkg.mVersionCode 5001 + " better than installed " + ps.versionCode); 5002 5003 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5004 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5005 getAppDexInstructionSets(ps)); 5006 synchronized (mInstallLock) { 5007 args.cleanUpResourcesLI(); 5008 } 5009 synchronized (mPackages) { 5010 mSettings.enableSystemPackageLPw(ps.name); 5011 } 5012 updatedPkgBetter = true; 5013 } 5014 } 5015 } 5016 5017 if (updatedPkg != null) { 5018 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5019 // initially 5020 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5021 5022 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5023 // flag set initially 5024 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5025 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5026 } 5027 } 5028 5029 // Verify certificates against what was last scanned 5030 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5031 5032 /* 5033 * A new system app appeared, but we already had a non-system one of the 5034 * same name installed earlier. 5035 */ 5036 boolean shouldHideSystemApp = false; 5037 if (updatedPkg == null && ps != null 5038 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5039 /* 5040 * Check to make sure the signatures match first. If they don't, 5041 * wipe the installed application and its data. 5042 */ 5043 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5044 != PackageManager.SIGNATURE_MATCH) { 5045 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5046 + " signatures don't match existing userdata copy; removing"); 5047 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5048 ps = null; 5049 } else { 5050 /* 5051 * If the newly-added system app is an older version than the 5052 * already installed version, hide it. It will be scanned later 5053 * and re-added like an update. 5054 */ 5055 if (pkg.mVersionCode <= ps.versionCode) { 5056 shouldHideSystemApp = true; 5057 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5058 + " but new version " + pkg.mVersionCode + " better than installed " 5059 + ps.versionCode + "; hiding system"); 5060 } else { 5061 /* 5062 * The newly found system app is a newer version that the 5063 * one previously installed. Simply remove the 5064 * already-installed application and replace it with our own 5065 * while keeping the application data. 5066 */ 5067 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5068 + " reverting from " + ps.codePathString + ": new version " 5069 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5070 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5071 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5072 getAppDexInstructionSets(ps)); 5073 synchronized (mInstallLock) { 5074 args.cleanUpResourcesLI(); 5075 } 5076 } 5077 } 5078 } 5079 5080 // The apk is forward locked (not public) if its code and resources 5081 // are kept in different files. (except for app in either system or 5082 // vendor path). 5083 // TODO grab this value from PackageSettings 5084 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5085 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5086 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5087 } 5088 } 5089 5090 // TODO: extend to support forward-locked splits 5091 String resourcePath = null; 5092 String baseResourcePath = null; 5093 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5094 if (ps != null && ps.resourcePathString != null) { 5095 resourcePath = ps.resourcePathString; 5096 baseResourcePath = ps.resourcePathString; 5097 } else { 5098 // Should not happen at all. Just log an error. 5099 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5100 } 5101 } else { 5102 resourcePath = pkg.codePath; 5103 baseResourcePath = pkg.baseCodePath; 5104 } 5105 5106 // Set application objects path explicitly. 5107 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5108 pkg.applicationInfo.setCodePath(pkg.codePath); 5109 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5110 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5111 pkg.applicationInfo.setResourcePath(resourcePath); 5112 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5113 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5114 5115 // Note that we invoke the following method only if we are about to unpack an application 5116 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5117 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5118 5119 /* 5120 * If the system app should be overridden by a previously installed 5121 * data, hide the system app now and let the /data/app scan pick it up 5122 * again. 5123 */ 5124 if (shouldHideSystemApp) { 5125 synchronized (mPackages) { 5126 /* 5127 * We have to grant systems permissions before we hide, because 5128 * grantPermissions will assume the package update is trying to 5129 * expand its permissions. 5130 */ 5131 grantPermissionsLPw(pkg, true, pkg.packageName); 5132 mSettings.disableSystemPackageLPw(pkg.packageName); 5133 } 5134 } 5135 5136 return scannedPkg; 5137 } 5138 5139 private static String fixProcessName(String defProcessName, 5140 String processName, int uid) { 5141 if (processName == null) { 5142 return defProcessName; 5143 } 5144 return processName; 5145 } 5146 5147 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5148 throws PackageManagerException { 5149 if (pkgSetting.signatures.mSignatures != null) { 5150 // Already existing package. Make sure signatures match 5151 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5152 == PackageManager.SIGNATURE_MATCH; 5153 if (!match) { 5154 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5155 == PackageManager.SIGNATURE_MATCH; 5156 } 5157 if (!match) { 5158 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5159 == PackageManager.SIGNATURE_MATCH; 5160 } 5161 if (!match) { 5162 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5163 + pkg.packageName + " signatures do not match the " 5164 + "previously installed version; ignoring!"); 5165 } 5166 } 5167 5168 // Check for shared user signatures 5169 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5170 // Already existing package. Make sure signatures match 5171 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5172 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5173 if (!match) { 5174 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5175 == PackageManager.SIGNATURE_MATCH; 5176 } 5177 if (!match) { 5178 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5179 == PackageManager.SIGNATURE_MATCH; 5180 } 5181 if (!match) { 5182 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5183 "Package " + pkg.packageName 5184 + " has no signatures that match those in shared user " 5185 + pkgSetting.sharedUser.name + "; ignoring!"); 5186 } 5187 } 5188 } 5189 5190 /** 5191 * Enforces that only the system UID or root's UID can call a method exposed 5192 * via Binder. 5193 * 5194 * @param message used as message if SecurityException is thrown 5195 * @throws SecurityException if the caller is not system or root 5196 */ 5197 private static final void enforceSystemOrRoot(String message) { 5198 final int uid = Binder.getCallingUid(); 5199 if (uid != Process.SYSTEM_UID && uid != 0) { 5200 throw new SecurityException(message); 5201 } 5202 } 5203 5204 @Override 5205 public void performBootDexOpt() { 5206 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5207 5208 // Before everything else, see whether we need to fstrim. 5209 try { 5210 IMountService ms = PackageHelper.getMountService(); 5211 if (ms != null) { 5212 final boolean isUpgrade = isUpgrade(); 5213 boolean doTrim = isUpgrade; 5214 if (doTrim) { 5215 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5216 } else { 5217 final long interval = android.provider.Settings.Global.getLong( 5218 mContext.getContentResolver(), 5219 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5220 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5221 if (interval > 0) { 5222 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5223 if (timeSinceLast > interval) { 5224 doTrim = true; 5225 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5226 + "; running immediately"); 5227 } 5228 } 5229 } 5230 if (doTrim) { 5231 if (!isFirstBoot()) { 5232 try { 5233 ActivityManagerNative.getDefault().showBootMessage( 5234 mContext.getResources().getString( 5235 R.string.android_upgrading_fstrim), true); 5236 } catch (RemoteException e) { 5237 } 5238 } 5239 ms.runMaintenance(); 5240 } 5241 } else { 5242 Slog.e(TAG, "Mount service unavailable!"); 5243 } 5244 } catch (RemoteException e) { 5245 // Can't happen; MountService is local 5246 } 5247 5248 final ArraySet<PackageParser.Package> pkgs; 5249 synchronized (mPackages) { 5250 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5251 } 5252 5253 if (pkgs != null) { 5254 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5255 // in case the device runs out of space. 5256 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5257 // Give priority to core apps. 5258 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5259 PackageParser.Package pkg = it.next(); 5260 if (pkg.coreApp) { 5261 if (DEBUG_DEXOPT) { 5262 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5263 } 5264 sortedPkgs.add(pkg); 5265 it.remove(); 5266 } 5267 } 5268 // Give priority to system apps that listen for pre boot complete. 5269 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5270 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5271 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5272 PackageParser.Package pkg = it.next(); 5273 if (pkgNames.contains(pkg.packageName)) { 5274 if (DEBUG_DEXOPT) { 5275 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5276 } 5277 sortedPkgs.add(pkg); 5278 it.remove(); 5279 } 5280 } 5281 // Give priority to system apps. 5282 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5283 PackageParser.Package pkg = it.next(); 5284 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5285 if (DEBUG_DEXOPT) { 5286 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5287 } 5288 sortedPkgs.add(pkg); 5289 it.remove(); 5290 } 5291 } 5292 // Give priority to updated system apps. 5293 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5294 PackageParser.Package pkg = it.next(); 5295 if (pkg.isUpdatedSystemApp()) { 5296 if (DEBUG_DEXOPT) { 5297 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5298 } 5299 sortedPkgs.add(pkg); 5300 it.remove(); 5301 } 5302 } 5303 // Give priority to apps that listen for boot complete. 5304 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5305 pkgNames = getPackageNamesForIntent(intent); 5306 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5307 PackageParser.Package pkg = it.next(); 5308 if (pkgNames.contains(pkg.packageName)) { 5309 if (DEBUG_DEXOPT) { 5310 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5311 } 5312 sortedPkgs.add(pkg); 5313 it.remove(); 5314 } 5315 } 5316 // Filter out packages that aren't recently used. 5317 filterRecentlyUsedApps(pkgs); 5318 // Add all remaining apps. 5319 for (PackageParser.Package pkg : pkgs) { 5320 if (DEBUG_DEXOPT) { 5321 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5322 } 5323 sortedPkgs.add(pkg); 5324 } 5325 5326 // If we want to be lazy, filter everything that wasn't recently used. 5327 if (mLazyDexOpt) { 5328 filterRecentlyUsedApps(sortedPkgs); 5329 } 5330 5331 int i = 0; 5332 int total = sortedPkgs.size(); 5333 File dataDir = Environment.getDataDirectory(); 5334 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5335 if (lowThreshold == 0) { 5336 throw new IllegalStateException("Invalid low memory threshold"); 5337 } 5338 for (PackageParser.Package pkg : sortedPkgs) { 5339 long usableSpace = dataDir.getUsableSpace(); 5340 if (usableSpace < lowThreshold) { 5341 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5342 break; 5343 } 5344 performBootDexOpt(pkg, ++i, total); 5345 } 5346 } 5347 } 5348 5349 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5350 // Filter out packages that aren't recently used. 5351 // 5352 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5353 // should do a full dexopt. 5354 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5355 int total = pkgs.size(); 5356 int skipped = 0; 5357 long now = System.currentTimeMillis(); 5358 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5359 PackageParser.Package pkg = i.next(); 5360 long then = pkg.mLastPackageUsageTimeInMills; 5361 if (then + mDexOptLRUThresholdInMills < now) { 5362 if (DEBUG_DEXOPT) { 5363 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5364 ((then == 0) ? "never" : new Date(then))); 5365 } 5366 i.remove(); 5367 skipped++; 5368 } 5369 } 5370 if (DEBUG_DEXOPT) { 5371 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5372 } 5373 } 5374 } 5375 5376 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5377 List<ResolveInfo> ris = null; 5378 try { 5379 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5380 intent, null, 0, UserHandle.USER_OWNER); 5381 } catch (RemoteException e) { 5382 } 5383 ArraySet<String> pkgNames = new ArraySet<String>(); 5384 if (ris != null) { 5385 for (ResolveInfo ri : ris) { 5386 pkgNames.add(ri.activityInfo.packageName); 5387 } 5388 } 5389 return pkgNames; 5390 } 5391 5392 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5393 if (DEBUG_DEXOPT) { 5394 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5395 } 5396 if (!isFirstBoot()) { 5397 try { 5398 ActivityManagerNative.getDefault().showBootMessage( 5399 mContext.getResources().getString(R.string.android_upgrading_apk, 5400 curr, total), true); 5401 } catch (RemoteException e) { 5402 } 5403 } 5404 PackageParser.Package p = pkg; 5405 synchronized (mInstallLock) { 5406 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5407 false /* force dex */, false /* defer */, true /* include dependencies */); 5408 } 5409 } 5410 5411 @Override 5412 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5413 return performDexOpt(packageName, instructionSet, false); 5414 } 5415 5416 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5417 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5418 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5419 if (!dexopt && !updateUsage) { 5420 // We aren't going to dexopt or update usage, so bail early. 5421 return false; 5422 } 5423 PackageParser.Package p; 5424 final String targetInstructionSet; 5425 synchronized (mPackages) { 5426 p = mPackages.get(packageName); 5427 if (p == null) { 5428 return false; 5429 } 5430 if (updateUsage) { 5431 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5432 } 5433 mPackageUsage.write(false); 5434 if (!dexopt) { 5435 // We aren't going to dexopt, so bail early. 5436 return false; 5437 } 5438 5439 targetInstructionSet = instructionSet != null ? instructionSet : 5440 getPrimaryInstructionSet(p.applicationInfo); 5441 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5442 return false; 5443 } 5444 } 5445 5446 synchronized (mInstallLock) { 5447 final String[] instructionSets = new String[] { targetInstructionSet }; 5448 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5449 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5450 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5451 } 5452 } 5453 5454 public ArraySet<String> getPackagesThatNeedDexOpt() { 5455 ArraySet<String> pkgs = null; 5456 synchronized (mPackages) { 5457 for (PackageParser.Package p : mPackages.values()) { 5458 if (DEBUG_DEXOPT) { 5459 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5460 } 5461 if (!p.mDexOptPerformed.isEmpty()) { 5462 continue; 5463 } 5464 if (pkgs == null) { 5465 pkgs = new ArraySet<String>(); 5466 } 5467 pkgs.add(p.packageName); 5468 } 5469 } 5470 return pkgs; 5471 } 5472 5473 public void shutdown() { 5474 mPackageUsage.write(true); 5475 } 5476 5477 @Override 5478 public void forceDexOpt(String packageName) { 5479 enforceSystemOrRoot("forceDexOpt"); 5480 5481 PackageParser.Package pkg; 5482 synchronized (mPackages) { 5483 pkg = mPackages.get(packageName); 5484 if (pkg == null) { 5485 throw new IllegalArgumentException("Missing package: " + packageName); 5486 } 5487 } 5488 5489 synchronized (mInstallLock) { 5490 final String[] instructionSets = new String[] { 5491 getPrimaryInstructionSet(pkg.applicationInfo) }; 5492 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5493 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5494 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5495 throw new IllegalStateException("Failed to dexopt: " + res); 5496 } 5497 } 5498 } 5499 5500 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5501 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5502 Slog.w(TAG, "Unable to update from " + oldPkg.name 5503 + " to " + newPkg.packageName 5504 + ": old package not in system partition"); 5505 return false; 5506 } else if (mPackages.get(oldPkg.name) != null) { 5507 Slog.w(TAG, "Unable to update from " + oldPkg.name 5508 + " to " + newPkg.packageName 5509 + ": old package still exists"); 5510 return false; 5511 } 5512 return true; 5513 } 5514 5515 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5516 int[] users = sUserManager.getUserIds(); 5517 int res = mInstaller.install(packageName, uid, uid, seinfo); 5518 if (res < 0) { 5519 return res; 5520 } 5521 for (int user : users) { 5522 if (user != 0) { 5523 res = mInstaller.createUserData(packageName, 5524 UserHandle.getUid(user, uid), user, seinfo); 5525 if (res < 0) { 5526 return res; 5527 } 5528 } 5529 } 5530 return res; 5531 } 5532 5533 private int removeDataDirsLI(String packageName) { 5534 int[] users = sUserManager.getUserIds(); 5535 int res = 0; 5536 for (int user : users) { 5537 int resInner = mInstaller.remove(packageName, user); 5538 if (resInner < 0) { 5539 res = resInner; 5540 } 5541 } 5542 5543 return res; 5544 } 5545 5546 private int deleteCodeCacheDirsLI(String packageName) { 5547 int[] users = sUserManager.getUserIds(); 5548 int res = 0; 5549 for (int user : users) { 5550 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5551 if (resInner < 0) { 5552 res = resInner; 5553 } 5554 } 5555 return res; 5556 } 5557 5558 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5559 PackageParser.Package changingLib) { 5560 if (file.path != null) { 5561 usesLibraryFiles.add(file.path); 5562 return; 5563 } 5564 PackageParser.Package p = mPackages.get(file.apk); 5565 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5566 // If we are doing this while in the middle of updating a library apk, 5567 // then we need to make sure to use that new apk for determining the 5568 // dependencies here. (We haven't yet finished committing the new apk 5569 // to the package manager state.) 5570 if (p == null || p.packageName.equals(changingLib.packageName)) { 5571 p = changingLib; 5572 } 5573 } 5574 if (p != null) { 5575 usesLibraryFiles.addAll(p.getAllCodePaths()); 5576 } 5577 } 5578 5579 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5580 PackageParser.Package changingLib) throws PackageManagerException { 5581 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5582 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5583 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5584 for (int i=0; i<N; i++) { 5585 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5586 if (file == null) { 5587 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5588 "Package " + pkg.packageName + " requires unavailable shared library " 5589 + pkg.usesLibraries.get(i) + "; failing!"); 5590 } 5591 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5592 } 5593 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5594 for (int i=0; i<N; i++) { 5595 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5596 if (file == null) { 5597 Slog.w(TAG, "Package " + pkg.packageName 5598 + " desires unavailable shared library " 5599 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5600 } else { 5601 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5602 } 5603 } 5604 N = usesLibraryFiles.size(); 5605 if (N > 0) { 5606 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5607 } else { 5608 pkg.usesLibraryFiles = null; 5609 } 5610 } 5611 } 5612 5613 private static boolean hasString(List<String> list, List<String> which) { 5614 if (list == null) { 5615 return false; 5616 } 5617 for (int i=list.size()-1; i>=0; i--) { 5618 for (int j=which.size()-1; j>=0; j--) { 5619 if (which.get(j).equals(list.get(i))) { 5620 return true; 5621 } 5622 } 5623 } 5624 return false; 5625 } 5626 5627 private void updateAllSharedLibrariesLPw() { 5628 for (PackageParser.Package pkg : mPackages.values()) { 5629 try { 5630 updateSharedLibrariesLPw(pkg, null); 5631 } catch (PackageManagerException e) { 5632 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5633 } 5634 } 5635 } 5636 5637 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5638 PackageParser.Package changingPkg) { 5639 ArrayList<PackageParser.Package> res = null; 5640 for (PackageParser.Package pkg : mPackages.values()) { 5641 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5642 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5643 if (res == null) { 5644 res = new ArrayList<PackageParser.Package>(); 5645 } 5646 res.add(pkg); 5647 try { 5648 updateSharedLibrariesLPw(pkg, changingPkg); 5649 } catch (PackageManagerException e) { 5650 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5651 } 5652 } 5653 } 5654 return res; 5655 } 5656 5657 /** 5658 * Derive the value of the {@code cpuAbiOverride} based on the provided 5659 * value and an optional stored value from the package settings. 5660 */ 5661 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5662 String cpuAbiOverride = null; 5663 5664 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5665 cpuAbiOverride = null; 5666 } else if (abiOverride != null) { 5667 cpuAbiOverride = abiOverride; 5668 } else if (settings != null) { 5669 cpuAbiOverride = settings.cpuAbiOverrideString; 5670 } 5671 5672 return cpuAbiOverride; 5673 } 5674 5675 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5676 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5677 boolean success = false; 5678 try { 5679 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5680 currentTime, user); 5681 success = true; 5682 return res; 5683 } finally { 5684 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5685 removeDataDirsLI(pkg.packageName); 5686 } 5687 } 5688 } 5689 5690 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5691 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5692 final File scanFile = new File(pkg.codePath); 5693 if (pkg.applicationInfo.getCodePath() == null || 5694 pkg.applicationInfo.getResourcePath() == null) { 5695 // Bail out. The resource and code paths haven't been set. 5696 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5697 "Code and resource paths haven't been set correctly"); 5698 } 5699 5700 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5701 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5702 } else { 5703 // Only allow system apps to be flagged as core apps. 5704 pkg.coreApp = false; 5705 } 5706 5707 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5708 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5709 } 5710 5711 if (mCustomResolverComponentName != null && 5712 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5713 setUpCustomResolverActivity(pkg); 5714 } 5715 5716 if (pkg.packageName.equals("android")) { 5717 synchronized (mPackages) { 5718 if (mAndroidApplication != null) { 5719 Slog.w(TAG, "*************************************************"); 5720 Slog.w(TAG, "Core android package being redefined. Skipping."); 5721 Slog.w(TAG, " file=" + scanFile); 5722 Slog.w(TAG, "*************************************************"); 5723 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5724 "Core android package being redefined. Skipping."); 5725 } 5726 5727 // Set up information for our fall-back user intent resolution activity. 5728 mPlatformPackage = pkg; 5729 pkg.mVersionCode = mSdkVersion; 5730 mAndroidApplication = pkg.applicationInfo; 5731 5732 if (!mResolverReplaced) { 5733 mResolveActivity.applicationInfo = mAndroidApplication; 5734 mResolveActivity.name = ResolverActivity.class.getName(); 5735 mResolveActivity.packageName = mAndroidApplication.packageName; 5736 mResolveActivity.processName = "system:ui"; 5737 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5738 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5739 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5740 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5741 mResolveActivity.exported = true; 5742 mResolveActivity.enabled = true; 5743 mResolveInfo.activityInfo = mResolveActivity; 5744 mResolveInfo.priority = 0; 5745 mResolveInfo.preferredOrder = 0; 5746 mResolveInfo.match = 0; 5747 mResolveComponentName = new ComponentName( 5748 mAndroidApplication.packageName, mResolveActivity.name); 5749 } 5750 } 5751 } 5752 5753 if (DEBUG_PACKAGE_SCANNING) { 5754 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5755 Log.d(TAG, "Scanning package " + pkg.packageName); 5756 } 5757 5758 if (mPackages.containsKey(pkg.packageName) 5759 || mSharedLibraries.containsKey(pkg.packageName)) { 5760 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5761 "Application package " + pkg.packageName 5762 + " already installed. Skipping duplicate."); 5763 } 5764 5765 // If we're only installing presumed-existing packages, require that the 5766 // scanned APK is both already known and at the path previously established 5767 // for it. Previously unknown packages we pick up normally, but if we have an 5768 // a priori expectation about this package's install presence, enforce it. 5769 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5770 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5771 if (known != null) { 5772 if (DEBUG_PACKAGE_SCANNING) { 5773 Log.d(TAG, "Examining " + pkg.codePath 5774 + " and requiring known paths " + known.codePathString 5775 + " & " + known.resourcePathString); 5776 } 5777 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5778 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5779 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5780 "Application package " + pkg.packageName 5781 + " found at " + pkg.applicationInfo.getCodePath() 5782 + " but expected at " + known.codePathString + "; ignoring."); 5783 } 5784 } 5785 } 5786 5787 // Initialize package source and resource directories 5788 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5789 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5790 5791 SharedUserSetting suid = null; 5792 PackageSetting pkgSetting = null; 5793 5794 if (!isSystemApp(pkg)) { 5795 // Only system apps can use these features. 5796 pkg.mOriginalPackages = null; 5797 pkg.mRealPackage = null; 5798 pkg.mAdoptPermissions = null; 5799 } 5800 5801 // writer 5802 synchronized (mPackages) { 5803 if (pkg.mSharedUserId != null) { 5804 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5805 if (suid == null) { 5806 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5807 "Creating application package " + pkg.packageName 5808 + " for shared user failed"); 5809 } 5810 if (DEBUG_PACKAGE_SCANNING) { 5811 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5812 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5813 + "): packages=" + suid.packages); 5814 } 5815 } 5816 5817 // Check if we are renaming from an original package name. 5818 PackageSetting origPackage = null; 5819 String realName = null; 5820 if (pkg.mOriginalPackages != null) { 5821 // This package may need to be renamed to a previously 5822 // installed name. Let's check on that... 5823 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5824 if (pkg.mOriginalPackages.contains(renamed)) { 5825 // This package had originally been installed as the 5826 // original name, and we have already taken care of 5827 // transitioning to the new one. Just update the new 5828 // one to continue using the old name. 5829 realName = pkg.mRealPackage; 5830 if (!pkg.packageName.equals(renamed)) { 5831 // Callers into this function may have already taken 5832 // care of renaming the package; only do it here if 5833 // it is not already done. 5834 pkg.setPackageName(renamed); 5835 } 5836 5837 } else { 5838 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5839 if ((origPackage = mSettings.peekPackageLPr( 5840 pkg.mOriginalPackages.get(i))) != null) { 5841 // We do have the package already installed under its 5842 // original name... should we use it? 5843 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5844 // New package is not compatible with original. 5845 origPackage = null; 5846 continue; 5847 } else if (origPackage.sharedUser != null) { 5848 // Make sure uid is compatible between packages. 5849 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5850 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5851 + " to " + pkg.packageName + ": old uid " 5852 + origPackage.sharedUser.name 5853 + " differs from " + pkg.mSharedUserId); 5854 origPackage = null; 5855 continue; 5856 } 5857 } else { 5858 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5859 + pkg.packageName + " to old name " + origPackage.name); 5860 } 5861 break; 5862 } 5863 } 5864 } 5865 } 5866 5867 if (mTransferedPackages.contains(pkg.packageName)) { 5868 Slog.w(TAG, "Package " + pkg.packageName 5869 + " was transferred to another, but its .apk remains"); 5870 } 5871 5872 // Just create the setting, don't add it yet. For already existing packages 5873 // the PkgSetting exists already and doesn't have to be created. 5874 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5875 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5876 pkg.applicationInfo.primaryCpuAbi, 5877 pkg.applicationInfo.secondaryCpuAbi, 5878 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5879 user, false); 5880 if (pkgSetting == null) { 5881 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5882 "Creating application package " + pkg.packageName + " failed"); 5883 } 5884 5885 if (pkgSetting.origPackage != null) { 5886 // If we are first transitioning from an original package, 5887 // fix up the new package's name now. We need to do this after 5888 // looking up the package under its new name, so getPackageLP 5889 // can take care of fiddling things correctly. 5890 pkg.setPackageName(origPackage.name); 5891 5892 // File a report about this. 5893 String msg = "New package " + pkgSetting.realName 5894 + " renamed to replace old package " + pkgSetting.name; 5895 reportSettingsProblem(Log.WARN, msg); 5896 5897 // Make a note of it. 5898 mTransferedPackages.add(origPackage.name); 5899 5900 // No longer need to retain this. 5901 pkgSetting.origPackage = null; 5902 } 5903 5904 if (realName != null) { 5905 // Make a note of it. 5906 mTransferedPackages.add(pkg.packageName); 5907 } 5908 5909 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5910 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5911 } 5912 5913 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5914 // Check all shared libraries and map to their actual file path. 5915 // We only do this here for apps not on a system dir, because those 5916 // are the only ones that can fail an install due to this. We 5917 // will take care of the system apps by updating all of their 5918 // library paths after the scan is done. 5919 updateSharedLibrariesLPw(pkg, null); 5920 } 5921 5922 if (mFoundPolicyFile) { 5923 SELinuxMMAC.assignSeinfoValue(pkg); 5924 } 5925 5926 pkg.applicationInfo.uid = pkgSetting.appId; 5927 pkg.mExtras = pkgSetting; 5928 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5929 try { 5930 verifySignaturesLP(pkgSetting, pkg); 5931 // We just determined the app is signed correctly, so bring 5932 // over the latest parsed certs. 5933 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5934 } catch (PackageManagerException e) { 5935 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5936 throw e; 5937 } 5938 // The signature has changed, but this package is in the system 5939 // image... let's recover! 5940 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5941 // However... if this package is part of a shared user, but it 5942 // doesn't match the signature of the shared user, let's fail. 5943 // What this means is that you can't change the signatures 5944 // associated with an overall shared user, which doesn't seem all 5945 // that unreasonable. 5946 if (pkgSetting.sharedUser != null) { 5947 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5948 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5949 throw new PackageManagerException( 5950 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5951 "Signature mismatch for shared user : " 5952 + pkgSetting.sharedUser); 5953 } 5954 } 5955 // File a report about this. 5956 String msg = "System package " + pkg.packageName 5957 + " signature changed; retaining data."; 5958 reportSettingsProblem(Log.WARN, msg); 5959 } 5960 } else { 5961 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5962 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5963 + pkg.packageName + " upgrade keys do not match the " 5964 + "previously installed version"); 5965 } else { 5966 // We just determined the app is signed correctly, so bring 5967 // over the latest parsed certs. 5968 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5969 } 5970 } 5971 // Verify that this new package doesn't have any content providers 5972 // that conflict with existing packages. Only do this if the 5973 // package isn't already installed, since we don't want to break 5974 // things that are installed. 5975 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5976 final int N = pkg.providers.size(); 5977 int i; 5978 for (i=0; i<N; i++) { 5979 PackageParser.Provider p = pkg.providers.get(i); 5980 if (p.info.authority != null) { 5981 String names[] = p.info.authority.split(";"); 5982 for (int j = 0; j < names.length; j++) { 5983 if (mProvidersByAuthority.containsKey(names[j])) { 5984 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5985 final String otherPackageName = 5986 ((other != null && other.getComponentName() != null) ? 5987 other.getComponentName().getPackageName() : "?"); 5988 throw new PackageManagerException( 5989 INSTALL_FAILED_CONFLICTING_PROVIDER, 5990 "Can't install because provider name " + names[j] 5991 + " (in package " + pkg.applicationInfo.packageName 5992 + ") is already used by " + otherPackageName); 5993 } 5994 } 5995 } 5996 } 5997 } 5998 5999 if (pkg.mAdoptPermissions != null) { 6000 // This package wants to adopt ownership of permissions from 6001 // another package. 6002 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6003 final String origName = pkg.mAdoptPermissions.get(i); 6004 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6005 if (orig != null) { 6006 if (verifyPackageUpdateLPr(orig, pkg)) { 6007 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6008 + pkg.packageName); 6009 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6010 } 6011 } 6012 } 6013 } 6014 } 6015 6016 final String pkgName = pkg.packageName; 6017 6018 final long scanFileTime = scanFile.lastModified(); 6019 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6020 pkg.applicationInfo.processName = fixProcessName( 6021 pkg.applicationInfo.packageName, 6022 pkg.applicationInfo.processName, 6023 pkg.applicationInfo.uid); 6024 6025 File dataPath; 6026 if (mPlatformPackage == pkg) { 6027 // The system package is special. 6028 dataPath = new File(Environment.getDataDirectory(), "system"); 6029 6030 pkg.applicationInfo.dataDir = dataPath.getPath(); 6031 6032 } else { 6033 // This is a normal package, need to make its data directory. 6034 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6035 UserHandle.USER_OWNER); 6036 6037 boolean uidError = false; 6038 if (dataPath.exists()) { 6039 int currentUid = 0; 6040 try { 6041 StructStat stat = Os.stat(dataPath.getPath()); 6042 currentUid = stat.st_uid; 6043 } catch (ErrnoException e) { 6044 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6045 } 6046 6047 // If we have mismatched owners for the data path, we have a problem. 6048 if (currentUid != pkg.applicationInfo.uid) { 6049 boolean recovered = false; 6050 if (currentUid == 0) { 6051 // The directory somehow became owned by root. Wow. 6052 // This is probably because the system was stopped while 6053 // installd was in the middle of messing with its libs 6054 // directory. Ask installd to fix that. 6055 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 6056 pkg.applicationInfo.uid); 6057 if (ret >= 0) { 6058 recovered = true; 6059 String msg = "Package " + pkg.packageName 6060 + " unexpectedly changed to uid 0; recovered to " + 6061 + pkg.applicationInfo.uid; 6062 reportSettingsProblem(Log.WARN, msg); 6063 } 6064 } 6065 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6066 || (scanFlags&SCAN_BOOTING) != 0)) { 6067 // If this is a system app, we can at least delete its 6068 // current data so the application will still work. 6069 int ret = removeDataDirsLI(pkgName); 6070 if (ret >= 0) { 6071 // TODO: Kill the processes first 6072 // Old data gone! 6073 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6074 ? "System package " : "Third party package "; 6075 String msg = prefix + pkg.packageName 6076 + " has changed from uid: " 6077 + currentUid + " to " 6078 + pkg.applicationInfo.uid + "; old data erased"; 6079 reportSettingsProblem(Log.WARN, msg); 6080 recovered = true; 6081 6082 // And now re-install the app. 6083 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6084 pkg.applicationInfo.seinfo); 6085 if (ret == -1) { 6086 // Ack should not happen! 6087 msg = prefix + pkg.packageName 6088 + " could not have data directory re-created after delete."; 6089 reportSettingsProblem(Log.WARN, msg); 6090 throw new PackageManagerException( 6091 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6092 } 6093 } 6094 if (!recovered) { 6095 mHasSystemUidErrors = true; 6096 } 6097 } else if (!recovered) { 6098 // If we allow this install to proceed, we will be broken. 6099 // Abort, abort! 6100 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6101 "scanPackageLI"); 6102 } 6103 if (!recovered) { 6104 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6105 + pkg.applicationInfo.uid + "/fs_" 6106 + currentUid; 6107 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6108 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6109 String msg = "Package " + pkg.packageName 6110 + " has mismatched uid: " 6111 + currentUid + " on disk, " 6112 + pkg.applicationInfo.uid + " in settings"; 6113 // writer 6114 synchronized (mPackages) { 6115 mSettings.mReadMessages.append(msg); 6116 mSettings.mReadMessages.append('\n'); 6117 uidError = true; 6118 if (!pkgSetting.uidError) { 6119 reportSettingsProblem(Log.ERROR, msg); 6120 } 6121 } 6122 } 6123 } 6124 pkg.applicationInfo.dataDir = dataPath.getPath(); 6125 if (mShouldRestoreconData) { 6126 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6127 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6128 pkg.applicationInfo.uid); 6129 } 6130 } else { 6131 if (DEBUG_PACKAGE_SCANNING) { 6132 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6133 Log.v(TAG, "Want this data dir: " + dataPath); 6134 } 6135 //invoke installer to do the actual installation 6136 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6137 pkg.applicationInfo.seinfo); 6138 if (ret < 0) { 6139 // Error from installer 6140 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6141 "Unable to create data dirs [errorCode=" + ret + "]"); 6142 } 6143 6144 if (dataPath.exists()) { 6145 pkg.applicationInfo.dataDir = dataPath.getPath(); 6146 } else { 6147 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6148 pkg.applicationInfo.dataDir = null; 6149 } 6150 } 6151 6152 pkgSetting.uidError = uidError; 6153 } 6154 6155 final String path = scanFile.getPath(); 6156 final String codePath = pkg.applicationInfo.getCodePath(); 6157 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6158 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6159 setBundledAppAbisAndRoots(pkg, pkgSetting); 6160 6161 // If we haven't found any native libraries for the app, check if it has 6162 // renderscript code. We'll need to force the app to 32 bit if it has 6163 // renderscript bitcode. 6164 if (pkg.applicationInfo.primaryCpuAbi == null 6165 && pkg.applicationInfo.secondaryCpuAbi == null 6166 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6167 NativeLibraryHelper.Handle handle = null; 6168 try { 6169 handle = NativeLibraryHelper.Handle.create(scanFile); 6170 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6171 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6172 } 6173 } catch (IOException ioe) { 6174 Slog.w(TAG, "Error scanning system app : " + ioe); 6175 } finally { 6176 IoUtils.closeQuietly(handle); 6177 } 6178 } 6179 6180 setNativeLibraryPaths(pkg); 6181 } else { 6182 // TODO: We can probably be smarter about this stuff. For installed apps, 6183 // we can calculate this information at install time once and for all. For 6184 // system apps, we can probably assume that this information doesn't change 6185 // after the first boot scan. As things stand, we do lots of unnecessary work. 6186 6187 // Give ourselves some initial paths; we'll come back for another 6188 // pass once we've determined ABI below. 6189 setNativeLibraryPaths(pkg); 6190 6191 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6192 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6193 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6194 6195 NativeLibraryHelper.Handle handle = null; 6196 try { 6197 handle = NativeLibraryHelper.Handle.create(scanFile); 6198 // TODO(multiArch): This can be null for apps that didn't go through the 6199 // usual installation process. We can calculate it again, like we 6200 // do during install time. 6201 // 6202 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6203 // unnecessary. 6204 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6205 6206 // Null out the abis so that they can be recalculated. 6207 pkg.applicationInfo.primaryCpuAbi = null; 6208 pkg.applicationInfo.secondaryCpuAbi = null; 6209 if (isMultiArch(pkg.applicationInfo)) { 6210 // Warn if we've set an abiOverride for multi-lib packages.. 6211 // By definition, we need to copy both 32 and 64 bit libraries for 6212 // such packages. 6213 if (pkg.cpuAbiOverride != null 6214 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6215 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6216 } 6217 6218 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6219 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6220 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6221 if (isAsec) { 6222 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6223 } else { 6224 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6225 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6226 useIsaSpecificSubdirs); 6227 } 6228 } 6229 6230 maybeThrowExceptionForMultiArchCopy( 6231 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6232 6233 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6234 if (isAsec) { 6235 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6236 } else { 6237 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6238 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6239 useIsaSpecificSubdirs); 6240 } 6241 } 6242 6243 maybeThrowExceptionForMultiArchCopy( 6244 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6245 6246 if (abi64 >= 0) { 6247 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6248 } 6249 6250 if (abi32 >= 0) { 6251 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6252 if (abi64 >= 0) { 6253 pkg.applicationInfo.secondaryCpuAbi = abi; 6254 } else { 6255 pkg.applicationInfo.primaryCpuAbi = abi; 6256 } 6257 } 6258 } else { 6259 String[] abiList = (cpuAbiOverride != null) ? 6260 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6261 6262 // Enable gross and lame hacks for apps that are built with old 6263 // SDK tools. We must scan their APKs for renderscript bitcode and 6264 // not launch them if it's present. Don't bother checking on devices 6265 // that don't have 64 bit support. 6266 boolean needsRenderScriptOverride = false; 6267 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6268 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6269 abiList = Build.SUPPORTED_32_BIT_ABIS; 6270 needsRenderScriptOverride = true; 6271 } 6272 6273 final int copyRet; 6274 if (isAsec) { 6275 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6276 } else { 6277 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6278 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6279 } 6280 6281 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6282 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6283 "Error unpackaging native libs for app, errorCode=" + copyRet); 6284 } 6285 6286 if (copyRet >= 0) { 6287 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6288 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6289 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6290 } else if (needsRenderScriptOverride) { 6291 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6292 } 6293 } 6294 } catch (IOException ioe) { 6295 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6296 } finally { 6297 IoUtils.closeQuietly(handle); 6298 } 6299 6300 // Now that we've calculated the ABIs and determined if it's an internal app, 6301 // we will go ahead and populate the nativeLibraryPath. 6302 setNativeLibraryPaths(pkg); 6303 6304 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6305 final int[] userIds = sUserManager.getUserIds(); 6306 synchronized (mInstallLock) { 6307 // Create a native library symlink only if we have native libraries 6308 // and if the native libraries are 32 bit libraries. We do not provide 6309 // this symlink for 64 bit libraries. 6310 if (pkg.applicationInfo.primaryCpuAbi != null && 6311 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6312 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6313 for (int userId : userIds) { 6314 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6315 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6316 "Failed linking native library dir (user=" + userId + ")"); 6317 } 6318 } 6319 } 6320 } 6321 } 6322 6323 // This is a special case for the "system" package, where the ABI is 6324 // dictated by the zygote configuration (and init.rc). We should keep track 6325 // of this ABI so that we can deal with "normal" applications that run under 6326 // the same UID correctly. 6327 if (mPlatformPackage == pkg) { 6328 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6329 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6330 } 6331 6332 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6333 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6334 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6335 // Copy the derived override back to the parsed package, so that we can 6336 // update the package settings accordingly. 6337 pkg.cpuAbiOverride = cpuAbiOverride; 6338 6339 if (DEBUG_ABI_SELECTION) { 6340 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6341 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6342 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6343 } 6344 6345 // Push the derived path down into PackageSettings so we know what to 6346 // clean up at uninstall time. 6347 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6348 6349 if (DEBUG_ABI_SELECTION) { 6350 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6351 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6352 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6353 } 6354 6355 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6356 // We don't do this here during boot because we can do it all 6357 // at once after scanning all existing packages. 6358 // 6359 // We also do this *before* we perform dexopt on this package, so that 6360 // we can avoid redundant dexopts, and also to make sure we've got the 6361 // code and package path correct. 6362 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6363 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6364 } 6365 6366 if ((scanFlags & SCAN_NO_DEX) == 0) { 6367 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6368 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6369 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6370 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6371 } 6372 } 6373 if (mFactoryTest && pkg.requestedPermissions.contains( 6374 android.Manifest.permission.FACTORY_TEST)) { 6375 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6376 } 6377 6378 ArrayList<PackageParser.Package> clientLibPkgs = null; 6379 6380 // writer 6381 synchronized (mPackages) { 6382 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6383 // Only system apps can add new shared libraries. 6384 if (pkg.libraryNames != null) { 6385 for (int i=0; i<pkg.libraryNames.size(); i++) { 6386 String name = pkg.libraryNames.get(i); 6387 boolean allowed = false; 6388 if (pkg.isUpdatedSystemApp()) { 6389 // New library entries can only be added through the 6390 // system image. This is important to get rid of a lot 6391 // of nasty edge cases: for example if we allowed a non- 6392 // system update of the app to add a library, then uninstalling 6393 // the update would make the library go away, and assumptions 6394 // we made such as through app install filtering would now 6395 // have allowed apps on the device which aren't compatible 6396 // with it. Better to just have the restriction here, be 6397 // conservative, and create many fewer cases that can negatively 6398 // impact the user experience. 6399 final PackageSetting sysPs = mSettings 6400 .getDisabledSystemPkgLPr(pkg.packageName); 6401 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6402 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6403 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6404 allowed = true; 6405 allowed = true; 6406 break; 6407 } 6408 } 6409 } 6410 } else { 6411 allowed = true; 6412 } 6413 if (allowed) { 6414 if (!mSharedLibraries.containsKey(name)) { 6415 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6416 } else if (!name.equals(pkg.packageName)) { 6417 Slog.w(TAG, "Package " + pkg.packageName + " library " 6418 + name + " already exists; skipping"); 6419 } 6420 } else { 6421 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6422 + name + " that is not declared on system image; skipping"); 6423 } 6424 } 6425 if ((scanFlags&SCAN_BOOTING) == 0) { 6426 // If we are not booting, we need to update any applications 6427 // that are clients of our shared library. If we are booting, 6428 // this will all be done once the scan is complete. 6429 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6430 } 6431 } 6432 } 6433 } 6434 6435 // We also need to dexopt any apps that are dependent on this library. Note that 6436 // if these fail, we should abort the install since installing the library will 6437 // result in some apps being broken. 6438 if (clientLibPkgs != null) { 6439 if ((scanFlags & SCAN_NO_DEX) == 0) { 6440 for (int i = 0; i < clientLibPkgs.size(); i++) { 6441 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6442 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6443 null /* instruction sets */, forceDex, 6444 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6445 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6446 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6447 "scanPackageLI failed to dexopt clientLibPkgs"); 6448 } 6449 } 6450 } 6451 } 6452 6453 // Request the ActivityManager to kill the process(only for existing packages) 6454 // so that we do not end up in a confused state while the user is still using the older 6455 // version of the application while the new one gets installed. 6456 if ((scanFlags & SCAN_REPLACING) != 0) { 6457 killApplication(pkg.applicationInfo.packageName, 6458 pkg.applicationInfo.uid, "update pkg"); 6459 } 6460 6461 // Also need to kill any apps that are dependent on the library. 6462 if (clientLibPkgs != null) { 6463 for (int i=0; i<clientLibPkgs.size(); i++) { 6464 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6465 killApplication(clientPkg.applicationInfo.packageName, 6466 clientPkg.applicationInfo.uid, "update lib"); 6467 } 6468 } 6469 6470 // writer 6471 synchronized (mPackages) { 6472 // We don't expect installation to fail beyond this point 6473 6474 // Add the new setting to mSettings 6475 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6476 // Add the new setting to mPackages 6477 mPackages.put(pkg.applicationInfo.packageName, pkg); 6478 // Make sure we don't accidentally delete its data. 6479 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6480 while (iter.hasNext()) { 6481 PackageCleanItem item = iter.next(); 6482 if (pkgName.equals(item.packageName)) { 6483 iter.remove(); 6484 } 6485 } 6486 6487 // Take care of first install / last update times. 6488 if (currentTime != 0) { 6489 if (pkgSetting.firstInstallTime == 0) { 6490 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6491 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6492 pkgSetting.lastUpdateTime = currentTime; 6493 } 6494 } else if (pkgSetting.firstInstallTime == 0) { 6495 // We need *something*. Take time time stamp of the file. 6496 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6497 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6498 if (scanFileTime != pkgSetting.timeStamp) { 6499 // A package on the system image has changed; consider this 6500 // to be an update. 6501 pkgSetting.lastUpdateTime = scanFileTime; 6502 } 6503 } 6504 6505 // Add the package's KeySets to the global KeySetManagerService 6506 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6507 try { 6508 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6509 if (pkg.mKeySetMapping != null) { 6510 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6511 if (pkg.mUpgradeKeySets != null) { 6512 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6513 } 6514 } 6515 } catch (NullPointerException e) { 6516 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6517 } catch (IllegalArgumentException e) { 6518 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6519 } 6520 6521 int N = pkg.providers.size(); 6522 StringBuilder r = null; 6523 int i; 6524 for (i=0; i<N; i++) { 6525 PackageParser.Provider p = pkg.providers.get(i); 6526 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6527 p.info.processName, pkg.applicationInfo.uid); 6528 mProviders.addProvider(p); 6529 p.syncable = p.info.isSyncable; 6530 if (p.info.authority != null) { 6531 String names[] = p.info.authority.split(";"); 6532 p.info.authority = null; 6533 for (int j = 0; j < names.length; j++) { 6534 if (j == 1 && p.syncable) { 6535 // We only want the first authority for a provider to possibly be 6536 // syncable, so if we already added this provider using a different 6537 // authority clear the syncable flag. We copy the provider before 6538 // changing it because the mProviders object contains a reference 6539 // to a provider that we don't want to change. 6540 // Only do this for the second authority since the resulting provider 6541 // object can be the same for all future authorities for this provider. 6542 p = new PackageParser.Provider(p); 6543 p.syncable = false; 6544 } 6545 if (!mProvidersByAuthority.containsKey(names[j])) { 6546 mProvidersByAuthority.put(names[j], p); 6547 if (p.info.authority == null) { 6548 p.info.authority = names[j]; 6549 } else { 6550 p.info.authority = p.info.authority + ";" + names[j]; 6551 } 6552 if (DEBUG_PACKAGE_SCANNING) { 6553 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6554 Log.d(TAG, "Registered content provider: " + names[j] 6555 + ", className = " + p.info.name + ", isSyncable = " 6556 + p.info.isSyncable); 6557 } 6558 } else { 6559 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6560 Slog.w(TAG, "Skipping provider name " + names[j] + 6561 " (in package " + pkg.applicationInfo.packageName + 6562 "): name already used by " 6563 + ((other != null && other.getComponentName() != null) 6564 ? other.getComponentName().getPackageName() : "?")); 6565 } 6566 } 6567 } 6568 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6569 if (r == null) { 6570 r = new StringBuilder(256); 6571 } else { 6572 r.append(' '); 6573 } 6574 r.append(p.info.name); 6575 } 6576 } 6577 if (r != null) { 6578 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6579 } 6580 6581 N = pkg.services.size(); 6582 r = null; 6583 for (i=0; i<N; i++) { 6584 PackageParser.Service s = pkg.services.get(i); 6585 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6586 s.info.processName, pkg.applicationInfo.uid); 6587 mServices.addService(s); 6588 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6589 if (r == null) { 6590 r = new StringBuilder(256); 6591 } else { 6592 r.append(' '); 6593 } 6594 r.append(s.info.name); 6595 } 6596 } 6597 if (r != null) { 6598 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6599 } 6600 6601 N = pkg.receivers.size(); 6602 r = null; 6603 for (i=0; i<N; i++) { 6604 PackageParser.Activity a = pkg.receivers.get(i); 6605 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6606 a.info.processName, pkg.applicationInfo.uid); 6607 mReceivers.addActivity(a, "receiver"); 6608 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6609 if (r == null) { 6610 r = new StringBuilder(256); 6611 } else { 6612 r.append(' '); 6613 } 6614 r.append(a.info.name); 6615 } 6616 } 6617 if (r != null) { 6618 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6619 } 6620 6621 N = pkg.activities.size(); 6622 r = null; 6623 for (i=0; i<N; i++) { 6624 PackageParser.Activity a = pkg.activities.get(i); 6625 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6626 a.info.processName, pkg.applicationInfo.uid); 6627 mActivities.addActivity(a, "activity"); 6628 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6629 if (r == null) { 6630 r = new StringBuilder(256); 6631 } else { 6632 r.append(' '); 6633 } 6634 r.append(a.info.name); 6635 } 6636 } 6637 if (r != null) { 6638 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6639 } 6640 6641 N = pkg.permissionGroups.size(); 6642 r = null; 6643 for (i=0; i<N; i++) { 6644 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6645 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6646 if (cur == null) { 6647 mPermissionGroups.put(pg.info.name, pg); 6648 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6649 if (r == null) { 6650 r = new StringBuilder(256); 6651 } else { 6652 r.append(' '); 6653 } 6654 r.append(pg.info.name); 6655 } 6656 } else { 6657 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6658 + pg.info.packageName + " ignored: original from " 6659 + cur.info.packageName); 6660 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6661 if (r == null) { 6662 r = new StringBuilder(256); 6663 } else { 6664 r.append(' '); 6665 } 6666 r.append("DUP:"); 6667 r.append(pg.info.name); 6668 } 6669 } 6670 } 6671 if (r != null) { 6672 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6673 } 6674 6675 N = pkg.permissions.size(); 6676 r = null; 6677 for (i=0; i<N; i++) { 6678 PackageParser.Permission p = pkg.permissions.get(i); 6679 ArrayMap<String, BasePermission> permissionMap = 6680 p.tree ? mSettings.mPermissionTrees 6681 : mSettings.mPermissions; 6682 p.group = mPermissionGroups.get(p.info.group); 6683 if (p.info.group == null || p.group != null) { 6684 BasePermission bp = permissionMap.get(p.info.name); 6685 6686 // Allow system apps to redefine non-system permissions 6687 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6688 final boolean currentOwnerIsSystem = (bp.perm != null 6689 && isSystemApp(bp.perm.owner)); 6690 if (isSystemApp(p.owner)) { 6691 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6692 // It's a built-in permission and no owner, take ownership now 6693 bp.packageSetting = pkgSetting; 6694 bp.perm = p; 6695 bp.uid = pkg.applicationInfo.uid; 6696 bp.sourcePackage = p.info.packageName; 6697 } else if (!currentOwnerIsSystem) { 6698 String msg = "New decl " + p.owner + " of permission " 6699 + p.info.name + " is system; overriding " + bp.sourcePackage; 6700 reportSettingsProblem(Log.WARN, msg); 6701 bp = null; 6702 } 6703 } 6704 } 6705 6706 if (bp == null) { 6707 bp = new BasePermission(p.info.name, p.info.packageName, 6708 BasePermission.TYPE_NORMAL); 6709 permissionMap.put(p.info.name, bp); 6710 } 6711 6712 if (bp.perm == null) { 6713 if (bp.sourcePackage == null 6714 || bp.sourcePackage.equals(p.info.packageName)) { 6715 BasePermission tree = findPermissionTreeLP(p.info.name); 6716 if (tree == null 6717 || tree.sourcePackage.equals(p.info.packageName)) { 6718 bp.packageSetting = pkgSetting; 6719 bp.perm = p; 6720 bp.uid = pkg.applicationInfo.uid; 6721 bp.sourcePackage = p.info.packageName; 6722 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6723 if (r == null) { 6724 r = new StringBuilder(256); 6725 } else { 6726 r.append(' '); 6727 } 6728 r.append(p.info.name); 6729 } 6730 } else { 6731 Slog.w(TAG, "Permission " + p.info.name + " from package " 6732 + p.info.packageName + " ignored: base tree " 6733 + tree.name + " is from package " 6734 + tree.sourcePackage); 6735 } 6736 } else { 6737 Slog.w(TAG, "Permission " + p.info.name + " from package " 6738 + p.info.packageName + " ignored: original from " 6739 + bp.sourcePackage); 6740 } 6741 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6742 if (r == null) { 6743 r = new StringBuilder(256); 6744 } else { 6745 r.append(' '); 6746 } 6747 r.append("DUP:"); 6748 r.append(p.info.name); 6749 } 6750 if (bp.perm == p) { 6751 bp.protectionLevel = p.info.protectionLevel; 6752 } 6753 } else { 6754 Slog.w(TAG, "Permission " + p.info.name + " from package " 6755 + p.info.packageName + " ignored: no group " 6756 + p.group); 6757 } 6758 } 6759 if (r != null) { 6760 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6761 } 6762 6763 N = pkg.instrumentation.size(); 6764 r = null; 6765 for (i=0; i<N; i++) { 6766 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6767 a.info.packageName = pkg.applicationInfo.packageName; 6768 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6769 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6770 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6771 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6772 a.info.dataDir = pkg.applicationInfo.dataDir; 6773 6774 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6775 // need other information about the application, like the ABI and what not ? 6776 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6777 mInstrumentation.put(a.getComponentName(), a); 6778 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6779 if (r == null) { 6780 r = new StringBuilder(256); 6781 } else { 6782 r.append(' '); 6783 } 6784 r.append(a.info.name); 6785 } 6786 } 6787 if (r != null) { 6788 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6789 } 6790 6791 if (pkg.protectedBroadcasts != null) { 6792 N = pkg.protectedBroadcasts.size(); 6793 for (i=0; i<N; i++) { 6794 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6795 } 6796 } 6797 6798 pkgSetting.setTimeStamp(scanFileTime); 6799 6800 // Create idmap files for pairs of (packages, overlay packages). 6801 // Note: "android", ie framework-res.apk, is handled by native layers. 6802 if (pkg.mOverlayTarget != null) { 6803 // This is an overlay package. 6804 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6805 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6806 mOverlays.put(pkg.mOverlayTarget, 6807 new ArrayMap<String, PackageParser.Package>()); 6808 } 6809 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6810 map.put(pkg.packageName, pkg); 6811 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6812 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6813 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6814 "scanPackageLI failed to createIdmap"); 6815 } 6816 } 6817 } else if (mOverlays.containsKey(pkg.packageName) && 6818 !pkg.packageName.equals("android")) { 6819 // This is a regular package, with one or more known overlay packages. 6820 createIdmapsForPackageLI(pkg); 6821 } 6822 } 6823 6824 return pkg; 6825 } 6826 6827 /** 6828 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6829 * i.e, so that all packages can be run inside a single process if required. 6830 * 6831 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6832 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6833 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6834 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6835 * updating a package that belongs to a shared user. 6836 * 6837 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6838 * adds unnecessary complexity. 6839 */ 6840 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6841 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6842 String requiredInstructionSet = null; 6843 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6844 requiredInstructionSet = VMRuntime.getInstructionSet( 6845 scannedPackage.applicationInfo.primaryCpuAbi); 6846 } 6847 6848 PackageSetting requirer = null; 6849 for (PackageSetting ps : packagesForUser) { 6850 // If packagesForUser contains scannedPackage, we skip it. This will happen 6851 // when scannedPackage is an update of an existing package. Without this check, 6852 // we will never be able to change the ABI of any package belonging to a shared 6853 // user, even if it's compatible with other packages. 6854 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6855 if (ps.primaryCpuAbiString == null) { 6856 continue; 6857 } 6858 6859 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6860 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6861 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6862 // this but there's not much we can do. 6863 String errorMessage = "Instruction set mismatch, " 6864 + ((requirer == null) ? "[caller]" : requirer) 6865 + " requires " + requiredInstructionSet + " whereas " + ps 6866 + " requires " + instructionSet; 6867 Slog.w(TAG, errorMessage); 6868 } 6869 6870 if (requiredInstructionSet == null) { 6871 requiredInstructionSet = instructionSet; 6872 requirer = ps; 6873 } 6874 } 6875 } 6876 6877 if (requiredInstructionSet != null) { 6878 String adjustedAbi; 6879 if (requirer != null) { 6880 // requirer != null implies that either scannedPackage was null or that scannedPackage 6881 // did not require an ABI, in which case we have to adjust scannedPackage to match 6882 // the ABI of the set (which is the same as requirer's ABI) 6883 adjustedAbi = requirer.primaryCpuAbiString; 6884 if (scannedPackage != null) { 6885 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6886 } 6887 } else { 6888 // requirer == null implies that we're updating all ABIs in the set to 6889 // match scannedPackage. 6890 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6891 } 6892 6893 for (PackageSetting ps : packagesForUser) { 6894 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6895 if (ps.primaryCpuAbiString != null) { 6896 continue; 6897 } 6898 6899 ps.primaryCpuAbiString = adjustedAbi; 6900 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6901 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6902 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6903 6904 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6905 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6906 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6907 ps.primaryCpuAbiString = null; 6908 ps.pkg.applicationInfo.primaryCpuAbi = null; 6909 return; 6910 } else { 6911 mInstaller.rmdex(ps.codePathString, 6912 getDexCodeInstructionSet(getPreferredInstructionSet())); 6913 } 6914 } 6915 } 6916 } 6917 } 6918 } 6919 6920 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6921 synchronized (mPackages) { 6922 mResolverReplaced = true; 6923 // Set up information for custom user intent resolution activity. 6924 mResolveActivity.applicationInfo = pkg.applicationInfo; 6925 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6926 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6927 mResolveActivity.processName = pkg.applicationInfo.packageName; 6928 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6929 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6930 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6931 mResolveActivity.theme = 0; 6932 mResolveActivity.exported = true; 6933 mResolveActivity.enabled = true; 6934 mResolveInfo.activityInfo = mResolveActivity; 6935 mResolveInfo.priority = 0; 6936 mResolveInfo.preferredOrder = 0; 6937 mResolveInfo.match = 0; 6938 mResolveComponentName = mCustomResolverComponentName; 6939 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6940 mResolveComponentName); 6941 } 6942 } 6943 6944 private static String calculateBundledApkRoot(final String codePathString) { 6945 final File codePath = new File(codePathString); 6946 final File codeRoot; 6947 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6948 codeRoot = Environment.getRootDirectory(); 6949 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6950 codeRoot = Environment.getOemDirectory(); 6951 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6952 codeRoot = Environment.getVendorDirectory(); 6953 } else { 6954 // Unrecognized code path; take its top real segment as the apk root: 6955 // e.g. /something/app/blah.apk => /something 6956 try { 6957 File f = codePath.getCanonicalFile(); 6958 File parent = f.getParentFile(); // non-null because codePath is a file 6959 File tmp; 6960 while ((tmp = parent.getParentFile()) != null) { 6961 f = parent; 6962 parent = tmp; 6963 } 6964 codeRoot = f; 6965 Slog.w(TAG, "Unrecognized code path " 6966 + codePath + " - using " + codeRoot); 6967 } catch (IOException e) { 6968 // Can't canonicalize the code path -- shenanigans? 6969 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6970 return Environment.getRootDirectory().getPath(); 6971 } 6972 } 6973 return codeRoot.getPath(); 6974 } 6975 6976 /** 6977 * Derive and set the location of native libraries for the given package, 6978 * which varies depending on where and how the package was installed. 6979 */ 6980 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6981 final ApplicationInfo info = pkg.applicationInfo; 6982 final String codePath = pkg.codePath; 6983 final File codeFile = new File(codePath); 6984 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6985 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6986 6987 info.nativeLibraryRootDir = null; 6988 info.nativeLibraryRootRequiresIsa = false; 6989 info.nativeLibraryDir = null; 6990 info.secondaryNativeLibraryDir = null; 6991 6992 if (isApkFile(codeFile)) { 6993 // Monolithic install 6994 if (bundledApp) { 6995 // If "/system/lib64/apkname" exists, assume that is the per-package 6996 // native library directory to use; otherwise use "/system/lib/apkname". 6997 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6998 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6999 getPrimaryInstructionSet(info)); 7000 7001 // This is a bundled system app so choose the path based on the ABI. 7002 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7003 // is just the default path. 7004 final String apkName = deriveCodePathName(codePath); 7005 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7006 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7007 apkName).getAbsolutePath(); 7008 7009 if (info.secondaryCpuAbi != null) { 7010 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7011 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7012 secondaryLibDir, apkName).getAbsolutePath(); 7013 } 7014 } else if (asecApp) { 7015 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7016 .getAbsolutePath(); 7017 } else { 7018 final String apkName = deriveCodePathName(codePath); 7019 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7020 .getAbsolutePath(); 7021 } 7022 7023 info.nativeLibraryRootRequiresIsa = false; 7024 info.nativeLibraryDir = info.nativeLibraryRootDir; 7025 } else { 7026 // Cluster install 7027 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7028 info.nativeLibraryRootRequiresIsa = true; 7029 7030 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7031 getPrimaryInstructionSet(info)).getAbsolutePath(); 7032 7033 if (info.secondaryCpuAbi != null) { 7034 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7035 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7036 } 7037 } 7038 } 7039 7040 /** 7041 * Calculate the abis and roots for a bundled app. These can uniquely 7042 * be determined from the contents of the system partition, i.e whether 7043 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7044 * of this information, and instead assume that the system was built 7045 * sensibly. 7046 */ 7047 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7048 PackageSetting pkgSetting) { 7049 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7050 7051 // If "/system/lib64/apkname" exists, assume that is the per-package 7052 // native library directory to use; otherwise use "/system/lib/apkname". 7053 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7054 setBundledAppAbi(pkg, apkRoot, apkName); 7055 // pkgSetting might be null during rescan following uninstall of updates 7056 // to a bundled app, so accommodate that possibility. The settings in 7057 // that case will be established later from the parsed package. 7058 // 7059 // If the settings aren't null, sync them up with what we've just derived. 7060 // note that apkRoot isn't stored in the package settings. 7061 if (pkgSetting != null) { 7062 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7063 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7064 } 7065 } 7066 7067 /** 7068 * Deduces the ABI of a bundled app and sets the relevant fields on the 7069 * parsed pkg object. 7070 * 7071 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7072 * under which system libraries are installed. 7073 * @param apkName the name of the installed package. 7074 */ 7075 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7076 final File codeFile = new File(pkg.codePath); 7077 7078 final boolean has64BitLibs; 7079 final boolean has32BitLibs; 7080 if (isApkFile(codeFile)) { 7081 // Monolithic install 7082 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7083 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7084 } else { 7085 // Cluster install 7086 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7087 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7088 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7089 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7090 has64BitLibs = (new File(rootDir, isa)).exists(); 7091 } else { 7092 has64BitLibs = false; 7093 } 7094 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7095 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7096 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7097 has32BitLibs = (new File(rootDir, isa)).exists(); 7098 } else { 7099 has32BitLibs = false; 7100 } 7101 } 7102 7103 if (has64BitLibs && !has32BitLibs) { 7104 // The package has 64 bit libs, but not 32 bit libs. Its primary 7105 // ABI should be 64 bit. We can safely assume here that the bundled 7106 // native libraries correspond to the most preferred ABI in the list. 7107 7108 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7109 pkg.applicationInfo.secondaryCpuAbi = null; 7110 } else if (has32BitLibs && !has64BitLibs) { 7111 // The package has 32 bit libs but not 64 bit libs. Its primary 7112 // ABI should be 32 bit. 7113 7114 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7115 pkg.applicationInfo.secondaryCpuAbi = null; 7116 } else if (has32BitLibs && has64BitLibs) { 7117 // The application has both 64 and 32 bit bundled libraries. We check 7118 // here that the app declares multiArch support, and warn if it doesn't. 7119 // 7120 // We will be lenient here and record both ABIs. The primary will be the 7121 // ABI that's higher on the list, i.e, a device that's configured to prefer 7122 // 64 bit apps will see a 64 bit primary ABI, 7123 7124 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7125 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7126 } 7127 7128 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7129 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7130 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7131 } else { 7132 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7133 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7134 } 7135 } else { 7136 pkg.applicationInfo.primaryCpuAbi = null; 7137 pkg.applicationInfo.secondaryCpuAbi = null; 7138 } 7139 } 7140 7141 private void killApplication(String pkgName, int appId, String reason) { 7142 // Request the ActivityManager to kill the process(only for existing packages) 7143 // so that we do not end up in a confused state while the user is still using the older 7144 // version of the application while the new one gets installed. 7145 IActivityManager am = ActivityManagerNative.getDefault(); 7146 if (am != null) { 7147 try { 7148 am.killApplicationWithAppId(pkgName, appId, reason); 7149 } catch (RemoteException e) { 7150 } 7151 } 7152 } 7153 7154 void removePackageLI(PackageSetting ps, boolean chatty) { 7155 if (DEBUG_INSTALL) { 7156 if (chatty) 7157 Log.d(TAG, "Removing package " + ps.name); 7158 } 7159 7160 // writer 7161 synchronized (mPackages) { 7162 mPackages.remove(ps.name); 7163 final PackageParser.Package pkg = ps.pkg; 7164 if (pkg != null) { 7165 cleanPackageDataStructuresLILPw(pkg, chatty); 7166 } 7167 } 7168 } 7169 7170 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7171 if (DEBUG_INSTALL) { 7172 if (chatty) 7173 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7174 } 7175 7176 // writer 7177 synchronized (mPackages) { 7178 mPackages.remove(pkg.applicationInfo.packageName); 7179 cleanPackageDataStructuresLILPw(pkg, chatty); 7180 } 7181 } 7182 7183 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7184 int N = pkg.providers.size(); 7185 StringBuilder r = null; 7186 int i; 7187 for (i=0; i<N; i++) { 7188 PackageParser.Provider p = pkg.providers.get(i); 7189 mProviders.removeProvider(p); 7190 if (p.info.authority == null) { 7191 7192 /* There was another ContentProvider with this authority when 7193 * this app was installed so this authority is null, 7194 * Ignore it as we don't have to unregister the provider. 7195 */ 7196 continue; 7197 } 7198 String names[] = p.info.authority.split(";"); 7199 for (int j = 0; j < names.length; j++) { 7200 if (mProvidersByAuthority.get(names[j]) == p) { 7201 mProvidersByAuthority.remove(names[j]); 7202 if (DEBUG_REMOVE) { 7203 if (chatty) 7204 Log.d(TAG, "Unregistered content provider: " + names[j] 7205 + ", className = " + p.info.name + ", isSyncable = " 7206 + p.info.isSyncable); 7207 } 7208 } 7209 } 7210 if (DEBUG_REMOVE && chatty) { 7211 if (r == null) { 7212 r = new StringBuilder(256); 7213 } else { 7214 r.append(' '); 7215 } 7216 r.append(p.info.name); 7217 } 7218 } 7219 if (r != null) { 7220 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7221 } 7222 7223 N = pkg.services.size(); 7224 r = null; 7225 for (i=0; i<N; i++) { 7226 PackageParser.Service s = pkg.services.get(i); 7227 mServices.removeService(s); 7228 if (chatty) { 7229 if (r == null) { 7230 r = new StringBuilder(256); 7231 } else { 7232 r.append(' '); 7233 } 7234 r.append(s.info.name); 7235 } 7236 } 7237 if (r != null) { 7238 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7239 } 7240 7241 N = pkg.receivers.size(); 7242 r = null; 7243 for (i=0; i<N; i++) { 7244 PackageParser.Activity a = pkg.receivers.get(i); 7245 mReceivers.removeActivity(a, "receiver"); 7246 if (DEBUG_REMOVE && chatty) { 7247 if (r == null) { 7248 r = new StringBuilder(256); 7249 } else { 7250 r.append(' '); 7251 } 7252 r.append(a.info.name); 7253 } 7254 } 7255 if (r != null) { 7256 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7257 } 7258 7259 N = pkg.activities.size(); 7260 r = null; 7261 for (i=0; i<N; i++) { 7262 PackageParser.Activity a = pkg.activities.get(i); 7263 mActivities.removeActivity(a, "activity"); 7264 if (DEBUG_REMOVE && chatty) { 7265 if (r == null) { 7266 r = new StringBuilder(256); 7267 } else { 7268 r.append(' '); 7269 } 7270 r.append(a.info.name); 7271 } 7272 } 7273 if (r != null) { 7274 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7275 } 7276 7277 N = pkg.permissions.size(); 7278 r = null; 7279 for (i=0; i<N; i++) { 7280 PackageParser.Permission p = pkg.permissions.get(i); 7281 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7282 if (bp == null) { 7283 bp = mSettings.mPermissionTrees.get(p.info.name); 7284 } 7285 if (bp != null && bp.perm == p) { 7286 bp.perm = null; 7287 if (DEBUG_REMOVE && chatty) { 7288 if (r == null) { 7289 r = new StringBuilder(256); 7290 } else { 7291 r.append(' '); 7292 } 7293 r.append(p.info.name); 7294 } 7295 } 7296 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7297 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7298 if (appOpPerms != null) { 7299 appOpPerms.remove(pkg.packageName); 7300 } 7301 } 7302 } 7303 if (r != null) { 7304 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7305 } 7306 7307 N = pkg.requestedPermissions.size(); 7308 r = null; 7309 for (i=0; i<N; i++) { 7310 String perm = pkg.requestedPermissions.get(i); 7311 BasePermission bp = mSettings.mPermissions.get(perm); 7312 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7313 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7314 if (appOpPerms != null) { 7315 appOpPerms.remove(pkg.packageName); 7316 if (appOpPerms.isEmpty()) { 7317 mAppOpPermissionPackages.remove(perm); 7318 } 7319 } 7320 } 7321 } 7322 if (r != null) { 7323 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7324 } 7325 7326 N = pkg.instrumentation.size(); 7327 r = null; 7328 for (i=0; i<N; i++) { 7329 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7330 mInstrumentation.remove(a.getComponentName()); 7331 if (DEBUG_REMOVE && chatty) { 7332 if (r == null) { 7333 r = new StringBuilder(256); 7334 } else { 7335 r.append(' '); 7336 } 7337 r.append(a.info.name); 7338 } 7339 } 7340 if (r != null) { 7341 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7342 } 7343 7344 r = null; 7345 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7346 // Only system apps can hold shared libraries. 7347 if (pkg.libraryNames != null) { 7348 for (i=0; i<pkg.libraryNames.size(); i++) { 7349 String name = pkg.libraryNames.get(i); 7350 SharedLibraryEntry cur = mSharedLibraries.get(name); 7351 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7352 mSharedLibraries.remove(name); 7353 if (DEBUG_REMOVE && chatty) { 7354 if (r == null) { 7355 r = new StringBuilder(256); 7356 } else { 7357 r.append(' '); 7358 } 7359 r.append(name); 7360 } 7361 } 7362 } 7363 } 7364 } 7365 if (r != null) { 7366 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7367 } 7368 } 7369 7370 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7371 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7372 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7373 return true; 7374 } 7375 } 7376 return false; 7377 } 7378 7379 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7380 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7381 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7382 7383 private void updatePermissionsLPw(String changingPkg, 7384 PackageParser.Package pkgInfo, int flags) { 7385 // Make sure there are no dangling permission trees. 7386 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7387 while (it.hasNext()) { 7388 final BasePermission bp = it.next(); 7389 if (bp.packageSetting == null) { 7390 // We may not yet have parsed the package, so just see if 7391 // we still know about its settings. 7392 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7393 } 7394 if (bp.packageSetting == null) { 7395 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7396 + " from package " + bp.sourcePackage); 7397 it.remove(); 7398 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7399 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7400 Slog.i(TAG, "Removing old permission tree: " + bp.name 7401 + " from package " + bp.sourcePackage); 7402 flags |= UPDATE_PERMISSIONS_ALL; 7403 it.remove(); 7404 } 7405 } 7406 } 7407 7408 // Make sure all dynamic permissions have been assigned to a package, 7409 // and make sure there are no dangling permissions. 7410 it = mSettings.mPermissions.values().iterator(); 7411 while (it.hasNext()) { 7412 final BasePermission bp = it.next(); 7413 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7414 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7415 + bp.name + " pkg=" + bp.sourcePackage 7416 + " info=" + bp.pendingInfo); 7417 if (bp.packageSetting == null && bp.pendingInfo != null) { 7418 final BasePermission tree = findPermissionTreeLP(bp.name); 7419 if (tree != null && tree.perm != null) { 7420 bp.packageSetting = tree.packageSetting; 7421 bp.perm = new PackageParser.Permission(tree.perm.owner, 7422 new PermissionInfo(bp.pendingInfo)); 7423 bp.perm.info.packageName = tree.perm.info.packageName; 7424 bp.perm.info.name = bp.name; 7425 bp.uid = tree.uid; 7426 } 7427 } 7428 } 7429 if (bp.packageSetting == null) { 7430 // We may not yet have parsed the package, so just see if 7431 // we still know about its settings. 7432 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7433 } 7434 if (bp.packageSetting == null) { 7435 Slog.w(TAG, "Removing dangling permission: " + bp.name 7436 + " from package " + bp.sourcePackage); 7437 it.remove(); 7438 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7439 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7440 Slog.i(TAG, "Removing old permission: " + bp.name 7441 + " from package " + bp.sourcePackage); 7442 flags |= UPDATE_PERMISSIONS_ALL; 7443 it.remove(); 7444 } 7445 } 7446 } 7447 7448 // Now update the permissions for all packages, in particular 7449 // replace the granted permissions of the system packages. 7450 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7451 for (PackageParser.Package pkg : mPackages.values()) { 7452 if (pkg != pkgInfo) { 7453 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7454 changingPkg); 7455 } 7456 } 7457 } 7458 7459 if (pkgInfo != null) { 7460 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7461 } 7462 } 7463 7464 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7465 String packageOfInterest) { 7466 // IMPORTANT: There are two types of permissions: install and runtime. 7467 // Install time permissions are granted when the app is installed to 7468 // all device users and users added in the future. Runtime permissions 7469 // are granted at runtime explicitly to specific users. Normal and signature 7470 // protected permissions are install time permissions. Dangerous permissions 7471 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7472 // otherwise they are runtime permissions. This function does not manage 7473 // runtime permissions except for the case an app targeting Lollipop MR1 7474 // being upgraded to target a newer SDK, in which case dangerous permissions 7475 // are transformed from install time to runtime ones. 7476 7477 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7478 if (ps == null) { 7479 return; 7480 } 7481 7482 PermissionsState permissionsState = ps.getPermissionsState(); 7483 PermissionsState origPermissions = permissionsState; 7484 7485 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7486 7487 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7488 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7489 7490 boolean changedInstallPermission = false; 7491 7492 if (replace) { 7493 ps.installPermissionsFixed = false; 7494 if (!ps.isSharedUser()) { 7495 origPermissions = new PermissionsState(permissionsState); 7496 permissionsState.reset(); 7497 } 7498 } 7499 7500 permissionsState.setGlobalGids(mGlobalGids); 7501 7502 final int N = pkg.requestedPermissions.size(); 7503 for (int i=0; i<N; i++) { 7504 final String name = pkg.requestedPermissions.get(i); 7505 final BasePermission bp = mSettings.mPermissions.get(name); 7506 7507 if (DEBUG_INSTALL) { 7508 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7509 } 7510 7511 if (bp == null || bp.packageSetting == null) { 7512 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7513 Slog.w(TAG, "Unknown permission " + name 7514 + " in package " + pkg.packageName); 7515 } 7516 continue; 7517 } 7518 7519 final String perm = bp.name; 7520 boolean allowedSig = false; 7521 int grant = GRANT_DENIED; 7522 7523 // Keep track of app op permissions. 7524 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7525 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7526 if (pkgs == null) { 7527 pkgs = new ArraySet<>(); 7528 mAppOpPermissionPackages.put(bp.name, pkgs); 7529 } 7530 pkgs.add(pkg.packageName); 7531 } 7532 7533 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7534 switch (level) { 7535 case PermissionInfo.PROTECTION_NORMAL: { 7536 // For all apps normal permissions are install time ones. 7537 grant = GRANT_INSTALL; 7538 } break; 7539 7540 case PermissionInfo.PROTECTION_DANGEROUS: { 7541 if (!RUNTIME_PERMISSIONS_ENABLED 7542 || pkg.applicationInfo.targetSdkVersion 7543 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7544 // For legacy apps dangerous permissions are install time ones. 7545 grant = GRANT_INSTALL; 7546 } else if (ps.isSystem()) { 7547 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7548 if (origPermissions.hasInstallPermission(bp.name)) { 7549 // If a system app had an install permission, then the app was 7550 // upgraded and we grant the permissions as runtime to all users. 7551 grant = GRANT_UPGRADE; 7552 upgradeUserIds = currentUserIds; 7553 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7554 // If users changed since the last permissions update for a 7555 // system app, we grant the permission as runtime to the new users. 7556 grant = GRANT_UPGRADE; 7557 upgradeUserIds = currentUserIds; 7558 for (int userId : updatedUserIds) { 7559 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7560 } 7561 } else { 7562 // Otherwise, we grant the permission as runtime if the app 7563 // already had it, i.e. we preserve runtime permissions. 7564 grant = GRANT_RUNTIME; 7565 } 7566 } else if (origPermissions.hasInstallPermission(bp.name)) { 7567 // For legacy apps that became modern, install becomes runtime. 7568 grant = GRANT_UPGRADE; 7569 upgradeUserIds = currentUserIds; 7570 } else if (replace) { 7571 // For upgraded modern apps keep runtime permissions unchanged. 7572 grant = GRANT_RUNTIME; 7573 } 7574 } break; 7575 7576 case PermissionInfo.PROTECTION_SIGNATURE: { 7577 // For all apps signature permissions are install time ones. 7578 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7579 if (allowedSig) { 7580 grant = GRANT_INSTALL; 7581 } 7582 } break; 7583 } 7584 7585 if (DEBUG_INSTALL) { 7586 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7587 } 7588 7589 if (grant != GRANT_DENIED) { 7590 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7591 // If this is an existing, non-system package, then 7592 // we can't add any new permissions to it. 7593 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7594 // Except... if this is a permission that was added 7595 // to the platform (note: need to only do this when 7596 // updating the platform). 7597 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7598 grant = GRANT_DENIED; 7599 } 7600 } 7601 } 7602 7603 switch (grant) { 7604 case GRANT_INSTALL: { 7605 // Grant an install permission. 7606 if (permissionsState.grantInstallPermission(bp) != 7607 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7608 changedInstallPermission = true; 7609 } 7610 } break; 7611 7612 case GRANT_RUNTIME: { 7613 // Grant previously granted runtime permissions. 7614 for (int userId : UserManagerService.getInstance().getUserIds()) { 7615 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7616 if (permissionsState.grantRuntimePermission(bp, userId) == 7617 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7618 // If we cannot put the permission as it was, we have to write. 7619 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7620 changedRuntimePermissionUserIds, userId); 7621 } 7622 } 7623 } 7624 } break; 7625 7626 case GRANT_UPGRADE: { 7627 // Grant runtime permissions for a previously held install permission. 7628 permissionsState.revokeInstallPermission(bp); 7629 for (int userId : upgradeUserIds) { 7630 if (permissionsState.grantRuntimePermission(bp, userId) != 7631 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7632 // If we granted the permission, we have to write. 7633 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7634 changedRuntimePermissionUserIds, userId); 7635 } 7636 } 7637 } break; 7638 7639 default: { 7640 if (packageOfInterest == null 7641 || packageOfInterest.equals(pkg.packageName)) { 7642 Slog.w(TAG, "Not granting permission " + perm 7643 + " to package " + pkg.packageName 7644 + " because it was previously installed without"); 7645 } 7646 } break; 7647 } 7648 } else { 7649 if (permissionsState.revokeInstallPermission(bp) != 7650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7651 changedInstallPermission = true; 7652 Slog.i(TAG, "Un-granting permission " + perm 7653 + " from package " + pkg.packageName 7654 + " (protectionLevel=" + bp.protectionLevel 7655 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7656 + ")"); 7657 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7658 // Don't print warning for app op permissions, since it is fine for them 7659 // not to be granted, there is a UI for the user to decide. 7660 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7661 Slog.w(TAG, "Not granting permission " + perm 7662 + " to package " + pkg.packageName 7663 + " (protectionLevel=" + bp.protectionLevel 7664 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7665 + ")"); 7666 } 7667 } 7668 } 7669 } 7670 7671 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7672 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7673 // This is the first that we have heard about this package, so the 7674 // permissions we have now selected are fixed until explicitly 7675 // changed. 7676 ps.installPermissionsFixed = true; 7677 } 7678 7679 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7680 7681 // Persist the runtime permissions state for users with changes. 7682 if (RUNTIME_PERMISSIONS_ENABLED) { 7683 for (int userId : changedRuntimePermissionUserIds) { 7684 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7685 } 7686 } 7687 } 7688 7689 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7690 boolean allowed = false; 7691 final int NP = PackageParser.NEW_PERMISSIONS.length; 7692 for (int ip=0; ip<NP; ip++) { 7693 final PackageParser.NewPermissionInfo npi 7694 = PackageParser.NEW_PERMISSIONS[ip]; 7695 if (npi.name.equals(perm) 7696 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7697 allowed = true; 7698 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7699 + pkg.packageName); 7700 break; 7701 } 7702 } 7703 return allowed; 7704 } 7705 7706 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7707 BasePermission bp, PermissionsState origPermissions) { 7708 boolean allowed; 7709 allowed = (compareSignatures( 7710 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7711 == PackageManager.SIGNATURE_MATCH) 7712 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7713 == PackageManager.SIGNATURE_MATCH); 7714 if (!allowed && (bp.protectionLevel 7715 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7716 if (isSystemApp(pkg)) { 7717 // For updated system applications, a system permission 7718 // is granted only if it had been defined by the original application. 7719 if (pkg.isUpdatedSystemApp()) { 7720 final PackageSetting sysPs = mSettings 7721 .getDisabledSystemPkgLPr(pkg.packageName); 7722 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7723 // If the original was granted this permission, we take 7724 // that grant decision as read and propagate it to the 7725 // update. 7726 if (sysPs.isPrivileged()) { 7727 allowed = true; 7728 } 7729 } else { 7730 // The system apk may have been updated with an older 7731 // version of the one on the data partition, but which 7732 // granted a new system permission that it didn't have 7733 // before. In this case we do want to allow the app to 7734 // now get the new permission if the ancestral apk is 7735 // privileged to get it. 7736 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7737 for (int j=0; 7738 j<sysPs.pkg.requestedPermissions.size(); j++) { 7739 if (perm.equals( 7740 sysPs.pkg.requestedPermissions.get(j))) { 7741 allowed = true; 7742 break; 7743 } 7744 } 7745 } 7746 } 7747 } else { 7748 allowed = isPrivilegedApp(pkg); 7749 } 7750 } 7751 } 7752 if (!allowed && (bp.protectionLevel 7753 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7754 // For development permissions, a development permission 7755 // is granted only if it was already granted. 7756 allowed = origPermissions.hasInstallPermission(perm); 7757 } 7758 return allowed; 7759 } 7760 7761 final class ActivityIntentResolver 7762 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7763 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7764 boolean defaultOnly, int userId) { 7765 if (!sUserManager.exists(userId)) return null; 7766 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7767 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7768 } 7769 7770 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7771 int userId) { 7772 if (!sUserManager.exists(userId)) return null; 7773 mFlags = flags; 7774 return super.queryIntent(intent, resolvedType, 7775 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7776 } 7777 7778 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7779 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7780 if (!sUserManager.exists(userId)) return null; 7781 if (packageActivities == null) { 7782 return null; 7783 } 7784 mFlags = flags; 7785 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7786 final int N = packageActivities.size(); 7787 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7788 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7789 7790 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7791 for (int i = 0; i < N; ++i) { 7792 intentFilters = packageActivities.get(i).intents; 7793 if (intentFilters != null && intentFilters.size() > 0) { 7794 PackageParser.ActivityIntentInfo[] array = 7795 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7796 intentFilters.toArray(array); 7797 listCut.add(array); 7798 } 7799 } 7800 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7801 } 7802 7803 public final void addActivity(PackageParser.Activity a, String type) { 7804 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7805 mActivities.put(a.getComponentName(), a); 7806 if (DEBUG_SHOW_INFO) 7807 Log.v( 7808 TAG, " " + type + " " + 7809 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7810 if (DEBUG_SHOW_INFO) 7811 Log.v(TAG, " Class=" + a.info.name); 7812 final int NI = a.intents.size(); 7813 for (int j=0; j<NI; j++) { 7814 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7815 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7816 intent.setPriority(0); 7817 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7818 + a.className + " with priority > 0, forcing to 0"); 7819 } 7820 if (DEBUG_SHOW_INFO) { 7821 Log.v(TAG, " IntentFilter:"); 7822 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7823 } 7824 if (!intent.debugCheck()) { 7825 Log.w(TAG, "==> For Activity " + a.info.name); 7826 } 7827 addFilter(intent); 7828 } 7829 } 7830 7831 public final void removeActivity(PackageParser.Activity a, String type) { 7832 mActivities.remove(a.getComponentName()); 7833 if (DEBUG_SHOW_INFO) { 7834 Log.v(TAG, " " + type + " " 7835 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7836 : a.info.name) + ":"); 7837 Log.v(TAG, " Class=" + a.info.name); 7838 } 7839 final int NI = a.intents.size(); 7840 for (int j=0; j<NI; j++) { 7841 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7842 if (DEBUG_SHOW_INFO) { 7843 Log.v(TAG, " IntentFilter:"); 7844 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7845 } 7846 removeFilter(intent); 7847 } 7848 } 7849 7850 @Override 7851 protected boolean allowFilterResult( 7852 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7853 ActivityInfo filterAi = filter.activity.info; 7854 for (int i=dest.size()-1; i>=0; i--) { 7855 ActivityInfo destAi = dest.get(i).activityInfo; 7856 if (destAi.name == filterAi.name 7857 && destAi.packageName == filterAi.packageName) { 7858 return false; 7859 } 7860 } 7861 return true; 7862 } 7863 7864 @Override 7865 protected ActivityIntentInfo[] newArray(int size) { 7866 return new ActivityIntentInfo[size]; 7867 } 7868 7869 @Override 7870 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7871 if (!sUserManager.exists(userId)) return true; 7872 PackageParser.Package p = filter.activity.owner; 7873 if (p != null) { 7874 PackageSetting ps = (PackageSetting)p.mExtras; 7875 if (ps != null) { 7876 // System apps are never considered stopped for purposes of 7877 // filtering, because there may be no way for the user to 7878 // actually re-launch them. 7879 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7880 && ps.getStopped(userId); 7881 } 7882 } 7883 return false; 7884 } 7885 7886 @Override 7887 protected boolean isPackageForFilter(String packageName, 7888 PackageParser.ActivityIntentInfo info) { 7889 return packageName.equals(info.activity.owner.packageName); 7890 } 7891 7892 @Override 7893 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7894 int match, int userId) { 7895 if (!sUserManager.exists(userId)) return null; 7896 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7897 return null; 7898 } 7899 final PackageParser.Activity activity = info.activity; 7900 if (mSafeMode && (activity.info.applicationInfo.flags 7901 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7902 return null; 7903 } 7904 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7905 if (ps == null) { 7906 return null; 7907 } 7908 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7909 ps.readUserState(userId), userId); 7910 if (ai == null) { 7911 return null; 7912 } 7913 final ResolveInfo res = new ResolveInfo(); 7914 res.activityInfo = ai; 7915 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7916 res.filter = info; 7917 } 7918 if (info != null) { 7919 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7920 } 7921 res.priority = info.getPriority(); 7922 res.preferredOrder = activity.owner.mPreferredOrder; 7923 //System.out.println("Result: " + res.activityInfo.className + 7924 // " = " + res.priority); 7925 res.match = match; 7926 res.isDefault = info.hasDefault; 7927 res.labelRes = info.labelRes; 7928 res.nonLocalizedLabel = info.nonLocalizedLabel; 7929 if (userNeedsBadging(userId)) { 7930 res.noResourceId = true; 7931 } else { 7932 res.icon = info.icon; 7933 } 7934 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7935 return res; 7936 } 7937 7938 @Override 7939 protected void sortResults(List<ResolveInfo> results) { 7940 Collections.sort(results, mResolvePrioritySorter); 7941 } 7942 7943 @Override 7944 protected void dumpFilter(PrintWriter out, String prefix, 7945 PackageParser.ActivityIntentInfo filter) { 7946 out.print(prefix); out.print( 7947 Integer.toHexString(System.identityHashCode(filter.activity))); 7948 out.print(' '); 7949 filter.activity.printComponentShortName(out); 7950 out.print(" filter "); 7951 out.println(Integer.toHexString(System.identityHashCode(filter))); 7952 } 7953 7954 @Override 7955 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7956 return filter.activity; 7957 } 7958 7959 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7960 PackageParser.Activity activity = (PackageParser.Activity)label; 7961 out.print(prefix); out.print( 7962 Integer.toHexString(System.identityHashCode(activity))); 7963 out.print(' '); 7964 activity.printComponentShortName(out); 7965 if (count > 1) { 7966 out.print(" ("); out.print(count); out.print(" filters)"); 7967 } 7968 out.println(); 7969 } 7970 7971// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7972// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7973// final List<ResolveInfo> retList = Lists.newArrayList(); 7974// while (i.hasNext()) { 7975// final ResolveInfo resolveInfo = i.next(); 7976// if (isEnabledLP(resolveInfo.activityInfo)) { 7977// retList.add(resolveInfo); 7978// } 7979// } 7980// return retList; 7981// } 7982 7983 // Keys are String (activity class name), values are Activity. 7984 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7985 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7986 private int mFlags; 7987 } 7988 7989 private final class ServiceIntentResolver 7990 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7991 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7992 boolean defaultOnly, int userId) { 7993 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7994 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7995 } 7996 7997 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7998 int userId) { 7999 if (!sUserManager.exists(userId)) return null; 8000 mFlags = flags; 8001 return super.queryIntent(intent, resolvedType, 8002 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8003 } 8004 8005 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8006 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8007 if (!sUserManager.exists(userId)) return null; 8008 if (packageServices == null) { 8009 return null; 8010 } 8011 mFlags = flags; 8012 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8013 final int N = packageServices.size(); 8014 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8015 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8016 8017 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8018 for (int i = 0; i < N; ++i) { 8019 intentFilters = packageServices.get(i).intents; 8020 if (intentFilters != null && intentFilters.size() > 0) { 8021 PackageParser.ServiceIntentInfo[] array = 8022 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8023 intentFilters.toArray(array); 8024 listCut.add(array); 8025 } 8026 } 8027 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8028 } 8029 8030 public final void addService(PackageParser.Service s) { 8031 mServices.put(s.getComponentName(), s); 8032 if (DEBUG_SHOW_INFO) { 8033 Log.v(TAG, " " 8034 + (s.info.nonLocalizedLabel != null 8035 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8036 Log.v(TAG, " Class=" + s.info.name); 8037 } 8038 final int NI = s.intents.size(); 8039 int j; 8040 for (j=0; j<NI; j++) { 8041 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8042 if (DEBUG_SHOW_INFO) { 8043 Log.v(TAG, " IntentFilter:"); 8044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8045 } 8046 if (!intent.debugCheck()) { 8047 Log.w(TAG, "==> For Service " + s.info.name); 8048 } 8049 addFilter(intent); 8050 } 8051 } 8052 8053 public final void removeService(PackageParser.Service s) { 8054 mServices.remove(s.getComponentName()); 8055 if (DEBUG_SHOW_INFO) { 8056 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8057 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8058 Log.v(TAG, " Class=" + s.info.name); 8059 } 8060 final int NI = s.intents.size(); 8061 int j; 8062 for (j=0; j<NI; j++) { 8063 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8064 if (DEBUG_SHOW_INFO) { 8065 Log.v(TAG, " IntentFilter:"); 8066 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8067 } 8068 removeFilter(intent); 8069 } 8070 } 8071 8072 @Override 8073 protected boolean allowFilterResult( 8074 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8075 ServiceInfo filterSi = filter.service.info; 8076 for (int i=dest.size()-1; i>=0; i--) { 8077 ServiceInfo destAi = dest.get(i).serviceInfo; 8078 if (destAi.name == filterSi.name 8079 && destAi.packageName == filterSi.packageName) { 8080 return false; 8081 } 8082 } 8083 return true; 8084 } 8085 8086 @Override 8087 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8088 return new PackageParser.ServiceIntentInfo[size]; 8089 } 8090 8091 @Override 8092 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8093 if (!sUserManager.exists(userId)) return true; 8094 PackageParser.Package p = filter.service.owner; 8095 if (p != null) { 8096 PackageSetting ps = (PackageSetting)p.mExtras; 8097 if (ps != null) { 8098 // System apps are never considered stopped for purposes of 8099 // filtering, because there may be no way for the user to 8100 // actually re-launch them. 8101 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8102 && ps.getStopped(userId); 8103 } 8104 } 8105 return false; 8106 } 8107 8108 @Override 8109 protected boolean isPackageForFilter(String packageName, 8110 PackageParser.ServiceIntentInfo info) { 8111 return packageName.equals(info.service.owner.packageName); 8112 } 8113 8114 @Override 8115 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8116 int match, int userId) { 8117 if (!sUserManager.exists(userId)) return null; 8118 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8119 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8120 return null; 8121 } 8122 final PackageParser.Service service = info.service; 8123 if (mSafeMode && (service.info.applicationInfo.flags 8124 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8125 return null; 8126 } 8127 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8128 if (ps == null) { 8129 return null; 8130 } 8131 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8132 ps.readUserState(userId), userId); 8133 if (si == null) { 8134 return null; 8135 } 8136 final ResolveInfo res = new ResolveInfo(); 8137 res.serviceInfo = si; 8138 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8139 res.filter = filter; 8140 } 8141 res.priority = info.getPriority(); 8142 res.preferredOrder = service.owner.mPreferredOrder; 8143 res.match = match; 8144 res.isDefault = info.hasDefault; 8145 res.labelRes = info.labelRes; 8146 res.nonLocalizedLabel = info.nonLocalizedLabel; 8147 res.icon = info.icon; 8148 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8149 return res; 8150 } 8151 8152 @Override 8153 protected void sortResults(List<ResolveInfo> results) { 8154 Collections.sort(results, mResolvePrioritySorter); 8155 } 8156 8157 @Override 8158 protected void dumpFilter(PrintWriter out, String prefix, 8159 PackageParser.ServiceIntentInfo filter) { 8160 out.print(prefix); out.print( 8161 Integer.toHexString(System.identityHashCode(filter.service))); 8162 out.print(' '); 8163 filter.service.printComponentShortName(out); 8164 out.print(" filter "); 8165 out.println(Integer.toHexString(System.identityHashCode(filter))); 8166 } 8167 8168 @Override 8169 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8170 return filter.service; 8171 } 8172 8173 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8174 PackageParser.Service service = (PackageParser.Service)label; 8175 out.print(prefix); out.print( 8176 Integer.toHexString(System.identityHashCode(service))); 8177 out.print(' '); 8178 service.printComponentShortName(out); 8179 if (count > 1) { 8180 out.print(" ("); out.print(count); out.print(" filters)"); 8181 } 8182 out.println(); 8183 } 8184 8185// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8186// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8187// final List<ResolveInfo> retList = Lists.newArrayList(); 8188// while (i.hasNext()) { 8189// final ResolveInfo resolveInfo = (ResolveInfo) i; 8190// if (isEnabledLP(resolveInfo.serviceInfo)) { 8191// retList.add(resolveInfo); 8192// } 8193// } 8194// return retList; 8195// } 8196 8197 // Keys are String (activity class name), values are Activity. 8198 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8199 = new ArrayMap<ComponentName, PackageParser.Service>(); 8200 private int mFlags; 8201 }; 8202 8203 private final class ProviderIntentResolver 8204 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8205 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8206 boolean defaultOnly, int userId) { 8207 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8208 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8209 } 8210 8211 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8212 int userId) { 8213 if (!sUserManager.exists(userId)) 8214 return null; 8215 mFlags = flags; 8216 return super.queryIntent(intent, resolvedType, 8217 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8218 } 8219 8220 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8221 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8222 if (!sUserManager.exists(userId)) 8223 return null; 8224 if (packageProviders == null) { 8225 return null; 8226 } 8227 mFlags = flags; 8228 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8229 final int N = packageProviders.size(); 8230 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8231 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8232 8233 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8234 for (int i = 0; i < N; ++i) { 8235 intentFilters = packageProviders.get(i).intents; 8236 if (intentFilters != null && intentFilters.size() > 0) { 8237 PackageParser.ProviderIntentInfo[] array = 8238 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8239 intentFilters.toArray(array); 8240 listCut.add(array); 8241 } 8242 } 8243 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8244 } 8245 8246 public final void addProvider(PackageParser.Provider p) { 8247 if (mProviders.containsKey(p.getComponentName())) { 8248 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8249 return; 8250 } 8251 8252 mProviders.put(p.getComponentName(), p); 8253 if (DEBUG_SHOW_INFO) { 8254 Log.v(TAG, " " 8255 + (p.info.nonLocalizedLabel != null 8256 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8257 Log.v(TAG, " Class=" + p.info.name); 8258 } 8259 final int NI = p.intents.size(); 8260 int j; 8261 for (j = 0; j < NI; j++) { 8262 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8263 if (DEBUG_SHOW_INFO) { 8264 Log.v(TAG, " IntentFilter:"); 8265 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8266 } 8267 if (!intent.debugCheck()) { 8268 Log.w(TAG, "==> For Provider " + p.info.name); 8269 } 8270 addFilter(intent); 8271 } 8272 } 8273 8274 public final void removeProvider(PackageParser.Provider p) { 8275 mProviders.remove(p.getComponentName()); 8276 if (DEBUG_SHOW_INFO) { 8277 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8278 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8279 Log.v(TAG, " Class=" + p.info.name); 8280 } 8281 final int NI = p.intents.size(); 8282 int j; 8283 for (j = 0; j < NI; j++) { 8284 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8285 if (DEBUG_SHOW_INFO) { 8286 Log.v(TAG, " IntentFilter:"); 8287 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8288 } 8289 removeFilter(intent); 8290 } 8291 } 8292 8293 @Override 8294 protected boolean allowFilterResult( 8295 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8296 ProviderInfo filterPi = filter.provider.info; 8297 for (int i = dest.size() - 1; i >= 0; i--) { 8298 ProviderInfo destPi = dest.get(i).providerInfo; 8299 if (destPi.name == filterPi.name 8300 && destPi.packageName == filterPi.packageName) { 8301 return false; 8302 } 8303 } 8304 return true; 8305 } 8306 8307 @Override 8308 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8309 return new PackageParser.ProviderIntentInfo[size]; 8310 } 8311 8312 @Override 8313 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8314 if (!sUserManager.exists(userId)) 8315 return true; 8316 PackageParser.Package p = filter.provider.owner; 8317 if (p != null) { 8318 PackageSetting ps = (PackageSetting) p.mExtras; 8319 if (ps != null) { 8320 // System apps are never considered stopped for purposes of 8321 // filtering, because there may be no way for the user to 8322 // actually re-launch them. 8323 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8324 && ps.getStopped(userId); 8325 } 8326 } 8327 return false; 8328 } 8329 8330 @Override 8331 protected boolean isPackageForFilter(String packageName, 8332 PackageParser.ProviderIntentInfo info) { 8333 return packageName.equals(info.provider.owner.packageName); 8334 } 8335 8336 @Override 8337 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8338 int match, int userId) { 8339 if (!sUserManager.exists(userId)) 8340 return null; 8341 final PackageParser.ProviderIntentInfo info = filter; 8342 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8343 return null; 8344 } 8345 final PackageParser.Provider provider = info.provider; 8346 if (mSafeMode && (provider.info.applicationInfo.flags 8347 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8348 return null; 8349 } 8350 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8351 if (ps == null) { 8352 return null; 8353 } 8354 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8355 ps.readUserState(userId), userId); 8356 if (pi == null) { 8357 return null; 8358 } 8359 final ResolveInfo res = new ResolveInfo(); 8360 res.providerInfo = pi; 8361 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8362 res.filter = filter; 8363 } 8364 res.priority = info.getPriority(); 8365 res.preferredOrder = provider.owner.mPreferredOrder; 8366 res.match = match; 8367 res.isDefault = info.hasDefault; 8368 res.labelRes = info.labelRes; 8369 res.nonLocalizedLabel = info.nonLocalizedLabel; 8370 res.icon = info.icon; 8371 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8372 return res; 8373 } 8374 8375 @Override 8376 protected void sortResults(List<ResolveInfo> results) { 8377 Collections.sort(results, mResolvePrioritySorter); 8378 } 8379 8380 @Override 8381 protected void dumpFilter(PrintWriter out, String prefix, 8382 PackageParser.ProviderIntentInfo filter) { 8383 out.print(prefix); 8384 out.print( 8385 Integer.toHexString(System.identityHashCode(filter.provider))); 8386 out.print(' '); 8387 filter.provider.printComponentShortName(out); 8388 out.print(" filter "); 8389 out.println(Integer.toHexString(System.identityHashCode(filter))); 8390 } 8391 8392 @Override 8393 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8394 return filter.provider; 8395 } 8396 8397 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8398 PackageParser.Provider provider = (PackageParser.Provider)label; 8399 out.print(prefix); out.print( 8400 Integer.toHexString(System.identityHashCode(provider))); 8401 out.print(' '); 8402 provider.printComponentShortName(out); 8403 if (count > 1) { 8404 out.print(" ("); out.print(count); out.print(" filters)"); 8405 } 8406 out.println(); 8407 } 8408 8409 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8410 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8411 private int mFlags; 8412 }; 8413 8414 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8415 new Comparator<ResolveInfo>() { 8416 public int compare(ResolveInfo r1, ResolveInfo r2) { 8417 int v1 = r1.priority; 8418 int v2 = r2.priority; 8419 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8420 if (v1 != v2) { 8421 return (v1 > v2) ? -1 : 1; 8422 } 8423 v1 = r1.preferredOrder; 8424 v2 = r2.preferredOrder; 8425 if (v1 != v2) { 8426 return (v1 > v2) ? -1 : 1; 8427 } 8428 if (r1.isDefault != r2.isDefault) { 8429 return r1.isDefault ? -1 : 1; 8430 } 8431 v1 = r1.match; 8432 v2 = r2.match; 8433 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8434 if (v1 != v2) { 8435 return (v1 > v2) ? -1 : 1; 8436 } 8437 if (r1.system != r2.system) { 8438 return r1.system ? -1 : 1; 8439 } 8440 return 0; 8441 } 8442 }; 8443 8444 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8445 new Comparator<ProviderInfo>() { 8446 public int compare(ProviderInfo p1, ProviderInfo p2) { 8447 final int v1 = p1.initOrder; 8448 final int v2 = p2.initOrder; 8449 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8450 } 8451 }; 8452 8453 static final void sendPackageBroadcast(String action, String pkg, 8454 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8455 int[] userIds) { 8456 IActivityManager am = ActivityManagerNative.getDefault(); 8457 if (am != null) { 8458 try { 8459 if (userIds == null) { 8460 userIds = am.getRunningUserIds(); 8461 } 8462 for (int id : userIds) { 8463 final Intent intent = new Intent(action, 8464 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8465 if (extras != null) { 8466 intent.putExtras(extras); 8467 } 8468 if (targetPkg != null) { 8469 intent.setPackage(targetPkg); 8470 } 8471 // Modify the UID when posting to other users 8472 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8473 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8474 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8475 intent.putExtra(Intent.EXTRA_UID, uid); 8476 } 8477 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8478 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8479 if (DEBUG_BROADCASTS) { 8480 RuntimeException here = new RuntimeException("here"); 8481 here.fillInStackTrace(); 8482 Slog.d(TAG, "Sending to user " + id + ": " 8483 + intent.toShortString(false, true, false, false) 8484 + " " + intent.getExtras(), here); 8485 } 8486 am.broadcastIntent(null, intent, null, finishedReceiver, 8487 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8488 finishedReceiver != null, false, id); 8489 } 8490 } catch (RemoteException ex) { 8491 } 8492 } 8493 } 8494 8495 /** 8496 * Check if the external storage media is available. This is true if there 8497 * is a mounted external storage medium or if the external storage is 8498 * emulated. 8499 */ 8500 private boolean isExternalMediaAvailable() { 8501 return mMediaMounted || Environment.isExternalStorageEmulated(); 8502 } 8503 8504 @Override 8505 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8506 // writer 8507 synchronized (mPackages) { 8508 if (!isExternalMediaAvailable()) { 8509 // If the external storage is no longer mounted at this point, 8510 // the caller may not have been able to delete all of this 8511 // packages files and can not delete any more. Bail. 8512 return null; 8513 } 8514 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8515 if (lastPackage != null) { 8516 pkgs.remove(lastPackage); 8517 } 8518 if (pkgs.size() > 0) { 8519 return pkgs.get(0); 8520 } 8521 } 8522 return null; 8523 } 8524 8525 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8526 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8527 userId, andCode ? 1 : 0, packageName); 8528 if (mSystemReady) { 8529 msg.sendToTarget(); 8530 } else { 8531 if (mPostSystemReadyMessages == null) { 8532 mPostSystemReadyMessages = new ArrayList<>(); 8533 } 8534 mPostSystemReadyMessages.add(msg); 8535 } 8536 } 8537 8538 void startCleaningPackages() { 8539 // reader 8540 synchronized (mPackages) { 8541 if (!isExternalMediaAvailable()) { 8542 return; 8543 } 8544 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8545 return; 8546 } 8547 } 8548 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8549 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8550 IActivityManager am = ActivityManagerNative.getDefault(); 8551 if (am != null) { 8552 try { 8553 am.startService(null, intent, null, UserHandle.USER_OWNER); 8554 } catch (RemoteException e) { 8555 } 8556 } 8557 } 8558 8559 @Override 8560 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8561 int installFlags, String installerPackageName, VerificationParams verificationParams, 8562 String packageAbiOverride) { 8563 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8564 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8565 } 8566 8567 @Override 8568 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8569 int installFlags, String installerPackageName, VerificationParams verificationParams, 8570 String packageAbiOverride, int userId) { 8571 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8572 8573 final int callingUid = Binder.getCallingUid(); 8574 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8575 8576 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8577 try { 8578 if (observer != null) { 8579 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8580 } 8581 } catch (RemoteException re) { 8582 } 8583 return; 8584 } 8585 8586 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8587 installFlags |= PackageManager.INSTALL_FROM_ADB; 8588 8589 } else { 8590 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8591 // about installerPackageName. 8592 8593 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8594 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8595 } 8596 8597 UserHandle user; 8598 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8599 user = UserHandle.ALL; 8600 } else { 8601 user = new UserHandle(userId); 8602 } 8603 8604 verificationParams.setInstallerUid(callingUid); 8605 8606 final File originFile = new File(originPath); 8607 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8608 8609 final Message msg = mHandler.obtainMessage(INIT_COPY); 8610 msg.obj = new InstallParams(origin, observer, installFlags, 8611 installerPackageName, null, verificationParams, user, packageAbiOverride); 8612 mHandler.sendMessage(msg); 8613 } 8614 8615 void installStage(String packageName, File stagedDir, String stagedCid, 8616 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8617 String installerPackageName, int installerUid, UserHandle user) { 8618 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8619 params.referrerUri, installerUid, null); 8620 8621 final OriginInfo origin; 8622 if (stagedDir != null) { 8623 origin = OriginInfo.fromStagedFile(stagedDir); 8624 } else { 8625 origin = OriginInfo.fromStagedContainer(stagedCid); 8626 } 8627 8628 final Message msg = mHandler.obtainMessage(INIT_COPY); 8629 msg.obj = new InstallParams(origin, observer, params.installFlags, 8630 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8631 mHandler.sendMessage(msg); 8632 } 8633 8634 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8635 Bundle extras = new Bundle(1); 8636 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8637 8638 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8639 packageName, extras, null, null, new int[] {userId}); 8640 try { 8641 IActivityManager am = ActivityManagerNative.getDefault(); 8642 final boolean isSystem = 8643 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8644 if (isSystem && am.isUserRunning(userId, false)) { 8645 // The just-installed/enabled app is bundled on the system, so presumed 8646 // to be able to run automatically without needing an explicit launch. 8647 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8648 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8649 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8650 .setPackage(packageName); 8651 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8652 android.app.AppOpsManager.OP_NONE, false, false, userId); 8653 } 8654 } catch (RemoteException e) { 8655 // shouldn't happen 8656 Slog.w(TAG, "Unable to bootstrap installed package", e); 8657 } 8658 } 8659 8660 @Override 8661 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8662 int userId) { 8663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8664 PackageSetting pkgSetting; 8665 final int uid = Binder.getCallingUid(); 8666 enforceCrossUserPermission(uid, userId, true, true, 8667 "setApplicationHiddenSetting for user " + userId); 8668 8669 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8670 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8671 return false; 8672 } 8673 8674 long callingId = Binder.clearCallingIdentity(); 8675 try { 8676 boolean sendAdded = false; 8677 boolean sendRemoved = false; 8678 // writer 8679 synchronized (mPackages) { 8680 pkgSetting = mSettings.mPackages.get(packageName); 8681 if (pkgSetting == null) { 8682 return false; 8683 } 8684 if (pkgSetting.getHidden(userId) != hidden) { 8685 pkgSetting.setHidden(hidden, userId); 8686 mSettings.writePackageRestrictionsLPr(userId); 8687 if (hidden) { 8688 sendRemoved = true; 8689 } else { 8690 sendAdded = true; 8691 } 8692 } 8693 } 8694 if (sendAdded) { 8695 sendPackageAddedForUser(packageName, pkgSetting, userId); 8696 return true; 8697 } 8698 if (sendRemoved) { 8699 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8700 "hiding pkg"); 8701 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8702 } 8703 } finally { 8704 Binder.restoreCallingIdentity(callingId); 8705 } 8706 return false; 8707 } 8708 8709 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8710 int userId) { 8711 final PackageRemovedInfo info = new PackageRemovedInfo(); 8712 info.removedPackage = packageName; 8713 info.removedUsers = new int[] {userId}; 8714 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8715 info.sendBroadcast(false, false, false); 8716 } 8717 8718 /** 8719 * Returns true if application is not found or there was an error. Otherwise it returns 8720 * the hidden state of the package for the given user. 8721 */ 8722 @Override 8723 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8725 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8726 false, "getApplicationHidden for user " + userId); 8727 PackageSetting pkgSetting; 8728 long callingId = Binder.clearCallingIdentity(); 8729 try { 8730 // writer 8731 synchronized (mPackages) { 8732 pkgSetting = mSettings.mPackages.get(packageName); 8733 if (pkgSetting == null) { 8734 return true; 8735 } 8736 return pkgSetting.getHidden(userId); 8737 } 8738 } finally { 8739 Binder.restoreCallingIdentity(callingId); 8740 } 8741 } 8742 8743 /** 8744 * @hide 8745 */ 8746 @Override 8747 public int installExistingPackageAsUser(String packageName, int userId) { 8748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8749 null); 8750 PackageSetting pkgSetting; 8751 final int uid = Binder.getCallingUid(); 8752 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8753 + userId); 8754 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8755 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8756 } 8757 8758 long callingId = Binder.clearCallingIdentity(); 8759 try { 8760 boolean sendAdded = false; 8761 Bundle extras = new Bundle(1); 8762 8763 // writer 8764 synchronized (mPackages) { 8765 pkgSetting = mSettings.mPackages.get(packageName); 8766 if (pkgSetting == null) { 8767 return PackageManager.INSTALL_FAILED_INVALID_URI; 8768 } 8769 if (!pkgSetting.getInstalled(userId)) { 8770 pkgSetting.setInstalled(true, userId); 8771 pkgSetting.setHidden(false, userId); 8772 mSettings.writePackageRestrictionsLPr(userId); 8773 sendAdded = true; 8774 } 8775 } 8776 8777 if (sendAdded) { 8778 sendPackageAddedForUser(packageName, pkgSetting, userId); 8779 } 8780 } finally { 8781 Binder.restoreCallingIdentity(callingId); 8782 } 8783 8784 return PackageManager.INSTALL_SUCCEEDED; 8785 } 8786 8787 boolean isUserRestricted(int userId, String restrictionKey) { 8788 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8789 if (restrictions.getBoolean(restrictionKey, false)) { 8790 Log.w(TAG, "User is restricted: " + restrictionKey); 8791 return true; 8792 } 8793 return false; 8794 } 8795 8796 @Override 8797 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8798 mContext.enforceCallingOrSelfPermission( 8799 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8800 "Only package verification agents can verify applications"); 8801 8802 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8803 final PackageVerificationResponse response = new PackageVerificationResponse( 8804 verificationCode, Binder.getCallingUid()); 8805 msg.arg1 = id; 8806 msg.obj = response; 8807 mHandler.sendMessage(msg); 8808 } 8809 8810 @Override 8811 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8812 long millisecondsToDelay) { 8813 mContext.enforceCallingOrSelfPermission( 8814 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8815 "Only package verification agents can extend verification timeouts"); 8816 8817 final PackageVerificationState state = mPendingVerification.get(id); 8818 final PackageVerificationResponse response = new PackageVerificationResponse( 8819 verificationCodeAtTimeout, Binder.getCallingUid()); 8820 8821 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8822 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8823 } 8824 if (millisecondsToDelay < 0) { 8825 millisecondsToDelay = 0; 8826 } 8827 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8828 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8829 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8830 } 8831 8832 if ((state != null) && !state.timeoutExtended()) { 8833 state.extendTimeout(); 8834 8835 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8836 msg.arg1 = id; 8837 msg.obj = response; 8838 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8839 } 8840 } 8841 8842 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8843 int verificationCode, UserHandle user) { 8844 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8845 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8846 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8847 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8848 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8849 8850 mContext.sendBroadcastAsUser(intent, user, 8851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8852 } 8853 8854 private ComponentName matchComponentForVerifier(String packageName, 8855 List<ResolveInfo> receivers) { 8856 ActivityInfo targetReceiver = null; 8857 8858 final int NR = receivers.size(); 8859 for (int i = 0; i < NR; i++) { 8860 final ResolveInfo info = receivers.get(i); 8861 if (info.activityInfo == null) { 8862 continue; 8863 } 8864 8865 if (packageName.equals(info.activityInfo.packageName)) { 8866 targetReceiver = info.activityInfo; 8867 break; 8868 } 8869 } 8870 8871 if (targetReceiver == null) { 8872 return null; 8873 } 8874 8875 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8876 } 8877 8878 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8879 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8880 if (pkgInfo.verifiers.length == 0) { 8881 return null; 8882 } 8883 8884 final int N = pkgInfo.verifiers.length; 8885 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8886 for (int i = 0; i < N; i++) { 8887 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8888 8889 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8890 receivers); 8891 if (comp == null) { 8892 continue; 8893 } 8894 8895 final int verifierUid = getUidForVerifier(verifierInfo); 8896 if (verifierUid == -1) { 8897 continue; 8898 } 8899 8900 if (DEBUG_VERIFY) { 8901 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8902 + " with the correct signature"); 8903 } 8904 sufficientVerifiers.add(comp); 8905 verificationState.addSufficientVerifier(verifierUid); 8906 } 8907 8908 return sufficientVerifiers; 8909 } 8910 8911 private int getUidForVerifier(VerifierInfo verifierInfo) { 8912 synchronized (mPackages) { 8913 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8914 if (pkg == null) { 8915 return -1; 8916 } else if (pkg.mSignatures.length != 1) { 8917 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8918 + " has more than one signature; ignoring"); 8919 return -1; 8920 } 8921 8922 /* 8923 * If the public key of the package's signature does not match 8924 * our expected public key, then this is a different package and 8925 * we should skip. 8926 */ 8927 8928 final byte[] expectedPublicKey; 8929 try { 8930 final Signature verifierSig = pkg.mSignatures[0]; 8931 final PublicKey publicKey = verifierSig.getPublicKey(); 8932 expectedPublicKey = publicKey.getEncoded(); 8933 } catch (CertificateException e) { 8934 return -1; 8935 } 8936 8937 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8938 8939 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8940 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8941 + " does not have the expected public key; ignoring"); 8942 return -1; 8943 } 8944 8945 return pkg.applicationInfo.uid; 8946 } 8947 } 8948 8949 @Override 8950 public void finishPackageInstall(int token) { 8951 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8952 8953 if (DEBUG_INSTALL) { 8954 Slog.v(TAG, "BM finishing package install for " + token); 8955 } 8956 8957 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8958 mHandler.sendMessage(msg); 8959 } 8960 8961 /** 8962 * Get the verification agent timeout. 8963 * 8964 * @return verification timeout in milliseconds 8965 */ 8966 private long getVerificationTimeout() { 8967 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8968 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8969 DEFAULT_VERIFICATION_TIMEOUT); 8970 } 8971 8972 /** 8973 * Get the default verification agent response code. 8974 * 8975 * @return default verification response code 8976 */ 8977 private int getDefaultVerificationResponse() { 8978 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8979 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8980 DEFAULT_VERIFICATION_RESPONSE); 8981 } 8982 8983 /** 8984 * Check whether or not package verification has been enabled. 8985 * 8986 * @return true if verification should be performed 8987 */ 8988 private boolean isVerificationEnabled(int userId, int installFlags) { 8989 if (!DEFAULT_VERIFY_ENABLE) { 8990 return false; 8991 } 8992 8993 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8994 8995 // Check if installing from ADB 8996 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8997 // Do not run verification in a test harness environment 8998 if (ActivityManager.isRunningInTestHarness()) { 8999 return false; 9000 } 9001 if (ensureVerifyAppsEnabled) { 9002 return true; 9003 } 9004 // Check if the developer does not want package verification for ADB installs 9005 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9006 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9007 return false; 9008 } 9009 } 9010 9011 if (ensureVerifyAppsEnabled) { 9012 return true; 9013 } 9014 9015 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9016 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9017 } 9018 9019 @Override 9020 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9021 throws RemoteException { 9022 mContext.enforceCallingOrSelfPermission( 9023 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9024 "Only intentfilter verification agents can verify applications"); 9025 9026 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9027 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9028 Binder.getCallingUid(), verificationCode, failedDomains); 9029 msg.arg1 = id; 9030 msg.obj = response; 9031 mHandler.sendMessage(msg); 9032 } 9033 9034 @Override 9035 public int getIntentVerificationStatus(String packageName, int userId) { 9036 synchronized (mPackages) { 9037 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9038 } 9039 } 9040 9041 @Override 9042 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9043 boolean result = false; 9044 synchronized (mPackages) { 9045 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9046 } 9047 scheduleWritePackageRestrictionsLocked(userId); 9048 return result; 9049 } 9050 9051 @Override 9052 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9053 synchronized (mPackages) { 9054 return mSettings.getIntentFilterVerificationsLPr(packageName); 9055 } 9056 } 9057 9058 @Override 9059 public List<IntentFilter> getAllIntentFilters(String packageName) { 9060 if (TextUtils.isEmpty(packageName)) { 9061 return Collections.<IntentFilter>emptyList(); 9062 } 9063 synchronized (mPackages) { 9064 PackageParser.Package pkg = mPackages.get(packageName); 9065 if (pkg == null || pkg.activities == null) { 9066 return Collections.<IntentFilter>emptyList(); 9067 } 9068 final int count = pkg.activities.size(); 9069 ArrayList<IntentFilter> result = new ArrayList<>(); 9070 for (int n=0; n<count; n++) { 9071 PackageParser.Activity activity = pkg.activities.get(n); 9072 if (activity.intents != null || activity.intents.size() > 0) { 9073 result.addAll(activity.intents); 9074 } 9075 } 9076 return result; 9077 } 9078 } 9079 9080 /** 9081 * Get the "allow unknown sources" setting. 9082 * 9083 * @return the current "allow unknown sources" setting 9084 */ 9085 private int getUnknownSourcesSettings() { 9086 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9087 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9088 -1); 9089 } 9090 9091 @Override 9092 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9093 final int uid = Binder.getCallingUid(); 9094 // writer 9095 synchronized (mPackages) { 9096 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9097 if (targetPackageSetting == null) { 9098 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9099 } 9100 9101 PackageSetting installerPackageSetting; 9102 if (installerPackageName != null) { 9103 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9104 if (installerPackageSetting == null) { 9105 throw new IllegalArgumentException("Unknown installer package: " 9106 + installerPackageName); 9107 } 9108 } else { 9109 installerPackageSetting = null; 9110 } 9111 9112 Signature[] callerSignature; 9113 Object obj = mSettings.getUserIdLPr(uid); 9114 if (obj != null) { 9115 if (obj instanceof SharedUserSetting) { 9116 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9117 } else if (obj instanceof PackageSetting) { 9118 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9119 } else { 9120 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9121 } 9122 } else { 9123 throw new SecurityException("Unknown calling uid " + uid); 9124 } 9125 9126 // Verify: can't set installerPackageName to a package that is 9127 // not signed with the same cert as the caller. 9128 if (installerPackageSetting != null) { 9129 if (compareSignatures(callerSignature, 9130 installerPackageSetting.signatures.mSignatures) 9131 != PackageManager.SIGNATURE_MATCH) { 9132 throw new SecurityException( 9133 "Caller does not have same cert as new installer package " 9134 + installerPackageName); 9135 } 9136 } 9137 9138 // Verify: if target already has an installer package, it must 9139 // be signed with the same cert as the caller. 9140 if (targetPackageSetting.installerPackageName != null) { 9141 PackageSetting setting = mSettings.mPackages.get( 9142 targetPackageSetting.installerPackageName); 9143 // If the currently set package isn't valid, then it's always 9144 // okay to change it. 9145 if (setting != null) { 9146 if (compareSignatures(callerSignature, 9147 setting.signatures.mSignatures) 9148 != PackageManager.SIGNATURE_MATCH) { 9149 throw new SecurityException( 9150 "Caller does not have same cert as old installer package " 9151 + targetPackageSetting.installerPackageName); 9152 } 9153 } 9154 } 9155 9156 // Okay! 9157 targetPackageSetting.installerPackageName = installerPackageName; 9158 scheduleWriteSettingsLocked(); 9159 } 9160 } 9161 9162 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9163 // Queue up an async operation since the package installation may take a little while. 9164 mHandler.post(new Runnable() { 9165 public void run() { 9166 mHandler.removeCallbacks(this); 9167 // Result object to be returned 9168 PackageInstalledInfo res = new PackageInstalledInfo(); 9169 res.returnCode = currentStatus; 9170 res.uid = -1; 9171 res.pkg = null; 9172 res.removedInfo = new PackageRemovedInfo(); 9173 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9174 args.doPreInstall(res.returnCode); 9175 synchronized (mInstallLock) { 9176 installPackageLI(args, res); 9177 } 9178 args.doPostInstall(res.returnCode, res.uid); 9179 } 9180 9181 // A restore should be performed at this point if (a) the install 9182 // succeeded, (b) the operation is not an update, and (c) the new 9183 // package has not opted out of backup participation. 9184 final boolean update = res.removedInfo.removedPackage != null; 9185 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9186 boolean doRestore = !update 9187 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9188 9189 // Set up the post-install work request bookkeeping. This will be used 9190 // and cleaned up by the post-install event handling regardless of whether 9191 // there's a restore pass performed. Token values are >= 1. 9192 int token; 9193 if (mNextInstallToken < 0) mNextInstallToken = 1; 9194 token = mNextInstallToken++; 9195 9196 PostInstallData data = new PostInstallData(args, res); 9197 mRunningInstalls.put(token, data); 9198 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9199 9200 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9201 // Pass responsibility to the Backup Manager. It will perform a 9202 // restore if appropriate, then pass responsibility back to the 9203 // Package Manager to run the post-install observer callbacks 9204 // and broadcasts. 9205 IBackupManager bm = IBackupManager.Stub.asInterface( 9206 ServiceManager.getService(Context.BACKUP_SERVICE)); 9207 if (bm != null) { 9208 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9209 + " to BM for possible restore"); 9210 try { 9211 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9212 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9213 } else { 9214 doRestore = false; 9215 } 9216 } catch (RemoteException e) { 9217 // can't happen; the backup manager is local 9218 } catch (Exception e) { 9219 Slog.e(TAG, "Exception trying to enqueue restore", e); 9220 doRestore = false; 9221 } 9222 } else { 9223 Slog.e(TAG, "Backup Manager not found!"); 9224 doRestore = false; 9225 } 9226 } 9227 9228 if (!doRestore) { 9229 // No restore possible, or the Backup Manager was mysteriously not 9230 // available -- just fire the post-install work request directly. 9231 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9232 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9233 mHandler.sendMessage(msg); 9234 } 9235 } 9236 }); 9237 } 9238 9239 private abstract class HandlerParams { 9240 private static final int MAX_RETRIES = 4; 9241 9242 /** 9243 * Number of times startCopy() has been attempted and had a non-fatal 9244 * error. 9245 */ 9246 private int mRetries = 0; 9247 9248 /** User handle for the user requesting the information or installation. */ 9249 private final UserHandle mUser; 9250 9251 HandlerParams(UserHandle user) { 9252 mUser = user; 9253 } 9254 9255 UserHandle getUser() { 9256 return mUser; 9257 } 9258 9259 final boolean startCopy() { 9260 boolean res; 9261 try { 9262 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9263 9264 if (++mRetries > MAX_RETRIES) { 9265 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9266 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9267 handleServiceError(); 9268 return false; 9269 } else { 9270 handleStartCopy(); 9271 res = true; 9272 } 9273 } catch (RemoteException e) { 9274 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9275 mHandler.sendEmptyMessage(MCS_RECONNECT); 9276 res = false; 9277 } 9278 handleReturnCode(); 9279 return res; 9280 } 9281 9282 final void serviceError() { 9283 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9284 handleServiceError(); 9285 handleReturnCode(); 9286 } 9287 9288 abstract void handleStartCopy() throws RemoteException; 9289 abstract void handleServiceError(); 9290 abstract void handleReturnCode(); 9291 } 9292 9293 class MeasureParams extends HandlerParams { 9294 private final PackageStats mStats; 9295 private boolean mSuccess; 9296 9297 private final IPackageStatsObserver mObserver; 9298 9299 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9300 super(new UserHandle(stats.userHandle)); 9301 mObserver = observer; 9302 mStats = stats; 9303 } 9304 9305 @Override 9306 public String toString() { 9307 return "MeasureParams{" 9308 + Integer.toHexString(System.identityHashCode(this)) 9309 + " " + mStats.packageName + "}"; 9310 } 9311 9312 @Override 9313 void handleStartCopy() throws RemoteException { 9314 synchronized (mInstallLock) { 9315 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9316 } 9317 9318 if (mSuccess) { 9319 final boolean mounted; 9320 if (Environment.isExternalStorageEmulated()) { 9321 mounted = true; 9322 } else { 9323 final String status = Environment.getExternalStorageState(); 9324 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9325 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9326 } 9327 9328 if (mounted) { 9329 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9330 9331 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9332 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9333 9334 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9335 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9336 9337 // Always subtract cache size, since it's a subdirectory 9338 mStats.externalDataSize -= mStats.externalCacheSize; 9339 9340 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9341 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9342 9343 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9344 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9345 } 9346 } 9347 } 9348 9349 @Override 9350 void handleReturnCode() { 9351 if (mObserver != null) { 9352 try { 9353 mObserver.onGetStatsCompleted(mStats, mSuccess); 9354 } catch (RemoteException e) { 9355 Slog.i(TAG, "Observer no longer exists."); 9356 } 9357 } 9358 } 9359 9360 @Override 9361 void handleServiceError() { 9362 Slog.e(TAG, "Could not measure application " + mStats.packageName 9363 + " external storage"); 9364 } 9365 } 9366 9367 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9368 throws RemoteException { 9369 long result = 0; 9370 for (File path : paths) { 9371 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9372 } 9373 return result; 9374 } 9375 9376 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9377 for (File path : paths) { 9378 try { 9379 mcs.clearDirectory(path.getAbsolutePath()); 9380 } catch (RemoteException e) { 9381 } 9382 } 9383 } 9384 9385 static class OriginInfo { 9386 /** 9387 * Location where install is coming from, before it has been 9388 * copied/renamed into place. This could be a single monolithic APK 9389 * file, or a cluster directory. This location may be untrusted. 9390 */ 9391 final File file; 9392 final String cid; 9393 9394 /** 9395 * Flag indicating that {@link #file} or {@link #cid} has already been 9396 * staged, meaning downstream users don't need to defensively copy the 9397 * contents. 9398 */ 9399 final boolean staged; 9400 9401 /** 9402 * Flag indicating that {@link #file} or {@link #cid} is an already 9403 * installed app that is being moved. 9404 */ 9405 final boolean existing; 9406 9407 final String resolvedPath; 9408 final File resolvedFile; 9409 9410 static OriginInfo fromNothing() { 9411 return new OriginInfo(null, null, false, false); 9412 } 9413 9414 static OriginInfo fromUntrustedFile(File file) { 9415 return new OriginInfo(file, null, false, false); 9416 } 9417 9418 static OriginInfo fromExistingFile(File file) { 9419 return new OriginInfo(file, null, false, true); 9420 } 9421 9422 static OriginInfo fromStagedFile(File file) { 9423 return new OriginInfo(file, null, true, false); 9424 } 9425 9426 static OriginInfo fromStagedContainer(String cid) { 9427 return new OriginInfo(null, cid, true, false); 9428 } 9429 9430 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9431 this.file = file; 9432 this.cid = cid; 9433 this.staged = staged; 9434 this.existing = existing; 9435 9436 if (cid != null) { 9437 resolvedPath = PackageHelper.getSdDir(cid); 9438 resolvedFile = new File(resolvedPath); 9439 } else if (file != null) { 9440 resolvedPath = file.getAbsolutePath(); 9441 resolvedFile = file; 9442 } else { 9443 resolvedPath = null; 9444 resolvedFile = null; 9445 } 9446 } 9447 } 9448 9449 class InstallParams extends HandlerParams { 9450 final OriginInfo origin; 9451 final IPackageInstallObserver2 observer; 9452 int installFlags; 9453 final String installerPackageName; 9454 final String volumeUuid; 9455 final VerificationParams verificationParams; 9456 private InstallArgs mArgs; 9457 private int mRet; 9458 final String packageAbiOverride; 9459 9460 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9461 String installerPackageName, String volumeUuid, 9462 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9463 super(user); 9464 this.origin = origin; 9465 this.observer = observer; 9466 this.installFlags = installFlags; 9467 this.installerPackageName = installerPackageName; 9468 this.volumeUuid = volumeUuid; 9469 this.verificationParams = verificationParams; 9470 this.packageAbiOverride = packageAbiOverride; 9471 } 9472 9473 @Override 9474 public String toString() { 9475 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9476 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9477 } 9478 9479 public ManifestDigest getManifestDigest() { 9480 if (verificationParams == null) { 9481 return null; 9482 } 9483 return verificationParams.getManifestDigest(); 9484 } 9485 9486 private int installLocationPolicy(PackageInfoLite pkgLite) { 9487 String packageName = pkgLite.packageName; 9488 int installLocation = pkgLite.installLocation; 9489 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9490 // reader 9491 synchronized (mPackages) { 9492 PackageParser.Package pkg = mPackages.get(packageName); 9493 if (pkg != null) { 9494 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9495 // Check for downgrading. 9496 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9497 try { 9498 checkDowngrade(pkg, pkgLite); 9499 } catch (PackageManagerException e) { 9500 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9501 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9502 } 9503 } 9504 // Check for updated system application. 9505 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9506 if (onSd) { 9507 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9508 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9509 } 9510 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9511 } else { 9512 if (onSd) { 9513 // Install flag overrides everything. 9514 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9515 } 9516 // If current upgrade specifies particular preference 9517 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9518 // Application explicitly specified internal. 9519 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9520 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9521 // App explictly prefers external. Let policy decide 9522 } else { 9523 // Prefer previous location 9524 if (isExternal(pkg)) { 9525 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9526 } 9527 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9528 } 9529 } 9530 } else { 9531 // Invalid install. Return error code 9532 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9533 } 9534 } 9535 } 9536 // All the special cases have been taken care of. 9537 // Return result based on recommended install location. 9538 if (onSd) { 9539 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9540 } 9541 return pkgLite.recommendedInstallLocation; 9542 } 9543 9544 /* 9545 * Invoke remote method to get package information and install 9546 * location values. Override install location based on default 9547 * policy if needed and then create install arguments based 9548 * on the install location. 9549 */ 9550 public void handleStartCopy() throws RemoteException { 9551 int ret = PackageManager.INSTALL_SUCCEEDED; 9552 9553 // If we're already staged, we've firmly committed to an install location 9554 if (origin.staged) { 9555 if (origin.file != null) { 9556 installFlags |= PackageManager.INSTALL_INTERNAL; 9557 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9558 } else if (origin.cid != null) { 9559 installFlags |= PackageManager.INSTALL_EXTERNAL; 9560 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9561 } else { 9562 throw new IllegalStateException("Invalid stage location"); 9563 } 9564 } 9565 9566 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9567 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9568 9569 PackageInfoLite pkgLite = null; 9570 9571 if (onInt && onSd) { 9572 // Check if both bits are set. 9573 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9574 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9575 } else { 9576 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9577 packageAbiOverride); 9578 9579 /* 9580 * If we have too little free space, try to free cache 9581 * before giving up. 9582 */ 9583 if (!origin.staged && pkgLite.recommendedInstallLocation 9584 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9585 // TODO: focus freeing disk space on the target device 9586 final StorageManager storage = StorageManager.from(mContext); 9587 final long lowThreshold = storage.getStorageLowBytes( 9588 Environment.getDataDirectory()); 9589 9590 final long sizeBytes = mContainerService.calculateInstalledSize( 9591 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9592 9593 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9594 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9595 installFlags, packageAbiOverride); 9596 } 9597 9598 /* 9599 * The cache free must have deleted the file we 9600 * downloaded to install. 9601 * 9602 * TODO: fix the "freeCache" call to not delete 9603 * the file we care about. 9604 */ 9605 if (pkgLite.recommendedInstallLocation 9606 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9607 pkgLite.recommendedInstallLocation 9608 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9609 } 9610 } 9611 } 9612 9613 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9614 int loc = pkgLite.recommendedInstallLocation; 9615 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9616 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9617 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9618 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9619 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9620 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9621 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9622 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9623 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9624 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9625 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9626 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9627 } else { 9628 // Override with defaults if needed. 9629 loc = installLocationPolicy(pkgLite); 9630 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9631 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9632 } else if (!onSd && !onInt) { 9633 // Override install location with flags 9634 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9635 // Set the flag to install on external media. 9636 installFlags |= PackageManager.INSTALL_EXTERNAL; 9637 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9638 } else { 9639 // Make sure the flag for installing on external 9640 // media is unset 9641 installFlags |= PackageManager.INSTALL_INTERNAL; 9642 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9643 } 9644 } 9645 } 9646 } 9647 9648 final InstallArgs args = createInstallArgs(this); 9649 mArgs = args; 9650 9651 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9652 /* 9653 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9654 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9655 */ 9656 int userIdentifier = getUser().getIdentifier(); 9657 if (userIdentifier == UserHandle.USER_ALL 9658 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9659 userIdentifier = UserHandle.USER_OWNER; 9660 } 9661 9662 /* 9663 * Determine if we have any installed package verifiers. If we 9664 * do, then we'll defer to them to verify the packages. 9665 */ 9666 final int requiredUid = mRequiredVerifierPackage == null ? -1 9667 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9668 if (!origin.existing && requiredUid != -1 9669 && isVerificationEnabled(userIdentifier, installFlags)) { 9670 final Intent verification = new Intent( 9671 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9672 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9673 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9674 PACKAGE_MIME_TYPE); 9675 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9676 9677 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9678 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9679 0 /* TODO: Which userId? */); 9680 9681 if (DEBUG_VERIFY) { 9682 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9683 + verification.toString() + " with " + pkgLite.verifiers.length 9684 + " optional verifiers"); 9685 } 9686 9687 final int verificationId = mPendingVerificationToken++; 9688 9689 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9690 9691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9692 installerPackageName); 9693 9694 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9695 installFlags); 9696 9697 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9698 pkgLite.packageName); 9699 9700 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9701 pkgLite.versionCode); 9702 9703 if (verificationParams != null) { 9704 if (verificationParams.getVerificationURI() != null) { 9705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9706 verificationParams.getVerificationURI()); 9707 } 9708 if (verificationParams.getOriginatingURI() != null) { 9709 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9710 verificationParams.getOriginatingURI()); 9711 } 9712 if (verificationParams.getReferrer() != null) { 9713 verification.putExtra(Intent.EXTRA_REFERRER, 9714 verificationParams.getReferrer()); 9715 } 9716 if (verificationParams.getOriginatingUid() >= 0) { 9717 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9718 verificationParams.getOriginatingUid()); 9719 } 9720 if (verificationParams.getInstallerUid() >= 0) { 9721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9722 verificationParams.getInstallerUid()); 9723 } 9724 } 9725 9726 final PackageVerificationState verificationState = new PackageVerificationState( 9727 requiredUid, args); 9728 9729 mPendingVerification.append(verificationId, verificationState); 9730 9731 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9732 receivers, verificationState); 9733 9734 /* 9735 * If any sufficient verifiers were listed in the package 9736 * manifest, attempt to ask them. 9737 */ 9738 if (sufficientVerifiers != null) { 9739 final int N = sufficientVerifiers.size(); 9740 if (N == 0) { 9741 Slog.i(TAG, "Additional verifiers required, but none installed."); 9742 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9743 } else { 9744 for (int i = 0; i < N; i++) { 9745 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9746 9747 final Intent sufficientIntent = new Intent(verification); 9748 sufficientIntent.setComponent(verifierComponent); 9749 9750 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9751 } 9752 } 9753 } 9754 9755 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9756 mRequiredVerifierPackage, receivers); 9757 if (ret == PackageManager.INSTALL_SUCCEEDED 9758 && mRequiredVerifierPackage != null) { 9759 /* 9760 * Send the intent to the required verification agent, 9761 * but only start the verification timeout after the 9762 * target BroadcastReceivers have run. 9763 */ 9764 verification.setComponent(requiredVerifierComponent); 9765 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9766 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9767 new BroadcastReceiver() { 9768 @Override 9769 public void onReceive(Context context, Intent intent) { 9770 final Message msg = mHandler 9771 .obtainMessage(CHECK_PENDING_VERIFICATION); 9772 msg.arg1 = verificationId; 9773 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9774 } 9775 }, null, 0, null, null); 9776 9777 /* 9778 * We don't want the copy to proceed until verification 9779 * succeeds, so null out this field. 9780 */ 9781 mArgs = null; 9782 } 9783 } else { 9784 /* 9785 * No package verification is enabled, so immediately start 9786 * the remote call to initiate copy using temporary file. 9787 */ 9788 ret = args.copyApk(mContainerService, true); 9789 } 9790 } 9791 9792 mRet = ret; 9793 } 9794 9795 @Override 9796 void handleReturnCode() { 9797 // If mArgs is null, then MCS couldn't be reached. When it 9798 // reconnects, it will try again to install. At that point, this 9799 // will succeed. 9800 if (mArgs != null) { 9801 processPendingInstall(mArgs, mRet); 9802 } 9803 } 9804 9805 @Override 9806 void handleServiceError() { 9807 mArgs = createInstallArgs(this); 9808 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9809 } 9810 9811 public boolean isForwardLocked() { 9812 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9813 } 9814 } 9815 9816 /** 9817 * Used during creation of InstallArgs 9818 * 9819 * @param installFlags package installation flags 9820 * @return true if should be installed on external storage 9821 */ 9822 private static boolean installOnExternalAsec(int installFlags) { 9823 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9824 return false; 9825 } 9826 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9827 return true; 9828 } 9829 return false; 9830 } 9831 9832 /** 9833 * Used during creation of InstallArgs 9834 * 9835 * @param installFlags package installation flags 9836 * @return true if should be installed as forward locked 9837 */ 9838 private static boolean installForwardLocked(int installFlags) { 9839 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9840 } 9841 9842 private InstallArgs createInstallArgs(InstallParams params) { 9843 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9844 return new AsecInstallArgs(params); 9845 } else { 9846 return new FileInstallArgs(params); 9847 } 9848 } 9849 9850 /** 9851 * Create args that describe an existing installed package. Typically used 9852 * when cleaning up old installs, or used as a move source. 9853 */ 9854 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9855 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9856 final boolean isInAsec; 9857 if (installOnExternalAsec(installFlags)) { 9858 /* Apps on SD card are always in ASEC containers. */ 9859 isInAsec = true; 9860 } else if (installForwardLocked(installFlags) 9861 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9862 /* 9863 * Forward-locked apps are only in ASEC containers if they're the 9864 * new style 9865 */ 9866 isInAsec = true; 9867 } else { 9868 isInAsec = false; 9869 } 9870 9871 if (isInAsec) { 9872 return new AsecInstallArgs(codePath, instructionSets, 9873 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9874 } else { 9875 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9876 instructionSets); 9877 } 9878 } 9879 9880 static abstract class InstallArgs { 9881 /** @see InstallParams#origin */ 9882 final OriginInfo origin; 9883 9884 final IPackageInstallObserver2 observer; 9885 // Always refers to PackageManager flags only 9886 final int installFlags; 9887 final String installerPackageName; 9888 final String volumeUuid; 9889 final ManifestDigest manifestDigest; 9890 final UserHandle user; 9891 final String abiOverride; 9892 9893 // The list of instruction sets supported by this app. This is currently 9894 // only used during the rmdex() phase to clean up resources. We can get rid of this 9895 // if we move dex files under the common app path. 9896 /* nullable */ String[] instructionSets; 9897 9898 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9899 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9900 UserHandle user, String[] instructionSets, String abiOverride) { 9901 this.origin = origin; 9902 this.installFlags = installFlags; 9903 this.observer = observer; 9904 this.installerPackageName = installerPackageName; 9905 this.volumeUuid = volumeUuid; 9906 this.manifestDigest = manifestDigest; 9907 this.user = user; 9908 this.instructionSets = instructionSets; 9909 this.abiOverride = abiOverride; 9910 } 9911 9912 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9913 abstract int doPreInstall(int status); 9914 9915 /** 9916 * Rename package into final resting place. All paths on the given 9917 * scanned package should be updated to reflect the rename. 9918 */ 9919 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9920 abstract int doPostInstall(int status, int uid); 9921 9922 /** @see PackageSettingBase#codePathString */ 9923 abstract String getCodePath(); 9924 /** @see PackageSettingBase#resourcePathString */ 9925 abstract String getResourcePath(); 9926 abstract String getLegacyNativeLibraryPath(); 9927 9928 // Need installer lock especially for dex file removal. 9929 abstract void cleanUpResourcesLI(); 9930 abstract boolean doPostDeleteLI(boolean delete); 9931 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9932 9933 /** 9934 * Called before the source arguments are copied. This is used mostly 9935 * for MoveParams when it needs to read the source file to put it in the 9936 * destination. 9937 */ 9938 int doPreCopy() { 9939 return PackageManager.INSTALL_SUCCEEDED; 9940 } 9941 9942 /** 9943 * Called after the source arguments are copied. This is used mostly for 9944 * MoveParams when it needs to read the source file to put it in the 9945 * destination. 9946 * 9947 * @return 9948 */ 9949 int doPostCopy(int uid) { 9950 return PackageManager.INSTALL_SUCCEEDED; 9951 } 9952 9953 protected boolean isFwdLocked() { 9954 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9955 } 9956 9957 protected boolean isExternalAsec() { 9958 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9959 } 9960 9961 UserHandle getUser() { 9962 return user; 9963 } 9964 } 9965 9966 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9967 if (!allCodePaths.isEmpty()) { 9968 if (instructionSets == null) { 9969 throw new IllegalStateException("instructionSet == null"); 9970 } 9971 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9972 for (String codePath : allCodePaths) { 9973 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9974 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9975 if (retCode < 0) { 9976 Slog.w(TAG, "Couldn't remove dex file for package: " 9977 + " at location " + codePath + ", retcode=" + retCode); 9978 // we don't consider this to be a failure of the core package deletion 9979 } 9980 } 9981 } 9982 } 9983 } 9984 9985 /** 9986 * Logic to handle installation of non-ASEC applications, including copying 9987 * and renaming logic. 9988 */ 9989 class FileInstallArgs extends InstallArgs { 9990 private File codeFile; 9991 private File resourceFile; 9992 private File legacyNativeLibraryPath; 9993 9994 // Example topology: 9995 // /data/app/com.example/base.apk 9996 // /data/app/com.example/split_foo.apk 9997 // /data/app/com.example/lib/arm/libfoo.so 9998 // /data/app/com.example/lib/arm64/libfoo.so 9999 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10000 10001 /** New install */ 10002 FileInstallArgs(InstallParams params) { 10003 super(params.origin, params.observer, params.installFlags, 10004 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10005 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10006 if (isFwdLocked()) { 10007 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10008 } 10009 } 10010 10011 /** Existing install */ 10012 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10013 String[] instructionSets) { 10014 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10015 this.codeFile = (codePath != null) ? new File(codePath) : null; 10016 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10017 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10018 new File(legacyNativeLibraryPath) : null; 10019 } 10020 10021 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10022 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10023 isFwdLocked(), abiOverride); 10024 10025 final StorageManager storage = StorageManager.from(mContext); 10026 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10027 } 10028 10029 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10030 if (origin.staged) { 10031 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10032 codeFile = origin.file; 10033 resourceFile = origin.file; 10034 return PackageManager.INSTALL_SUCCEEDED; 10035 } 10036 10037 try { 10038 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10039 codeFile = tempDir; 10040 resourceFile = tempDir; 10041 } catch (IOException e) { 10042 Slog.w(TAG, "Failed to create copy file: " + e); 10043 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10044 } 10045 10046 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10047 @Override 10048 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10049 if (!FileUtils.isValidExtFilename(name)) { 10050 throw new IllegalArgumentException("Invalid filename: " + name); 10051 } 10052 try { 10053 final File file = new File(codeFile, name); 10054 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10055 O_RDWR | O_CREAT, 0644); 10056 Os.chmod(file.getAbsolutePath(), 0644); 10057 return new ParcelFileDescriptor(fd); 10058 } catch (ErrnoException e) { 10059 throw new RemoteException("Failed to open: " + e.getMessage()); 10060 } 10061 } 10062 }; 10063 10064 int ret = PackageManager.INSTALL_SUCCEEDED; 10065 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10066 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10067 Slog.e(TAG, "Failed to copy package"); 10068 return ret; 10069 } 10070 10071 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10072 NativeLibraryHelper.Handle handle = null; 10073 try { 10074 handle = NativeLibraryHelper.Handle.create(codeFile); 10075 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10076 abiOverride); 10077 } catch (IOException e) { 10078 Slog.e(TAG, "Copying native libraries failed", e); 10079 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10080 } finally { 10081 IoUtils.closeQuietly(handle); 10082 } 10083 10084 return ret; 10085 } 10086 10087 int doPreInstall(int status) { 10088 if (status != PackageManager.INSTALL_SUCCEEDED) { 10089 cleanUp(); 10090 } 10091 return status; 10092 } 10093 10094 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10095 if (status != PackageManager.INSTALL_SUCCEEDED) { 10096 cleanUp(); 10097 return false; 10098 } else { 10099 final File targetDir = codeFile.getParentFile(); 10100 final File beforeCodeFile = codeFile; 10101 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10102 10103 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10104 try { 10105 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10106 } catch (ErrnoException e) { 10107 Slog.d(TAG, "Failed to rename", e); 10108 return false; 10109 } 10110 10111 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10112 Slog.d(TAG, "Failed to restorecon"); 10113 return false; 10114 } 10115 10116 // Reflect the rename internally 10117 codeFile = afterCodeFile; 10118 resourceFile = afterCodeFile; 10119 10120 // Reflect the rename in scanned details 10121 pkg.codePath = afterCodeFile.getAbsolutePath(); 10122 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10123 pkg.baseCodePath); 10124 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10125 pkg.splitCodePaths); 10126 10127 // Reflect the rename in app info 10128 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10129 pkg.applicationInfo.setCodePath(pkg.codePath); 10130 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10131 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10132 pkg.applicationInfo.setResourcePath(pkg.codePath); 10133 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10134 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10135 10136 return true; 10137 } 10138 } 10139 10140 int doPostInstall(int status, int uid) { 10141 if (status != PackageManager.INSTALL_SUCCEEDED) { 10142 cleanUp(); 10143 } 10144 return status; 10145 } 10146 10147 @Override 10148 String getCodePath() { 10149 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10150 } 10151 10152 @Override 10153 String getResourcePath() { 10154 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10155 } 10156 10157 @Override 10158 String getLegacyNativeLibraryPath() { 10159 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10160 } 10161 10162 private boolean cleanUp() { 10163 if (codeFile == null || !codeFile.exists()) { 10164 return false; 10165 } 10166 10167 if (codeFile.isDirectory()) { 10168 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10169 } else { 10170 codeFile.delete(); 10171 } 10172 10173 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10174 resourceFile.delete(); 10175 } 10176 10177 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10178 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10179 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10180 } 10181 legacyNativeLibraryPath.delete(); 10182 } 10183 10184 return true; 10185 } 10186 10187 void cleanUpResourcesLI() { 10188 // Try enumerating all code paths before deleting 10189 List<String> allCodePaths = Collections.EMPTY_LIST; 10190 if (codeFile != null && codeFile.exists()) { 10191 try { 10192 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10193 allCodePaths = pkg.getAllCodePaths(); 10194 } catch (PackageParserException e) { 10195 // Ignored; we tried our best 10196 } 10197 } 10198 10199 cleanUp(); 10200 removeDexFiles(allCodePaths, instructionSets); 10201 } 10202 10203 boolean doPostDeleteLI(boolean delete) { 10204 // XXX err, shouldn't we respect the delete flag? 10205 cleanUpResourcesLI(); 10206 return true; 10207 } 10208 } 10209 10210 private boolean isAsecExternal(String cid) { 10211 final String asecPath = PackageHelper.getSdFilesystem(cid); 10212 return !asecPath.startsWith(mAsecInternalPath); 10213 } 10214 10215 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10216 PackageManagerException { 10217 if (copyRet < 0) { 10218 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10219 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10220 throw new PackageManagerException(copyRet, message); 10221 } 10222 } 10223 } 10224 10225 /** 10226 * Extract the MountService "container ID" from the full code path of an 10227 * .apk. 10228 */ 10229 static String cidFromCodePath(String fullCodePath) { 10230 int eidx = fullCodePath.lastIndexOf("/"); 10231 String subStr1 = fullCodePath.substring(0, eidx); 10232 int sidx = subStr1.lastIndexOf("/"); 10233 return subStr1.substring(sidx+1, eidx); 10234 } 10235 10236 /** 10237 * Logic to handle installation of ASEC applications, including copying and 10238 * renaming logic. 10239 */ 10240 class AsecInstallArgs extends InstallArgs { 10241 static final String RES_FILE_NAME = "pkg.apk"; 10242 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10243 10244 String cid; 10245 String packagePath; 10246 String resourcePath; 10247 String legacyNativeLibraryDir; 10248 10249 /** New install */ 10250 AsecInstallArgs(InstallParams params) { 10251 super(params.origin, params.observer, params.installFlags, 10252 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10253 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10254 } 10255 10256 /** Existing install */ 10257 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10258 boolean isExternal, boolean isForwardLocked) { 10259 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10260 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10261 instructionSets, null); 10262 // Hackily pretend we're still looking at a full code path 10263 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10264 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10265 } 10266 10267 // Extract cid from fullCodePath 10268 int eidx = fullCodePath.lastIndexOf("/"); 10269 String subStr1 = fullCodePath.substring(0, eidx); 10270 int sidx = subStr1.lastIndexOf("/"); 10271 cid = subStr1.substring(sidx+1, eidx); 10272 setMountPath(subStr1); 10273 } 10274 10275 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10276 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10277 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10278 instructionSets, null); 10279 this.cid = cid; 10280 setMountPath(PackageHelper.getSdDir(cid)); 10281 } 10282 10283 void createCopyFile() { 10284 cid = mInstallerService.allocateExternalStageCidLegacy(); 10285 } 10286 10287 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10288 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10289 abiOverride); 10290 10291 final File target; 10292 if (isExternalAsec()) { 10293 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10294 } else { 10295 target = Environment.getDataDirectory(); 10296 } 10297 10298 final StorageManager storage = StorageManager.from(mContext); 10299 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10300 } 10301 10302 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10303 if (origin.staged) { 10304 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10305 cid = origin.cid; 10306 setMountPath(PackageHelper.getSdDir(cid)); 10307 return PackageManager.INSTALL_SUCCEEDED; 10308 } 10309 10310 if (temp) { 10311 createCopyFile(); 10312 } else { 10313 /* 10314 * Pre-emptively destroy the container since it's destroyed if 10315 * copying fails due to it existing anyway. 10316 */ 10317 PackageHelper.destroySdDir(cid); 10318 } 10319 10320 final String newMountPath = imcs.copyPackageToContainer( 10321 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10322 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10323 10324 if (newMountPath != null) { 10325 setMountPath(newMountPath); 10326 return PackageManager.INSTALL_SUCCEEDED; 10327 } else { 10328 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10329 } 10330 } 10331 10332 @Override 10333 String getCodePath() { 10334 return packagePath; 10335 } 10336 10337 @Override 10338 String getResourcePath() { 10339 return resourcePath; 10340 } 10341 10342 @Override 10343 String getLegacyNativeLibraryPath() { 10344 return legacyNativeLibraryDir; 10345 } 10346 10347 int doPreInstall(int status) { 10348 if (status != PackageManager.INSTALL_SUCCEEDED) { 10349 // Destroy container 10350 PackageHelper.destroySdDir(cid); 10351 } else { 10352 boolean mounted = PackageHelper.isContainerMounted(cid); 10353 if (!mounted) { 10354 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10355 Process.SYSTEM_UID); 10356 if (newMountPath != null) { 10357 setMountPath(newMountPath); 10358 } else { 10359 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10360 } 10361 } 10362 } 10363 return status; 10364 } 10365 10366 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10367 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10368 String newMountPath = null; 10369 if (PackageHelper.isContainerMounted(cid)) { 10370 // Unmount the container 10371 if (!PackageHelper.unMountSdDir(cid)) { 10372 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10373 return false; 10374 } 10375 } 10376 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10377 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10378 " which might be stale. Will try to clean up."); 10379 // Clean up the stale container and proceed to recreate. 10380 if (!PackageHelper.destroySdDir(newCacheId)) { 10381 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10382 return false; 10383 } 10384 // Successfully cleaned up stale container. Try to rename again. 10385 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10386 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10387 + " inspite of cleaning it up."); 10388 return false; 10389 } 10390 } 10391 if (!PackageHelper.isContainerMounted(newCacheId)) { 10392 Slog.w(TAG, "Mounting container " + newCacheId); 10393 newMountPath = PackageHelper.mountSdDir(newCacheId, 10394 getEncryptKey(), Process.SYSTEM_UID); 10395 } else { 10396 newMountPath = PackageHelper.getSdDir(newCacheId); 10397 } 10398 if (newMountPath == null) { 10399 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10400 return false; 10401 } 10402 Log.i(TAG, "Succesfully renamed " + cid + 10403 " to " + newCacheId + 10404 " at new path: " + newMountPath); 10405 cid = newCacheId; 10406 10407 final File beforeCodeFile = new File(packagePath); 10408 setMountPath(newMountPath); 10409 final File afterCodeFile = new File(packagePath); 10410 10411 // Reflect the rename in scanned details 10412 pkg.codePath = afterCodeFile.getAbsolutePath(); 10413 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10414 pkg.baseCodePath); 10415 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10416 pkg.splitCodePaths); 10417 10418 // Reflect the rename in app info 10419 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10420 pkg.applicationInfo.setCodePath(pkg.codePath); 10421 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10422 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10423 pkg.applicationInfo.setResourcePath(pkg.codePath); 10424 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10425 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10426 10427 return true; 10428 } 10429 10430 private void setMountPath(String mountPath) { 10431 final File mountFile = new File(mountPath); 10432 10433 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10434 if (monolithicFile.exists()) { 10435 packagePath = monolithicFile.getAbsolutePath(); 10436 if (isFwdLocked()) { 10437 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10438 } else { 10439 resourcePath = packagePath; 10440 } 10441 } else { 10442 packagePath = mountFile.getAbsolutePath(); 10443 resourcePath = packagePath; 10444 } 10445 10446 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10447 } 10448 10449 int doPostInstall(int status, int uid) { 10450 if (status != PackageManager.INSTALL_SUCCEEDED) { 10451 cleanUp(); 10452 } else { 10453 final int groupOwner; 10454 final String protectedFile; 10455 if (isFwdLocked()) { 10456 groupOwner = UserHandle.getSharedAppGid(uid); 10457 protectedFile = RES_FILE_NAME; 10458 } else { 10459 groupOwner = -1; 10460 protectedFile = null; 10461 } 10462 10463 if (uid < Process.FIRST_APPLICATION_UID 10464 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10465 Slog.e(TAG, "Failed to finalize " + cid); 10466 PackageHelper.destroySdDir(cid); 10467 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10468 } 10469 10470 boolean mounted = PackageHelper.isContainerMounted(cid); 10471 if (!mounted) { 10472 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10473 } 10474 } 10475 return status; 10476 } 10477 10478 private void cleanUp() { 10479 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10480 10481 // Destroy secure container 10482 PackageHelper.destroySdDir(cid); 10483 } 10484 10485 private List<String> getAllCodePaths() { 10486 final File codeFile = new File(getCodePath()); 10487 if (codeFile != null && codeFile.exists()) { 10488 try { 10489 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10490 return pkg.getAllCodePaths(); 10491 } catch (PackageParserException e) { 10492 // Ignored; we tried our best 10493 } 10494 } 10495 return Collections.EMPTY_LIST; 10496 } 10497 10498 void cleanUpResourcesLI() { 10499 // Enumerate all code paths before deleting 10500 cleanUpResourcesLI(getAllCodePaths()); 10501 } 10502 10503 private void cleanUpResourcesLI(List<String> allCodePaths) { 10504 cleanUp(); 10505 removeDexFiles(allCodePaths, instructionSets); 10506 } 10507 10508 10509 10510 String getPackageName() { 10511 return getAsecPackageName(cid); 10512 } 10513 10514 boolean doPostDeleteLI(boolean delete) { 10515 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10516 final List<String> allCodePaths = getAllCodePaths(); 10517 boolean mounted = PackageHelper.isContainerMounted(cid); 10518 if (mounted) { 10519 // Unmount first 10520 if (PackageHelper.unMountSdDir(cid)) { 10521 mounted = false; 10522 } 10523 } 10524 if (!mounted && delete) { 10525 cleanUpResourcesLI(allCodePaths); 10526 } 10527 return !mounted; 10528 } 10529 10530 @Override 10531 int doPreCopy() { 10532 if (isFwdLocked()) { 10533 if (!PackageHelper.fixSdPermissions(cid, 10534 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10535 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10536 } 10537 } 10538 10539 return PackageManager.INSTALL_SUCCEEDED; 10540 } 10541 10542 @Override 10543 int doPostCopy(int uid) { 10544 if (isFwdLocked()) { 10545 if (uid < Process.FIRST_APPLICATION_UID 10546 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10547 RES_FILE_NAME)) { 10548 Slog.e(TAG, "Failed to finalize " + cid); 10549 PackageHelper.destroySdDir(cid); 10550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10551 } 10552 } 10553 10554 return PackageManager.INSTALL_SUCCEEDED; 10555 } 10556 } 10557 10558 static String getAsecPackageName(String packageCid) { 10559 int idx = packageCid.lastIndexOf("-"); 10560 if (idx == -1) { 10561 return packageCid; 10562 } 10563 return packageCid.substring(0, idx); 10564 } 10565 10566 // Utility method used to create code paths based on package name and available index. 10567 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10568 String idxStr = ""; 10569 int idx = 1; 10570 // Fall back to default value of idx=1 if prefix is not 10571 // part of oldCodePath 10572 if (oldCodePath != null) { 10573 String subStr = oldCodePath; 10574 // Drop the suffix right away 10575 if (suffix != null && subStr.endsWith(suffix)) { 10576 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10577 } 10578 // If oldCodePath already contains prefix find out the 10579 // ending index to either increment or decrement. 10580 int sidx = subStr.lastIndexOf(prefix); 10581 if (sidx != -1) { 10582 subStr = subStr.substring(sidx + prefix.length()); 10583 if (subStr != null) { 10584 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10585 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10586 } 10587 try { 10588 idx = Integer.parseInt(subStr); 10589 if (idx <= 1) { 10590 idx++; 10591 } else { 10592 idx--; 10593 } 10594 } catch(NumberFormatException e) { 10595 } 10596 } 10597 } 10598 } 10599 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10600 return prefix + idxStr; 10601 } 10602 10603 private File getNextCodePath(File targetDir, String packageName) { 10604 int suffix = 1; 10605 File result; 10606 do { 10607 result = new File(targetDir, packageName + "-" + suffix); 10608 suffix++; 10609 } while (result.exists()); 10610 return result; 10611 } 10612 10613 // Utility method that returns the relative package path with respect 10614 // to the installation directory. Like say for /data/data/com.test-1.apk 10615 // string com.test-1 is returned. 10616 static String deriveCodePathName(String codePath) { 10617 if (codePath == null) { 10618 return null; 10619 } 10620 final File codeFile = new File(codePath); 10621 final String name = codeFile.getName(); 10622 if (codeFile.isDirectory()) { 10623 return name; 10624 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10625 final int lastDot = name.lastIndexOf('.'); 10626 return name.substring(0, lastDot); 10627 } else { 10628 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10629 return null; 10630 } 10631 } 10632 10633 class PackageInstalledInfo { 10634 String name; 10635 int uid; 10636 // The set of users that originally had this package installed. 10637 int[] origUsers; 10638 // The set of users that now have this package installed. 10639 int[] newUsers; 10640 PackageParser.Package pkg; 10641 int returnCode; 10642 String returnMsg; 10643 PackageRemovedInfo removedInfo; 10644 10645 public void setError(int code, String msg) { 10646 returnCode = code; 10647 returnMsg = msg; 10648 Slog.w(TAG, msg); 10649 } 10650 10651 public void setError(String msg, PackageParserException e) { 10652 returnCode = e.error; 10653 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10654 Slog.w(TAG, msg, e); 10655 } 10656 10657 public void setError(String msg, PackageManagerException e) { 10658 returnCode = e.error; 10659 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10660 Slog.w(TAG, msg, e); 10661 } 10662 10663 // In some error cases we want to convey more info back to the observer 10664 String origPackage; 10665 String origPermission; 10666 } 10667 10668 /* 10669 * Install a non-existing package. 10670 */ 10671 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10672 UserHandle user, String installerPackageName, String volumeUuid, 10673 PackageInstalledInfo res) { 10674 // Remember this for later, in case we need to rollback this install 10675 String pkgName = pkg.packageName; 10676 10677 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10678 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10679 UserHandle.USER_OWNER).exists(); 10680 synchronized(mPackages) { 10681 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10682 // A package with the same name is already installed, though 10683 // it has been renamed to an older name. The package we 10684 // are trying to install should be installed as an update to 10685 // the existing one, but that has not been requested, so bail. 10686 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10687 + " without first uninstalling package running as " 10688 + mSettings.mRenamedPackages.get(pkgName)); 10689 return; 10690 } 10691 if (mPackages.containsKey(pkgName)) { 10692 // Don't allow installation over an existing package with the same name. 10693 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10694 + " without first uninstalling."); 10695 return; 10696 } 10697 } 10698 10699 try { 10700 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10701 System.currentTimeMillis(), user); 10702 10703 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10704 // delete the partially installed application. the data directory will have to be 10705 // restored if it was already existing 10706 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10707 // remove package from internal structures. Note that we want deletePackageX to 10708 // delete the package data and cache directories that it created in 10709 // scanPackageLocked, unless those directories existed before we even tried to 10710 // install. 10711 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10712 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10713 res.removedInfo, true); 10714 } 10715 10716 } catch (PackageManagerException e) { 10717 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10718 } 10719 } 10720 10721 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10722 // Upgrade keysets are being used. Determine if new package has a superset of the 10723 // required keys. 10724 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10725 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10726 for (int i = 0; i < upgradeKeySets.length; i++) { 10727 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10728 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10729 return true; 10730 } 10731 } 10732 return false; 10733 } 10734 10735 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10736 UserHandle user, String installerPackageName, String volumeUuid, 10737 PackageInstalledInfo res) { 10738 PackageParser.Package oldPackage; 10739 String pkgName = pkg.packageName; 10740 int[] allUsers; 10741 boolean[] perUserInstalled; 10742 10743 // First find the old package info and check signatures 10744 synchronized(mPackages) { 10745 oldPackage = mPackages.get(pkgName); 10746 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10747 PackageSetting ps = mSettings.mPackages.get(pkgName); 10748 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10749 // default to original signature matching 10750 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10751 != PackageManager.SIGNATURE_MATCH) { 10752 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10753 "New package has a different signature: " + pkgName); 10754 return; 10755 } 10756 } else { 10757 if(!checkUpgradeKeySetLP(ps, pkg)) { 10758 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10759 "New package not signed by keys specified by upgrade-keysets: " 10760 + pkgName); 10761 return; 10762 } 10763 } 10764 10765 // In case of rollback, remember per-user/profile install state 10766 allUsers = sUserManager.getUserIds(); 10767 perUserInstalled = new boolean[allUsers.length]; 10768 for (int i = 0; i < allUsers.length; i++) { 10769 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10770 } 10771 } 10772 10773 boolean sysPkg = (isSystemApp(oldPackage)); 10774 if (sysPkg) { 10775 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10776 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10777 } else { 10778 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10779 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10780 } 10781 } 10782 10783 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10784 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10785 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10786 String volumeUuid, PackageInstalledInfo res) { 10787 String pkgName = deletedPackage.packageName; 10788 boolean deletedPkg = true; 10789 boolean updatedSettings = false; 10790 10791 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10792 + deletedPackage); 10793 long origUpdateTime; 10794 if (pkg.mExtras != null) { 10795 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10796 } else { 10797 origUpdateTime = 0; 10798 } 10799 10800 // First delete the existing package while retaining the data directory 10801 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10802 res.removedInfo, true)) { 10803 // If the existing package wasn't successfully deleted 10804 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10805 deletedPkg = false; 10806 } else { 10807 // Successfully deleted the old package; proceed with replace. 10808 10809 // If deleted package lived in a container, give users a chance to 10810 // relinquish resources before killing. 10811 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10812 if (DEBUG_INSTALL) { 10813 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10814 } 10815 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10816 final ArrayList<String> pkgList = new ArrayList<String>(1); 10817 pkgList.add(deletedPackage.applicationInfo.packageName); 10818 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10819 } 10820 10821 deleteCodeCacheDirsLI(pkgName); 10822 try { 10823 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10824 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10825 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10826 perUserInstalled, res, user); 10827 updatedSettings = true; 10828 } catch (PackageManagerException e) { 10829 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10830 } 10831 } 10832 10833 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10834 // remove package from internal structures. Note that we want deletePackageX to 10835 // delete the package data and cache directories that it created in 10836 // scanPackageLocked, unless those directories existed before we even tried to 10837 // install. 10838 if(updatedSettings) { 10839 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10840 deletePackageLI( 10841 pkgName, null, true, allUsers, perUserInstalled, 10842 PackageManager.DELETE_KEEP_DATA, 10843 res.removedInfo, true); 10844 } 10845 // Since we failed to install the new package we need to restore the old 10846 // package that we deleted. 10847 if (deletedPkg) { 10848 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10849 File restoreFile = new File(deletedPackage.codePath); 10850 // Parse old package 10851 boolean oldExternal = isExternal(deletedPackage); 10852 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10853 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10854 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10855 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10856 try { 10857 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10858 } catch (PackageManagerException e) { 10859 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10860 + e.getMessage()); 10861 return; 10862 } 10863 // Restore of old package succeeded. Update permissions. 10864 // writer 10865 synchronized (mPackages) { 10866 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10867 UPDATE_PERMISSIONS_ALL); 10868 // can downgrade to reader 10869 mSettings.writeLPr(); 10870 } 10871 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10872 } 10873 } 10874 } 10875 10876 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10877 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10878 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10879 String volumeUuid, PackageInstalledInfo res) { 10880 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10881 + ", old=" + deletedPackage); 10882 boolean disabledSystem = false; 10883 boolean updatedSettings = false; 10884 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10885 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10886 != 0) { 10887 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10888 } 10889 String packageName = deletedPackage.packageName; 10890 if (packageName == null) { 10891 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10892 "Attempt to delete null packageName."); 10893 return; 10894 } 10895 PackageParser.Package oldPkg; 10896 PackageSetting oldPkgSetting; 10897 // reader 10898 synchronized (mPackages) { 10899 oldPkg = mPackages.get(packageName); 10900 oldPkgSetting = mSettings.mPackages.get(packageName); 10901 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10902 (oldPkgSetting == null)) { 10903 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10904 "Couldn't find package:" + packageName + " information"); 10905 return; 10906 } 10907 } 10908 10909 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10910 10911 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10912 res.removedInfo.removedPackage = packageName; 10913 // Remove existing system package 10914 removePackageLI(oldPkgSetting, true); 10915 // writer 10916 synchronized (mPackages) { 10917 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10918 if (!disabledSystem && deletedPackage != null) { 10919 // We didn't need to disable the .apk as a current system package, 10920 // which means we are replacing another update that is already 10921 // installed. We need to make sure to delete the older one's .apk. 10922 res.removedInfo.args = createInstallArgsForExisting(0, 10923 deletedPackage.applicationInfo.getCodePath(), 10924 deletedPackage.applicationInfo.getResourcePath(), 10925 deletedPackage.applicationInfo.nativeLibraryRootDir, 10926 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10927 } else { 10928 res.removedInfo.args = null; 10929 } 10930 } 10931 10932 // Successfully disabled the old package. Now proceed with re-installation 10933 deleteCodeCacheDirsLI(packageName); 10934 10935 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10936 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10937 10938 PackageParser.Package newPackage = null; 10939 try { 10940 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10941 if (newPackage.mExtras != null) { 10942 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10943 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10944 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10945 10946 // is the update attempting to change shared user? that isn't going to work... 10947 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10948 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10949 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10950 + " to " + newPkgSetting.sharedUser); 10951 updatedSettings = true; 10952 } 10953 } 10954 10955 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10956 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10957 perUserInstalled, res, user); 10958 updatedSettings = true; 10959 } 10960 10961 } catch (PackageManagerException e) { 10962 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10963 } 10964 10965 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10966 // Re installation failed. Restore old information 10967 // Remove new pkg information 10968 if (newPackage != null) { 10969 removeInstalledPackageLI(newPackage, true); 10970 } 10971 // Add back the old system package 10972 try { 10973 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10974 } catch (PackageManagerException e) { 10975 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10976 } 10977 // Restore the old system information in Settings 10978 synchronized (mPackages) { 10979 if (disabledSystem) { 10980 mSettings.enableSystemPackageLPw(packageName); 10981 } 10982 if (updatedSettings) { 10983 mSettings.setInstallerPackageName(packageName, 10984 oldPkgSetting.installerPackageName); 10985 } 10986 mSettings.writeLPr(); 10987 } 10988 } 10989 } 10990 10991 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10992 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10993 UserHandle user) { 10994 String pkgName = newPackage.packageName; 10995 synchronized (mPackages) { 10996 //write settings. the installStatus will be incomplete at this stage. 10997 //note that the new package setting would have already been 10998 //added to mPackages. It hasn't been persisted yet. 10999 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11000 mSettings.writeLPr(); 11001 } 11002 11003 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11004 11005 synchronized (mPackages) { 11006 updatePermissionsLPw(newPackage.packageName, newPackage, 11007 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11008 ? UPDATE_PERMISSIONS_ALL : 0)); 11009 // For system-bundled packages, we assume that installing an upgraded version 11010 // of the package implies that the user actually wants to run that new code, 11011 // so we enable the package. 11012 PackageSetting ps = mSettings.mPackages.get(pkgName); 11013 if (ps != null) { 11014 if (isSystemApp(newPackage)) { 11015 // NB: implicit assumption that system package upgrades apply to all users 11016 if (DEBUG_INSTALL) { 11017 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11018 } 11019 if (res.origUsers != null) { 11020 for (int userHandle : res.origUsers) { 11021 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11022 userHandle, installerPackageName); 11023 } 11024 } 11025 // Also convey the prior install/uninstall state 11026 if (allUsers != null && perUserInstalled != null) { 11027 for (int i = 0; i < allUsers.length; i++) { 11028 if (DEBUG_INSTALL) { 11029 Slog.d(TAG, " user " + allUsers[i] 11030 + " => " + perUserInstalled[i]); 11031 } 11032 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11033 } 11034 // these install state changes will be persisted in the 11035 // upcoming call to mSettings.writeLPr(). 11036 } 11037 } 11038 // It's implied that when a user requests installation, they want the app to be 11039 // installed and enabled. 11040 int userId = user.getIdentifier(); 11041 if (userId != UserHandle.USER_ALL) { 11042 ps.setInstalled(true, userId); 11043 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11044 } 11045 } 11046 res.name = pkgName; 11047 res.uid = newPackage.applicationInfo.uid; 11048 res.pkg = newPackage; 11049 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11050 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11051 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11052 //to update install status 11053 mSettings.writeLPr(); 11054 } 11055 } 11056 11057 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11058 final int installFlags = args.installFlags; 11059 final String installerPackageName = args.installerPackageName; 11060 final String volumeUuid = args.volumeUuid; 11061 final File tmpPackageFile = new File(args.getCodePath()); 11062 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11063 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11064 || (args.volumeUuid != null)); 11065 boolean replace = false; 11066 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11067 // Result object to be returned 11068 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11069 11070 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11071 // Retrieve PackageSettings and parse package 11072 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11073 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11074 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11075 PackageParser pp = new PackageParser(); 11076 pp.setSeparateProcesses(mSeparateProcesses); 11077 pp.setDisplayMetrics(mMetrics); 11078 11079 final PackageParser.Package pkg; 11080 try { 11081 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11082 } catch (PackageParserException e) { 11083 res.setError("Failed parse during installPackageLI", e); 11084 return; 11085 } 11086 11087 // Mark that we have an install time CPU ABI override. 11088 pkg.cpuAbiOverride = args.abiOverride; 11089 11090 String pkgName = res.name = pkg.packageName; 11091 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11092 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11093 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11094 return; 11095 } 11096 } 11097 11098 try { 11099 pp.collectCertificates(pkg, parseFlags); 11100 pp.collectManifestDigest(pkg); 11101 } catch (PackageParserException e) { 11102 res.setError("Failed collect during installPackageLI", e); 11103 return; 11104 } 11105 11106 /* If the installer passed in a manifest digest, compare it now. */ 11107 if (args.manifestDigest != null) { 11108 if (DEBUG_INSTALL) { 11109 final String parsedManifest = pkg.manifestDigest == null ? "null" 11110 : pkg.manifestDigest.toString(); 11111 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11112 + parsedManifest); 11113 } 11114 11115 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11116 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11117 return; 11118 } 11119 } else if (DEBUG_INSTALL) { 11120 final String parsedManifest = pkg.manifestDigest == null 11121 ? "null" : pkg.manifestDigest.toString(); 11122 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11123 } 11124 11125 // Get rid of all references to package scan path via parser. 11126 pp = null; 11127 String oldCodePath = null; 11128 boolean systemApp = false; 11129 synchronized (mPackages) { 11130 // Check if installing already existing package 11131 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11132 String oldName = mSettings.mRenamedPackages.get(pkgName); 11133 if (pkg.mOriginalPackages != null 11134 && pkg.mOriginalPackages.contains(oldName) 11135 && mPackages.containsKey(oldName)) { 11136 // This package is derived from an original package, 11137 // and this device has been updating from that original 11138 // name. We must continue using the original name, so 11139 // rename the new package here. 11140 pkg.setPackageName(oldName); 11141 pkgName = pkg.packageName; 11142 replace = true; 11143 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11144 + oldName + " pkgName=" + pkgName); 11145 } else if (mPackages.containsKey(pkgName)) { 11146 // This package, under its official name, already exists 11147 // on the device; we should replace it. 11148 replace = true; 11149 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11150 } 11151 } 11152 11153 PackageSetting ps = mSettings.mPackages.get(pkgName); 11154 if (ps != null) { 11155 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11156 11157 // Quick sanity check that we're signed correctly if updating; 11158 // we'll check this again later when scanning, but we want to 11159 // bail early here before tripping over redefined permissions. 11160 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11161 try { 11162 verifySignaturesLP(ps, pkg); 11163 } catch (PackageManagerException e) { 11164 res.setError(e.error, e.getMessage()); 11165 return; 11166 } 11167 } else { 11168 if (!checkUpgradeKeySetLP(ps, pkg)) { 11169 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11170 + pkg.packageName + " upgrade keys do not match the " 11171 + "previously installed version"); 11172 return; 11173 } 11174 } 11175 11176 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11177 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11178 systemApp = (ps.pkg.applicationInfo.flags & 11179 ApplicationInfo.FLAG_SYSTEM) != 0; 11180 } 11181 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11182 } 11183 11184 // Check whether the newly-scanned package wants to define an already-defined perm 11185 int N = pkg.permissions.size(); 11186 for (int i = N-1; i >= 0; i--) { 11187 PackageParser.Permission perm = pkg.permissions.get(i); 11188 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11189 if (bp != null) { 11190 // If the defining package is signed with our cert, it's okay. This 11191 // also includes the "updating the same package" case, of course. 11192 // "updating same package" could also involve key-rotation. 11193 final boolean sigsOk; 11194 if (!bp.sourcePackage.equals(pkg.packageName) 11195 || !(bp.packageSetting instanceof PackageSetting) 11196 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11197 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11198 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11199 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11200 } else { 11201 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11202 } 11203 if (!sigsOk) { 11204 // If the owning package is the system itself, we log but allow 11205 // install to proceed; we fail the install on all other permission 11206 // redefinitions. 11207 if (!bp.sourcePackage.equals("android")) { 11208 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11209 + pkg.packageName + " attempting to redeclare permission " 11210 + perm.info.name + " already owned by " + bp.sourcePackage); 11211 res.origPermission = perm.info.name; 11212 res.origPackage = bp.sourcePackage; 11213 return; 11214 } else { 11215 Slog.w(TAG, "Package " + pkg.packageName 11216 + " attempting to redeclare system permission " 11217 + perm.info.name + "; ignoring new declaration"); 11218 pkg.permissions.remove(i); 11219 } 11220 } 11221 } 11222 } 11223 11224 } 11225 11226 if (systemApp && onExternal) { 11227 // Disable updates to system apps on sdcard 11228 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11229 "Cannot install updates to system apps on sdcard"); 11230 return; 11231 } 11232 11233 // Run dexopt before old package gets removed, to minimize time when app is not available 11234 int result = mPackageDexOptimizer 11235 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11236 false /* defer */, false /* inclDependencies */); 11237 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11238 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11239 return; 11240 } 11241 11242 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11243 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11244 return; 11245 } 11246 11247 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11248 11249 // Call with SCAN_NO_DEX, since dexopt has already been made 11250 if (replace) { 11251 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11252 installerPackageName, volumeUuid, res); 11253 } else { 11254 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES 11255 | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res); 11256 } 11257 synchronized (mPackages) { 11258 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11259 if (ps != null) { 11260 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11261 } 11262 } 11263 } 11264 11265 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11266 if (mIntentFilterVerifierComponent == null) { 11267 Slog.d(TAG, "No IntentFilter verification will not be done as " 11268 + "there is no IntentFilterVerifier available!"); 11269 return; 11270 } 11271 11272 final int verifierUid = getPackageUid( 11273 mIntentFilterVerifierComponent.getPackageName(), 11274 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11275 11276 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11277 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11278 msg.obj = pkg; 11279 msg.arg1 = userId; 11280 msg.arg2 = verifierUid; 11281 11282 mHandler.sendMessage(msg); 11283 } 11284 11285 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11286 PackageParser.Package pkg) { 11287 int size = pkg.activities.size(); 11288 if (size == 0) { 11289 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11290 return; 11291 } 11292 11293 final boolean hasDomainURLs = hasDomainURLs(pkg); 11294 if (!hasDomainURLs) { 11295 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11296 return; 11297 } 11298 11299 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11300 + " Activities needs verification ..."); 11301 11302 final int verificationId = mIntentFilterVerificationToken++; 11303 int count = 0; 11304 final String packageName = pkg.packageName; 11305 ArrayList<String> allHosts = new ArrayList<>(); 11306 11307 synchronized (mPackages) { 11308 for (PackageParser.Activity a : pkg.activities) { 11309 for (ActivityIntentInfo filter : a.intents) { 11310 boolean needsFilterVerification = filter.needsVerification(); 11311 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11312 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11313 mIntentFilterVerifier.addOneIntentFilterVerification( 11314 verifierUid, userId, verificationId, filter, packageName); 11315 count++; 11316 } else if (!needsFilterVerification) { 11317 Slog.d(TAG, "No verification needed for IntentFilter:" 11318 + filter.toString()); 11319 if (hasValidDomains(filter)) { 11320 allHosts.addAll(filter.getHostsList()); 11321 } 11322 } else { 11323 Slog.d(TAG, "Verification already done for IntentFilter:" 11324 + filter.toString()); 11325 } 11326 } 11327 } 11328 } 11329 11330 if (count > 0) { 11331 mIntentFilterVerifier.startVerifications(userId); 11332 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11333 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11334 } else { 11335 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11336 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11337 packageName, allHosts) != null) { 11338 scheduleWriteSettingsLocked(); 11339 } 11340 } 11341 } 11342 11343 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11344 final ComponentName cn = filter.activity.getComponentName(); 11345 final String packageName = cn.getPackageName(); 11346 11347 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11348 packageName); 11349 if (ivi == null) { 11350 return true; 11351 } 11352 int status = ivi.getStatus(); 11353 switch (status) { 11354 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11355 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11356 return true; 11357 11358 default: 11359 // Nothing to do 11360 return false; 11361 } 11362 } 11363 11364 private static boolean isMultiArch(PackageSetting ps) { 11365 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11366 } 11367 11368 private static boolean isMultiArch(ApplicationInfo info) { 11369 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11370 } 11371 11372 private static boolean isExternal(PackageParser.Package pkg) { 11373 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11374 } 11375 11376 private static boolean isExternal(PackageSetting ps) { 11377 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11378 } 11379 11380 private static boolean isExternal(ApplicationInfo info) { 11381 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11382 } 11383 11384 private static boolean isSystemApp(PackageParser.Package pkg) { 11385 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11386 } 11387 11388 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11389 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11390 } 11391 11392 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11393 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11394 } 11395 11396 private static boolean isSystemApp(PackageSetting ps) { 11397 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11398 } 11399 11400 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11401 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11402 } 11403 11404 private int packageFlagsToInstallFlags(PackageSetting ps) { 11405 int installFlags = 0; 11406 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11407 // This existing package was an external ASEC install when we have 11408 // the external flag without a UUID 11409 installFlags |= PackageManager.INSTALL_EXTERNAL; 11410 } 11411 if (ps.isForwardLocked()) { 11412 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11413 } 11414 return installFlags; 11415 } 11416 11417 private void deleteTempPackageFiles() { 11418 final FilenameFilter filter = new FilenameFilter() { 11419 public boolean accept(File dir, String name) { 11420 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11421 } 11422 }; 11423 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11424 file.delete(); 11425 } 11426 } 11427 11428 @Override 11429 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11430 int flags) { 11431 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11432 flags); 11433 } 11434 11435 @Override 11436 public void deletePackage(final String packageName, 11437 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11438 mContext.enforceCallingOrSelfPermission( 11439 android.Manifest.permission.DELETE_PACKAGES, null); 11440 final int uid = Binder.getCallingUid(); 11441 if (UserHandle.getUserId(uid) != userId) { 11442 mContext.enforceCallingPermission( 11443 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11444 "deletePackage for user " + userId); 11445 } 11446 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11447 try { 11448 observer.onPackageDeleted(packageName, 11449 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11450 } catch (RemoteException re) { 11451 } 11452 return; 11453 } 11454 11455 boolean uninstallBlocked = false; 11456 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11457 int[] users = sUserManager.getUserIds(); 11458 for (int i = 0; i < users.length; ++i) { 11459 if (getBlockUninstallForUser(packageName, users[i])) { 11460 uninstallBlocked = true; 11461 break; 11462 } 11463 } 11464 } else { 11465 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11466 } 11467 if (uninstallBlocked) { 11468 try { 11469 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11470 null); 11471 } catch (RemoteException re) { 11472 } 11473 return; 11474 } 11475 11476 if (DEBUG_REMOVE) { 11477 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11478 } 11479 // Queue up an async operation since the package deletion may take a little while. 11480 mHandler.post(new Runnable() { 11481 public void run() { 11482 mHandler.removeCallbacks(this); 11483 final int returnCode = deletePackageX(packageName, userId, flags); 11484 if (observer != null) { 11485 try { 11486 observer.onPackageDeleted(packageName, returnCode, null); 11487 } catch (RemoteException e) { 11488 Log.i(TAG, "Observer no longer exists."); 11489 } //end catch 11490 } //end if 11491 } //end run 11492 }); 11493 } 11494 11495 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11496 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11497 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11498 try { 11499 if (dpm != null) { 11500 if (dpm.isDeviceOwner(packageName)) { 11501 return true; 11502 } 11503 int[] users; 11504 if (userId == UserHandle.USER_ALL) { 11505 users = sUserManager.getUserIds(); 11506 } else { 11507 users = new int[]{userId}; 11508 } 11509 for (int i = 0; i < users.length; ++i) { 11510 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11511 return true; 11512 } 11513 } 11514 } 11515 } catch (RemoteException e) { 11516 } 11517 return false; 11518 } 11519 11520 /** 11521 * This method is an internal method that could be get invoked either 11522 * to delete an installed package or to clean up a failed installation. 11523 * After deleting an installed package, a broadcast is sent to notify any 11524 * listeners that the package has been installed. For cleaning up a failed 11525 * installation, the broadcast is not necessary since the package's 11526 * installation wouldn't have sent the initial broadcast either 11527 * The key steps in deleting a package are 11528 * deleting the package information in internal structures like mPackages, 11529 * deleting the packages base directories through installd 11530 * updating mSettings to reflect current status 11531 * persisting settings for later use 11532 * sending a broadcast if necessary 11533 */ 11534 private int deletePackageX(String packageName, int userId, int flags) { 11535 final PackageRemovedInfo info = new PackageRemovedInfo(); 11536 final boolean res; 11537 11538 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11539 ? UserHandle.ALL : new UserHandle(userId); 11540 11541 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11542 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11543 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11544 } 11545 11546 boolean removedForAllUsers = false; 11547 boolean systemUpdate = false; 11548 11549 // for the uninstall-updates case and restricted profiles, remember the per- 11550 // userhandle installed state 11551 int[] allUsers; 11552 boolean[] perUserInstalled; 11553 synchronized (mPackages) { 11554 PackageSetting ps = mSettings.mPackages.get(packageName); 11555 allUsers = sUserManager.getUserIds(); 11556 perUserInstalled = new boolean[allUsers.length]; 11557 for (int i = 0; i < allUsers.length; i++) { 11558 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11559 } 11560 } 11561 11562 synchronized (mInstallLock) { 11563 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11564 res = deletePackageLI(packageName, removeForUser, 11565 true, allUsers, perUserInstalled, 11566 flags | REMOVE_CHATTY, info, true); 11567 systemUpdate = info.isRemovedPackageSystemUpdate; 11568 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11569 removedForAllUsers = true; 11570 } 11571 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11572 + " removedForAllUsers=" + removedForAllUsers); 11573 } 11574 11575 if (res) { 11576 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11577 11578 // If the removed package was a system update, the old system package 11579 // was re-enabled; we need to broadcast this information 11580 if (systemUpdate) { 11581 Bundle extras = new Bundle(1); 11582 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11583 ? info.removedAppId : info.uid); 11584 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11585 11586 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11587 extras, null, null, null); 11588 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11589 extras, null, null, null); 11590 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11591 null, packageName, null, null); 11592 } 11593 } 11594 // Force a gc here. 11595 Runtime.getRuntime().gc(); 11596 // Delete the resources here after sending the broadcast to let 11597 // other processes clean up before deleting resources. 11598 if (info.args != null) { 11599 synchronized (mInstallLock) { 11600 info.args.doPostDeleteLI(true); 11601 } 11602 } 11603 11604 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11605 } 11606 11607 static class PackageRemovedInfo { 11608 String removedPackage; 11609 int uid = -1; 11610 int removedAppId = -1; 11611 int[] removedUsers = null; 11612 boolean isRemovedPackageSystemUpdate = false; 11613 // Clean up resources deleted packages. 11614 InstallArgs args = null; 11615 11616 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11617 Bundle extras = new Bundle(1); 11618 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11619 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11620 if (replacing) { 11621 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11622 } 11623 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11624 if (removedPackage != null) { 11625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11626 extras, null, null, removedUsers); 11627 if (fullRemove && !replacing) { 11628 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11629 extras, null, null, removedUsers); 11630 } 11631 } 11632 if (removedAppId >= 0) { 11633 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11634 removedUsers); 11635 } 11636 } 11637 } 11638 11639 /* 11640 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11641 * flag is not set, the data directory is removed as well. 11642 * make sure this flag is set for partially installed apps. If not its meaningless to 11643 * delete a partially installed application. 11644 */ 11645 private void removePackageDataLI(PackageSetting ps, 11646 int[] allUserHandles, boolean[] perUserInstalled, 11647 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11648 String packageName = ps.name; 11649 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11650 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11651 // Retrieve object to delete permissions for shared user later on 11652 final PackageSetting deletedPs; 11653 // reader 11654 synchronized (mPackages) { 11655 deletedPs = mSettings.mPackages.get(packageName); 11656 if (outInfo != null) { 11657 outInfo.removedPackage = packageName; 11658 outInfo.removedUsers = deletedPs != null 11659 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11660 : null; 11661 } 11662 } 11663 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11664 removeDataDirsLI(packageName); 11665 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11666 } 11667 // writer 11668 synchronized (mPackages) { 11669 if (deletedPs != null) { 11670 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11671 if (outInfo != null) { 11672 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11673 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11674 } 11675 updatePermissionsLPw(deletedPs.name, null, 0); 11676 if (deletedPs.sharedUser != null) { 11677 // Remove permissions associated with package. Since runtime 11678 // permissions are per user we have to kill the removed package 11679 // or packages running under the shared user of the removed 11680 // package if revoking the permissions requested only by the removed 11681 // package is successful and this causes a change in gids. 11682 for (int userId : UserManagerService.getInstance().getUserIds()) { 11683 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11684 userId); 11685 if (userIdToKill == UserHandle.USER_ALL 11686 || userIdToKill >= UserHandle.USER_OWNER) { 11687 // If gids changed for this user, kill all affected packages. 11688 mHandler.post(new Runnable() { 11689 @Override 11690 public void run() { 11691 // This has to happen with no lock held. 11692 killSettingPackagesForUser(deletedPs, userIdToKill, 11693 KILL_APP_REASON_GIDS_CHANGED); 11694 } 11695 }); 11696 break; 11697 } 11698 } 11699 } 11700 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11701 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11702 } 11703 // make sure to preserve per-user disabled state if this removal was just 11704 // a downgrade of a system app to the factory package 11705 if (allUserHandles != null && perUserInstalled != null) { 11706 if (DEBUG_REMOVE) { 11707 Slog.d(TAG, "Propagating install state across downgrade"); 11708 } 11709 for (int i = 0; i < allUserHandles.length; i++) { 11710 if (DEBUG_REMOVE) { 11711 Slog.d(TAG, " user " + allUserHandles[i] 11712 + " => " + perUserInstalled[i]); 11713 } 11714 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11715 } 11716 } 11717 } 11718 // can downgrade to reader 11719 if (writeSettings) { 11720 // Save settings now 11721 mSettings.writeLPr(); 11722 } 11723 } 11724 if (outInfo != null) { 11725 // A user ID was deleted here. Go through all users and remove it 11726 // from KeyStore. 11727 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11728 } 11729 } 11730 11731 static boolean locationIsPrivileged(File path) { 11732 try { 11733 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11734 .getCanonicalPath(); 11735 return path.getCanonicalPath().startsWith(privilegedAppDir); 11736 } catch (IOException e) { 11737 Slog.e(TAG, "Unable to access code path " + path); 11738 } 11739 return false; 11740 } 11741 11742 /* 11743 * Tries to delete system package. 11744 */ 11745 private boolean deleteSystemPackageLI(PackageSetting newPs, 11746 int[] allUserHandles, boolean[] perUserInstalled, 11747 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11748 final boolean applyUserRestrictions 11749 = (allUserHandles != null) && (perUserInstalled != null); 11750 PackageSetting disabledPs = null; 11751 // Confirm if the system package has been updated 11752 // An updated system app can be deleted. This will also have to restore 11753 // the system pkg from system partition 11754 // reader 11755 synchronized (mPackages) { 11756 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11757 } 11758 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11759 + " disabledPs=" + disabledPs); 11760 if (disabledPs == null) { 11761 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11762 return false; 11763 } else if (DEBUG_REMOVE) { 11764 Slog.d(TAG, "Deleting system pkg from data partition"); 11765 } 11766 if (DEBUG_REMOVE) { 11767 if (applyUserRestrictions) { 11768 Slog.d(TAG, "Remembering install states:"); 11769 for (int i = 0; i < allUserHandles.length; i++) { 11770 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11771 } 11772 } 11773 } 11774 // Delete the updated package 11775 outInfo.isRemovedPackageSystemUpdate = true; 11776 if (disabledPs.versionCode < newPs.versionCode) { 11777 // Delete data for downgrades 11778 flags &= ~PackageManager.DELETE_KEEP_DATA; 11779 } else { 11780 // Preserve data by setting flag 11781 flags |= PackageManager.DELETE_KEEP_DATA; 11782 } 11783 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11784 allUserHandles, perUserInstalled, outInfo, writeSettings); 11785 if (!ret) { 11786 return false; 11787 } 11788 // writer 11789 synchronized (mPackages) { 11790 // Reinstate the old system package 11791 mSettings.enableSystemPackageLPw(newPs.name); 11792 // Remove any native libraries from the upgraded package. 11793 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11794 } 11795 // Install the system package 11796 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11797 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11798 if (locationIsPrivileged(disabledPs.codePath)) { 11799 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11800 } 11801 11802 final PackageParser.Package newPkg; 11803 try { 11804 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11805 } catch (PackageManagerException e) { 11806 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11807 return false; 11808 } 11809 11810 // writer 11811 synchronized (mPackages) { 11812 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11813 updatePermissionsLPw(newPkg.packageName, newPkg, 11814 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11815 if (applyUserRestrictions) { 11816 if (DEBUG_REMOVE) { 11817 Slog.d(TAG, "Propagating install state across reinstall"); 11818 } 11819 for (int i = 0; i < allUserHandles.length; i++) { 11820 if (DEBUG_REMOVE) { 11821 Slog.d(TAG, " user " + allUserHandles[i] 11822 + " => " + perUserInstalled[i]); 11823 } 11824 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11825 } 11826 // Regardless of writeSettings we need to ensure that this restriction 11827 // state propagation is persisted 11828 mSettings.writeAllUsersPackageRestrictionsLPr(); 11829 } 11830 // can downgrade to reader here 11831 if (writeSettings) { 11832 mSettings.writeLPr(); 11833 } 11834 } 11835 return true; 11836 } 11837 11838 private boolean deleteInstalledPackageLI(PackageSetting ps, 11839 boolean deleteCodeAndResources, int flags, 11840 int[] allUserHandles, boolean[] perUserInstalled, 11841 PackageRemovedInfo outInfo, boolean writeSettings) { 11842 if (outInfo != null) { 11843 outInfo.uid = ps.appId; 11844 } 11845 11846 // Delete package data from internal structures and also remove data if flag is set 11847 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11848 11849 // Delete application code and resources 11850 if (deleteCodeAndResources && (outInfo != null)) { 11851 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11852 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11853 getAppDexInstructionSets(ps)); 11854 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11855 } 11856 return true; 11857 } 11858 11859 @Override 11860 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11861 int userId) { 11862 mContext.enforceCallingOrSelfPermission( 11863 android.Manifest.permission.DELETE_PACKAGES, null); 11864 synchronized (mPackages) { 11865 PackageSetting ps = mSettings.mPackages.get(packageName); 11866 if (ps == null) { 11867 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11868 return false; 11869 } 11870 if (!ps.getInstalled(userId)) { 11871 // Can't block uninstall for an app that is not installed or enabled. 11872 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11873 return false; 11874 } 11875 ps.setBlockUninstall(blockUninstall, userId); 11876 mSettings.writePackageRestrictionsLPr(userId); 11877 } 11878 return true; 11879 } 11880 11881 @Override 11882 public boolean getBlockUninstallForUser(String packageName, int userId) { 11883 synchronized (mPackages) { 11884 PackageSetting ps = mSettings.mPackages.get(packageName); 11885 if (ps == null) { 11886 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11887 return false; 11888 } 11889 return ps.getBlockUninstall(userId); 11890 } 11891 } 11892 11893 /* 11894 * This method handles package deletion in general 11895 */ 11896 private boolean deletePackageLI(String packageName, UserHandle user, 11897 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11898 int flags, PackageRemovedInfo outInfo, 11899 boolean writeSettings) { 11900 if (packageName == null) { 11901 Slog.w(TAG, "Attempt to delete null packageName."); 11902 return false; 11903 } 11904 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11905 PackageSetting ps; 11906 boolean dataOnly = false; 11907 int removeUser = -1; 11908 int appId = -1; 11909 synchronized (mPackages) { 11910 ps = mSettings.mPackages.get(packageName); 11911 if (ps == null) { 11912 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11913 return false; 11914 } 11915 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11916 && user.getIdentifier() != UserHandle.USER_ALL) { 11917 // The caller is asking that the package only be deleted for a single 11918 // user. To do this, we just mark its uninstalled state and delete 11919 // its data. If this is a system app, we only allow this to happen if 11920 // they have set the special DELETE_SYSTEM_APP which requests different 11921 // semantics than normal for uninstalling system apps. 11922 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11923 ps.setUserState(user.getIdentifier(), 11924 COMPONENT_ENABLED_STATE_DEFAULT, 11925 false, //installed 11926 true, //stopped 11927 true, //notLaunched 11928 false, //hidden 11929 null, null, null, 11930 false, // blockUninstall 11931 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11932 if (!isSystemApp(ps)) { 11933 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11934 // Other user 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, "Still installed by other users"); 11938 removeUser = user.getIdentifier(); 11939 appId = ps.appId; 11940 mSettings.writePackageRestrictionsLPr(removeUser); 11941 } else { 11942 // We need to set it back to 'installed' so the uninstall 11943 // broadcasts will be sent correctly. 11944 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11945 ps.setInstalled(true, user.getIdentifier()); 11946 } 11947 } else { 11948 // This is a system app, so we assume that the 11949 // other users still have this package installed, so all 11950 // we need to do is clear this user's data and save that 11951 // it is uninstalled. 11952 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11953 removeUser = user.getIdentifier(); 11954 appId = ps.appId; 11955 mSettings.writePackageRestrictionsLPr(removeUser); 11956 } 11957 } 11958 } 11959 11960 if (removeUser >= 0) { 11961 // From above, we determined that we are deleting this only 11962 // for a single user. Continue the work here. 11963 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11964 if (outInfo != null) { 11965 outInfo.removedPackage = packageName; 11966 outInfo.removedAppId = appId; 11967 outInfo.removedUsers = new int[] {removeUser}; 11968 } 11969 mInstaller.clearUserData(packageName, removeUser); 11970 removeKeystoreDataIfNeeded(removeUser, appId); 11971 schedulePackageCleaning(packageName, removeUser, false); 11972 return true; 11973 } 11974 11975 if (dataOnly) { 11976 // Delete application data first 11977 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11978 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11979 return true; 11980 } 11981 11982 boolean ret = false; 11983 if (isSystemApp(ps)) { 11984 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11985 // When an updated system application is deleted we delete the existing resources as well and 11986 // fall back to existing code in system partition 11987 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11988 flags, outInfo, writeSettings); 11989 } else { 11990 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11991 // Kill application pre-emptively especially for apps on sd. 11992 killApplication(packageName, ps.appId, "uninstall pkg"); 11993 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11994 allUserHandles, perUserInstalled, 11995 outInfo, writeSettings); 11996 } 11997 11998 return ret; 11999 } 12000 12001 private final class ClearStorageConnection implements ServiceConnection { 12002 IMediaContainerService mContainerService; 12003 12004 @Override 12005 public void onServiceConnected(ComponentName name, IBinder service) { 12006 synchronized (this) { 12007 mContainerService = IMediaContainerService.Stub.asInterface(service); 12008 notifyAll(); 12009 } 12010 } 12011 12012 @Override 12013 public void onServiceDisconnected(ComponentName name) { 12014 } 12015 } 12016 12017 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12018 final boolean mounted; 12019 if (Environment.isExternalStorageEmulated()) { 12020 mounted = true; 12021 } else { 12022 final String status = Environment.getExternalStorageState(); 12023 12024 mounted = status.equals(Environment.MEDIA_MOUNTED) 12025 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12026 } 12027 12028 if (!mounted) { 12029 return; 12030 } 12031 12032 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12033 int[] users; 12034 if (userId == UserHandle.USER_ALL) { 12035 users = sUserManager.getUserIds(); 12036 } else { 12037 users = new int[] { userId }; 12038 } 12039 final ClearStorageConnection conn = new ClearStorageConnection(); 12040 if (mContext.bindServiceAsUser( 12041 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12042 try { 12043 for (int curUser : users) { 12044 long timeout = SystemClock.uptimeMillis() + 5000; 12045 synchronized (conn) { 12046 long now = SystemClock.uptimeMillis(); 12047 while (conn.mContainerService == null && now < timeout) { 12048 try { 12049 conn.wait(timeout - now); 12050 } catch (InterruptedException e) { 12051 } 12052 } 12053 } 12054 if (conn.mContainerService == null) { 12055 return; 12056 } 12057 12058 final UserEnvironment userEnv = new UserEnvironment(curUser); 12059 clearDirectory(conn.mContainerService, 12060 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12061 if (allData) { 12062 clearDirectory(conn.mContainerService, 12063 userEnv.buildExternalStorageAppDataDirs(packageName)); 12064 clearDirectory(conn.mContainerService, 12065 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12066 } 12067 } 12068 } finally { 12069 mContext.unbindService(conn); 12070 } 12071 } 12072 } 12073 12074 @Override 12075 public void clearApplicationUserData(final String packageName, 12076 final IPackageDataObserver observer, final int userId) { 12077 mContext.enforceCallingOrSelfPermission( 12078 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12079 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12080 // Queue up an async operation since the package deletion may take a little while. 12081 mHandler.post(new Runnable() { 12082 public void run() { 12083 mHandler.removeCallbacks(this); 12084 final boolean succeeded; 12085 synchronized (mInstallLock) { 12086 succeeded = clearApplicationUserDataLI(packageName, userId); 12087 } 12088 clearExternalStorageDataSync(packageName, userId, true); 12089 if (succeeded) { 12090 // invoke DeviceStorageMonitor's update method to clear any notifications 12091 DeviceStorageMonitorInternal 12092 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12093 if (dsm != null) { 12094 dsm.checkMemory(); 12095 } 12096 } 12097 if(observer != null) { 12098 try { 12099 observer.onRemoveCompleted(packageName, succeeded); 12100 } catch (RemoteException e) { 12101 Log.i(TAG, "Observer no longer exists."); 12102 } 12103 } //end if observer 12104 } //end run 12105 }); 12106 } 12107 12108 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12109 if (packageName == null) { 12110 Slog.w(TAG, "Attempt to delete null packageName."); 12111 return false; 12112 } 12113 12114 // Try finding details about the requested package 12115 PackageParser.Package pkg; 12116 synchronized (mPackages) { 12117 pkg = mPackages.get(packageName); 12118 if (pkg == null) { 12119 final PackageSetting ps = mSettings.mPackages.get(packageName); 12120 if (ps != null) { 12121 pkg = ps.pkg; 12122 } 12123 } 12124 } 12125 12126 if (pkg == null) { 12127 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12128 } 12129 12130 // Always delete data directories for package, even if we found no other 12131 // record of app. This helps users recover from UID mismatches without 12132 // resorting to a full data wipe. 12133 int retCode = mInstaller.clearUserData(packageName, userId); 12134 if (retCode < 0) { 12135 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12136 return false; 12137 } 12138 12139 if (pkg == null) { 12140 return false; 12141 } 12142 12143 if (pkg != null && pkg.applicationInfo != null) { 12144 final int appId = pkg.applicationInfo.uid; 12145 removeKeystoreDataIfNeeded(userId, appId); 12146 } 12147 12148 // Create a native library symlink only if we have native libraries 12149 // and if the native libraries are 32 bit libraries. We do not provide 12150 // this symlink for 64 bit libraries. 12151 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12152 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12153 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12154 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12155 Slog.w(TAG, "Failed linking native library dir"); 12156 return false; 12157 } 12158 } 12159 12160 return true; 12161 } 12162 12163 /** 12164 * Remove entries from the keystore daemon. Will only remove it if the 12165 * {@code appId} is valid. 12166 */ 12167 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12168 if (appId < 0) { 12169 return; 12170 } 12171 12172 final KeyStore keyStore = KeyStore.getInstance(); 12173 if (keyStore != null) { 12174 if (userId == UserHandle.USER_ALL) { 12175 for (final int individual : sUserManager.getUserIds()) { 12176 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12177 } 12178 } else { 12179 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12180 } 12181 } else { 12182 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12183 } 12184 } 12185 12186 @Override 12187 public void deleteApplicationCacheFiles(final String packageName, 12188 final IPackageDataObserver observer) { 12189 mContext.enforceCallingOrSelfPermission( 12190 android.Manifest.permission.DELETE_CACHE_FILES, null); 12191 // Queue up an async operation since the package deletion may take a little while. 12192 final int userId = UserHandle.getCallingUserId(); 12193 mHandler.post(new Runnable() { 12194 public void run() { 12195 mHandler.removeCallbacks(this); 12196 final boolean succeded; 12197 synchronized (mInstallLock) { 12198 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12199 } 12200 clearExternalStorageDataSync(packageName, userId, false); 12201 if(observer != null) { 12202 try { 12203 observer.onRemoveCompleted(packageName, succeded); 12204 } catch (RemoteException e) { 12205 Log.i(TAG, "Observer no longer exists."); 12206 } 12207 } //end if observer 12208 } //end run 12209 }); 12210 } 12211 12212 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12213 if (packageName == null) { 12214 Slog.w(TAG, "Attempt to delete null packageName."); 12215 return false; 12216 } 12217 PackageParser.Package p; 12218 synchronized (mPackages) { 12219 p = mPackages.get(packageName); 12220 } 12221 if (p == null) { 12222 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12223 return false; 12224 } 12225 final ApplicationInfo applicationInfo = p.applicationInfo; 12226 if (applicationInfo == null) { 12227 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12228 return false; 12229 } 12230 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12231 if (retCode < 0) { 12232 Slog.w(TAG, "Couldn't remove cache files for package: " 12233 + packageName + " u" + userId); 12234 return false; 12235 } 12236 return true; 12237 } 12238 12239 @Override 12240 public void getPackageSizeInfo(final String packageName, int userHandle, 12241 final IPackageStatsObserver observer) { 12242 mContext.enforceCallingOrSelfPermission( 12243 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12244 if (packageName == null) { 12245 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12246 } 12247 12248 PackageStats stats = new PackageStats(packageName, userHandle); 12249 12250 /* 12251 * Queue up an async operation since the package measurement may take a 12252 * little while. 12253 */ 12254 Message msg = mHandler.obtainMessage(INIT_COPY); 12255 msg.obj = new MeasureParams(stats, observer); 12256 mHandler.sendMessage(msg); 12257 } 12258 12259 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12260 PackageStats pStats) { 12261 if (packageName == null) { 12262 Slog.w(TAG, "Attempt to get size of null packageName."); 12263 return false; 12264 } 12265 PackageParser.Package p; 12266 boolean dataOnly = false; 12267 String libDirRoot = null; 12268 String asecPath = null; 12269 PackageSetting ps = null; 12270 synchronized (mPackages) { 12271 p = mPackages.get(packageName); 12272 ps = mSettings.mPackages.get(packageName); 12273 if(p == null) { 12274 dataOnly = true; 12275 if((ps == null) || (ps.pkg == null)) { 12276 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12277 return false; 12278 } 12279 p = ps.pkg; 12280 } 12281 if (ps != null) { 12282 libDirRoot = ps.legacyNativeLibraryPathString; 12283 } 12284 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12285 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12286 if (secureContainerId != null) { 12287 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12288 } 12289 } 12290 } 12291 String publicSrcDir = null; 12292 if(!dataOnly) { 12293 final ApplicationInfo applicationInfo = p.applicationInfo; 12294 if (applicationInfo == null) { 12295 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12296 return false; 12297 } 12298 if (p.isForwardLocked()) { 12299 publicSrcDir = applicationInfo.getBaseResourcePath(); 12300 } 12301 } 12302 // TODO: extend to measure size of split APKs 12303 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12304 // not just the first level. 12305 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12306 // just the primary. 12307 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12308 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12309 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12310 if (res < 0) { 12311 return false; 12312 } 12313 12314 // Fix-up for forward-locked applications in ASEC containers. 12315 if (!isExternal(p)) { 12316 pStats.codeSize += pStats.externalCodeSize; 12317 pStats.externalCodeSize = 0L; 12318 } 12319 12320 return true; 12321 } 12322 12323 12324 @Override 12325 public void addPackageToPreferred(String packageName) { 12326 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12327 } 12328 12329 @Override 12330 public void removePackageFromPreferred(String packageName) { 12331 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12332 } 12333 12334 @Override 12335 public List<PackageInfo> getPreferredPackages(int flags) { 12336 return new ArrayList<PackageInfo>(); 12337 } 12338 12339 private int getUidTargetSdkVersionLockedLPr(int uid) { 12340 Object obj = mSettings.getUserIdLPr(uid); 12341 if (obj instanceof SharedUserSetting) { 12342 final SharedUserSetting sus = (SharedUserSetting) obj; 12343 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12344 final Iterator<PackageSetting> it = sus.packages.iterator(); 12345 while (it.hasNext()) { 12346 final PackageSetting ps = it.next(); 12347 if (ps.pkg != null) { 12348 int v = ps.pkg.applicationInfo.targetSdkVersion; 12349 if (v < vers) vers = v; 12350 } 12351 } 12352 return vers; 12353 } else if (obj instanceof PackageSetting) { 12354 final PackageSetting ps = (PackageSetting) obj; 12355 if (ps.pkg != null) { 12356 return ps.pkg.applicationInfo.targetSdkVersion; 12357 } 12358 } 12359 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12360 } 12361 12362 @Override 12363 public void addPreferredActivity(IntentFilter filter, int match, 12364 ComponentName[] set, ComponentName activity, int userId) { 12365 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12366 "Adding preferred"); 12367 } 12368 12369 private void addPreferredActivityInternal(IntentFilter filter, int match, 12370 ComponentName[] set, ComponentName activity, boolean always, int userId, 12371 String opname) { 12372 // writer 12373 int callingUid = Binder.getCallingUid(); 12374 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12375 if (filter.countActions() == 0) { 12376 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12377 return; 12378 } 12379 synchronized (mPackages) { 12380 if (mContext.checkCallingOrSelfPermission( 12381 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12382 != PackageManager.PERMISSION_GRANTED) { 12383 if (getUidTargetSdkVersionLockedLPr(callingUid) 12384 < Build.VERSION_CODES.FROYO) { 12385 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12386 + callingUid); 12387 return; 12388 } 12389 mContext.enforceCallingOrSelfPermission( 12390 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12391 } 12392 12393 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12394 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12395 + userId + ":"); 12396 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12397 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12398 scheduleWritePackageRestrictionsLocked(userId); 12399 } 12400 } 12401 12402 @Override 12403 public void replacePreferredActivity(IntentFilter filter, int match, 12404 ComponentName[] set, ComponentName activity, int userId) { 12405 if (filter.countActions() != 1) { 12406 throw new IllegalArgumentException( 12407 "replacePreferredActivity expects filter to have only 1 action."); 12408 } 12409 if (filter.countDataAuthorities() != 0 12410 || filter.countDataPaths() != 0 12411 || filter.countDataSchemes() > 1 12412 || filter.countDataTypes() != 0) { 12413 throw new IllegalArgumentException( 12414 "replacePreferredActivity expects filter to have no data authorities, " + 12415 "paths, or types; and at most one scheme."); 12416 } 12417 12418 final int callingUid = Binder.getCallingUid(); 12419 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12420 synchronized (mPackages) { 12421 if (mContext.checkCallingOrSelfPermission( 12422 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12423 != PackageManager.PERMISSION_GRANTED) { 12424 if (getUidTargetSdkVersionLockedLPr(callingUid) 12425 < Build.VERSION_CODES.FROYO) { 12426 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12427 + Binder.getCallingUid()); 12428 return; 12429 } 12430 mContext.enforceCallingOrSelfPermission( 12431 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12432 } 12433 12434 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12435 if (pir != null) { 12436 // Get all of the existing entries that exactly match this filter. 12437 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12438 if (existing != null && existing.size() == 1) { 12439 PreferredActivity cur = existing.get(0); 12440 if (DEBUG_PREFERRED) { 12441 Slog.i(TAG, "Checking replace of preferred:"); 12442 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12443 if (!cur.mPref.mAlways) { 12444 Slog.i(TAG, " -- CUR; not mAlways!"); 12445 } else { 12446 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12447 Slog.i(TAG, " -- CUR: mSet=" 12448 + Arrays.toString(cur.mPref.mSetComponents)); 12449 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12450 Slog.i(TAG, " -- NEW: mMatch=" 12451 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12452 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12453 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12454 } 12455 } 12456 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12457 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12458 && cur.mPref.sameSet(set)) { 12459 // Setting the preferred activity to what it happens to be already 12460 if (DEBUG_PREFERRED) { 12461 Slog.i(TAG, "Replacing with same preferred activity " 12462 + cur.mPref.mShortComponent + " for user " 12463 + userId + ":"); 12464 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12465 } 12466 return; 12467 } 12468 } 12469 12470 if (existing != null) { 12471 if (DEBUG_PREFERRED) { 12472 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12473 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12474 } 12475 for (int i = 0; i < existing.size(); i++) { 12476 PreferredActivity pa = existing.get(i); 12477 if (DEBUG_PREFERRED) { 12478 Slog.i(TAG, "Removing existing preferred activity " 12479 + pa.mPref.mComponent + ":"); 12480 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12481 } 12482 pir.removeFilter(pa); 12483 } 12484 } 12485 } 12486 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12487 "Replacing preferred"); 12488 } 12489 } 12490 12491 @Override 12492 public void clearPackagePreferredActivities(String packageName) { 12493 final int uid = Binder.getCallingUid(); 12494 // writer 12495 synchronized (mPackages) { 12496 PackageParser.Package pkg = mPackages.get(packageName); 12497 if (pkg == null || pkg.applicationInfo.uid != uid) { 12498 if (mContext.checkCallingOrSelfPermission( 12499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12500 != PackageManager.PERMISSION_GRANTED) { 12501 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12502 < Build.VERSION_CODES.FROYO) { 12503 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12504 + Binder.getCallingUid()); 12505 return; 12506 } 12507 mContext.enforceCallingOrSelfPermission( 12508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12509 } 12510 } 12511 12512 int user = UserHandle.getCallingUserId(); 12513 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12514 scheduleWritePackageRestrictionsLocked(user); 12515 } 12516 } 12517 } 12518 12519 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12520 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12521 ArrayList<PreferredActivity> removed = null; 12522 boolean changed = false; 12523 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12524 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12525 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12526 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12527 continue; 12528 } 12529 Iterator<PreferredActivity> it = pir.filterIterator(); 12530 while (it.hasNext()) { 12531 PreferredActivity pa = it.next(); 12532 // Mark entry for removal only if it matches the package name 12533 // and the entry is of type "always". 12534 if (packageName == null || 12535 (pa.mPref.mComponent.getPackageName().equals(packageName) 12536 && pa.mPref.mAlways)) { 12537 if (removed == null) { 12538 removed = new ArrayList<PreferredActivity>(); 12539 } 12540 removed.add(pa); 12541 } 12542 } 12543 if (removed != null) { 12544 for (int j=0; j<removed.size(); j++) { 12545 PreferredActivity pa = removed.get(j); 12546 pir.removeFilter(pa); 12547 } 12548 changed = true; 12549 } 12550 } 12551 return changed; 12552 } 12553 12554 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12555 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12556 if (userId == UserHandle.USER_ALL) { 12557 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12558 for (int oneUserId : sUserManager.getUserIds()) { 12559 scheduleWritePackageRestrictionsLocked(oneUserId); 12560 } 12561 } else { 12562 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12563 scheduleWritePackageRestrictionsLocked(userId); 12564 } 12565 } 12566 12567 @Override 12568 public void resetPreferredActivities(int userId) { 12569 /* TODO: Actually use userId. Why is it being passed in? */ 12570 mContext.enforceCallingOrSelfPermission( 12571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12572 // writer 12573 synchronized (mPackages) { 12574 int user = UserHandle.getCallingUserId(); 12575 clearPackagePreferredActivitiesLPw(null, user); 12576 mSettings.readDefaultPreferredAppsLPw(this, user); 12577 scheduleWritePackageRestrictionsLocked(user); 12578 } 12579 } 12580 12581 @Override 12582 public int getPreferredActivities(List<IntentFilter> outFilters, 12583 List<ComponentName> outActivities, String packageName) { 12584 12585 int num = 0; 12586 final int userId = UserHandle.getCallingUserId(); 12587 // reader 12588 synchronized (mPackages) { 12589 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12590 if (pir != null) { 12591 final Iterator<PreferredActivity> it = pir.filterIterator(); 12592 while (it.hasNext()) { 12593 final PreferredActivity pa = it.next(); 12594 if (packageName == null 12595 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12596 && pa.mPref.mAlways)) { 12597 if (outFilters != null) { 12598 outFilters.add(new IntentFilter(pa)); 12599 } 12600 if (outActivities != null) { 12601 outActivities.add(pa.mPref.mComponent); 12602 } 12603 } 12604 } 12605 } 12606 } 12607 12608 return num; 12609 } 12610 12611 @Override 12612 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12613 int userId) { 12614 int callingUid = Binder.getCallingUid(); 12615 if (callingUid != Process.SYSTEM_UID) { 12616 throw new SecurityException( 12617 "addPersistentPreferredActivity can only be run by the system"); 12618 } 12619 if (filter.countActions() == 0) { 12620 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12621 return; 12622 } 12623 synchronized (mPackages) { 12624 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12625 " :"); 12626 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12627 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12628 new PersistentPreferredActivity(filter, activity)); 12629 scheduleWritePackageRestrictionsLocked(userId); 12630 } 12631 } 12632 12633 @Override 12634 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12635 int callingUid = Binder.getCallingUid(); 12636 if (callingUid != Process.SYSTEM_UID) { 12637 throw new SecurityException( 12638 "clearPackagePersistentPreferredActivities can only be run by the system"); 12639 } 12640 ArrayList<PersistentPreferredActivity> removed = null; 12641 boolean changed = false; 12642 synchronized (mPackages) { 12643 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12644 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12645 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12646 .valueAt(i); 12647 if (userId != thisUserId) { 12648 continue; 12649 } 12650 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12651 while (it.hasNext()) { 12652 PersistentPreferredActivity ppa = it.next(); 12653 // Mark entry for removal only if it matches the package name. 12654 if (ppa.mComponent.getPackageName().equals(packageName)) { 12655 if (removed == null) { 12656 removed = new ArrayList<PersistentPreferredActivity>(); 12657 } 12658 removed.add(ppa); 12659 } 12660 } 12661 if (removed != null) { 12662 for (int j=0; j<removed.size(); j++) { 12663 PersistentPreferredActivity ppa = removed.get(j); 12664 ppir.removeFilter(ppa); 12665 } 12666 changed = true; 12667 } 12668 } 12669 12670 if (changed) { 12671 scheduleWritePackageRestrictionsLocked(userId); 12672 } 12673 } 12674 } 12675 12676 /** 12677 * Non-Binder method, support for the backup/restore mechanism: write the 12678 * full set of preferred activities in its canonical XML format. Returns true 12679 * on success; false otherwise. 12680 */ 12681 @Override 12682 public byte[] getPreferredActivityBackup(int userId) { 12683 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12684 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12685 } 12686 12687 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12688 try { 12689 final XmlSerializer serializer = new FastXmlSerializer(); 12690 serializer.setOutput(dataStream, "utf-8"); 12691 serializer.startDocument(null, true); 12692 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12693 12694 synchronized (mPackages) { 12695 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12696 } 12697 12698 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12699 serializer.endDocument(); 12700 serializer.flush(); 12701 } catch (Exception e) { 12702 if (DEBUG_BACKUP) { 12703 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12704 } 12705 return null; 12706 } 12707 12708 return dataStream.toByteArray(); 12709 } 12710 12711 @Override 12712 public void restorePreferredActivities(byte[] backup, int userId) { 12713 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12714 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12715 } 12716 12717 try { 12718 final XmlPullParser parser = Xml.newPullParser(); 12719 parser.setInput(new ByteArrayInputStream(backup), null); 12720 12721 int type; 12722 while ((type = parser.next()) != XmlPullParser.START_TAG 12723 && type != XmlPullParser.END_DOCUMENT) { 12724 } 12725 if (type != XmlPullParser.START_TAG) { 12726 // oops didn't find a start tag?! 12727 if (DEBUG_BACKUP) { 12728 Slog.e(TAG, "Didn't find start tag during restore"); 12729 } 12730 return; 12731 } 12732 12733 // this is supposed to be TAG_PREFERRED_BACKUP 12734 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12735 if (DEBUG_BACKUP) { 12736 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12737 } 12738 return; 12739 } 12740 12741 // skip interfering stuff, then we're aligned with the backing implementation 12742 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12743 synchronized (mPackages) { 12744 mSettings.readPreferredActivitiesLPw(parser, userId); 12745 } 12746 } catch (Exception e) { 12747 if (DEBUG_BACKUP) { 12748 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12749 } 12750 } 12751 } 12752 12753 @Override 12754 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12755 int sourceUserId, int targetUserId, int flags) { 12756 mContext.enforceCallingOrSelfPermission( 12757 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12758 int callingUid = Binder.getCallingUid(); 12759 enforceOwnerRights(ownerPackage, callingUid); 12760 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12761 if (intentFilter.countActions() == 0) { 12762 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12763 return; 12764 } 12765 synchronized (mPackages) { 12766 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12767 ownerPackage, targetUserId, flags); 12768 CrossProfileIntentResolver resolver = 12769 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12770 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12771 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12772 if (existing != null) { 12773 int size = existing.size(); 12774 for (int i = 0; i < size; i++) { 12775 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12776 return; 12777 } 12778 } 12779 } 12780 resolver.addFilter(newFilter); 12781 scheduleWritePackageRestrictionsLocked(sourceUserId); 12782 } 12783 } 12784 12785 @Override 12786 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12787 mContext.enforceCallingOrSelfPermission( 12788 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12789 int callingUid = Binder.getCallingUid(); 12790 enforceOwnerRights(ownerPackage, callingUid); 12791 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12792 synchronized (mPackages) { 12793 CrossProfileIntentResolver resolver = 12794 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12795 ArraySet<CrossProfileIntentFilter> set = 12796 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12797 for (CrossProfileIntentFilter filter : set) { 12798 if (filter.getOwnerPackage().equals(ownerPackage)) { 12799 resolver.removeFilter(filter); 12800 } 12801 } 12802 scheduleWritePackageRestrictionsLocked(sourceUserId); 12803 } 12804 } 12805 12806 // Enforcing that callingUid is owning pkg on userId 12807 private void enforceOwnerRights(String pkg, int callingUid) { 12808 // The system owns everything. 12809 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12810 return; 12811 } 12812 int callingUserId = UserHandle.getUserId(callingUid); 12813 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12814 if (pi == null) { 12815 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12816 + callingUserId); 12817 } 12818 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12819 throw new SecurityException("Calling uid " + callingUid 12820 + " does not own package " + pkg); 12821 } 12822 } 12823 12824 @Override 12825 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12826 Intent intent = new Intent(Intent.ACTION_MAIN); 12827 intent.addCategory(Intent.CATEGORY_HOME); 12828 12829 final int callingUserId = UserHandle.getCallingUserId(); 12830 List<ResolveInfo> list = queryIntentActivities(intent, null, 12831 PackageManager.GET_META_DATA, callingUserId); 12832 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12833 true, false, false, callingUserId); 12834 12835 allHomeCandidates.clear(); 12836 if (list != null) { 12837 for (ResolveInfo ri : list) { 12838 allHomeCandidates.add(ri); 12839 } 12840 } 12841 return (preferred == null || preferred.activityInfo == null) 12842 ? null 12843 : new ComponentName(preferred.activityInfo.packageName, 12844 preferred.activityInfo.name); 12845 } 12846 12847 @Override 12848 public void setApplicationEnabledSetting(String appPackageName, 12849 int newState, int flags, int userId, String callingPackage) { 12850 if (!sUserManager.exists(userId)) return; 12851 if (callingPackage == null) { 12852 callingPackage = Integer.toString(Binder.getCallingUid()); 12853 } 12854 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12855 } 12856 12857 @Override 12858 public void setComponentEnabledSetting(ComponentName componentName, 12859 int newState, int flags, int userId) { 12860 if (!sUserManager.exists(userId)) return; 12861 setEnabledSetting(componentName.getPackageName(), 12862 componentName.getClassName(), newState, flags, userId, null); 12863 } 12864 12865 private void setEnabledSetting(final String packageName, String className, int newState, 12866 final int flags, int userId, String callingPackage) { 12867 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12868 || newState == COMPONENT_ENABLED_STATE_ENABLED 12869 || newState == COMPONENT_ENABLED_STATE_DISABLED 12870 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12871 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12872 throw new IllegalArgumentException("Invalid new component state: " 12873 + newState); 12874 } 12875 PackageSetting pkgSetting; 12876 final int uid = Binder.getCallingUid(); 12877 final int permission = mContext.checkCallingOrSelfPermission( 12878 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12879 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12880 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12881 boolean sendNow = false; 12882 boolean isApp = (className == null); 12883 String componentName = isApp ? packageName : className; 12884 int packageUid = -1; 12885 ArrayList<String> components; 12886 12887 // writer 12888 synchronized (mPackages) { 12889 pkgSetting = mSettings.mPackages.get(packageName); 12890 if (pkgSetting == null) { 12891 if (className == null) { 12892 throw new IllegalArgumentException( 12893 "Unknown package: " + packageName); 12894 } 12895 throw new IllegalArgumentException( 12896 "Unknown component: " + packageName 12897 + "/" + className); 12898 } 12899 // Allow root and verify that userId is not being specified by a different user 12900 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12901 throw new SecurityException( 12902 "Permission Denial: attempt to change component state from pid=" 12903 + Binder.getCallingPid() 12904 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12905 } 12906 if (className == null) { 12907 // We're dealing with an application/package level state change 12908 if (pkgSetting.getEnabled(userId) == newState) { 12909 // Nothing to do 12910 return; 12911 } 12912 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12913 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12914 // Don't care about who enables an app. 12915 callingPackage = null; 12916 } 12917 pkgSetting.setEnabled(newState, userId, callingPackage); 12918 // pkgSetting.pkg.mSetEnabled = newState; 12919 } else { 12920 // We're dealing with a component level state change 12921 // First, verify that this is a valid class name. 12922 PackageParser.Package pkg = pkgSetting.pkg; 12923 if (pkg == null || !pkg.hasComponentClassName(className)) { 12924 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12925 throw new IllegalArgumentException("Component class " + className 12926 + " does not exist in " + packageName); 12927 } else { 12928 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12929 + className + " does not exist in " + packageName); 12930 } 12931 } 12932 switch (newState) { 12933 case COMPONENT_ENABLED_STATE_ENABLED: 12934 if (!pkgSetting.enableComponentLPw(className, userId)) { 12935 return; 12936 } 12937 break; 12938 case COMPONENT_ENABLED_STATE_DISABLED: 12939 if (!pkgSetting.disableComponentLPw(className, userId)) { 12940 return; 12941 } 12942 break; 12943 case COMPONENT_ENABLED_STATE_DEFAULT: 12944 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12945 return; 12946 } 12947 break; 12948 default: 12949 Slog.e(TAG, "Invalid new component state: " + newState); 12950 return; 12951 } 12952 } 12953 scheduleWritePackageRestrictionsLocked(userId); 12954 components = mPendingBroadcasts.get(userId, packageName); 12955 final boolean newPackage = components == null; 12956 if (newPackage) { 12957 components = new ArrayList<String>(); 12958 } 12959 if (!components.contains(componentName)) { 12960 components.add(componentName); 12961 } 12962 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12963 sendNow = true; 12964 // Purge entry from pending broadcast list if another one exists already 12965 // since we are sending one right away. 12966 mPendingBroadcasts.remove(userId, packageName); 12967 } else { 12968 if (newPackage) { 12969 mPendingBroadcasts.put(userId, packageName, components); 12970 } 12971 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12972 // Schedule a message 12973 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12974 } 12975 } 12976 } 12977 12978 long callingId = Binder.clearCallingIdentity(); 12979 try { 12980 if (sendNow) { 12981 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12982 sendPackageChangedBroadcast(packageName, 12983 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12984 } 12985 } finally { 12986 Binder.restoreCallingIdentity(callingId); 12987 } 12988 } 12989 12990 private void sendPackageChangedBroadcast(String packageName, 12991 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12992 if (DEBUG_INSTALL) 12993 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12994 + componentNames); 12995 Bundle extras = new Bundle(4); 12996 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12997 String nameList[] = new String[componentNames.size()]; 12998 componentNames.toArray(nameList); 12999 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13000 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13001 extras.putInt(Intent.EXTRA_UID, packageUid); 13002 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13003 new int[] {UserHandle.getUserId(packageUid)}); 13004 } 13005 13006 @Override 13007 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13008 if (!sUserManager.exists(userId)) return; 13009 final int uid = Binder.getCallingUid(); 13010 final int permission = mContext.checkCallingOrSelfPermission( 13011 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13012 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13013 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13014 // writer 13015 synchronized (mPackages) { 13016 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13017 uid, userId)) { 13018 scheduleWritePackageRestrictionsLocked(userId); 13019 } 13020 } 13021 } 13022 13023 @Override 13024 public String getInstallerPackageName(String packageName) { 13025 // reader 13026 synchronized (mPackages) { 13027 return mSettings.getInstallerPackageNameLPr(packageName); 13028 } 13029 } 13030 13031 @Override 13032 public int getApplicationEnabledSetting(String packageName, int userId) { 13033 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13034 int uid = Binder.getCallingUid(); 13035 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13036 // reader 13037 synchronized (mPackages) { 13038 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13039 } 13040 } 13041 13042 @Override 13043 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13044 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13045 int uid = Binder.getCallingUid(); 13046 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13047 // reader 13048 synchronized (mPackages) { 13049 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13050 } 13051 } 13052 13053 @Override 13054 public void enterSafeMode() { 13055 enforceSystemOrRoot("Only the system can request entering safe mode"); 13056 13057 if (!mSystemReady) { 13058 mSafeMode = true; 13059 } 13060 } 13061 13062 @Override 13063 public void systemReady() { 13064 mSystemReady = true; 13065 13066 // Read the compatibilty setting when the system is ready. 13067 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13068 mContext.getContentResolver(), 13069 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13070 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13071 if (DEBUG_SETTINGS) { 13072 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13073 } 13074 13075 synchronized (mPackages) { 13076 // Verify that all of the preferred activity components actually 13077 // exist. It is possible for applications to be updated and at 13078 // that point remove a previously declared activity component that 13079 // had been set as a preferred activity. We try to clean this up 13080 // the next time we encounter that preferred activity, but it is 13081 // possible for the user flow to never be able to return to that 13082 // situation so here we do a sanity check to make sure we haven't 13083 // left any junk around. 13084 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13085 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13086 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13087 removed.clear(); 13088 for (PreferredActivity pa : pir.filterSet()) { 13089 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13090 removed.add(pa); 13091 } 13092 } 13093 if (removed.size() > 0) { 13094 for (int r=0; r<removed.size(); r++) { 13095 PreferredActivity pa = removed.get(r); 13096 Slog.w(TAG, "Removing dangling preferred activity: " 13097 + pa.mPref.mComponent); 13098 pir.removeFilter(pa); 13099 } 13100 mSettings.writePackageRestrictionsLPr( 13101 mSettings.mPreferredActivities.keyAt(i)); 13102 } 13103 } 13104 } 13105 sUserManager.systemReady(); 13106 13107 // Kick off any messages waiting for system ready 13108 if (mPostSystemReadyMessages != null) { 13109 for (Message msg : mPostSystemReadyMessages) { 13110 msg.sendToTarget(); 13111 } 13112 mPostSystemReadyMessages = null; 13113 } 13114 13115 // Watch for external volumes that come and go over time 13116 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13117 storage.registerListener(mStorageListener); 13118 13119 mInstallerService.systemReady(); 13120 } 13121 13122 @Override 13123 public boolean isSafeMode() { 13124 return mSafeMode; 13125 } 13126 13127 @Override 13128 public boolean hasSystemUidErrors() { 13129 return mHasSystemUidErrors; 13130 } 13131 13132 static String arrayToString(int[] array) { 13133 StringBuffer buf = new StringBuffer(128); 13134 buf.append('['); 13135 if (array != null) { 13136 for (int i=0; i<array.length; i++) { 13137 if (i > 0) buf.append(", "); 13138 buf.append(array[i]); 13139 } 13140 } 13141 buf.append(']'); 13142 return buf.toString(); 13143 } 13144 13145 static class DumpState { 13146 public static final int DUMP_LIBS = 1 << 0; 13147 public static final int DUMP_FEATURES = 1 << 1; 13148 public static final int DUMP_RESOLVERS = 1 << 2; 13149 public static final int DUMP_PERMISSIONS = 1 << 3; 13150 public static final int DUMP_PACKAGES = 1 << 4; 13151 public static final int DUMP_SHARED_USERS = 1 << 5; 13152 public static final int DUMP_MESSAGES = 1 << 6; 13153 public static final int DUMP_PROVIDERS = 1 << 7; 13154 public static final int DUMP_VERIFIERS = 1 << 8; 13155 public static final int DUMP_PREFERRED = 1 << 9; 13156 public static final int DUMP_PREFERRED_XML = 1 << 10; 13157 public static final int DUMP_KEYSETS = 1 << 11; 13158 public static final int DUMP_VERSION = 1 << 12; 13159 public static final int DUMP_INSTALLS = 1 << 13; 13160 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13161 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13162 13163 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13164 13165 private int mTypes; 13166 13167 private int mOptions; 13168 13169 private boolean mTitlePrinted; 13170 13171 private SharedUserSetting mSharedUser; 13172 13173 public boolean isDumping(int type) { 13174 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13175 return true; 13176 } 13177 13178 return (mTypes & type) != 0; 13179 } 13180 13181 public void setDump(int type) { 13182 mTypes |= type; 13183 } 13184 13185 public boolean isOptionEnabled(int option) { 13186 return (mOptions & option) != 0; 13187 } 13188 13189 public void setOptionEnabled(int option) { 13190 mOptions |= option; 13191 } 13192 13193 public boolean onTitlePrinted() { 13194 final boolean printed = mTitlePrinted; 13195 mTitlePrinted = true; 13196 return printed; 13197 } 13198 13199 public boolean getTitlePrinted() { 13200 return mTitlePrinted; 13201 } 13202 13203 public void setTitlePrinted(boolean enabled) { 13204 mTitlePrinted = enabled; 13205 } 13206 13207 public SharedUserSetting getSharedUser() { 13208 return mSharedUser; 13209 } 13210 13211 public void setSharedUser(SharedUserSetting user) { 13212 mSharedUser = user; 13213 } 13214 } 13215 13216 @Override 13217 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13218 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13219 != PackageManager.PERMISSION_GRANTED) { 13220 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13221 + Binder.getCallingPid() 13222 + ", uid=" + Binder.getCallingUid() 13223 + " without permission " 13224 + android.Manifest.permission.DUMP); 13225 return; 13226 } 13227 13228 DumpState dumpState = new DumpState(); 13229 boolean fullPreferred = false; 13230 boolean checkin = false; 13231 13232 String packageName = null; 13233 13234 int opti = 0; 13235 while (opti < args.length) { 13236 String opt = args[opti]; 13237 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13238 break; 13239 } 13240 opti++; 13241 13242 if ("-a".equals(opt)) { 13243 // Right now we only know how to print all. 13244 } else if ("-h".equals(opt)) { 13245 pw.println("Package manager dump options:"); 13246 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13247 pw.println(" --checkin: dump for a checkin"); 13248 pw.println(" -f: print details of intent filters"); 13249 pw.println(" -h: print this help"); 13250 pw.println(" cmd may be one of:"); 13251 pw.println(" l[ibraries]: list known shared libraries"); 13252 pw.println(" f[ibraries]: list device features"); 13253 pw.println(" k[eysets]: print known keysets"); 13254 pw.println(" r[esolvers]: dump intent resolvers"); 13255 pw.println(" perm[issions]: dump permissions"); 13256 pw.println(" pref[erred]: print preferred package settings"); 13257 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13258 pw.println(" prov[iders]: dump content providers"); 13259 pw.println(" p[ackages]: dump installed packages"); 13260 pw.println(" s[hared-users]: dump shared user IDs"); 13261 pw.println(" m[essages]: print collected runtime messages"); 13262 pw.println(" v[erifiers]: print package verifier info"); 13263 pw.println(" version: print database version info"); 13264 pw.println(" write: write current settings now"); 13265 pw.println(" <package.name>: info about given package"); 13266 pw.println(" installs: details about install sessions"); 13267 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13268 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13269 return; 13270 } else if ("--checkin".equals(opt)) { 13271 checkin = true; 13272 } else if ("-f".equals(opt)) { 13273 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13274 } else { 13275 pw.println("Unknown argument: " + opt + "; use -h for help"); 13276 } 13277 } 13278 13279 // Is the caller requesting to dump a particular piece of data? 13280 if (opti < args.length) { 13281 String cmd = args[opti]; 13282 opti++; 13283 // Is this a package name? 13284 if ("android".equals(cmd) || cmd.contains(".")) { 13285 packageName = cmd; 13286 // When dumping a single package, we always dump all of its 13287 // filter information since the amount of data will be reasonable. 13288 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13289 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13290 dumpState.setDump(DumpState.DUMP_LIBS); 13291 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13292 dumpState.setDump(DumpState.DUMP_FEATURES); 13293 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13294 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13295 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13296 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13297 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13298 dumpState.setDump(DumpState.DUMP_PREFERRED); 13299 } else if ("preferred-xml".equals(cmd)) { 13300 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13301 if (opti < args.length && "--full".equals(args[opti])) { 13302 fullPreferred = true; 13303 opti++; 13304 } 13305 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13306 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13307 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13308 dumpState.setDump(DumpState.DUMP_PACKAGES); 13309 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13310 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13311 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13312 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13313 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13314 dumpState.setDump(DumpState.DUMP_MESSAGES); 13315 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13316 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13317 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13318 || "intent-filter-verifiers".equals(cmd)) { 13319 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13320 } else if ("version".equals(cmd)) { 13321 dumpState.setDump(DumpState.DUMP_VERSION); 13322 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13323 dumpState.setDump(DumpState.DUMP_KEYSETS); 13324 } else if ("installs".equals(cmd)) { 13325 dumpState.setDump(DumpState.DUMP_INSTALLS); 13326 } else if ("write".equals(cmd)) { 13327 synchronized (mPackages) { 13328 mSettings.writeLPr(); 13329 pw.println("Settings written."); 13330 return; 13331 } 13332 } 13333 } 13334 13335 if (checkin) { 13336 pw.println("vers,1"); 13337 } 13338 13339 // reader 13340 synchronized (mPackages) { 13341 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13342 if (!checkin) { 13343 if (dumpState.onTitlePrinted()) 13344 pw.println(); 13345 pw.println("Database versions:"); 13346 pw.print(" SDK Version:"); 13347 pw.print(" internal="); 13348 pw.print(mSettings.mInternalSdkPlatform); 13349 pw.print(" external="); 13350 pw.println(mSettings.mExternalSdkPlatform); 13351 pw.print(" DB Version:"); 13352 pw.print(" internal="); 13353 pw.print(mSettings.mInternalDatabaseVersion); 13354 pw.print(" external="); 13355 pw.println(mSettings.mExternalDatabaseVersion); 13356 } 13357 } 13358 13359 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13360 if (!checkin) { 13361 if (dumpState.onTitlePrinted()) 13362 pw.println(); 13363 pw.println("Verifiers:"); 13364 pw.print(" Required: "); 13365 pw.print(mRequiredVerifierPackage); 13366 pw.print(" (uid="); 13367 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13368 pw.println(")"); 13369 } else if (mRequiredVerifierPackage != null) { 13370 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13371 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13372 } 13373 } 13374 13375 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13376 packageName == null) { 13377 if (mIntentFilterVerifierComponent != null) { 13378 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13379 if (!checkin) { 13380 if (dumpState.onTitlePrinted()) 13381 pw.println(); 13382 pw.println("Intent Filter Verifier:"); 13383 pw.print(" Using: "); 13384 pw.print(verifierPackageName); 13385 pw.print(" (uid="); 13386 pw.print(getPackageUid(verifierPackageName, 0)); 13387 pw.println(")"); 13388 } else if (verifierPackageName != null) { 13389 pw.print("ifv,"); pw.print(verifierPackageName); 13390 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13391 } 13392 } else { 13393 pw.println(); 13394 pw.println("No Intent Filter Verifier available!"); 13395 } 13396 } 13397 13398 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13399 boolean printedHeader = false; 13400 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13401 while (it.hasNext()) { 13402 String name = it.next(); 13403 SharedLibraryEntry ent = mSharedLibraries.get(name); 13404 if (!checkin) { 13405 if (!printedHeader) { 13406 if (dumpState.onTitlePrinted()) 13407 pw.println(); 13408 pw.println("Libraries:"); 13409 printedHeader = true; 13410 } 13411 pw.print(" "); 13412 } else { 13413 pw.print("lib,"); 13414 } 13415 pw.print(name); 13416 if (!checkin) { 13417 pw.print(" -> "); 13418 } 13419 if (ent.path != null) { 13420 if (!checkin) { 13421 pw.print("(jar) "); 13422 pw.print(ent.path); 13423 } else { 13424 pw.print(",jar,"); 13425 pw.print(ent.path); 13426 } 13427 } else { 13428 if (!checkin) { 13429 pw.print("(apk) "); 13430 pw.print(ent.apk); 13431 } else { 13432 pw.print(",apk,"); 13433 pw.print(ent.apk); 13434 } 13435 } 13436 pw.println(); 13437 } 13438 } 13439 13440 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13441 if (dumpState.onTitlePrinted()) 13442 pw.println(); 13443 if (!checkin) { 13444 pw.println("Features:"); 13445 } 13446 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13447 while (it.hasNext()) { 13448 String name = it.next(); 13449 if (!checkin) { 13450 pw.print(" "); 13451 } else { 13452 pw.print("feat,"); 13453 } 13454 pw.println(name); 13455 } 13456 } 13457 13458 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13459 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13460 : "Activity Resolver Table:", " ", packageName, 13461 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13462 dumpState.setTitlePrinted(true); 13463 } 13464 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13465 : "Receiver Resolver Table:", " ", packageName, 13466 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13467 dumpState.setTitlePrinted(true); 13468 } 13469 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13470 : "Service Resolver Table:", " ", packageName, 13471 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13472 dumpState.setTitlePrinted(true); 13473 } 13474 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13475 : "Provider Resolver Table:", " ", packageName, 13476 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13477 dumpState.setTitlePrinted(true); 13478 } 13479 } 13480 13481 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13482 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13483 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13484 int user = mSettings.mPreferredActivities.keyAt(i); 13485 if (pir.dump(pw, 13486 dumpState.getTitlePrinted() 13487 ? "\nPreferred Activities User " + user + ":" 13488 : "Preferred Activities User " + user + ":", " ", 13489 packageName, true, false)) { 13490 dumpState.setTitlePrinted(true); 13491 } 13492 } 13493 } 13494 13495 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13496 pw.flush(); 13497 FileOutputStream fout = new FileOutputStream(fd); 13498 BufferedOutputStream str = new BufferedOutputStream(fout); 13499 XmlSerializer serializer = new FastXmlSerializer(); 13500 try { 13501 serializer.setOutput(str, "utf-8"); 13502 serializer.startDocument(null, true); 13503 serializer.setFeature( 13504 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13505 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13506 serializer.endDocument(); 13507 serializer.flush(); 13508 } catch (IllegalArgumentException e) { 13509 pw.println("Failed writing: " + e); 13510 } catch (IllegalStateException e) { 13511 pw.println("Failed writing: " + e); 13512 } catch (IOException e) { 13513 pw.println("Failed writing: " + e); 13514 } 13515 } 13516 13517 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13518 pw.println(); 13519 int count = mSettings.mPackages.size(); 13520 if (count == 0) { 13521 pw.println("No domain preferred apps!"); 13522 pw.println(); 13523 } else { 13524 final String prefix = " "; 13525 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13526 if (allPackageSettings.size() == 0) { 13527 pw.println("No domain preferred apps!"); 13528 pw.println(); 13529 } else { 13530 pw.println("Domain preferred apps status:"); 13531 pw.println(); 13532 count = 0; 13533 for (PackageSetting ps : allPackageSettings) { 13534 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13535 if (ivi == null || ivi.getPackageName() == null) continue; 13536 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13537 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13538 pw.println(prefix + "Status: " + ivi.getStatusString()); 13539 pw.println(); 13540 count++; 13541 } 13542 if (count == 0) { 13543 pw.println(prefix + "No domain preferred app status!"); 13544 pw.println(); 13545 } 13546 for (int userId : sUserManager.getUserIds()) { 13547 pw.println("Domain preferred apps for User " + userId + ":"); 13548 pw.println(); 13549 count = 0; 13550 for (PackageSetting ps : allPackageSettings) { 13551 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13552 if (ivi == null || ivi.getPackageName() == null) { 13553 continue; 13554 } 13555 final int status = ps.getDomainVerificationStatusForUser(userId); 13556 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13557 continue; 13558 } 13559 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13560 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13561 String statusStr = IntentFilterVerificationInfo. 13562 getStatusStringFromValue(status); 13563 pw.println(prefix + "Status: " + statusStr); 13564 pw.println(); 13565 count++; 13566 } 13567 if (count == 0) { 13568 pw.println(prefix + "No domain preferred apps!"); 13569 pw.println(); 13570 } 13571 } 13572 } 13573 } 13574 } 13575 13576 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13577 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13578 if (packageName == null) { 13579 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13580 if (iperm == 0) { 13581 if (dumpState.onTitlePrinted()) 13582 pw.println(); 13583 pw.println("AppOp Permissions:"); 13584 } 13585 pw.print(" AppOp Permission "); 13586 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13587 pw.println(":"); 13588 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13589 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13590 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13591 } 13592 } 13593 } 13594 } 13595 13596 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13597 boolean printedSomething = false; 13598 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13599 if (packageName != null && !packageName.equals(p.info.packageName)) { 13600 continue; 13601 } 13602 if (!printedSomething) { 13603 if (dumpState.onTitlePrinted()) 13604 pw.println(); 13605 pw.println("Registered ContentProviders:"); 13606 printedSomething = true; 13607 } 13608 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13609 pw.print(" "); pw.println(p.toString()); 13610 } 13611 printedSomething = false; 13612 for (Map.Entry<String, PackageParser.Provider> entry : 13613 mProvidersByAuthority.entrySet()) { 13614 PackageParser.Provider p = entry.getValue(); 13615 if (packageName != null && !packageName.equals(p.info.packageName)) { 13616 continue; 13617 } 13618 if (!printedSomething) { 13619 if (dumpState.onTitlePrinted()) 13620 pw.println(); 13621 pw.println("ContentProvider Authorities:"); 13622 printedSomething = true; 13623 } 13624 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13625 pw.print(" "); pw.println(p.toString()); 13626 if (p.info != null && p.info.applicationInfo != null) { 13627 final String appInfo = p.info.applicationInfo.toString(); 13628 pw.print(" applicationInfo="); pw.println(appInfo); 13629 } 13630 } 13631 } 13632 13633 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13634 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13635 } 13636 13637 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13638 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13639 } 13640 13641 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13642 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13643 } 13644 13645 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13646 // XXX should handle packageName != null by dumping only install data that 13647 // the given package is involved with. 13648 if (dumpState.onTitlePrinted()) pw.println(); 13649 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13650 } 13651 13652 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13653 if (dumpState.onTitlePrinted()) pw.println(); 13654 mSettings.dumpReadMessagesLPr(pw, dumpState); 13655 13656 pw.println(); 13657 pw.println("Package warning 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.println(line); 13665 } 13666 } catch (IOException ignored) { 13667 } finally { 13668 IoUtils.closeQuietly(in); 13669 } 13670 } 13671 13672 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13673 BufferedReader in = null; 13674 String line = null; 13675 try { 13676 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13677 while ((line = in.readLine()) != null) { 13678 if (line.contains("ignored: updated version")) continue; 13679 pw.print("msg,"); 13680 pw.println(line); 13681 } 13682 } catch (IOException ignored) { 13683 } finally { 13684 IoUtils.closeQuietly(in); 13685 } 13686 } 13687 } 13688 } 13689 13690 // ------- apps on sdcard specific code ------- 13691 static final boolean DEBUG_SD_INSTALL = false; 13692 13693 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13694 13695 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13696 13697 private boolean mMediaMounted = false; 13698 13699 static String getEncryptKey() { 13700 try { 13701 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13702 SD_ENCRYPTION_KEYSTORE_NAME); 13703 if (sdEncKey == null) { 13704 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13705 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13706 if (sdEncKey == null) { 13707 Slog.e(TAG, "Failed to create encryption keys"); 13708 return null; 13709 } 13710 } 13711 return sdEncKey; 13712 } catch (NoSuchAlgorithmException nsae) { 13713 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13714 return null; 13715 } catch (IOException ioe) { 13716 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13717 return null; 13718 } 13719 } 13720 13721 /* 13722 * Update media status on PackageManager. 13723 */ 13724 @Override 13725 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13726 int callingUid = Binder.getCallingUid(); 13727 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13728 throw new SecurityException("Media status can only be updated by the system"); 13729 } 13730 // reader; this apparently protects mMediaMounted, but should probably 13731 // be a different lock in that case. 13732 synchronized (mPackages) { 13733 Log.i(TAG, "Updating external media status from " 13734 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13735 + (mediaStatus ? "mounted" : "unmounted")); 13736 if (DEBUG_SD_INSTALL) 13737 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13738 + ", mMediaMounted=" + mMediaMounted); 13739 if (mediaStatus == mMediaMounted) { 13740 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13741 : 0, -1); 13742 mHandler.sendMessage(msg); 13743 return; 13744 } 13745 mMediaMounted = mediaStatus; 13746 } 13747 // Queue up an async operation since the package installation may take a 13748 // little while. 13749 mHandler.post(new Runnable() { 13750 public void run() { 13751 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13752 } 13753 }); 13754 } 13755 13756 /** 13757 * Called by MountService when the initial ASECs to scan are available. 13758 * Should block until all the ASEC containers are finished being scanned. 13759 */ 13760 public void scanAvailableAsecs() { 13761 updateExternalMediaStatusInner(true, false, false); 13762 if (mShouldRestoreconData) { 13763 SELinuxMMAC.setRestoreconDone(); 13764 mShouldRestoreconData = false; 13765 } 13766 } 13767 13768 /* 13769 * Collect information of applications on external media, map them against 13770 * existing containers and update information based on current mount status. 13771 * Please note that we always have to report status if reportStatus has been 13772 * set to true especially when unloading packages. 13773 */ 13774 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13775 boolean externalStorage) { 13776 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13777 int[] uidArr = EmptyArray.INT; 13778 13779 final String[] list = PackageHelper.getSecureContainerList(); 13780 if (ArrayUtils.isEmpty(list)) { 13781 Log.i(TAG, "No secure containers found"); 13782 } else { 13783 // Process list of secure containers and categorize them 13784 // as active or stale based on their package internal state. 13785 13786 // reader 13787 synchronized (mPackages) { 13788 for (String cid : list) { 13789 // Leave stages untouched for now; installer service owns them 13790 if (PackageInstallerService.isStageName(cid)) continue; 13791 13792 if (DEBUG_SD_INSTALL) 13793 Log.i(TAG, "Processing container " + cid); 13794 String pkgName = getAsecPackageName(cid); 13795 if (pkgName == null) { 13796 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13797 continue; 13798 } 13799 if (DEBUG_SD_INSTALL) 13800 Log.i(TAG, "Looking for pkg : " + pkgName); 13801 13802 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13803 if (ps == null) { 13804 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13805 continue; 13806 } 13807 13808 /* 13809 * Skip packages that are not external if we're unmounting 13810 * external storage. 13811 */ 13812 if (externalStorage && !isMounted && !isExternal(ps)) { 13813 continue; 13814 } 13815 13816 final AsecInstallArgs args = new AsecInstallArgs(cid, 13817 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13818 // The package status is changed only if the code path 13819 // matches between settings and the container id. 13820 if (ps.codePathString != null 13821 && ps.codePathString.startsWith(args.getCodePath())) { 13822 if (DEBUG_SD_INSTALL) { 13823 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13824 + " at code path: " + ps.codePathString); 13825 } 13826 13827 // We do have a valid package installed on sdcard 13828 processCids.put(args, ps.codePathString); 13829 final int uid = ps.appId; 13830 if (uid != -1) { 13831 uidArr = ArrayUtils.appendInt(uidArr, uid); 13832 } 13833 } else { 13834 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13835 + ps.codePathString); 13836 } 13837 } 13838 } 13839 13840 Arrays.sort(uidArr); 13841 } 13842 13843 // Process packages with valid entries. 13844 if (isMounted) { 13845 if (DEBUG_SD_INSTALL) 13846 Log.i(TAG, "Loading packages"); 13847 loadMediaPackages(processCids, uidArr); 13848 startCleaningPackages(); 13849 mInstallerService.onSecureContainersAvailable(); 13850 } else { 13851 if (DEBUG_SD_INSTALL) 13852 Log.i(TAG, "Unloading packages"); 13853 unloadMediaPackages(processCids, uidArr, reportStatus); 13854 } 13855 } 13856 13857 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13858 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13859 final int size = infos.size(); 13860 final String[] packageNames = new String[size]; 13861 final int[] packageUids = new int[size]; 13862 for (int i = 0; i < size; i++) { 13863 final ApplicationInfo info = infos.get(i); 13864 packageNames[i] = info.packageName; 13865 packageUids[i] = info.uid; 13866 } 13867 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13868 finishedReceiver); 13869 } 13870 13871 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13872 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13873 sendResourcesChangedBroadcast(mediaStatus, replacing, 13874 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13875 } 13876 13877 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13878 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13879 int size = pkgList.length; 13880 if (size > 0) { 13881 // Send broadcasts here 13882 Bundle extras = new Bundle(); 13883 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13884 if (uidArr != null) { 13885 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13886 } 13887 if (replacing) { 13888 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13889 } 13890 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13891 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13892 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13893 } 13894 } 13895 13896 /* 13897 * Look at potentially valid container ids from processCids If package 13898 * information doesn't match the one on record or package scanning fails, 13899 * the cid is added to list of removeCids. We currently don't delete stale 13900 * containers. 13901 */ 13902 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13903 ArrayList<String> pkgList = new ArrayList<String>(); 13904 Set<AsecInstallArgs> keys = processCids.keySet(); 13905 13906 for (AsecInstallArgs args : keys) { 13907 String codePath = processCids.get(args); 13908 if (DEBUG_SD_INSTALL) 13909 Log.i(TAG, "Loading container : " + args.cid); 13910 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13911 try { 13912 // Make sure there are no container errors first. 13913 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13914 Slog.e(TAG, "Failed to mount cid : " + args.cid 13915 + " when installing from sdcard"); 13916 continue; 13917 } 13918 // Check code path here. 13919 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13920 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13921 + " does not match one in settings " + codePath); 13922 continue; 13923 } 13924 // Parse package 13925 int parseFlags = mDefParseFlags; 13926 if (args.isExternalAsec()) { 13927 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13928 } 13929 if (args.isFwdLocked()) { 13930 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13931 } 13932 13933 synchronized (mInstallLock) { 13934 PackageParser.Package pkg = null; 13935 try { 13936 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13937 } catch (PackageManagerException e) { 13938 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13939 } 13940 // Scan the package 13941 if (pkg != null) { 13942 /* 13943 * TODO why is the lock being held? doPostInstall is 13944 * called in other places without the lock. This needs 13945 * to be straightened out. 13946 */ 13947 // writer 13948 synchronized (mPackages) { 13949 retCode = PackageManager.INSTALL_SUCCEEDED; 13950 pkgList.add(pkg.packageName); 13951 // Post process args 13952 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13953 pkg.applicationInfo.uid); 13954 } 13955 } else { 13956 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13957 } 13958 } 13959 13960 } finally { 13961 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13962 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13963 } 13964 } 13965 } 13966 // writer 13967 synchronized (mPackages) { 13968 // If the platform SDK has changed since the last time we booted, 13969 // we need to re-grant app permission to catch any new ones that 13970 // appear. This is really a hack, and means that apps can in some 13971 // cases get permissions that the user didn't initially explicitly 13972 // allow... it would be nice to have some better way to handle 13973 // this situation. 13974 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13975 if (regrantPermissions) 13976 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13977 + mSdkVersion + "; regranting permissions for external storage"); 13978 mSettings.mExternalSdkPlatform = mSdkVersion; 13979 13980 // Make sure group IDs have been assigned, and any permission 13981 // changes in other apps are accounted for 13982 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13983 | (regrantPermissions 13984 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13985 : 0)); 13986 13987 mSettings.updateExternalDatabaseVersion(); 13988 13989 // can downgrade to reader 13990 // Persist settings 13991 mSettings.writeLPr(); 13992 } 13993 // Send a broadcast to let everyone know we are done processing 13994 if (pkgList.size() > 0) { 13995 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13996 } 13997 } 13998 13999 /* 14000 * Utility method to unload a list of specified containers 14001 */ 14002 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14003 // Just unmount all valid containers. 14004 for (AsecInstallArgs arg : cidArgs) { 14005 synchronized (mInstallLock) { 14006 arg.doPostDeleteLI(false); 14007 } 14008 } 14009 } 14010 14011 /* 14012 * Unload packages mounted on external media. This involves deleting package 14013 * data from internal structures, sending broadcasts about diabled packages, 14014 * gc'ing to free up references, unmounting all secure containers 14015 * corresponding to packages on external media, and posting a 14016 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14017 * that we always have to post this message if status has been requested no 14018 * matter what. 14019 */ 14020 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14021 final boolean reportStatus) { 14022 if (DEBUG_SD_INSTALL) 14023 Log.i(TAG, "unloading media packages"); 14024 ArrayList<String> pkgList = new ArrayList<String>(); 14025 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14026 final Set<AsecInstallArgs> keys = processCids.keySet(); 14027 for (AsecInstallArgs args : keys) { 14028 String pkgName = args.getPackageName(); 14029 if (DEBUG_SD_INSTALL) 14030 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14031 // Delete package internally 14032 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14033 synchronized (mInstallLock) { 14034 boolean res = deletePackageLI(pkgName, null, false, null, null, 14035 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14036 if (res) { 14037 pkgList.add(pkgName); 14038 } else { 14039 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14040 failedList.add(args); 14041 } 14042 } 14043 } 14044 14045 // reader 14046 synchronized (mPackages) { 14047 // We didn't update the settings after removing each package; 14048 // write them now for all packages. 14049 mSettings.writeLPr(); 14050 } 14051 14052 // We have to absolutely send UPDATED_MEDIA_STATUS only 14053 // after confirming that all the receivers processed the ordered 14054 // broadcast when packages get disabled, force a gc to clean things up. 14055 // and unload all the containers. 14056 if (pkgList.size() > 0) { 14057 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14058 new IIntentReceiver.Stub() { 14059 public void performReceive(Intent intent, int resultCode, String data, 14060 Bundle extras, boolean ordered, boolean sticky, 14061 int sendingUser) throws RemoteException { 14062 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14063 reportStatus ? 1 : 0, 1, keys); 14064 mHandler.sendMessage(msg); 14065 } 14066 }); 14067 } else { 14068 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14069 keys); 14070 mHandler.sendMessage(msg); 14071 } 14072 } 14073 14074 private void loadPrivatePackages(VolumeInfo vol) { 14075 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14076 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14077 synchronized (mPackages) { 14078 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14079 for (PackageSetting ps : packages) { 14080 synchronized (mInstallLock) { 14081 final PackageParser.Package pkg; 14082 try { 14083 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14084 loaded.add(pkg.applicationInfo); 14085 } catch (PackageManagerException e) { 14086 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14087 } 14088 } 14089 } 14090 14091 // TODO: regrant any permissions that changed based since original install 14092 14093 mSettings.writeLPr(); 14094 } 14095 14096 Slog.d(TAG, "Loaded packages " + loaded); 14097 sendResourcesChangedBroadcast(true, false, loaded, null); 14098 } 14099 14100 private void unloadPrivatePackages(VolumeInfo vol) { 14101 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14102 synchronized (mPackages) { 14103 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14104 for (PackageSetting ps : packages) { 14105 if (ps.pkg == null) continue; 14106 synchronized (mInstallLock) { 14107 final ApplicationInfo info = ps.pkg.applicationInfo; 14108 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14109 if (deletePackageLI(ps.name, null, false, null, null, 14110 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14111 unloaded.add(info); 14112 } else { 14113 Slog.w(TAG, "Failed to unload " + ps.codePath); 14114 } 14115 } 14116 } 14117 14118 mSettings.writeLPr(); 14119 } 14120 14121 Slog.d(TAG, "Unloaded packages " + unloaded); 14122 sendResourcesChangedBroadcast(false, false, unloaded, null); 14123 } 14124 14125 @Override 14126 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14127 final int flags) { 14128 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14129 14130 final int installFlags; 14131 if ((flags & MOVE_INTERNAL) != 0) { 14132 installFlags = INSTALL_INTERNAL; 14133 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14134 installFlags = INSTALL_EXTERNAL; 14135 } else { 14136 throw new IllegalArgumentException("Unsupported move flags " + flags); 14137 } 14138 14139 try { 14140 movePackageInternal(packageName, null, installFlags, false, 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 @Override 14151 public void movePackageAndData(final String packageName, final String volumeUuid, 14152 final IPackageMoveObserver observer) { 14153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14154 try { 14155 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14156 } catch (PackageManagerException e) { 14157 Slog.d(TAG, "Failed to move " + packageName, e); 14158 try { 14159 observer.packageMoved(packageName, e.error); 14160 } catch (RemoteException ignored) { 14161 } 14162 } 14163 } 14164 14165 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14166 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14167 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14168 14169 final String currentVolumeUuid; 14170 final File codeFile; 14171 final String installerPackageName; 14172 final String packageAbiOverride; 14173 final int appId; 14174 final String seinfo; 14175 14176 // reader 14177 synchronized (mPackages) { 14178 final PackageParser.Package pkg = mPackages.get(packageName); 14179 final PackageSetting ps = mSettings.mPackages.get(packageName); 14180 if (pkg == null || ps == null) { 14181 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14182 } 14183 14184 if (pkg.applicationInfo.isSystemApp()) { 14185 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14186 "Cannot move system application"); 14187 } else if (pkg.mOperationPending) { 14188 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14189 "Attempt to move package which has pending operations"); 14190 } 14191 14192 // TODO: yell if already in desired location 14193 14194 pkg.mOperationPending = true; 14195 14196 currentVolumeUuid = ps.volumeUuid; 14197 codeFile = new File(pkg.codePath); 14198 installerPackageName = ps.installerPackageName; 14199 packageAbiOverride = ps.cpuAbiOverrideString; 14200 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14201 seinfo = pkg.applicationInfo.seinfo; 14202 } 14203 14204 if (andData) { 14205 Slog.d(TAG, "Moving " + packageName + " private data from " + currentVolumeUuid + " to " 14206 + volumeUuid); 14207 synchronized (mInstallLock) { 14208 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14209 seinfo) != 0) { 14210 synchronized (mPackages) { 14211 final PackageParser.Package pkg = mPackages.get(packageName); 14212 if (pkg != null) { 14213 pkg.mOperationPending = false; 14214 } 14215 } 14216 14217 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14218 "Failed to move private data"); 14219 } 14220 } 14221 } 14222 14223 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14224 @Override 14225 public void onUserActionRequired(Intent intent) throws RemoteException { 14226 throw new IllegalStateException(); 14227 } 14228 14229 @Override 14230 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14231 Bundle extras) throws RemoteException { 14232 Slog.d(TAG, "Install result for move: " 14233 + PackageManager.installStatusToString(returnCode, msg)); 14234 14235 // We usually have a new package now after the install, but if 14236 // we failed we need to clear the pending flag on the original 14237 // package object. 14238 synchronized (mPackages) { 14239 final PackageParser.Package pkg = mPackages.get(packageName); 14240 if (pkg != null) { 14241 pkg.mOperationPending = false; 14242 } 14243 } 14244 14245 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14246 switch (status) { 14247 case PackageInstaller.STATUS_SUCCESS: 14248 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14249 break; 14250 case PackageInstaller.STATUS_FAILURE_STORAGE: 14251 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14252 break; 14253 default: 14254 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14255 break; 14256 } 14257 } 14258 }; 14259 14260 // Treat a move like reinstalling an existing app, which ensures that we 14261 // process everythign uniformly, like unpacking native libraries. 14262 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14263 14264 final Message msg = mHandler.obtainMessage(INIT_COPY); 14265 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14266 msg.obj = new InstallParams(origin, installObserver, installFlags, 14267 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14268 mHandler.sendMessage(msg); 14269 } 14270 14271 @Override 14272 public boolean setInstallLocation(int loc) { 14273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14274 null); 14275 if (getInstallLocation() == loc) { 14276 return true; 14277 } 14278 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14279 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14280 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14281 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14282 return true; 14283 } 14284 return false; 14285 } 14286 14287 @Override 14288 public int getInstallLocation() { 14289 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14290 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14291 PackageHelper.APP_INSTALL_AUTO); 14292 } 14293 14294 /** Called by UserManagerService */ 14295 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14296 mDirtyUsers.remove(userHandle); 14297 mSettings.removeUserLPw(userHandle); 14298 mPendingBroadcasts.remove(userHandle); 14299 if (mInstaller != null) { 14300 // Technically, we shouldn't be doing this with the package lock 14301 // held. However, this is very rare, and there is already so much 14302 // other disk I/O going on, that we'll let it slide for now. 14303 mInstaller.removeUserDataDirs(userHandle); 14304 } 14305 mUserNeedsBadging.delete(userHandle); 14306 removeUnusedPackagesLILPw(userManager, userHandle); 14307 } 14308 14309 /** 14310 * We're removing userHandle and would like to remove any downloaded packages 14311 * that are no longer in use by any other user. 14312 * @param userHandle the user being removed 14313 */ 14314 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14315 final boolean DEBUG_CLEAN_APKS = false; 14316 int [] users = userManager.getUserIdsLPr(); 14317 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14318 while (psit.hasNext()) { 14319 PackageSetting ps = psit.next(); 14320 if (ps.pkg == null) { 14321 continue; 14322 } 14323 final String packageName = ps.pkg.packageName; 14324 // Skip over if system app 14325 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14326 continue; 14327 } 14328 if (DEBUG_CLEAN_APKS) { 14329 Slog.i(TAG, "Checking package " + packageName); 14330 } 14331 boolean keep = false; 14332 for (int i = 0; i < users.length; i++) { 14333 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14334 keep = true; 14335 if (DEBUG_CLEAN_APKS) { 14336 Slog.i(TAG, " Keeping package " + packageName + " for user " 14337 + users[i]); 14338 } 14339 break; 14340 } 14341 } 14342 if (!keep) { 14343 if (DEBUG_CLEAN_APKS) { 14344 Slog.i(TAG, " Removing package " + packageName); 14345 } 14346 mHandler.post(new Runnable() { 14347 public void run() { 14348 deletePackageX(packageName, userHandle, 0); 14349 } //end run 14350 }); 14351 } 14352 } 14353 } 14354 14355 /** Called by UserManagerService */ 14356 void createNewUserLILPw(int userHandle, File path) { 14357 if (mInstaller != null) { 14358 mInstaller.createUserConfig(userHandle); 14359 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14360 } 14361 } 14362 14363 void newUserCreatedLILPw(int userHandle) { 14364 // Adding a user requires updating runtime permissions for system apps. 14365 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14366 } 14367 14368 @Override 14369 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14370 mContext.enforceCallingOrSelfPermission( 14371 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14372 "Only package verification agents can read the verifier device identity"); 14373 14374 synchronized (mPackages) { 14375 return mSettings.getVerifierDeviceIdentityLPw(); 14376 } 14377 } 14378 14379 @Override 14380 public void setPermissionEnforced(String permission, boolean enforced) { 14381 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14382 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14383 synchronized (mPackages) { 14384 if (mSettings.mReadExternalStorageEnforced == null 14385 || mSettings.mReadExternalStorageEnforced != enforced) { 14386 mSettings.mReadExternalStorageEnforced = enforced; 14387 mSettings.writeLPr(); 14388 } 14389 } 14390 // kill any non-foreground processes so we restart them and 14391 // grant/revoke the GID. 14392 final IActivityManager am = ActivityManagerNative.getDefault(); 14393 if (am != null) { 14394 final long token = Binder.clearCallingIdentity(); 14395 try { 14396 am.killProcessesBelowForeground("setPermissionEnforcement"); 14397 } catch (RemoteException e) { 14398 } finally { 14399 Binder.restoreCallingIdentity(token); 14400 } 14401 } 14402 } else { 14403 throw new IllegalArgumentException("No selective enforcement for " + permission); 14404 } 14405 } 14406 14407 @Override 14408 @Deprecated 14409 public boolean isPermissionEnforced(String permission) { 14410 return true; 14411 } 14412 14413 @Override 14414 public boolean isStorageLow() { 14415 final long token = Binder.clearCallingIdentity(); 14416 try { 14417 final DeviceStorageMonitorInternal 14418 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14419 if (dsm != null) { 14420 return dsm.isMemoryLow(); 14421 } else { 14422 return false; 14423 } 14424 } finally { 14425 Binder.restoreCallingIdentity(token); 14426 } 14427 } 14428 14429 @Override 14430 public IPackageInstaller getPackageInstaller() { 14431 return mInstallerService; 14432 } 14433 14434 private boolean userNeedsBadging(int userId) { 14435 int index = mUserNeedsBadging.indexOfKey(userId); 14436 if (index < 0) { 14437 final UserInfo userInfo; 14438 final long token = Binder.clearCallingIdentity(); 14439 try { 14440 userInfo = sUserManager.getUserInfo(userId); 14441 } finally { 14442 Binder.restoreCallingIdentity(token); 14443 } 14444 final boolean b; 14445 if (userInfo != null && userInfo.isManagedProfile()) { 14446 b = true; 14447 } else { 14448 b = false; 14449 } 14450 mUserNeedsBadging.put(userId, b); 14451 return b; 14452 } 14453 return mUserNeedsBadging.valueAt(index); 14454 } 14455 14456 @Override 14457 public KeySet getKeySetByAlias(String packageName, String alias) { 14458 if (packageName == null || alias == null) { 14459 return null; 14460 } 14461 synchronized(mPackages) { 14462 final PackageParser.Package pkg = mPackages.get(packageName); 14463 if (pkg == null) { 14464 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14465 throw new IllegalArgumentException("Unknown package: " + packageName); 14466 } 14467 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14468 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14469 } 14470 } 14471 14472 @Override 14473 public KeySet getSigningKeySet(String packageName) { 14474 if (packageName == null) { 14475 return null; 14476 } 14477 synchronized(mPackages) { 14478 final PackageParser.Package pkg = mPackages.get(packageName); 14479 if (pkg == null) { 14480 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14481 throw new IllegalArgumentException("Unknown package: " + packageName); 14482 } 14483 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14484 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14485 throw new SecurityException("May not access signing KeySet of other apps."); 14486 } 14487 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14488 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14489 } 14490 } 14491 14492 @Override 14493 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14494 if (packageName == null || ks == null) { 14495 return false; 14496 } 14497 synchronized(mPackages) { 14498 final PackageParser.Package pkg = mPackages.get(packageName); 14499 if (pkg == null) { 14500 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14501 throw new IllegalArgumentException("Unknown package: " + packageName); 14502 } 14503 IBinder ksh = ks.getToken(); 14504 if (ksh instanceof KeySetHandle) { 14505 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14506 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14507 } 14508 return false; 14509 } 14510 } 14511 14512 @Override 14513 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14514 if (packageName == null || ks == null) { 14515 return false; 14516 } 14517 synchronized(mPackages) { 14518 final PackageParser.Package pkg = mPackages.get(packageName); 14519 if (pkg == null) { 14520 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14521 throw new IllegalArgumentException("Unknown package: " + packageName); 14522 } 14523 IBinder ksh = ks.getToken(); 14524 if (ksh instanceof KeySetHandle) { 14525 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14526 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14527 } 14528 return false; 14529 } 14530 } 14531 14532 public void getUsageStatsIfNoPackageUsageInfo() { 14533 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14534 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14535 if (usm == null) { 14536 throw new IllegalStateException("UsageStatsManager must be initialized"); 14537 } 14538 long now = System.currentTimeMillis(); 14539 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14540 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14541 String packageName = entry.getKey(); 14542 PackageParser.Package pkg = mPackages.get(packageName); 14543 if (pkg == null) { 14544 continue; 14545 } 14546 UsageStats usage = entry.getValue(); 14547 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14548 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14549 } 14550 } 14551 } 14552 14553 /** 14554 * Check and throw if the given before/after packages would be considered a 14555 * downgrade. 14556 */ 14557 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14558 throws PackageManagerException { 14559 if (after.versionCode < before.mVersionCode) { 14560 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14561 "Update version code " + after.versionCode + " is older than current " 14562 + before.mVersionCode); 14563 } else if (after.versionCode == before.mVersionCode) { 14564 if (after.baseRevisionCode < before.baseRevisionCode) { 14565 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14566 "Update base revision code " + after.baseRevisionCode 14567 + " is older than current " + before.baseRevisionCode); 14568 } 14569 14570 if (!ArrayUtils.isEmpty(after.splitNames)) { 14571 for (int i = 0; i < after.splitNames.length; i++) { 14572 final String splitName = after.splitNames[i]; 14573 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14574 if (j != -1) { 14575 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14576 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14577 "Update split " + splitName + " revision code " 14578 + after.splitRevisionCodes[i] + " is older than current " 14579 + before.splitRevisionCodes[j]); 14580 } 14581 } 14582 } 14583 } 14584 } 14585 } 14586} 14587