PackageManagerService.java revision 0788595e0c9bc5e8c1907c63db595010006ef5b4
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MOVE_EXTERNAL_MEDIA; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 55import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 56import static android.content.pm.PackageManager.MOVE_INTERNAL; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import org.xmlpull.v1.XmlPullParser; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.text.format.DateUtils; 165import android.util.ArrayMap; 166import android.util.ArraySet; 167import android.util.AtomicFile; 168import android.util.DisplayMetrics; 169import android.util.EventLog; 170import android.util.ExceptionUtils; 171import android.util.Log; 172import android.util.LogPrinter; 173import android.util.PrintStreamPrinter; 174import android.util.Slog; 175import android.util.SparseArray; 176import android.util.SparseBooleanArray; 177import android.util.Xml; 178import android.view.Display; 179 180import dalvik.system.DexFile; 181import dalvik.system.VMRuntime; 182 183import libcore.io.IoUtils; 184import libcore.util.EmptyArray; 185 186import com.android.internal.R; 187import com.android.internal.app.IMediaContainerService; 188import com.android.internal.app.ResolverActivity; 189import com.android.internal.content.NativeLibraryHelper; 190import com.android.internal.content.PackageHelper; 191import com.android.internal.os.IParcelFileDescriptorFactory; 192import com.android.internal.util.ArrayUtils; 193import com.android.internal.util.FastPrintWriter; 194import com.android.internal.util.FastXmlSerializer; 195import com.android.internal.util.IndentingPrintWriter; 196import com.android.server.EventLogTags; 197import com.android.server.IntentResolver; 198import com.android.server.LocalServices; 199import com.android.server.ServiceThread; 200import com.android.server.SystemConfig; 201import com.android.server.Watchdog; 202import com.android.server.pm.Settings.DatabaseVersion; 203import com.android.server.storage.DeviceStorageMonitorInternal; 204 205import org.xmlpull.v1.XmlSerializer; 206 207import java.io.BufferedInputStream; 208import java.io.BufferedOutputStream; 209import java.io.BufferedReader; 210import java.io.ByteArrayInputStream; 211import java.io.ByteArrayOutputStream; 212import java.io.File; 213import java.io.FileDescriptor; 214import java.io.FileNotFoundException; 215import java.io.FileOutputStream; 216import java.io.FileReader; 217import java.io.FilenameFilter; 218import java.io.IOException; 219import java.io.InputStream; 220import java.io.PrintWriter; 221import java.nio.charset.StandardCharsets; 222import java.security.NoSuchAlgorithmException; 223import java.security.PublicKey; 224import java.security.cert.CertificateEncodingException; 225import java.security.cert.CertificateException; 226import java.text.SimpleDateFormat; 227import java.util.ArrayList; 228import java.util.Arrays; 229import java.util.Collection; 230import java.util.Collections; 231import java.util.Comparator; 232import java.util.Date; 233import java.util.Iterator; 234import java.util.List; 235import java.util.Map; 236import java.util.Objects; 237import java.util.Set; 238import java.util.concurrent.atomic.AtomicBoolean; 239import java.util.concurrent.atomic.AtomicLong; 240 241/** 242 * Keep track of all those .apks everywhere. 243 * 244 * This is very central to the platform's security; please run the unit 245 * tests whenever making modifications here: 246 * 247mmm frameworks/base/tests/AndroidTests 248adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 249adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 250 * 251 * {@hide} 252 */ 253public class PackageManagerService extends IPackageManager.Stub { 254 static final String TAG = "PackageManager"; 255 static final boolean DEBUG_SETTINGS = false; 256 static final boolean DEBUG_PREFERRED = false; 257 static final boolean DEBUG_UPGRADE = false; 258 private static final boolean DEBUG_BACKUP = true; 259 private static final boolean DEBUG_INSTALL = false; 260 private static final boolean DEBUG_REMOVE = false; 261 private static final boolean DEBUG_BROADCASTS = false; 262 private static final boolean DEBUG_SHOW_INFO = false; 263 private static final boolean DEBUG_PACKAGE_INFO = false; 264 private static final boolean DEBUG_INTENT_MATCHING = false; 265 private static final boolean DEBUG_PACKAGE_SCANNING = false; 266 private static final boolean DEBUG_VERIFY = false; 267 private static final boolean DEBUG_DEXOPT = false; 268 private static final boolean DEBUG_ABI_SELECTION = false; 269 270 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 271 272 private static final int RADIO_UID = Process.PHONE_UID; 273 private static final int LOG_UID = Process.LOG_UID; 274 private static final int NFC_UID = Process.NFC_UID; 275 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 276 private static final int SHELL_UID = Process.SHELL_UID; 277 278 // Cap the size of permission trees that 3rd party apps can define 279 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 280 281 // Suffix used during package installation when copying/moving 282 // package apks to install directory. 283 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 284 285 static final int SCAN_NO_DEX = 1<<1; 286 static final int SCAN_FORCE_DEX = 1<<2; 287 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 288 static final int SCAN_NEW_INSTALL = 1<<4; 289 static final int SCAN_NO_PATHS = 1<<5; 290 static final int SCAN_UPDATE_TIME = 1<<6; 291 static final int SCAN_DEFER_DEX = 1<<7; 292 static final int SCAN_BOOTING = 1<<8; 293 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 294 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 295 static final int SCAN_REPLACING = 1<<11; 296 static final int SCAN_REQUIRE_KNOWN = 1<<12; 297 298 static final int REMOVE_CHATTY = 1<<16; 299 300 /** 301 * Timeout (in milliseconds) after which the watchdog should declare that 302 * our handler thread is wedged. The usual default for such things is one 303 * minute but we sometimes do very lengthy I/O operations on this thread, 304 * such as installing multi-gigabyte applications, so ours needs to be longer. 305 */ 306 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 307 308 /** 309 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 310 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 311 * settings entry if available, otherwise we use the hardcoded default. If it's been 312 * more than this long since the last fstrim, we force one during the boot sequence. 313 * 314 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 315 * one gets run at the next available charging+idle time. This final mandatory 316 * no-fstrim check kicks in only of the other scheduling criteria is never met. 317 */ 318 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 319 320 /** 321 * Whether verification is enabled by default. 322 */ 323 private static final boolean DEFAULT_VERIFY_ENABLE = true; 324 325 /** 326 * The default maximum time to wait for the verification agent to return in 327 * milliseconds. 328 */ 329 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 330 331 /** 332 * The default response for package verification timeout. 333 * 334 * This can be either PackageManager.VERIFICATION_ALLOW or 335 * PackageManager.VERIFICATION_REJECT. 336 */ 337 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 338 339 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 340 341 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 342 DEFAULT_CONTAINER_PACKAGE, 343 "com.android.defcontainer.DefaultContainerService"); 344 345 private static final String KILL_APP_REASON_GIDS_CHANGED = 346 "permission grant or revoke changed gids"; 347 348 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 349 "permissions revoked"; 350 351 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 352 353 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 354 355 /** Permission grant: not grant the permission. */ 356 private static final int GRANT_DENIED = 1; 357 358 /** Permission grant: grant the permission as an install permission. */ 359 private static final int GRANT_INSTALL = 2; 360 361 /** Permission grant: grant the permission as a runtime one. */ 362 private static final int GRANT_RUNTIME = 3; 363 364 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 365 private static final int GRANT_UPGRADE = 4; 366 367 final ServiceThread mHandlerThread; 368 369 final PackageHandler mHandler; 370 371 /** 372 * Messages for {@link #mHandler} that need to wait for system ready before 373 * being dispatched. 374 */ 375 private ArrayList<Message> mPostSystemReadyMessages; 376 377 final int mSdkVersion = Build.VERSION.SDK_INT; 378 379 final Context mContext; 380 final boolean mFactoryTest; 381 final boolean mOnlyCore; 382 final boolean mLazyDexOpt; 383 final long mDexOptLRUThresholdInMills; 384 final DisplayMetrics mMetrics; 385 final int mDefParseFlags; 386 final String[] mSeparateProcesses; 387 final boolean mIsUpgrade; 388 389 // This is where all application persistent data goes. 390 final File mAppDataDir; 391 392 // This is where all application persistent data goes for secondary users. 393 final File mUserAppDataDir; 394 395 /** The location for ASEC container files on internal storage. */ 396 final String mAsecInternalPath; 397 398 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 399 // LOCK HELD. Can be called with mInstallLock held. 400 final Installer mInstaller; 401 402 /** Directory where installed third-party apps stored */ 403 final File mAppInstallDir; 404 405 /** 406 * Directory to which applications installed internally have their 407 * 32 bit native libraries copied. 408 */ 409 private File mAppLib32InstallDir; 410 411 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 412 // apps. 413 final File mDrmAppPrivateInstallDir; 414 415 // ---------------------------------------------------------------- 416 417 // Lock for state used when installing and doing other long running 418 // operations. Methods that must be called with this lock held have 419 // the suffix "LI". 420 final Object mInstallLock = new Object(); 421 422 // ---------------------------------------------------------------- 423 424 // Keys are String (package name), values are Package. This also serves 425 // as the lock for the global state. Methods that must be called with 426 // this lock held have the prefix "LP". 427 final ArrayMap<String, PackageParser.Package> mPackages = 428 new ArrayMap<String, PackageParser.Package>(); 429 430 // Tracks available target package names -> overlay package paths. 431 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 432 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 433 434 final Settings mSettings; 435 boolean mRestoredSettings; 436 437 // System configuration read by SystemConfig. 438 final int[] mGlobalGids; 439 final SparseArray<ArraySet<String>> mSystemPermissions; 440 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 441 442 // If mac_permissions.xml was found for seinfo labeling. 443 boolean mFoundPolicyFile; 444 445 // If a recursive restorecon of /data/data/<pkg> is needed. 446 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 447 448 public static final class SharedLibraryEntry { 449 public final String path; 450 public final String apk; 451 452 SharedLibraryEntry(String _path, String _apk) { 453 path = _path; 454 apk = _apk; 455 } 456 } 457 458 // Currently known shared libraries. 459 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 460 new ArrayMap<String, SharedLibraryEntry>(); 461 462 // All available activities, for your resolving pleasure. 463 final ActivityIntentResolver mActivities = 464 new ActivityIntentResolver(); 465 466 // All available receivers, for your resolving pleasure. 467 final ActivityIntentResolver mReceivers = 468 new ActivityIntentResolver(); 469 470 // All available services, for your resolving pleasure. 471 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 472 473 // All available providers, for your resolving pleasure. 474 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 475 476 // Mapping from provider base names (first directory in content URI codePath) 477 // to the provider information. 478 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 479 new ArrayMap<String, PackageParser.Provider>(); 480 481 // Mapping from instrumentation class names to info about them. 482 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 483 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 484 485 // Mapping from permission names to info about them. 486 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 487 new ArrayMap<String, PackageParser.PermissionGroup>(); 488 489 // Packages whose data we have transfered into another package, thus 490 // should no longer exist. 491 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 492 493 // Broadcast actions that are only available to the system. 494 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 495 496 /** List of packages waiting for verification. */ 497 final SparseArray<PackageVerificationState> mPendingVerification 498 = new SparseArray<PackageVerificationState>(); 499 500 /** Set of packages associated with each app op permission. */ 501 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 502 503 final PackageInstallerService mInstallerService; 504 505 private final PackageDexOptimizer mPackageDexOptimizer; 506 // Cache of users who need badging. 507 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 508 509 /** Token for keys in mPendingVerification. */ 510 private int mPendingVerificationToken = 0; 511 512 volatile boolean mSystemReady; 513 volatile boolean mSafeMode; 514 volatile boolean mHasSystemUidErrors; 515 516 ApplicationInfo mAndroidApplication; 517 final ActivityInfo mResolveActivity = new ActivityInfo(); 518 final ResolveInfo mResolveInfo = new ResolveInfo(); 519 ComponentName mResolveComponentName; 520 PackageParser.Package mPlatformPackage; 521 ComponentName mCustomResolverComponentName; 522 523 boolean mResolverReplaced = false; 524 525 private final ComponentName mIntentFilterVerifierComponent; 526 private int mIntentFilterVerificationToken = 0; 527 528 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 529 = new SparseArray<IntentFilterVerificationState>(); 530 531 private interface IntentFilterVerifier<T extends IntentFilter> { 532 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 533 T filter, String packageName); 534 void startVerifications(int userId); 535 void receiveVerificationResponse(int verificationId); 536 } 537 538 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 539 private Context mContext; 540 private ComponentName mIntentFilterVerifierComponent; 541 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 542 543 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 544 mContext = context; 545 mIntentFilterVerifierComponent = verifierComponent; 546 } 547 548 private String getDefaultScheme() { 549 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 550 return IntentFilter.SCHEME_HTTP; 551 } 552 553 @Override 554 public void startVerifications(int userId) { 555 // Launch verifications requests 556 int count = mCurrentIntentFilterVerifications.size(); 557 for (int n=0; n<count; n++) { 558 int verificationId = mCurrentIntentFilterVerifications.get(n); 559 final IntentFilterVerificationState ivs = 560 mIntentFilterVerificationStates.get(verificationId); 561 562 String packageName = ivs.getPackageName(); 563 boolean modified = false; 564 565 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 566 final int filterCount = filters.size(); 567 ArraySet<String> domainsSet = new ArraySet<>(); 568 for (int m=0; m<filterCount; m++) { 569 PackageParser.ActivityIntentInfo filter = filters.get(m); 570 domainsSet.addAll(filter.getHostsList()); 571 } 572 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 573 synchronized (mPackages) { 574 modified = mSettings.createIntentFilterVerificationIfNeededLPw( 575 packageName, domainsList); 576 if (modified) { 577 scheduleWriteSettingsLocked(); 578 } 579 } 580 sendVerificationRequest(userId, verificationId, ivs); 581 } 582 mCurrentIntentFilterVerifications.clear(); 583 } 584 585 private void sendVerificationRequest(int userId, int verificationId, 586 IntentFilterVerificationState ivs) { 587 588 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 589 verificationIntent.putExtra( 590 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 591 verificationId); 592 verificationIntent.putExtra( 593 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 594 getDefaultScheme()); 595 verificationIntent.putExtra( 596 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 597 ivs.getHostsString()); 598 verificationIntent.putExtra( 599 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 600 ivs.getPackageName()); 601 verificationIntent.setComponent(mIntentFilterVerifierComponent); 602 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 603 604 UserHandle user = new UserHandle(userId); 605 mContext.sendBroadcastAsUser(verificationIntent, user); 606 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 607 } 608 609 public void receiveVerificationResponse(int verificationId) { 610 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 611 612 final boolean verified = ivs.isVerified(); 613 614 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 615 final int count = filters.size(); 616 for (int n=0; n<count; n++) { 617 PackageParser.ActivityIntentInfo filter = filters.get(n); 618 filter.setVerified(verified); 619 620 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 621 + verified + " and hosts:" + ivs.getHostsString()); 622 } 623 624 mIntentFilterVerificationStates.remove(verificationId); 625 626 final String packageName = ivs.getPackageName(); 627 IntentFilterVerificationInfo ivi = null; 628 629 synchronized (mPackages) { 630 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 631 } 632 if (ivi == null) { 633 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 634 + verificationId + " packageName:" + packageName); 635 return; 636 } 637 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: " 638 + verificationId); 639 640 synchronized (mPackages) { 641 if (verified) { 642 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 643 } else { 644 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 645 } 646 scheduleWriteSettingsLocked(); 647 648 final int userId = ivs.getUserId(); 649 if (userId != UserHandle.USER_ALL) { 650 final int userStatus = 651 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 652 653 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 654 boolean needUpdate = false; 655 656 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 657 // already been set by the User thru the Disambiguation dialog 658 switch (userStatus) { 659 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 660 if (verified) { 661 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 662 } else { 663 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 664 } 665 needUpdate = true; 666 break; 667 668 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 669 if (verified) { 670 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 671 needUpdate = true; 672 } 673 break; 674 675 default: 676 // Nothing to do 677 } 678 679 if (needUpdate) { 680 mSettings.updateIntentFilterVerificationStatusLPw( 681 packageName, updatedStatus, userId); 682 scheduleWritePackageRestrictionsLocked(userId); 683 } 684 } 685 } 686 } 687 688 @Override 689 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 690 ActivityIntentInfo filter, String packageName) { 691 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 692 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 693 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 694 return false; 695 } 696 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 697 if (ivs == null) { 698 ivs = createDomainVerificationState(verifierId, userId, verificationId, 699 packageName); 700 } 701 ArrayList<String> hosts = filter.getHostsList(); 702 if (!hasValidHosts(hosts)) { 703 return false; 704 } 705 ivs.addFilter(filter); 706 return true; 707 } 708 709 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 710 int userId, int verificationId, String packageName) { 711 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 712 verifierId, userId, packageName); 713 ivs.setPendingState(); 714 synchronized (mPackages) { 715 mIntentFilterVerificationStates.append(verificationId, ivs); 716 mCurrentIntentFilterVerifications.add(verificationId); 717 } 718 return ivs; 719 } 720 } 721 722 private static boolean hasValidHosts(ArrayList<String> hosts) { 723 if (hosts.size() == 0) { 724 Slog.d(TAG, "IntentFilter does not contain any data hosts"); 725 return false; 726 } 727 String hostEndBase = null; 728 for (String host : hosts) { 729 String[] hostParts = host.split("\\."); 730 // Should be at minimum a host like "example.com" 731 if (hostParts.length < 2) { 732 Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host); 733 return false; 734 } 735 // Verify that we have the same ending domain 736 int length = hostParts.length; 737 String hostEnd = hostParts[length - 1] + hostParts[length - 2]; 738 if (hostEndBase == null) { 739 hostEndBase = hostEnd; 740 } 741 if (!hostEnd.equalsIgnoreCase(hostEndBase)) { 742 Slog.d(TAG, "IntentFilter does not contain the same data domains"); 743 return false; 744 } 745 } 746 return true; 747 } 748 749 private IntentFilterVerifier mIntentFilterVerifier; 750 751 // Set of pending broadcasts for aggregating enable/disable of components. 752 static class PendingPackageBroadcasts { 753 // for each user id, a map of <package name -> components within that package> 754 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 755 756 public PendingPackageBroadcasts() { 757 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 758 } 759 760 public ArrayList<String> get(int userId, String packageName) { 761 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 762 return packages.get(packageName); 763 } 764 765 public void put(int userId, String packageName, ArrayList<String> components) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 packages.put(packageName, components); 768 } 769 770 public void remove(int userId, String packageName) { 771 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 772 if (packages != null) { 773 packages.remove(packageName); 774 } 775 } 776 777 public void remove(int userId) { 778 mUidMap.remove(userId); 779 } 780 781 public int userIdCount() { 782 return mUidMap.size(); 783 } 784 785 public int userIdAt(int n) { 786 return mUidMap.keyAt(n); 787 } 788 789 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 790 return mUidMap.get(userId); 791 } 792 793 public int size() { 794 // total number of pending broadcast entries across all userIds 795 int num = 0; 796 for (int i = 0; i< mUidMap.size(); i++) { 797 num += mUidMap.valueAt(i).size(); 798 } 799 return num; 800 } 801 802 public void clear() { 803 mUidMap.clear(); 804 } 805 806 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 807 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 808 if (map == null) { 809 map = new ArrayMap<String, ArrayList<String>>(); 810 mUidMap.put(userId, map); 811 } 812 return map; 813 } 814 } 815 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 816 817 // Service Connection to remote media container service to copy 818 // package uri's from external media onto secure containers 819 // or internal storage. 820 private IMediaContainerService mContainerService = null; 821 822 static final int SEND_PENDING_BROADCAST = 1; 823 static final int MCS_BOUND = 3; 824 static final int END_COPY = 4; 825 static final int INIT_COPY = 5; 826 static final int MCS_UNBIND = 6; 827 static final int START_CLEANING_PACKAGE = 7; 828 static final int FIND_INSTALL_LOC = 8; 829 static final int POST_INSTALL = 9; 830 static final int MCS_RECONNECT = 10; 831 static final int MCS_GIVE_UP = 11; 832 static final int UPDATED_MEDIA_STATUS = 12; 833 static final int WRITE_SETTINGS = 13; 834 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 835 static final int PACKAGE_VERIFIED = 15; 836 static final int CHECK_PENDING_VERIFICATION = 16; 837 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 838 static final int INTENT_FILTER_VERIFIED = 18; 839 840 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 841 842 // Delay time in millisecs 843 static final int BROADCAST_DELAY = 10 * 1000; 844 845 static UserManagerService sUserManager; 846 847 // Stores a list of users whose package restrictions file needs to be updated 848 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 849 850 final private DefaultContainerConnection mDefContainerConn = 851 new DefaultContainerConnection(); 852 class DefaultContainerConnection implements ServiceConnection { 853 public void onServiceConnected(ComponentName name, IBinder service) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 855 IMediaContainerService imcs = 856 IMediaContainerService.Stub.asInterface(service); 857 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 858 } 859 860 public void onServiceDisconnected(ComponentName name) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 862 } 863 }; 864 865 // Recordkeeping of restore-after-install operations that are currently in flight 866 // between the Package Manager and the Backup Manager 867 class PostInstallData { 868 public InstallArgs args; 869 public PackageInstalledInfo res; 870 871 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 872 args = _a; 873 res = _r; 874 } 875 }; 876 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 877 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 878 879 // backup/restore of preferred activity state 880 private static final String TAG_PREFERRED_BACKUP = "pa"; 881 882 private final String mRequiredVerifierPackage; 883 884 private final PackageUsage mPackageUsage = new PackageUsage(); 885 886 private class PackageUsage { 887 private static final int WRITE_INTERVAL 888 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 889 890 private final Object mFileLock = new Object(); 891 private final AtomicLong mLastWritten = new AtomicLong(0); 892 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 893 894 private boolean mIsHistoricalPackageUsageAvailable = true; 895 896 boolean isHistoricalPackageUsageAvailable() { 897 return mIsHistoricalPackageUsageAvailable; 898 } 899 900 void write(boolean force) { 901 if (force) { 902 writeInternal(); 903 return; 904 } 905 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 906 && !DEBUG_DEXOPT) { 907 return; 908 } 909 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 910 new Thread("PackageUsage_DiskWriter") { 911 @Override 912 public void run() { 913 try { 914 writeInternal(); 915 } finally { 916 mBackgroundWriteRunning.set(false); 917 } 918 } 919 }.start(); 920 } 921 } 922 923 private void writeInternal() { 924 synchronized (mPackages) { 925 synchronized (mFileLock) { 926 AtomicFile file = getFile(); 927 FileOutputStream f = null; 928 try { 929 f = file.startWrite(); 930 BufferedOutputStream out = new BufferedOutputStream(f); 931 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 932 StringBuilder sb = new StringBuilder(); 933 for (PackageParser.Package pkg : mPackages.values()) { 934 if (pkg.mLastPackageUsageTimeInMills == 0) { 935 continue; 936 } 937 sb.setLength(0); 938 sb.append(pkg.packageName); 939 sb.append(' '); 940 sb.append((long)pkg.mLastPackageUsageTimeInMills); 941 sb.append('\n'); 942 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 943 } 944 out.flush(); 945 file.finishWrite(f); 946 } catch (IOException e) { 947 if (f != null) { 948 file.failWrite(f); 949 } 950 Log.e(TAG, "Failed to write package usage times", e); 951 } 952 } 953 } 954 mLastWritten.set(SystemClock.elapsedRealtime()); 955 } 956 957 void readLP() { 958 synchronized (mFileLock) { 959 AtomicFile file = getFile(); 960 BufferedInputStream in = null; 961 try { 962 in = new BufferedInputStream(file.openRead()); 963 StringBuffer sb = new StringBuffer(); 964 while (true) { 965 String packageName = readToken(in, sb, ' '); 966 if (packageName == null) { 967 break; 968 } 969 String timeInMillisString = readToken(in, sb, '\n'); 970 if (timeInMillisString == null) { 971 throw new IOException("Failed to find last usage time for package " 972 + packageName); 973 } 974 PackageParser.Package pkg = mPackages.get(packageName); 975 if (pkg == null) { 976 continue; 977 } 978 long timeInMillis; 979 try { 980 timeInMillis = Long.parseLong(timeInMillisString.toString()); 981 } catch (NumberFormatException e) { 982 throw new IOException("Failed to parse " + timeInMillisString 983 + " as a long.", e); 984 } 985 pkg.mLastPackageUsageTimeInMills = timeInMillis; 986 } 987 } catch (FileNotFoundException expected) { 988 mIsHistoricalPackageUsageAvailable = false; 989 } catch (IOException e) { 990 Log.w(TAG, "Failed to read package usage times", e); 991 } finally { 992 IoUtils.closeQuietly(in); 993 } 994 } 995 mLastWritten.set(SystemClock.elapsedRealtime()); 996 } 997 998 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 999 throws IOException { 1000 sb.setLength(0); 1001 while (true) { 1002 int ch = in.read(); 1003 if (ch == -1) { 1004 if (sb.length() == 0) { 1005 return null; 1006 } 1007 throw new IOException("Unexpected EOF"); 1008 } 1009 if (ch == endOfToken) { 1010 return sb.toString(); 1011 } 1012 sb.append((char)ch); 1013 } 1014 } 1015 1016 private AtomicFile getFile() { 1017 File dataDir = Environment.getDataDirectory(); 1018 File systemDir = new File(dataDir, "system"); 1019 File fname = new File(systemDir, "package-usage.list"); 1020 return new AtomicFile(fname); 1021 } 1022 } 1023 1024 class PackageHandler extends Handler { 1025 private boolean mBound = false; 1026 final ArrayList<HandlerParams> mPendingInstalls = 1027 new ArrayList<HandlerParams>(); 1028 1029 private boolean connectToService() { 1030 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1031 " DefaultContainerService"); 1032 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1034 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1035 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 mBound = true; 1038 return true; 1039 } 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 return false; 1042 } 1043 1044 private void disconnectService() { 1045 mContainerService = null; 1046 mBound = false; 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1048 mContext.unbindService(mDefContainerConn); 1049 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1050 } 1051 1052 PackageHandler(Looper looper) { 1053 super(looper); 1054 } 1055 1056 public void handleMessage(Message msg) { 1057 try { 1058 doHandleMessage(msg); 1059 } finally { 1060 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1061 } 1062 } 1063 1064 void doHandleMessage(Message msg) { 1065 switch (msg.what) { 1066 case INIT_COPY: { 1067 HandlerParams params = (HandlerParams) msg.obj; 1068 int idx = mPendingInstalls.size(); 1069 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1070 // If a bind was already initiated we dont really 1071 // need to do anything. The pending install 1072 // will be processed later on. 1073 if (!mBound) { 1074 // If this is the only one pending we might 1075 // have to bind to the service again. 1076 if (!connectToService()) { 1077 Slog.e(TAG, "Failed to bind to media container service"); 1078 params.serviceError(); 1079 return; 1080 } else { 1081 // Once we bind to the service, the first 1082 // pending request will be processed. 1083 mPendingInstalls.add(idx, params); 1084 } 1085 } else { 1086 mPendingInstalls.add(idx, params); 1087 // Already bound to the service. Just make 1088 // sure we trigger off processing the first request. 1089 if (idx == 0) { 1090 mHandler.sendEmptyMessage(MCS_BOUND); 1091 } 1092 } 1093 break; 1094 } 1095 case MCS_BOUND: { 1096 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1097 if (msg.obj != null) { 1098 mContainerService = (IMediaContainerService) msg.obj; 1099 } 1100 if (mContainerService == null) { 1101 // Something seriously wrong. Bail out 1102 Slog.e(TAG, "Cannot bind to media container service"); 1103 for (HandlerParams params : mPendingInstalls) { 1104 // Indicate service bind error 1105 params.serviceError(); 1106 } 1107 mPendingInstalls.clear(); 1108 } else if (mPendingInstalls.size() > 0) { 1109 HandlerParams params = mPendingInstalls.get(0); 1110 if (params != null) { 1111 if (params.startCopy()) { 1112 // We are done... look for more work or to 1113 // go idle. 1114 if (DEBUG_SD_INSTALL) Log.i(TAG, 1115 "Checking for more work or unbind..."); 1116 // Delete pending install 1117 if (mPendingInstalls.size() > 0) { 1118 mPendingInstalls.remove(0); 1119 } 1120 if (mPendingInstalls.size() == 0) { 1121 if (mBound) { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, 1123 "Posting delayed MCS_UNBIND"); 1124 removeMessages(MCS_UNBIND); 1125 Message ubmsg = obtainMessage(MCS_UNBIND); 1126 // Unbind after a little delay, to avoid 1127 // continual thrashing. 1128 sendMessageDelayed(ubmsg, 10000); 1129 } 1130 } else { 1131 // There are more pending requests in queue. 1132 // Just post MCS_BOUND message to trigger processing 1133 // of next pending install. 1134 if (DEBUG_SD_INSTALL) Log.i(TAG, 1135 "Posting MCS_BOUND for next work"); 1136 mHandler.sendEmptyMessage(MCS_BOUND); 1137 } 1138 } 1139 } 1140 } else { 1141 // Should never happen ideally. 1142 Slog.w(TAG, "Empty queue"); 1143 } 1144 break; 1145 } 1146 case MCS_RECONNECT: { 1147 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1148 if (mPendingInstalls.size() > 0) { 1149 if (mBound) { 1150 disconnectService(); 1151 } 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 for (HandlerParams params : mPendingInstalls) { 1155 // Indicate service bind error 1156 params.serviceError(); 1157 } 1158 mPendingInstalls.clear(); 1159 } 1160 } 1161 break; 1162 } 1163 case MCS_UNBIND: { 1164 // If there is no actual work left, then time to unbind. 1165 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1166 1167 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1168 if (mBound) { 1169 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1170 1171 disconnectService(); 1172 } 1173 } else if (mPendingInstalls.size() > 0) { 1174 // There are more pending requests in queue. 1175 // Just post MCS_BOUND message to trigger processing 1176 // of next pending install. 1177 mHandler.sendEmptyMessage(MCS_BOUND); 1178 } 1179 1180 break; 1181 } 1182 case MCS_GIVE_UP: { 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1184 mPendingInstalls.remove(0); 1185 break; 1186 } 1187 case SEND_PENDING_BROADCAST: { 1188 String packages[]; 1189 ArrayList<String> components[]; 1190 int size = 0; 1191 int uids[]; 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1193 synchronized (mPackages) { 1194 if (mPendingBroadcasts == null) { 1195 return; 1196 } 1197 size = mPendingBroadcasts.size(); 1198 if (size <= 0) { 1199 // Nothing to be done. Just return 1200 return; 1201 } 1202 packages = new String[size]; 1203 components = new ArrayList[size]; 1204 uids = new int[size]; 1205 int i = 0; // filling out the above arrays 1206 1207 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1208 int packageUserId = mPendingBroadcasts.userIdAt(n); 1209 Iterator<Map.Entry<String, ArrayList<String>>> it 1210 = mPendingBroadcasts.packagesForUserId(packageUserId) 1211 .entrySet().iterator(); 1212 while (it.hasNext() && i < size) { 1213 Map.Entry<String, ArrayList<String>> ent = it.next(); 1214 packages[i] = ent.getKey(); 1215 components[i] = ent.getValue(); 1216 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1217 uids[i] = (ps != null) 1218 ? UserHandle.getUid(packageUserId, ps.appId) 1219 : -1; 1220 i++; 1221 } 1222 } 1223 size = i; 1224 mPendingBroadcasts.clear(); 1225 } 1226 // Send broadcasts 1227 for (int i = 0; i < size; i++) { 1228 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1229 } 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1231 break; 1232 } 1233 case START_CLEANING_PACKAGE: { 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1235 final String packageName = (String)msg.obj; 1236 final int userId = msg.arg1; 1237 final boolean andCode = msg.arg2 != 0; 1238 synchronized (mPackages) { 1239 if (userId == UserHandle.USER_ALL) { 1240 int[] users = sUserManager.getUserIds(); 1241 for (int user : users) { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(user, packageName, andCode)); 1244 } 1245 } else { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(userId, packageName, andCode)); 1248 } 1249 } 1250 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1251 startCleaningPackages(); 1252 } break; 1253 case POST_INSTALL: { 1254 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1255 PostInstallData data = mRunningInstalls.get(msg.arg1); 1256 mRunningInstalls.delete(msg.arg1); 1257 boolean deleteOld = false; 1258 1259 if (data != null) { 1260 InstallArgs args = data.args; 1261 PackageInstalledInfo res = data.res; 1262 1263 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1264 res.removedInfo.sendBroadcast(false, true, false); 1265 Bundle extras = new Bundle(1); 1266 extras.putInt(Intent.EXTRA_UID, res.uid); 1267 1268 // Now that we successfully installed the package, grant runtime 1269 // permissions if requested before broadcasting the install. 1270 if ((args.installFlags 1271 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1272 grantRequestedRuntimePermissions(res.pkg, 1273 args.user.getIdentifier()); 1274 } 1275 1276 // Determine the set of users who are adding this 1277 // package for the first time vs. those who are seeing 1278 // an update. 1279 int[] firstUsers; 1280 int[] updateUsers = new int[0]; 1281 if (res.origUsers == null || res.origUsers.length == 0) { 1282 firstUsers = res.newUsers; 1283 } else { 1284 firstUsers = new int[0]; 1285 for (int i=0; i<res.newUsers.length; i++) { 1286 int user = res.newUsers[i]; 1287 boolean isNew = true; 1288 for (int j=0; j<res.origUsers.length; j++) { 1289 if (res.origUsers[j] == user) { 1290 isNew = false; 1291 break; 1292 } 1293 } 1294 if (isNew) { 1295 int[] newFirst = new int[firstUsers.length+1]; 1296 System.arraycopy(firstUsers, 0, newFirst, 0, 1297 firstUsers.length); 1298 newFirst[firstUsers.length] = user; 1299 firstUsers = newFirst; 1300 } else { 1301 int[] newUpdate = new int[updateUsers.length+1]; 1302 System.arraycopy(updateUsers, 0, newUpdate, 0, 1303 updateUsers.length); 1304 newUpdate[updateUsers.length] = user; 1305 updateUsers = newUpdate; 1306 } 1307 } 1308 } 1309 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1310 res.pkg.applicationInfo.packageName, 1311 extras, null, null, firstUsers); 1312 final boolean update = res.removedInfo.removedPackage != null; 1313 if (update) { 1314 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 if (update) { 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1324 null, null, 1325 res.pkg.applicationInfo.packageName, null, updateUsers); 1326 1327 // treat asec-hosted packages like removable media on upgrade 1328 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1329 if (DEBUG_INSTALL) { 1330 Slog.i(TAG, "upgrading pkg " + res.pkg 1331 + " is ASEC-hosted -> AVAILABLE"); 1332 } 1333 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1334 ArrayList<String> pkgList = new ArrayList<String>(1); 1335 pkgList.add(res.pkg.applicationInfo.packageName); 1336 sendResourcesChangedBroadcast(true, true, 1337 pkgList,uidArray, null); 1338 } 1339 } 1340 if (res.removedInfo.args != null) { 1341 // Remove the replaced package's older resources safely now 1342 deleteOld = true; 1343 } 1344 1345 // Log current value of "unknown sources" setting 1346 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1347 getUnknownSourcesSettings()); 1348 } 1349 // Force a gc to clear up things 1350 Runtime.getRuntime().gc(); 1351 // We delete after a gc for applications on sdcard. 1352 if (deleteOld) { 1353 synchronized (mInstallLock) { 1354 res.removedInfo.args.doPostDeleteLI(true); 1355 } 1356 } 1357 if (args.observer != null) { 1358 try { 1359 Bundle extras = extrasForInstallResult(res); 1360 args.observer.onPackageInstalled(res.name, res.returnCode, 1361 res.returnMsg, extras); 1362 } catch (RemoteException e) { 1363 Slog.i(TAG, "Observer no longer exists."); 1364 } 1365 } 1366 } else { 1367 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1368 } 1369 } break; 1370 case UPDATED_MEDIA_STATUS: { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1372 boolean reportStatus = msg.arg1 == 1; 1373 boolean doGc = msg.arg2 == 1; 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1375 if (doGc) { 1376 // Force a gc to clear up stale containers. 1377 Runtime.getRuntime().gc(); 1378 } 1379 if (msg.obj != null) { 1380 @SuppressWarnings("unchecked") 1381 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1383 // Unload containers 1384 unloadAllContainers(args); 1385 } 1386 if (reportStatus) { 1387 try { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1389 PackageHelper.getMountService().finishMediaUpdate(); 1390 } catch (RemoteException e) { 1391 Log.e(TAG, "MountService not running?"); 1392 } 1393 } 1394 } break; 1395 case WRITE_SETTINGS: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 synchronized (mPackages) { 1398 removeMessages(WRITE_SETTINGS); 1399 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1400 mSettings.writeLPr(); 1401 mDirtyUsers.clear(); 1402 } 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1404 } break; 1405 case WRITE_PACKAGE_RESTRICTIONS: { 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 synchronized (mPackages) { 1408 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1409 for (int userId : mDirtyUsers) { 1410 mSettings.writePackageRestrictionsLPr(userId); 1411 } 1412 mDirtyUsers.clear(); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 } break; 1416 case CHECK_PENDING_VERIFICATION: { 1417 final int verificationId = msg.arg1; 1418 final PackageVerificationState state = mPendingVerification.get(verificationId); 1419 1420 if ((state != null) && !state.timeoutExtended()) { 1421 final InstallArgs args = state.getInstallArgs(); 1422 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1423 1424 Slog.i(TAG, "Verification timed out for " + originUri); 1425 mPendingVerification.remove(verificationId); 1426 1427 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1428 1429 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1430 Slog.i(TAG, "Continuing with installation of " + originUri); 1431 state.setVerifierResponse(Binder.getCallingUid(), 1432 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1433 broadcastPackageVerified(verificationId, originUri, 1434 PackageManager.VERIFICATION_ALLOW, 1435 state.getInstallArgs().getUser()); 1436 try { 1437 ret = args.copyApk(mContainerService, true); 1438 } catch (RemoteException e) { 1439 Slog.e(TAG, "Could not contact the ContainerService"); 1440 } 1441 } else { 1442 broadcastPackageVerified(verificationId, originUri, 1443 PackageManager.VERIFICATION_REJECT, 1444 state.getInstallArgs().getUser()); 1445 } 1446 1447 processPendingInstall(args, ret); 1448 mHandler.sendEmptyMessage(MCS_UNBIND); 1449 } 1450 break; 1451 } 1452 case PACKAGE_VERIFIED: { 1453 final int verificationId = msg.arg1; 1454 1455 final PackageVerificationState state = mPendingVerification.get(verificationId); 1456 if (state == null) { 1457 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1458 break; 1459 } 1460 1461 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1462 1463 state.setVerifierResponse(response.callerUid, response.code); 1464 1465 if (state.isVerificationComplete()) { 1466 mPendingVerification.remove(verificationId); 1467 1468 final InstallArgs args = state.getInstallArgs(); 1469 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1470 1471 int ret; 1472 if (state.isInstallAllowed()) { 1473 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1474 broadcastPackageVerified(verificationId, originUri, 1475 response.code, state.getInstallArgs().getUser()); 1476 try { 1477 ret = args.copyApk(mContainerService, true); 1478 } catch (RemoteException e) { 1479 Slog.e(TAG, "Could not contact the ContainerService"); 1480 } 1481 } else { 1482 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1483 } 1484 1485 processPendingInstall(args, ret); 1486 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 1490 break; 1491 } 1492 case START_INTENT_FILTER_VERIFICATIONS: { 1493 int userId = msg.arg1; 1494 int verifierUid = msg.arg2; 1495 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1496 1497 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1498 break; 1499 } 1500 case INTENT_FILTER_VERIFIED: { 1501 final int verificationId = msg.arg1; 1502 1503 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1504 verificationId); 1505 if (state == null) { 1506 Slog.w(TAG, "Invalid IntentFilter verification token " 1507 + verificationId + " received"); 1508 break; 1509 } 1510 1511 final int userId = state.getUserId(); 1512 1513 Slog.d(TAG, "Processing IntentFilter verification with token:" 1514 + verificationId + " and userId:" + userId); 1515 1516 final IntentFilterVerificationResponse response = 1517 (IntentFilterVerificationResponse) msg.obj; 1518 1519 state.setVerifierResponse(response.callerUid, response.code); 1520 1521 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1522 + " and userId:" + userId 1523 + " is settings verifier response with response code:" 1524 + response.code); 1525 1526 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1527 Slog.d(TAG, "Domains failing verification: " 1528 + response.getFailedDomainsString()); 1529 } 1530 1531 if (state.isVerificationComplete()) { 1532 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1533 } else { 1534 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1535 + " was not said to be complete"); 1536 } 1537 1538 break; 1539 } 1540 } 1541 } 1542 } 1543 1544 private StorageEventListener mStorageListener = new StorageEventListener() { 1545 @Override 1546 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1547 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1548 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1549 loadPrivatePackages(vol); 1550 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1551 unloadPrivatePackages(vol); 1552 } 1553 } 1554 1555 if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) { 1556 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1557 updateExternalMediaStatus(true, false); 1558 } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) { 1559 updateExternalMediaStatus(false, false); 1560 } 1561 } 1562 } 1563 }; 1564 1565 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1566 if (userId >= UserHandle.USER_OWNER) { 1567 grantRequestedRuntimePermissionsForUser(pkg, userId); 1568 } else if (userId == UserHandle.USER_ALL) { 1569 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1570 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1571 } 1572 } 1573 } 1574 1575 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1576 SettingBase sb = (SettingBase) pkg.mExtras; 1577 if (sb == null) { 1578 return; 1579 } 1580 1581 PermissionsState permissionsState = sb.getPermissionsState(); 1582 1583 for (String permission : pkg.requestedPermissions) { 1584 BasePermission bp = mSettings.mPermissions.get(permission); 1585 if (bp != null && bp.isRuntime()) { 1586 permissionsState.grantRuntimePermission(bp, userId); 1587 } 1588 } 1589 } 1590 1591 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1592 Bundle extras = null; 1593 switch (res.returnCode) { 1594 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1595 extras = new Bundle(); 1596 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1597 res.origPermission); 1598 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1599 res.origPackage); 1600 break; 1601 } 1602 } 1603 return extras; 1604 } 1605 1606 void scheduleWriteSettingsLocked() { 1607 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1608 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1609 } 1610 } 1611 1612 void scheduleWritePackageRestrictionsLocked(int userId) { 1613 if (!sUserManager.exists(userId)) return; 1614 mDirtyUsers.add(userId); 1615 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1616 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1617 } 1618 } 1619 1620 public static PackageManagerService main(Context context, Installer installer, 1621 boolean factoryTest, boolean onlyCore) { 1622 PackageManagerService m = new PackageManagerService(context, installer, 1623 factoryTest, onlyCore); 1624 ServiceManager.addService("package", m); 1625 return m; 1626 } 1627 1628 static String[] splitString(String str, char sep) { 1629 int count = 1; 1630 int i = 0; 1631 while ((i=str.indexOf(sep, i)) >= 0) { 1632 count++; 1633 i++; 1634 } 1635 1636 String[] res = new String[count]; 1637 i=0; 1638 count = 0; 1639 int lastI=0; 1640 while ((i=str.indexOf(sep, i)) >= 0) { 1641 res[count] = str.substring(lastI, i); 1642 count++; 1643 i++; 1644 lastI = i; 1645 } 1646 res[count] = str.substring(lastI, str.length()); 1647 return res; 1648 } 1649 1650 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1651 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1652 Context.DISPLAY_SERVICE); 1653 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1654 } 1655 1656 public PackageManagerService(Context context, Installer installer, 1657 boolean factoryTest, boolean onlyCore) { 1658 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1659 SystemClock.uptimeMillis()); 1660 1661 if (mSdkVersion <= 0) { 1662 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1663 } 1664 1665 mContext = context; 1666 mFactoryTest = factoryTest; 1667 mOnlyCore = onlyCore; 1668 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1669 mMetrics = new DisplayMetrics(); 1670 mSettings = new Settings(mPackages); 1671 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1674 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1675 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1676 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1677 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1682 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1683 1684 // TODO: add a property to control this? 1685 long dexOptLRUThresholdInMinutes; 1686 if (mLazyDexOpt) { 1687 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1688 } else { 1689 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1690 } 1691 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1692 1693 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1694 if (separateProcesses != null && separateProcesses.length() > 0) { 1695 if ("*".equals(separateProcesses)) { 1696 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1697 mSeparateProcesses = null; 1698 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1699 } else { 1700 mDefParseFlags = 0; 1701 mSeparateProcesses = separateProcesses.split(","); 1702 Slog.w(TAG, "Running with debug.separate_processes: " 1703 + separateProcesses); 1704 } 1705 } else { 1706 mDefParseFlags = 0; 1707 mSeparateProcesses = null; 1708 } 1709 1710 mInstaller = installer; 1711 mPackageDexOptimizer = new PackageDexOptimizer(this); 1712 1713 getDefaultDisplayMetrics(context, mMetrics); 1714 1715 SystemConfig systemConfig = SystemConfig.getInstance(); 1716 mGlobalGids = systemConfig.getGlobalGids(); 1717 mSystemPermissions = systemConfig.getSystemPermissions(); 1718 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1719 1720 synchronized (mInstallLock) { 1721 // writer 1722 synchronized (mPackages) { 1723 mHandlerThread = new ServiceThread(TAG, 1724 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1725 mHandlerThread.start(); 1726 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1727 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1728 1729 File dataDir = Environment.getDataDirectory(); 1730 mAppDataDir = new File(dataDir, "data"); 1731 mAppInstallDir = new File(dataDir, "app"); 1732 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1733 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1734 mUserAppDataDir = new File(dataDir, "user"); 1735 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1736 1737 sUserManager = new UserManagerService(context, this, 1738 mInstallLock, mPackages); 1739 1740 // Propagate permission configuration in to package manager. 1741 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1742 = systemConfig.getPermissions(); 1743 for (int i=0; i<permConfig.size(); i++) { 1744 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1745 BasePermission bp = mSettings.mPermissions.get(perm.name); 1746 if (bp == null) { 1747 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1748 mSettings.mPermissions.put(perm.name, bp); 1749 } 1750 if (perm.gids != null) { 1751 bp.setGids(perm.gids, perm.perUser); 1752 } 1753 } 1754 1755 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1756 for (int i=0; i<libConfig.size(); i++) { 1757 mSharedLibraries.put(libConfig.keyAt(i), 1758 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1759 } 1760 1761 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1762 1763 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1764 mSdkVersion, mOnlyCore); 1765 1766 String customResolverActivity = Resources.getSystem().getString( 1767 R.string.config_customResolverActivity); 1768 if (TextUtils.isEmpty(customResolverActivity)) { 1769 customResolverActivity = null; 1770 } else { 1771 mCustomResolverComponentName = ComponentName.unflattenFromString( 1772 customResolverActivity); 1773 } 1774 1775 long startTime = SystemClock.uptimeMillis(); 1776 1777 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1778 startTime); 1779 1780 // Set flag to monitor and not change apk file paths when 1781 // scanning install directories. 1782 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1783 1784 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1785 1786 /** 1787 * Add everything in the in the boot class path to the 1788 * list of process files because dexopt will have been run 1789 * if necessary during zygote startup. 1790 */ 1791 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1792 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1793 1794 if (bootClassPath != null) { 1795 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1796 for (String element : bootClassPathElements) { 1797 alreadyDexOpted.add(element); 1798 } 1799 } else { 1800 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1801 } 1802 1803 if (systemServerClassPath != null) { 1804 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1805 for (String element : systemServerClassPathElements) { 1806 alreadyDexOpted.add(element); 1807 } 1808 } else { 1809 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1810 } 1811 1812 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1813 final String[] dexCodeInstructionSets = 1814 getDexCodeInstructionSets( 1815 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1816 1817 /** 1818 * Ensure all external libraries have had dexopt run on them. 1819 */ 1820 if (mSharedLibraries.size() > 0) { 1821 // NOTE: For now, we're compiling these system "shared libraries" 1822 // (and framework jars) into all available architectures. It's possible 1823 // to compile them only when we come across an app that uses them (there's 1824 // already logic for that in scanPackageLI) but that adds some complexity. 1825 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1826 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1827 final String lib = libEntry.path; 1828 if (lib == null) { 1829 continue; 1830 } 1831 1832 try { 1833 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1834 dexCodeInstructionSet, 1835 false); 1836 if (dexoptRequired != DexFile.UP_TO_DATE) { 1837 alreadyDexOpted.add(lib); 1838 1839 // The list of "shared libraries" we have at this point is 1840 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1841 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1842 } else { 1843 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1844 } 1845 } 1846 } catch (FileNotFoundException e) { 1847 Slog.w(TAG, "Library not found: " + lib); 1848 } catch (IOException e) { 1849 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1850 + e.getMessage()); 1851 } 1852 } 1853 } 1854 } 1855 1856 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1857 1858 // Gross hack for now: we know this file doesn't contain any 1859 // code, so don't dexopt it to avoid the resulting log spew. 1860 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1861 1862 // Gross hack for now: we know this file is only part of 1863 // the boot class path for art, so don't dexopt it to 1864 // avoid the resulting log spew. 1865 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1866 1867 /** 1868 * And there are a number of commands implemented in Java, which 1869 * we currently need to do the dexopt on so that they can be 1870 * run from a non-root shell. 1871 */ 1872 String[] frameworkFiles = frameworkDir.list(); 1873 if (frameworkFiles != null) { 1874 // TODO: We could compile these only for the most preferred ABI. We should 1875 // first double check that the dex files for these commands are not referenced 1876 // by other system apps. 1877 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1878 for (int i=0; i<frameworkFiles.length; i++) { 1879 File libPath = new File(frameworkDir, frameworkFiles[i]); 1880 String path = libPath.getPath(); 1881 // Skip the file if we already did it. 1882 if (alreadyDexOpted.contains(path)) { 1883 continue; 1884 } 1885 // Skip the file if it is not a type we want to dexopt. 1886 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1887 continue; 1888 } 1889 try { 1890 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1891 dexCodeInstructionSet, 1892 false); 1893 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1894 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1895 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1896 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1897 } 1898 } catch (FileNotFoundException e) { 1899 Slog.w(TAG, "Jar not found: " + path); 1900 } catch (IOException e) { 1901 Slog.w(TAG, "Exception reading jar: " + path, e); 1902 } 1903 } 1904 } 1905 } 1906 1907 // Collect vendor overlay packages. 1908 // (Do this before scanning any apps.) 1909 // For security and version matching reason, only consider 1910 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1911 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1912 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1913 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1914 1915 // Find base frameworks (resource packages without code). 1916 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR 1918 | PackageParser.PARSE_IS_PRIVILEGED, 1919 scanFlags | SCAN_NO_DEX, 0); 1920 1921 // Collected privileged system packages. 1922 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1923 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1924 | PackageParser.PARSE_IS_SYSTEM_DIR 1925 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1926 1927 // Collect ordinary system packages. 1928 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1929 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1930 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1931 1932 // Collect all vendor packages. 1933 File vendorAppDir = new File("/vendor/app"); 1934 try { 1935 vendorAppDir = vendorAppDir.getCanonicalFile(); 1936 } catch (IOException e) { 1937 // failed to look up canonical path, continue with original one 1938 } 1939 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1941 1942 // Collect all OEM packages. 1943 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1944 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1945 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1946 1947 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1948 mInstaller.moveFiles(); 1949 1950 // Prune any system packages that no longer exist. 1951 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1952 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1953 if (!mOnlyCore) { 1954 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1955 while (psit.hasNext()) { 1956 PackageSetting ps = psit.next(); 1957 1958 /* 1959 * If this is not a system app, it can't be a 1960 * disable system app. 1961 */ 1962 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1963 continue; 1964 } 1965 1966 /* 1967 * If the package is scanned, it's not erased. 1968 */ 1969 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1970 if (scannedPkg != null) { 1971 /* 1972 * If the system app is both scanned and in the 1973 * disabled packages list, then it must have been 1974 * added via OTA. Remove it from the currently 1975 * scanned package so the previously user-installed 1976 * application can be scanned. 1977 */ 1978 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1979 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1980 + ps.name + "; removing system app. Last known codePath=" 1981 + ps.codePathString + ", installStatus=" + ps.installStatus 1982 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1983 + scannedPkg.mVersionCode); 1984 removePackageLI(ps, true); 1985 expectingBetter.put(ps.name, ps.codePath); 1986 } 1987 1988 continue; 1989 } 1990 1991 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1992 psit.remove(); 1993 logCriticalInfo(Log.WARN, "System package " + ps.name 1994 + " no longer exists; wiping its data"); 1995 removeDataDirsLI(ps.name); 1996 } else { 1997 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1998 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1999 possiblyDeletedUpdatedSystemApps.add(ps.name); 2000 } 2001 } 2002 } 2003 } 2004 2005 //look for any incomplete package installations 2006 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2007 //clean up list 2008 for(int i = 0; i < deletePkgsList.size(); i++) { 2009 //clean up here 2010 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2011 } 2012 //delete tmp files 2013 deleteTempPackageFiles(); 2014 2015 // Remove any shared userIDs that have no associated packages 2016 mSettings.pruneSharedUsersLPw(); 2017 2018 if (!mOnlyCore) { 2019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2020 SystemClock.uptimeMillis()); 2021 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2022 2023 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2024 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2025 2026 /** 2027 * Remove disable package settings for any updated system 2028 * apps that were removed via an OTA. If they're not a 2029 * previously-updated app, remove them completely. 2030 * Otherwise, just revoke their system-level permissions. 2031 */ 2032 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2033 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2034 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2035 2036 String msg; 2037 if (deletedPkg == null) { 2038 msg = "Updated system package " + deletedAppName 2039 + " no longer exists; wiping its data"; 2040 removeDataDirsLI(deletedAppName); 2041 } else { 2042 msg = "Updated system app + " + deletedAppName 2043 + " no longer present; removing system privileges for " 2044 + deletedAppName; 2045 2046 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2047 2048 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2049 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2050 } 2051 logCriticalInfo(Log.WARN, msg); 2052 } 2053 2054 /** 2055 * Make sure all system apps that we expected to appear on 2056 * the userdata partition actually showed up. If they never 2057 * appeared, crawl back and revive the system version. 2058 */ 2059 for (int i = 0; i < expectingBetter.size(); i++) { 2060 final String packageName = expectingBetter.keyAt(i); 2061 if (!mPackages.containsKey(packageName)) { 2062 final File scanFile = expectingBetter.valueAt(i); 2063 2064 logCriticalInfo(Log.WARN, "Expected better " + packageName 2065 + " but never showed up; reverting to system"); 2066 2067 final int reparseFlags; 2068 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2069 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2070 | PackageParser.PARSE_IS_SYSTEM_DIR 2071 | PackageParser.PARSE_IS_PRIVILEGED; 2072 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2073 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2074 | PackageParser.PARSE_IS_SYSTEM_DIR; 2075 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2076 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2077 | PackageParser.PARSE_IS_SYSTEM_DIR; 2078 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2079 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2080 | PackageParser.PARSE_IS_SYSTEM_DIR; 2081 } else { 2082 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2083 continue; 2084 } 2085 2086 mSettings.enableSystemPackageLPw(packageName); 2087 2088 try { 2089 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2090 } catch (PackageManagerException e) { 2091 Slog.e(TAG, "Failed to parse original system package: " 2092 + e.getMessage()); 2093 } 2094 } 2095 } 2096 } 2097 2098 // Now that we know all of the shared libraries, update all clients to have 2099 // the correct library paths. 2100 updateAllSharedLibrariesLPw(); 2101 2102 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2103 // NOTE: We ignore potential failures here during a system scan (like 2104 // the rest of the commands above) because there's precious little we 2105 // can do about it. A settings error is reported, though. 2106 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2107 false /* force dexopt */, false /* defer dexopt */); 2108 } 2109 2110 // Now that we know all the packages we are keeping, 2111 // read and update their last usage times. 2112 mPackageUsage.readLP(); 2113 2114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2115 SystemClock.uptimeMillis()); 2116 Slog.i(TAG, "Time to scan packages: " 2117 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2118 + " seconds"); 2119 2120 // If the platform SDK has changed since the last time we booted, 2121 // we need to re-grant app permission to catch any new ones that 2122 // appear. This is really a hack, and means that apps can in some 2123 // cases get permissions that the user didn't initially explicitly 2124 // allow... it would be nice to have some better way to handle 2125 // this situation. 2126 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2127 != mSdkVersion; 2128 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2129 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2130 + "; regranting permissions for internal storage"); 2131 mSettings.mInternalSdkPlatform = mSdkVersion; 2132 2133 // For now runtime permissions are toggled via a system property. 2134 if (!RUNTIME_PERMISSIONS_ENABLED) { 2135 // Remove the runtime permissions state if the feature 2136 // was disabled by flipping the system property. 2137 mSettings.deleteRuntimePermissionsFiles(); 2138 } 2139 2140 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2141 | (regrantPermissions 2142 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2143 : 0)); 2144 2145 // If this is the first boot, and it is a normal boot, then 2146 // we need to initialize the default preferred apps. 2147 if (!mRestoredSettings && !onlyCore) { 2148 mSettings.readDefaultPreferredAppsLPw(this, 0); 2149 } 2150 2151 // If this is first boot after an OTA, and a normal boot, then 2152 // we need to clear code cache directories. 2153 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2154 if (mIsUpgrade && !onlyCore) { 2155 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2156 for (String pkgName : mSettings.mPackages.keySet()) { 2157 deleteCodeCacheDirsLI(pkgName); 2158 } 2159 mSettings.mFingerprint = Build.FINGERPRINT; 2160 } 2161 2162 // All the changes are done during package scanning. 2163 mSettings.updateInternalDatabaseVersion(); 2164 2165 // can downgrade to reader 2166 mSettings.writeLPr(); 2167 2168 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2169 SystemClock.uptimeMillis()); 2170 2171 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2172 2173 mInstallerService = new PackageInstallerService(context, this); 2174 2175 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2176 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2177 mIntentFilterVerifierComponent); 2178 2179 } // synchronized (mPackages) 2180 } // synchronized (mInstallLock) 2181 2182 // Now after opening every single application zip, make sure they 2183 // are all flushed. Not really needed, but keeps things nice and 2184 // tidy. 2185 Runtime.getRuntime().gc(); 2186 } 2187 2188 @Override 2189 public boolean isFirstBoot() { 2190 return !mRestoredSettings; 2191 } 2192 2193 @Override 2194 public boolean isOnlyCoreApps() { 2195 return mOnlyCore; 2196 } 2197 2198 @Override 2199 public boolean isUpgrade() { 2200 return mIsUpgrade; 2201 } 2202 2203 private String getRequiredVerifierLPr() { 2204 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2205 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2206 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2207 2208 String requiredVerifier = null; 2209 2210 final int N = receivers.size(); 2211 for (int i = 0; i < N; i++) { 2212 final ResolveInfo info = receivers.get(i); 2213 2214 if (info.activityInfo == null) { 2215 continue; 2216 } 2217 2218 final String packageName = info.activityInfo.packageName; 2219 2220 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2221 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2222 continue; 2223 } 2224 2225 if (requiredVerifier != null) { 2226 throw new RuntimeException("There can be only one required verifier"); 2227 } 2228 2229 requiredVerifier = packageName; 2230 } 2231 2232 return requiredVerifier; 2233 } 2234 2235 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2236 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2237 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2238 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2239 2240 ComponentName verifierComponentName = null; 2241 2242 int priority = -1000; 2243 final int N = receivers.size(); 2244 for (int i = 0; i < N; i++) { 2245 final ResolveInfo info = receivers.get(i); 2246 2247 if (info.activityInfo == null) { 2248 continue; 2249 } 2250 2251 final String packageName = info.activityInfo.packageName; 2252 2253 final PackageSetting ps = mSettings.mPackages.get(packageName); 2254 if (ps == null) { 2255 continue; 2256 } 2257 2258 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2259 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2260 continue; 2261 } 2262 2263 // Select the IntentFilterVerifier with the highest priority 2264 if (priority < info.priority) { 2265 priority = info.priority; 2266 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2267 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2268 " with priority: " + info.priority); 2269 } 2270 } 2271 2272 return verifierComponentName; 2273 } 2274 2275 @Override 2276 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2277 throws RemoteException { 2278 try { 2279 return super.onTransact(code, data, reply, flags); 2280 } catch (RuntimeException e) { 2281 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2282 Slog.wtf(TAG, "Package Manager Crash", e); 2283 } 2284 throw e; 2285 } 2286 } 2287 2288 void cleanupInstallFailedPackage(PackageSetting ps) { 2289 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2290 2291 removeDataDirsLI(ps.name); 2292 if (ps.codePath != null) { 2293 if (ps.codePath.isDirectory()) { 2294 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2295 } else { 2296 ps.codePath.delete(); 2297 } 2298 } 2299 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2300 if (ps.resourcePath.isDirectory()) { 2301 FileUtils.deleteContents(ps.resourcePath); 2302 } 2303 ps.resourcePath.delete(); 2304 } 2305 mSettings.removePackageLPw(ps.name); 2306 } 2307 2308 static int[] appendInts(int[] cur, int[] add) { 2309 if (add == null) return cur; 2310 if (cur == null) return add; 2311 final int N = add.length; 2312 for (int i=0; i<N; i++) { 2313 cur = appendInt(cur, add[i]); 2314 } 2315 return cur; 2316 } 2317 2318 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2319 if (!sUserManager.exists(userId)) return null; 2320 final PackageSetting ps = (PackageSetting) p.mExtras; 2321 if (ps == null) { 2322 return null; 2323 } 2324 2325 final PermissionsState permissionsState = ps.getPermissionsState(); 2326 2327 final int[] gids = permissionsState.computeGids(userId); 2328 final Set<String> permissions = permissionsState.getPermissions(userId); 2329 final PackageUserState state = ps.readUserState(userId); 2330 2331 return PackageParser.generatePackageInfo(p, gids, flags, 2332 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2333 } 2334 2335 @Override 2336 public boolean isPackageAvailable(String packageName, int userId) { 2337 if (!sUserManager.exists(userId)) return false; 2338 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2339 synchronized (mPackages) { 2340 PackageParser.Package p = mPackages.get(packageName); 2341 if (p != null) { 2342 final PackageSetting ps = (PackageSetting) p.mExtras; 2343 if (ps != null) { 2344 final PackageUserState state = ps.readUserState(userId); 2345 if (state != null) { 2346 return PackageParser.isAvailable(state); 2347 } 2348 } 2349 } 2350 } 2351 return false; 2352 } 2353 2354 @Override 2355 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2356 if (!sUserManager.exists(userId)) return null; 2357 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2358 // reader 2359 synchronized (mPackages) { 2360 PackageParser.Package p = mPackages.get(packageName); 2361 if (DEBUG_PACKAGE_INFO) 2362 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2363 if (p != null) { 2364 return generatePackageInfo(p, flags, userId); 2365 } 2366 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2367 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2368 } 2369 } 2370 return null; 2371 } 2372 2373 @Override 2374 public String[] currentToCanonicalPackageNames(String[] names) { 2375 String[] out = new String[names.length]; 2376 // reader 2377 synchronized (mPackages) { 2378 for (int i=names.length-1; i>=0; i--) { 2379 PackageSetting ps = mSettings.mPackages.get(names[i]); 2380 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2381 } 2382 } 2383 return out; 2384 } 2385 2386 @Override 2387 public String[] canonicalToCurrentPackageNames(String[] names) { 2388 String[] out = new String[names.length]; 2389 // reader 2390 synchronized (mPackages) { 2391 for (int i=names.length-1; i>=0; i--) { 2392 String cur = mSettings.mRenamedPackages.get(names[i]); 2393 out[i] = cur != null ? cur : names[i]; 2394 } 2395 } 2396 return out; 2397 } 2398 2399 @Override 2400 public int getPackageUid(String packageName, int userId) { 2401 if (!sUserManager.exists(userId)) return -1; 2402 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2403 2404 // reader 2405 synchronized (mPackages) { 2406 PackageParser.Package p = mPackages.get(packageName); 2407 if(p != null) { 2408 return UserHandle.getUid(userId, p.applicationInfo.uid); 2409 } 2410 PackageSetting ps = mSettings.mPackages.get(packageName); 2411 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2412 return -1; 2413 } 2414 p = ps.pkg; 2415 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2416 } 2417 } 2418 2419 @Override 2420 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2421 if (!sUserManager.exists(userId)) { 2422 return null; 2423 } 2424 2425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2426 "getPackageGids"); 2427 2428 // reader 2429 synchronized (mPackages) { 2430 PackageParser.Package p = mPackages.get(packageName); 2431 if (DEBUG_PACKAGE_INFO) { 2432 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2433 } 2434 if (p != null) { 2435 PackageSetting ps = (PackageSetting) p.mExtras; 2436 return ps.getPermissionsState().computeGids(userId); 2437 } 2438 } 2439 2440 return null; 2441 } 2442 2443 static PermissionInfo generatePermissionInfo( 2444 BasePermission bp, int flags) { 2445 if (bp.perm != null) { 2446 return PackageParser.generatePermissionInfo(bp.perm, flags); 2447 } 2448 PermissionInfo pi = new PermissionInfo(); 2449 pi.name = bp.name; 2450 pi.packageName = bp.sourcePackage; 2451 pi.nonLocalizedLabel = bp.name; 2452 pi.protectionLevel = bp.protectionLevel; 2453 return pi; 2454 } 2455 2456 @Override 2457 public PermissionInfo getPermissionInfo(String name, int flags) { 2458 // reader 2459 synchronized (mPackages) { 2460 final BasePermission p = mSettings.mPermissions.get(name); 2461 if (p != null) { 2462 return generatePermissionInfo(p, flags); 2463 } 2464 return null; 2465 } 2466 } 2467 2468 @Override 2469 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2470 // reader 2471 synchronized (mPackages) { 2472 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2473 for (BasePermission p : mSettings.mPermissions.values()) { 2474 if (group == null) { 2475 if (p.perm == null || p.perm.info.group == null) { 2476 out.add(generatePermissionInfo(p, flags)); 2477 } 2478 } else { 2479 if (p.perm != null && group.equals(p.perm.info.group)) { 2480 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2481 } 2482 } 2483 } 2484 2485 if (out.size() > 0) { 2486 return out; 2487 } 2488 return mPermissionGroups.containsKey(group) ? out : null; 2489 } 2490 } 2491 2492 @Override 2493 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2494 // reader 2495 synchronized (mPackages) { 2496 return PackageParser.generatePermissionGroupInfo( 2497 mPermissionGroups.get(name), flags); 2498 } 2499 } 2500 2501 @Override 2502 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2503 // reader 2504 synchronized (mPackages) { 2505 final int N = mPermissionGroups.size(); 2506 ArrayList<PermissionGroupInfo> out 2507 = new ArrayList<PermissionGroupInfo>(N); 2508 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2509 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2510 } 2511 return out; 2512 } 2513 } 2514 2515 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2516 int userId) { 2517 if (!sUserManager.exists(userId)) return null; 2518 PackageSetting ps = mSettings.mPackages.get(packageName); 2519 if (ps != null) { 2520 if (ps.pkg == null) { 2521 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2522 flags, userId); 2523 if (pInfo != null) { 2524 return pInfo.applicationInfo; 2525 } 2526 return null; 2527 } 2528 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2529 ps.readUserState(userId), userId); 2530 } 2531 return null; 2532 } 2533 2534 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2535 int userId) { 2536 if (!sUserManager.exists(userId)) return null; 2537 PackageSetting ps = mSettings.mPackages.get(packageName); 2538 if (ps != null) { 2539 PackageParser.Package pkg = ps.pkg; 2540 if (pkg == null) { 2541 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2542 return null; 2543 } 2544 // Only data remains, so we aren't worried about code paths 2545 pkg = new PackageParser.Package(packageName); 2546 pkg.applicationInfo.packageName = packageName; 2547 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2548 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2549 pkg.applicationInfo.dataDir = 2550 getDataPathForPackage(packageName, 0).getPath(); 2551 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2552 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2553 } 2554 return generatePackageInfo(pkg, flags, userId); 2555 } 2556 return null; 2557 } 2558 2559 @Override 2560 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2561 if (!sUserManager.exists(userId)) return null; 2562 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2563 // writer 2564 synchronized (mPackages) { 2565 PackageParser.Package p = mPackages.get(packageName); 2566 if (DEBUG_PACKAGE_INFO) Log.v( 2567 TAG, "getApplicationInfo " + packageName 2568 + ": " + p); 2569 if (p != null) { 2570 PackageSetting ps = mSettings.mPackages.get(packageName); 2571 if (ps == null) return null; 2572 // Note: isEnabledLP() does not apply here - always return info 2573 return PackageParser.generateApplicationInfo( 2574 p, flags, ps.readUserState(userId), userId); 2575 } 2576 if ("android".equals(packageName)||"system".equals(packageName)) { 2577 return mAndroidApplication; 2578 } 2579 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2580 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2581 } 2582 } 2583 return null; 2584 } 2585 2586 2587 @Override 2588 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2589 mContext.enforceCallingOrSelfPermission( 2590 android.Manifest.permission.CLEAR_APP_CACHE, null); 2591 // Queue up an async operation since clearing cache may take a little while. 2592 mHandler.post(new Runnable() { 2593 public void run() { 2594 mHandler.removeCallbacks(this); 2595 int retCode = -1; 2596 synchronized (mInstallLock) { 2597 retCode = mInstaller.freeCache(freeStorageSize); 2598 if (retCode < 0) { 2599 Slog.w(TAG, "Couldn't clear application caches"); 2600 } 2601 } 2602 if (observer != null) { 2603 try { 2604 observer.onRemoveCompleted(null, (retCode >= 0)); 2605 } catch (RemoteException e) { 2606 Slog.w(TAG, "RemoveException when invoking call back"); 2607 } 2608 } 2609 } 2610 }); 2611 } 2612 2613 @Override 2614 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2615 mContext.enforceCallingOrSelfPermission( 2616 android.Manifest.permission.CLEAR_APP_CACHE, null); 2617 // Queue up an async operation since clearing cache may take a little while. 2618 mHandler.post(new Runnable() { 2619 public void run() { 2620 mHandler.removeCallbacks(this); 2621 int retCode = -1; 2622 synchronized (mInstallLock) { 2623 retCode = mInstaller.freeCache(freeStorageSize); 2624 if (retCode < 0) { 2625 Slog.w(TAG, "Couldn't clear application caches"); 2626 } 2627 } 2628 if(pi != null) { 2629 try { 2630 // Callback via pending intent 2631 int code = (retCode >= 0) ? 1 : 0; 2632 pi.sendIntent(null, code, null, 2633 null, null); 2634 } catch (SendIntentException e1) { 2635 Slog.i(TAG, "Failed to send pending intent"); 2636 } 2637 } 2638 } 2639 }); 2640 } 2641 2642 void freeStorage(long freeStorageSize) throws IOException { 2643 synchronized (mInstallLock) { 2644 if (mInstaller.freeCache(freeStorageSize) < 0) { 2645 throw new IOException("Failed to free enough space"); 2646 } 2647 } 2648 } 2649 2650 @Override 2651 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2652 if (!sUserManager.exists(userId)) return null; 2653 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2654 synchronized (mPackages) { 2655 PackageParser.Activity a = mActivities.mActivities.get(component); 2656 2657 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2658 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2659 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2660 if (ps == null) return null; 2661 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2662 userId); 2663 } 2664 if (mResolveComponentName.equals(component)) { 2665 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2666 new PackageUserState(), userId); 2667 } 2668 } 2669 return null; 2670 } 2671 2672 @Override 2673 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2674 String resolvedType) { 2675 synchronized (mPackages) { 2676 PackageParser.Activity a = mActivities.mActivities.get(component); 2677 if (a == null) { 2678 return false; 2679 } 2680 for (int i=0; i<a.intents.size(); i++) { 2681 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2682 intent.getData(), intent.getCategories(), TAG) >= 0) { 2683 return true; 2684 } 2685 } 2686 return false; 2687 } 2688 } 2689 2690 @Override 2691 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2692 if (!sUserManager.exists(userId)) return null; 2693 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2694 synchronized (mPackages) { 2695 PackageParser.Activity a = mReceivers.mActivities.get(component); 2696 if (DEBUG_PACKAGE_INFO) Log.v( 2697 TAG, "getReceiverInfo " + component + ": " + a); 2698 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2699 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2700 if (ps == null) return null; 2701 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2702 userId); 2703 } 2704 } 2705 return null; 2706 } 2707 2708 @Override 2709 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2710 if (!sUserManager.exists(userId)) return null; 2711 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2712 synchronized (mPackages) { 2713 PackageParser.Service s = mServices.mServices.get(component); 2714 if (DEBUG_PACKAGE_INFO) Log.v( 2715 TAG, "getServiceInfo " + component + ": " + s); 2716 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2717 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2718 if (ps == null) return null; 2719 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2720 userId); 2721 } 2722 } 2723 return null; 2724 } 2725 2726 @Override 2727 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2728 if (!sUserManager.exists(userId)) return null; 2729 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2730 synchronized (mPackages) { 2731 PackageParser.Provider p = mProviders.mProviders.get(component); 2732 if (DEBUG_PACKAGE_INFO) Log.v( 2733 TAG, "getProviderInfo " + component + ": " + p); 2734 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2735 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2736 if (ps == null) return null; 2737 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2738 userId); 2739 } 2740 } 2741 return null; 2742 } 2743 2744 @Override 2745 public String[] getSystemSharedLibraryNames() { 2746 Set<String> libSet; 2747 synchronized (mPackages) { 2748 libSet = mSharedLibraries.keySet(); 2749 int size = libSet.size(); 2750 if (size > 0) { 2751 String[] libs = new String[size]; 2752 libSet.toArray(libs); 2753 return libs; 2754 } 2755 } 2756 return null; 2757 } 2758 2759 /** 2760 * @hide 2761 */ 2762 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2763 synchronized (mPackages) { 2764 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2765 if (lib != null && lib.apk != null) { 2766 return mPackages.get(lib.apk); 2767 } 2768 } 2769 return null; 2770 } 2771 2772 @Override 2773 public FeatureInfo[] getSystemAvailableFeatures() { 2774 Collection<FeatureInfo> featSet; 2775 synchronized (mPackages) { 2776 featSet = mAvailableFeatures.values(); 2777 int size = featSet.size(); 2778 if (size > 0) { 2779 FeatureInfo[] features = new FeatureInfo[size+1]; 2780 featSet.toArray(features); 2781 FeatureInfo fi = new FeatureInfo(); 2782 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2783 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2784 features[size] = fi; 2785 return features; 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public boolean hasSystemFeature(String name) { 2793 synchronized (mPackages) { 2794 return mAvailableFeatures.containsKey(name); 2795 } 2796 } 2797 2798 private void checkValidCaller(int uid, int userId) { 2799 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2800 return; 2801 2802 throw new SecurityException("Caller uid=" + uid 2803 + " is not privileged to communicate with user=" + userId); 2804 } 2805 2806 @Override 2807 public int checkPermission(String permName, String pkgName, int userId) { 2808 if (!sUserManager.exists(userId)) { 2809 return PackageManager.PERMISSION_DENIED; 2810 } 2811 2812 synchronized (mPackages) { 2813 final PackageParser.Package p = mPackages.get(pkgName); 2814 if (p != null && p.mExtras != null) { 2815 final PackageSetting ps = (PackageSetting) p.mExtras; 2816 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2817 return PackageManager.PERMISSION_GRANTED; 2818 } 2819 } 2820 } 2821 2822 return PackageManager.PERMISSION_DENIED; 2823 } 2824 2825 @Override 2826 public int checkUidPermission(String permName, int uid) { 2827 final int userId = UserHandle.getUserId(uid); 2828 2829 if (!sUserManager.exists(userId)) { 2830 return PackageManager.PERMISSION_DENIED; 2831 } 2832 2833 synchronized (mPackages) { 2834 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2835 if (obj != null) { 2836 final SettingBase ps = (SettingBase) obj; 2837 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2838 return PackageManager.PERMISSION_GRANTED; 2839 } 2840 } else { 2841 ArraySet<String> perms = mSystemPermissions.get(uid); 2842 if (perms != null && perms.contains(permName)) { 2843 return PackageManager.PERMISSION_GRANTED; 2844 } 2845 } 2846 } 2847 2848 return PackageManager.PERMISSION_DENIED; 2849 } 2850 2851 /** 2852 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2853 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2854 * @param checkShell TODO(yamasani): 2855 * @param message the message to log on security exception 2856 */ 2857 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2858 boolean checkShell, String message) { 2859 if (userId < 0) { 2860 throw new IllegalArgumentException("Invalid userId " + userId); 2861 } 2862 if (checkShell) { 2863 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2864 } 2865 if (userId == UserHandle.getUserId(callingUid)) return; 2866 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2867 if (requireFullPermission) { 2868 mContext.enforceCallingOrSelfPermission( 2869 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2870 } else { 2871 try { 2872 mContext.enforceCallingOrSelfPermission( 2873 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2874 } catch (SecurityException se) { 2875 mContext.enforceCallingOrSelfPermission( 2876 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2877 } 2878 } 2879 } 2880 } 2881 2882 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2883 if (callingUid == Process.SHELL_UID) { 2884 if (userHandle >= 0 2885 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2886 throw new SecurityException("Shell does not have permission to access user " 2887 + userHandle); 2888 } else if (userHandle < 0) { 2889 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2890 + Debug.getCallers(3)); 2891 } 2892 } 2893 } 2894 2895 private BasePermission findPermissionTreeLP(String permName) { 2896 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2897 if (permName.startsWith(bp.name) && 2898 permName.length() > bp.name.length() && 2899 permName.charAt(bp.name.length()) == '.') { 2900 return bp; 2901 } 2902 } 2903 return null; 2904 } 2905 2906 private BasePermission checkPermissionTreeLP(String permName) { 2907 if (permName != null) { 2908 BasePermission bp = findPermissionTreeLP(permName); 2909 if (bp != null) { 2910 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2911 return bp; 2912 } 2913 throw new SecurityException("Calling uid " 2914 + Binder.getCallingUid() 2915 + " is not allowed to add to permission tree " 2916 + bp.name + " owned by uid " + bp.uid); 2917 } 2918 } 2919 throw new SecurityException("No permission tree found for " + permName); 2920 } 2921 2922 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2923 if (s1 == null) { 2924 return s2 == null; 2925 } 2926 if (s2 == null) { 2927 return false; 2928 } 2929 if (s1.getClass() != s2.getClass()) { 2930 return false; 2931 } 2932 return s1.equals(s2); 2933 } 2934 2935 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2936 if (pi1.icon != pi2.icon) return false; 2937 if (pi1.logo != pi2.logo) return false; 2938 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2939 if (!compareStrings(pi1.name, pi2.name)) return false; 2940 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2941 // We'll take care of setting this one. 2942 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2943 // These are not currently stored in settings. 2944 //if (!compareStrings(pi1.group, pi2.group)) return false; 2945 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2946 //if (pi1.labelRes != pi2.labelRes) return false; 2947 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2948 return true; 2949 } 2950 2951 int permissionInfoFootprint(PermissionInfo info) { 2952 int size = info.name.length(); 2953 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2954 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2955 return size; 2956 } 2957 2958 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2959 int size = 0; 2960 for (BasePermission perm : mSettings.mPermissions.values()) { 2961 if (perm.uid == tree.uid) { 2962 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2963 } 2964 } 2965 return size; 2966 } 2967 2968 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2969 // We calculate the max size of permissions defined by this uid and throw 2970 // if that plus the size of 'info' would exceed our stated maximum. 2971 if (tree.uid != Process.SYSTEM_UID) { 2972 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2973 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2974 throw new SecurityException("Permission tree size cap exceeded"); 2975 } 2976 } 2977 } 2978 2979 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2980 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2981 throw new SecurityException("Label must be specified in permission"); 2982 } 2983 BasePermission tree = checkPermissionTreeLP(info.name); 2984 BasePermission bp = mSettings.mPermissions.get(info.name); 2985 boolean added = bp == null; 2986 boolean changed = true; 2987 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2988 if (added) { 2989 enforcePermissionCapLocked(info, tree); 2990 bp = new BasePermission(info.name, tree.sourcePackage, 2991 BasePermission.TYPE_DYNAMIC); 2992 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2993 throw new SecurityException( 2994 "Not allowed to modify non-dynamic permission " 2995 + info.name); 2996 } else { 2997 if (bp.protectionLevel == fixedLevel 2998 && bp.perm.owner.equals(tree.perm.owner) 2999 && bp.uid == tree.uid 3000 && comparePermissionInfos(bp.perm.info, info)) { 3001 changed = false; 3002 } 3003 } 3004 bp.protectionLevel = fixedLevel; 3005 info = new PermissionInfo(info); 3006 info.protectionLevel = fixedLevel; 3007 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3008 bp.perm.info.packageName = tree.perm.info.packageName; 3009 bp.uid = tree.uid; 3010 if (added) { 3011 mSettings.mPermissions.put(info.name, bp); 3012 } 3013 if (changed) { 3014 if (!async) { 3015 mSettings.writeLPr(); 3016 } else { 3017 scheduleWriteSettingsLocked(); 3018 } 3019 } 3020 return added; 3021 } 3022 3023 @Override 3024 public boolean addPermission(PermissionInfo info) { 3025 synchronized (mPackages) { 3026 return addPermissionLocked(info, false); 3027 } 3028 } 3029 3030 @Override 3031 public boolean addPermissionAsync(PermissionInfo info) { 3032 synchronized (mPackages) { 3033 return addPermissionLocked(info, true); 3034 } 3035 } 3036 3037 @Override 3038 public void removePermission(String name) { 3039 synchronized (mPackages) { 3040 checkPermissionTreeLP(name); 3041 BasePermission bp = mSettings.mPermissions.get(name); 3042 if (bp != null) { 3043 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3044 throw new SecurityException( 3045 "Not allowed to modify non-dynamic permission " 3046 + name); 3047 } 3048 mSettings.mPermissions.remove(name); 3049 mSettings.writeLPr(); 3050 } 3051 } 3052 } 3053 3054 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3055 BasePermission bp) { 3056 int index = pkg.requestedPermissions.indexOf(bp.name); 3057 if (index == -1) { 3058 throw new SecurityException("Package " + pkg.packageName 3059 + " has not requested permission " + bp.name); 3060 } 3061 if (!bp.isRuntime()) { 3062 throw new SecurityException("Permission " + bp.name 3063 + " is not a changeable permission type"); 3064 } 3065 } 3066 3067 @Override 3068 public boolean grantPermission(String packageName, String name, int userId) { 3069 if (!RUNTIME_PERMISSIONS_ENABLED) { 3070 return false; 3071 } 3072 3073 if (!sUserManager.exists(userId)) { 3074 return false; 3075 } 3076 3077 mContext.enforceCallingOrSelfPermission( 3078 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3079 "grantPermission"); 3080 3081 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3082 "grantPermission"); 3083 3084 boolean gidsChanged = false; 3085 final SettingBase sb; 3086 3087 synchronized (mPackages) { 3088 final PackageParser.Package pkg = mPackages.get(packageName); 3089 if (pkg == null) { 3090 throw new IllegalArgumentException("Unknown package: " + packageName); 3091 } 3092 3093 final BasePermission bp = mSettings.mPermissions.get(name); 3094 if (bp == null) { 3095 throw new IllegalArgumentException("Unknown permission: " + name); 3096 } 3097 3098 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3099 3100 sb = (SettingBase) pkg.mExtras; 3101 if (sb == null) { 3102 throw new IllegalArgumentException("Unknown package: " + packageName); 3103 } 3104 3105 final PermissionsState permissionsState = sb.getPermissionsState(); 3106 3107 final int result = permissionsState.grantRuntimePermission(bp, userId); 3108 switch (result) { 3109 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3110 return false; 3111 } 3112 3113 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3114 gidsChanged = true; 3115 } break; 3116 } 3117 3118 // Not critical if that is lost - app has to request again. 3119 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3120 } 3121 3122 if (gidsChanged) { 3123 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3124 } 3125 3126 return true; 3127 } 3128 3129 @Override 3130 public boolean revokePermission(String packageName, String name, int userId) { 3131 if (!RUNTIME_PERMISSIONS_ENABLED) { 3132 return false; 3133 } 3134 3135 if (!sUserManager.exists(userId)) { 3136 return false; 3137 } 3138 3139 mContext.enforceCallingOrSelfPermission( 3140 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3141 "revokePermission"); 3142 3143 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3144 "revokePermission"); 3145 3146 final SettingBase sb; 3147 3148 synchronized (mPackages) { 3149 final PackageParser.Package pkg = mPackages.get(packageName); 3150 if (pkg == null) { 3151 throw new IllegalArgumentException("Unknown package: " + packageName); 3152 } 3153 3154 final BasePermission bp = mSettings.mPermissions.get(name); 3155 if (bp == null) { 3156 throw new IllegalArgumentException("Unknown permission: " + name); 3157 } 3158 3159 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3160 3161 sb = (SettingBase) pkg.mExtras; 3162 if (sb == null) { 3163 throw new IllegalArgumentException("Unknown package: " + packageName); 3164 } 3165 3166 final PermissionsState permissionsState = sb.getPermissionsState(); 3167 3168 if (permissionsState.revokeRuntimePermission(bp, userId) == 3169 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3170 return false; 3171 } 3172 3173 // Critical, after this call all should never have the permission. 3174 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3175 } 3176 3177 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3178 3179 return true; 3180 } 3181 3182 @Override 3183 public boolean isProtectedBroadcast(String actionName) { 3184 synchronized (mPackages) { 3185 return mProtectedBroadcasts.contains(actionName); 3186 } 3187 } 3188 3189 @Override 3190 public int checkSignatures(String pkg1, String pkg2) { 3191 synchronized (mPackages) { 3192 final PackageParser.Package p1 = mPackages.get(pkg1); 3193 final PackageParser.Package p2 = mPackages.get(pkg2); 3194 if (p1 == null || p1.mExtras == null 3195 || p2 == null || p2.mExtras == null) { 3196 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3197 } 3198 return compareSignatures(p1.mSignatures, p2.mSignatures); 3199 } 3200 } 3201 3202 @Override 3203 public int checkUidSignatures(int uid1, int uid2) { 3204 // Map to base uids. 3205 uid1 = UserHandle.getAppId(uid1); 3206 uid2 = UserHandle.getAppId(uid2); 3207 // reader 3208 synchronized (mPackages) { 3209 Signature[] s1; 3210 Signature[] s2; 3211 Object obj = mSettings.getUserIdLPr(uid1); 3212 if (obj != null) { 3213 if (obj instanceof SharedUserSetting) { 3214 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3215 } else if (obj instanceof PackageSetting) { 3216 s1 = ((PackageSetting)obj).signatures.mSignatures; 3217 } else { 3218 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3219 } 3220 } else { 3221 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3222 } 3223 obj = mSettings.getUserIdLPr(uid2); 3224 if (obj != null) { 3225 if (obj instanceof SharedUserSetting) { 3226 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3227 } else if (obj instanceof PackageSetting) { 3228 s2 = ((PackageSetting)obj).signatures.mSignatures; 3229 } else { 3230 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3231 } 3232 } else { 3233 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3234 } 3235 return compareSignatures(s1, s2); 3236 } 3237 } 3238 3239 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3240 final long identity = Binder.clearCallingIdentity(); 3241 try { 3242 if (sb instanceof SharedUserSetting) { 3243 SharedUserSetting sus = (SharedUserSetting) sb; 3244 final int packageCount = sus.packages.size(); 3245 for (int i = 0; i < packageCount; i++) { 3246 PackageSetting susPs = sus.packages.valueAt(i); 3247 if (userId == UserHandle.USER_ALL) { 3248 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3249 } else { 3250 final int uid = UserHandle.getUid(userId, susPs.appId); 3251 killUid(uid, reason); 3252 } 3253 } 3254 } else if (sb instanceof PackageSetting) { 3255 PackageSetting ps = (PackageSetting) sb; 3256 if (userId == UserHandle.USER_ALL) { 3257 killApplication(ps.pkg.packageName, ps.appId, reason); 3258 } else { 3259 final int uid = UserHandle.getUid(userId, ps.appId); 3260 killUid(uid, reason); 3261 } 3262 } 3263 } finally { 3264 Binder.restoreCallingIdentity(identity); 3265 } 3266 } 3267 3268 private static void killUid(int uid, String reason) { 3269 IActivityManager am = ActivityManagerNative.getDefault(); 3270 if (am != null) { 3271 try { 3272 am.killUid(uid, reason); 3273 } catch (RemoteException e) { 3274 /* ignore - same process */ 3275 } 3276 } 3277 } 3278 3279 /** 3280 * Compares two sets of signatures. Returns: 3281 * <br /> 3282 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3283 * <br /> 3284 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3285 * <br /> 3286 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3287 * <br /> 3288 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3289 * <br /> 3290 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3291 */ 3292 static int compareSignatures(Signature[] s1, Signature[] s2) { 3293 if (s1 == null) { 3294 return s2 == null 3295 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3296 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3297 } 3298 3299 if (s2 == null) { 3300 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3301 } 3302 3303 if (s1.length != s2.length) { 3304 return PackageManager.SIGNATURE_NO_MATCH; 3305 } 3306 3307 // Since both signature sets are of size 1, we can compare without HashSets. 3308 if (s1.length == 1) { 3309 return s1[0].equals(s2[0]) ? 3310 PackageManager.SIGNATURE_MATCH : 3311 PackageManager.SIGNATURE_NO_MATCH; 3312 } 3313 3314 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3315 for (Signature sig : s1) { 3316 set1.add(sig); 3317 } 3318 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3319 for (Signature sig : s2) { 3320 set2.add(sig); 3321 } 3322 // Make sure s2 contains all signatures in s1. 3323 if (set1.equals(set2)) { 3324 return PackageManager.SIGNATURE_MATCH; 3325 } 3326 return PackageManager.SIGNATURE_NO_MATCH; 3327 } 3328 3329 /** 3330 * If the database version for this type of package (internal storage or 3331 * external storage) is less than the version where package signatures 3332 * were updated, return true. 3333 */ 3334 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3335 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3336 DatabaseVersion.SIGNATURE_END_ENTITY)) 3337 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3338 DatabaseVersion.SIGNATURE_END_ENTITY)); 3339 } 3340 3341 /** 3342 * Used for backward compatibility to make sure any packages with 3343 * certificate chains get upgraded to the new style. {@code existingSigs} 3344 * will be in the old format (since they were stored on disk from before the 3345 * system upgrade) and {@code scannedSigs} will be in the newer format. 3346 */ 3347 private int compareSignaturesCompat(PackageSignatures existingSigs, 3348 PackageParser.Package scannedPkg) { 3349 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3350 return PackageManager.SIGNATURE_NO_MATCH; 3351 } 3352 3353 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3354 for (Signature sig : existingSigs.mSignatures) { 3355 existingSet.add(sig); 3356 } 3357 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3358 for (Signature sig : scannedPkg.mSignatures) { 3359 try { 3360 Signature[] chainSignatures = sig.getChainSignatures(); 3361 for (Signature chainSig : chainSignatures) { 3362 scannedCompatSet.add(chainSig); 3363 } 3364 } catch (CertificateEncodingException e) { 3365 scannedCompatSet.add(sig); 3366 } 3367 } 3368 /* 3369 * Make sure the expanded scanned set contains all signatures in the 3370 * existing one. 3371 */ 3372 if (scannedCompatSet.equals(existingSet)) { 3373 // Migrate the old signatures to the new scheme. 3374 existingSigs.assignSignatures(scannedPkg.mSignatures); 3375 // The new KeySets will be re-added later in the scanning process. 3376 synchronized (mPackages) { 3377 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3378 } 3379 return PackageManager.SIGNATURE_MATCH; 3380 } 3381 return PackageManager.SIGNATURE_NO_MATCH; 3382 } 3383 3384 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3385 if (isExternal(scannedPkg)) { 3386 return mSettings.isExternalDatabaseVersionOlderThan( 3387 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3388 } else { 3389 return mSettings.isInternalDatabaseVersionOlderThan( 3390 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3391 } 3392 } 3393 3394 private int compareSignaturesRecover(PackageSignatures existingSigs, 3395 PackageParser.Package scannedPkg) { 3396 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3397 return PackageManager.SIGNATURE_NO_MATCH; 3398 } 3399 3400 String msg = null; 3401 try { 3402 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3403 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3404 + scannedPkg.packageName); 3405 return PackageManager.SIGNATURE_MATCH; 3406 } 3407 } catch (CertificateException e) { 3408 msg = e.getMessage(); 3409 } 3410 3411 logCriticalInfo(Log.INFO, 3412 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3413 return PackageManager.SIGNATURE_NO_MATCH; 3414 } 3415 3416 @Override 3417 public String[] getPackagesForUid(int uid) { 3418 uid = UserHandle.getAppId(uid); 3419 // reader 3420 synchronized (mPackages) { 3421 Object obj = mSettings.getUserIdLPr(uid); 3422 if (obj instanceof SharedUserSetting) { 3423 final SharedUserSetting sus = (SharedUserSetting) obj; 3424 final int N = sus.packages.size(); 3425 final String[] res = new String[N]; 3426 final Iterator<PackageSetting> it = sus.packages.iterator(); 3427 int i = 0; 3428 while (it.hasNext()) { 3429 res[i++] = it.next().name; 3430 } 3431 return res; 3432 } else if (obj instanceof PackageSetting) { 3433 final PackageSetting ps = (PackageSetting) obj; 3434 return new String[] { ps.name }; 3435 } 3436 } 3437 return null; 3438 } 3439 3440 @Override 3441 public String getNameForUid(int uid) { 3442 // reader 3443 synchronized (mPackages) { 3444 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3445 if (obj instanceof SharedUserSetting) { 3446 final SharedUserSetting sus = (SharedUserSetting) obj; 3447 return sus.name + ":" + sus.userId; 3448 } else if (obj instanceof PackageSetting) { 3449 final PackageSetting ps = (PackageSetting) obj; 3450 return ps.name; 3451 } 3452 } 3453 return null; 3454 } 3455 3456 @Override 3457 public int getUidForSharedUser(String sharedUserName) { 3458 if(sharedUserName == null) { 3459 return -1; 3460 } 3461 // reader 3462 synchronized (mPackages) { 3463 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3464 if (suid == null) { 3465 return -1; 3466 } 3467 return suid.userId; 3468 } 3469 } 3470 3471 @Override 3472 public int getFlagsForUid(int uid) { 3473 synchronized (mPackages) { 3474 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3475 if (obj instanceof SharedUserSetting) { 3476 final SharedUserSetting sus = (SharedUserSetting) obj; 3477 return sus.pkgFlags; 3478 } else if (obj instanceof PackageSetting) { 3479 final PackageSetting ps = (PackageSetting) obj; 3480 return ps.pkgFlags; 3481 } 3482 } 3483 return 0; 3484 } 3485 3486 @Override 3487 public int getPrivateFlagsForUid(int uid) { 3488 synchronized (mPackages) { 3489 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3490 if (obj instanceof SharedUserSetting) { 3491 final SharedUserSetting sus = (SharedUserSetting) obj; 3492 return sus.pkgPrivateFlags; 3493 } else if (obj instanceof PackageSetting) { 3494 final PackageSetting ps = (PackageSetting) obj; 3495 return ps.pkgPrivateFlags; 3496 } 3497 } 3498 return 0; 3499 } 3500 3501 @Override 3502 public boolean isUidPrivileged(int uid) { 3503 uid = UserHandle.getAppId(uid); 3504 // reader 3505 synchronized (mPackages) { 3506 Object obj = mSettings.getUserIdLPr(uid); 3507 if (obj instanceof SharedUserSetting) { 3508 final SharedUserSetting sus = (SharedUserSetting) obj; 3509 final Iterator<PackageSetting> it = sus.packages.iterator(); 3510 while (it.hasNext()) { 3511 if (it.next().isPrivileged()) { 3512 return true; 3513 } 3514 } 3515 } else if (obj instanceof PackageSetting) { 3516 final PackageSetting ps = (PackageSetting) obj; 3517 return ps.isPrivileged(); 3518 } 3519 } 3520 return false; 3521 } 3522 3523 @Override 3524 public String[] getAppOpPermissionPackages(String permissionName) { 3525 synchronized (mPackages) { 3526 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3527 if (pkgs == null) { 3528 return null; 3529 } 3530 return pkgs.toArray(new String[pkgs.size()]); 3531 } 3532 } 3533 3534 @Override 3535 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3536 int flags, int userId) { 3537 if (!sUserManager.exists(userId)) return null; 3538 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3539 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3540 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3541 } 3542 3543 @Override 3544 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3545 IntentFilter filter, int match, ComponentName activity) { 3546 final int userId = UserHandle.getCallingUserId(); 3547 if (DEBUG_PREFERRED) { 3548 Log.v(TAG, "setLastChosenActivity intent=" + intent 3549 + " resolvedType=" + resolvedType 3550 + " flags=" + flags 3551 + " filter=" + filter 3552 + " match=" + match 3553 + " activity=" + activity); 3554 filter.dump(new PrintStreamPrinter(System.out), " "); 3555 } 3556 intent.setComponent(null); 3557 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3558 // Find any earlier preferred or last chosen entries and nuke them 3559 findPreferredActivity(intent, resolvedType, 3560 flags, query, 0, false, true, false, userId); 3561 // Add the new activity as the last chosen for this filter 3562 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3563 "Setting last chosen"); 3564 } 3565 3566 @Override 3567 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3568 final int userId = UserHandle.getCallingUserId(); 3569 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3570 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3571 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3572 false, false, false, userId); 3573 } 3574 3575 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3576 int flags, List<ResolveInfo> query, int userId) { 3577 if (query != null) { 3578 final int N = query.size(); 3579 if (N == 1) { 3580 return query.get(0); 3581 } else if (N > 1) { 3582 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3583 // If there is more than one activity with the same priority, 3584 // then let the user decide between them. 3585 ResolveInfo r0 = query.get(0); 3586 ResolveInfo r1 = query.get(1); 3587 if (DEBUG_INTENT_MATCHING || debug) { 3588 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3589 + r1.activityInfo.name + "=" + r1.priority); 3590 } 3591 // If the first activity has a higher priority, or a different 3592 // default, then it is always desireable to pick it. 3593 if (r0.priority != r1.priority 3594 || r0.preferredOrder != r1.preferredOrder 3595 || r0.isDefault != r1.isDefault) { 3596 return query.get(0); 3597 } 3598 // If we have saved a preference for a preferred activity for 3599 // this Intent, use that. 3600 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3601 flags, query, r0.priority, true, false, debug, userId); 3602 if (ri != null) { 3603 return ri; 3604 } 3605 if (userId != 0) { 3606 ri = new ResolveInfo(mResolveInfo); 3607 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3608 ri.activityInfo.applicationInfo = new ApplicationInfo( 3609 ri.activityInfo.applicationInfo); 3610 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3611 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3612 return ri; 3613 } 3614 return mResolveInfo; 3615 } 3616 } 3617 return null; 3618 } 3619 3620 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3621 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3622 final int N = query.size(); 3623 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3624 .get(userId); 3625 // Get the list of persistent preferred activities that handle the intent 3626 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3627 List<PersistentPreferredActivity> pprefs = ppir != null 3628 ? ppir.queryIntent(intent, resolvedType, 3629 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3630 : null; 3631 if (pprefs != null && pprefs.size() > 0) { 3632 final int M = pprefs.size(); 3633 for (int i=0; i<M; i++) { 3634 final PersistentPreferredActivity ppa = pprefs.get(i); 3635 if (DEBUG_PREFERRED || debug) { 3636 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3637 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3638 + "\n component=" + ppa.mComponent); 3639 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3640 } 3641 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3642 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3643 if (DEBUG_PREFERRED || debug) { 3644 Slog.v(TAG, "Found persistent preferred activity:"); 3645 if (ai != null) { 3646 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3647 } else { 3648 Slog.v(TAG, " null"); 3649 } 3650 } 3651 if (ai == null) { 3652 // This previously registered persistent preferred activity 3653 // component is no longer known. Ignore it and do NOT remove it. 3654 continue; 3655 } 3656 for (int j=0; j<N; j++) { 3657 final ResolveInfo ri = query.get(j); 3658 if (!ri.activityInfo.applicationInfo.packageName 3659 .equals(ai.applicationInfo.packageName)) { 3660 continue; 3661 } 3662 if (!ri.activityInfo.name.equals(ai.name)) { 3663 continue; 3664 } 3665 // Found a persistent preference that can handle the intent. 3666 if (DEBUG_PREFERRED || debug) { 3667 Slog.v(TAG, "Returning persistent preferred activity: " + 3668 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3669 } 3670 return ri; 3671 } 3672 } 3673 } 3674 return null; 3675 } 3676 3677 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3678 List<ResolveInfo> query, int priority, boolean always, 3679 boolean removeMatches, boolean debug, int userId) { 3680 if (!sUserManager.exists(userId)) return null; 3681 // writer 3682 synchronized (mPackages) { 3683 if (intent.getSelector() != null) { 3684 intent = intent.getSelector(); 3685 } 3686 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3687 3688 // Try to find a matching persistent preferred activity. 3689 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3690 debug, userId); 3691 3692 // If a persistent preferred activity matched, use it. 3693 if (pri != null) { 3694 return pri; 3695 } 3696 3697 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3698 // Get the list of preferred activities that handle the intent 3699 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3700 List<PreferredActivity> prefs = pir != null 3701 ? pir.queryIntent(intent, resolvedType, 3702 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3703 : null; 3704 if (prefs != null && prefs.size() > 0) { 3705 boolean changed = false; 3706 try { 3707 // First figure out how good the original match set is. 3708 // We will only allow preferred activities that came 3709 // from the same match quality. 3710 int match = 0; 3711 3712 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3713 3714 final int N = query.size(); 3715 for (int j=0; j<N; j++) { 3716 final ResolveInfo ri = query.get(j); 3717 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3718 + ": 0x" + Integer.toHexString(match)); 3719 if (ri.match > match) { 3720 match = ri.match; 3721 } 3722 } 3723 3724 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3725 + Integer.toHexString(match)); 3726 3727 match &= IntentFilter.MATCH_CATEGORY_MASK; 3728 final int M = prefs.size(); 3729 for (int i=0; i<M; i++) { 3730 final PreferredActivity pa = prefs.get(i); 3731 if (DEBUG_PREFERRED || debug) { 3732 Slog.v(TAG, "Checking PreferredActivity ds=" 3733 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3734 + "\n component=" + pa.mPref.mComponent); 3735 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3736 } 3737 if (pa.mPref.mMatch != match) { 3738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3739 + Integer.toHexString(pa.mPref.mMatch)); 3740 continue; 3741 } 3742 // If it's not an "always" type preferred activity and that's what we're 3743 // looking for, skip it. 3744 if (always && !pa.mPref.mAlways) { 3745 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3746 continue; 3747 } 3748 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3749 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3750 if (DEBUG_PREFERRED || debug) { 3751 Slog.v(TAG, "Found preferred activity:"); 3752 if (ai != null) { 3753 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3754 } else { 3755 Slog.v(TAG, " null"); 3756 } 3757 } 3758 if (ai == null) { 3759 // This previously registered preferred activity 3760 // component is no longer known. Most likely an update 3761 // to the app was installed and in the new version this 3762 // component no longer exists. Clean it up by removing 3763 // it from the preferred activities list, and skip it. 3764 Slog.w(TAG, "Removing dangling preferred activity: " 3765 + pa.mPref.mComponent); 3766 pir.removeFilter(pa); 3767 changed = true; 3768 continue; 3769 } 3770 for (int j=0; j<N; j++) { 3771 final ResolveInfo ri = query.get(j); 3772 if (!ri.activityInfo.applicationInfo.packageName 3773 .equals(ai.applicationInfo.packageName)) { 3774 continue; 3775 } 3776 if (!ri.activityInfo.name.equals(ai.name)) { 3777 continue; 3778 } 3779 3780 if (removeMatches) { 3781 pir.removeFilter(pa); 3782 changed = true; 3783 if (DEBUG_PREFERRED) { 3784 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3785 } 3786 break; 3787 } 3788 3789 // Okay we found a previously set preferred or last chosen app. 3790 // If the result set is different from when this 3791 // was created, we need to clear it and re-ask the 3792 // user their preference, if we're looking for an "always" type entry. 3793 if (always && !pa.mPref.sameSet(query)) { 3794 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3795 + intent + " type " + resolvedType); 3796 if (DEBUG_PREFERRED) { 3797 Slog.v(TAG, "Removing preferred activity since set changed " 3798 + pa.mPref.mComponent); 3799 } 3800 pir.removeFilter(pa); 3801 // Re-add the filter as a "last chosen" entry (!always) 3802 PreferredActivity lastChosen = new PreferredActivity( 3803 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3804 pir.addFilter(lastChosen); 3805 changed = true; 3806 return null; 3807 } 3808 3809 // Yay! Either the set matched or we're looking for the last chosen 3810 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3811 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3812 return ri; 3813 } 3814 } 3815 } finally { 3816 if (changed) { 3817 if (DEBUG_PREFERRED) { 3818 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3819 } 3820 scheduleWritePackageRestrictionsLocked(userId); 3821 } 3822 } 3823 } 3824 } 3825 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3826 return null; 3827 } 3828 3829 /* 3830 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3831 */ 3832 @Override 3833 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3834 int targetUserId) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3837 List<CrossProfileIntentFilter> matches = 3838 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3839 if (matches != null) { 3840 int size = matches.size(); 3841 for (int i = 0; i < size; i++) { 3842 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3843 } 3844 } 3845 return false; 3846 } 3847 3848 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3849 String resolvedType, int userId) { 3850 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3851 if (resolver != null) { 3852 return resolver.queryIntent(intent, resolvedType, false, userId); 3853 } 3854 return null; 3855 } 3856 3857 @Override 3858 public List<ResolveInfo> queryIntentActivities(Intent intent, 3859 String resolvedType, int flags, int userId) { 3860 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3862 ComponentName comp = intent.getComponent(); 3863 if (comp == null) { 3864 if (intent.getSelector() != null) { 3865 intent = intent.getSelector(); 3866 comp = intent.getComponent(); 3867 } 3868 } 3869 3870 if (comp != null) { 3871 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3872 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3873 if (ai != null) { 3874 final ResolveInfo ri = new ResolveInfo(); 3875 ri.activityInfo = ai; 3876 list.add(ri); 3877 } 3878 return list; 3879 } 3880 3881 // reader 3882 synchronized (mPackages) { 3883 final String pkgName = intent.getPackage(); 3884 if (pkgName == null) { 3885 List<CrossProfileIntentFilter> matchingFilters = 3886 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3887 // Check for results that need to skip the current profile. 3888 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3889 resolvedType, flags, userId); 3890 if (resolveInfo != null) { 3891 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3892 result.add(resolveInfo); 3893 return filterIfNotPrimaryUser(result, userId); 3894 } 3895 // Check for cross profile results. 3896 resolveInfo = queryCrossProfileIntents( 3897 matchingFilters, intent, resolvedType, flags, userId); 3898 3899 // Check for results in the current profile. 3900 List<ResolveInfo> result = mActivities.queryIntent( 3901 intent, resolvedType, flags, userId); 3902 if (resolveInfo != null) { 3903 result.add(resolveInfo); 3904 Collections.sort(result, mResolvePrioritySorter); 3905 } 3906 result = filterIfNotPrimaryUser(result, userId); 3907 if (result.size() > 1) { 3908 return filterCandidatesWithDomainPreferedActivitiesLPr(result); 3909 } 3910 3911 return result; 3912 } 3913 final PackageParser.Package pkg = mPackages.get(pkgName); 3914 if (pkg != null) { 3915 return filterIfNotPrimaryUser( 3916 mActivities.queryIntentForPackage( 3917 intent, resolvedType, flags, pkg.activities, userId), 3918 userId); 3919 } 3920 return new ArrayList<ResolveInfo>(); 3921 } 3922 } 3923 3924 /** 3925 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3926 * 3927 * @return filtered list 3928 */ 3929 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3930 if (userId == UserHandle.USER_OWNER) { 3931 return resolveInfos; 3932 } 3933 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3934 ResolveInfo info = resolveInfos.get(i); 3935 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3936 resolveInfos.remove(i); 3937 } 3938 } 3939 return resolveInfos; 3940 } 3941 3942 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 3943 List<ResolveInfo> candidates) { 3944 if (DEBUG_PREFERRED) { 3945 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 3946 candidates.size()); 3947 } 3948 final int userId = UserHandle.getCallingUserId(); 3949 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 3950 synchronized (mPackages) { 3951 final int count = candidates.size(); 3952 // First, try to use the domain prefered App 3953 for (int n=0; n<count; n++) { 3954 ResolveInfo info = candidates.get(n); 3955 String packageName = info.activityInfo.packageName; 3956 PackageSetting ps = mSettings.mPackages.get(packageName); 3957 if (ps != null) { 3958 // Try to get the status from User settings first 3959 int status = getDomainVerificationStatusLPr(ps, userId); 3960 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 3961 result.add(info); 3962 } 3963 } 3964 } 3965 // There is not much we can do, add all candidates 3966 if (result.size() == 0) { 3967 result.addAll(candidates); 3968 } 3969 } 3970 if (DEBUG_PREFERRED) { 3971 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 3972 result.size()); 3973 } 3974 return result; 3975 } 3976 3977 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 3978 int status = ps.getDomainVerificationStatusForUser(userId); 3979 // if none available, get the master status 3980 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 3981 if (ps.getIntentFilterVerificationInfo() != null) { 3982 status = ps.getIntentFilterVerificationInfo().getStatus(); 3983 } 3984 } 3985 return status; 3986 } 3987 3988 private ResolveInfo querySkipCurrentProfileIntents( 3989 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3990 int flags, int sourceUserId) { 3991 if (matchingFilters != null) { 3992 int size = matchingFilters.size(); 3993 for (int i = 0; i < size; i ++) { 3994 CrossProfileIntentFilter filter = matchingFilters.get(i); 3995 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3996 // Checking if there are activities in the target user that can handle the 3997 // intent. 3998 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3999 flags, sourceUserId); 4000 if (resolveInfo != null) { 4001 return resolveInfo; 4002 } 4003 } 4004 } 4005 } 4006 return null; 4007 } 4008 4009 // Return matching ResolveInfo if any for skip current profile intent filters. 4010 private ResolveInfo queryCrossProfileIntents( 4011 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4012 int flags, int sourceUserId) { 4013 if (matchingFilters != null) { 4014 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4015 // match the same intent. For performance reasons, it is better not to 4016 // run queryIntent twice for the same userId 4017 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4018 int size = matchingFilters.size(); 4019 for (int i = 0; i < size; i++) { 4020 CrossProfileIntentFilter filter = matchingFilters.get(i); 4021 int targetUserId = filter.getTargetUserId(); 4022 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4023 && !alreadyTriedUserIds.get(targetUserId)) { 4024 // Checking if there are activities in the target user that can handle the 4025 // intent. 4026 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4027 flags, sourceUserId); 4028 if (resolveInfo != null) return resolveInfo; 4029 alreadyTriedUserIds.put(targetUserId, true); 4030 } 4031 } 4032 } 4033 return null; 4034 } 4035 4036 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4037 String resolvedType, int flags, int sourceUserId) { 4038 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4039 resolvedType, flags, filter.getTargetUserId()); 4040 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4041 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4042 } 4043 return null; 4044 } 4045 4046 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4047 int sourceUserId, int targetUserId) { 4048 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4049 String className; 4050 if (targetUserId == UserHandle.USER_OWNER) { 4051 className = FORWARD_INTENT_TO_USER_OWNER; 4052 } else { 4053 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4054 } 4055 ComponentName forwardingActivityComponentName = new ComponentName( 4056 mAndroidApplication.packageName, className); 4057 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4058 sourceUserId); 4059 if (targetUserId == UserHandle.USER_OWNER) { 4060 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4061 forwardingResolveInfo.noResourceId = true; 4062 } 4063 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4064 forwardingResolveInfo.priority = 0; 4065 forwardingResolveInfo.preferredOrder = 0; 4066 forwardingResolveInfo.match = 0; 4067 forwardingResolveInfo.isDefault = true; 4068 forwardingResolveInfo.filter = filter; 4069 forwardingResolveInfo.targetUserId = targetUserId; 4070 return forwardingResolveInfo; 4071 } 4072 4073 @Override 4074 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4075 Intent[] specifics, String[] specificTypes, Intent intent, 4076 String resolvedType, int flags, int userId) { 4077 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4079 false, "query intent activity options"); 4080 final String resultsAction = intent.getAction(); 4081 4082 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4083 | PackageManager.GET_RESOLVED_FILTER, userId); 4084 4085 if (DEBUG_INTENT_MATCHING) { 4086 Log.v(TAG, "Query " + intent + ": " + results); 4087 } 4088 4089 int specificsPos = 0; 4090 int N; 4091 4092 // todo: note that the algorithm used here is O(N^2). This 4093 // isn't a problem in our current environment, but if we start running 4094 // into situations where we have more than 5 or 10 matches then this 4095 // should probably be changed to something smarter... 4096 4097 // First we go through and resolve each of the specific items 4098 // that were supplied, taking care of removing any corresponding 4099 // duplicate items in the generic resolve list. 4100 if (specifics != null) { 4101 for (int i=0; i<specifics.length; i++) { 4102 final Intent sintent = specifics[i]; 4103 if (sintent == null) { 4104 continue; 4105 } 4106 4107 if (DEBUG_INTENT_MATCHING) { 4108 Log.v(TAG, "Specific #" + i + ": " + sintent); 4109 } 4110 4111 String action = sintent.getAction(); 4112 if (resultsAction != null && resultsAction.equals(action)) { 4113 // If this action was explicitly requested, then don't 4114 // remove things that have it. 4115 action = null; 4116 } 4117 4118 ResolveInfo ri = null; 4119 ActivityInfo ai = null; 4120 4121 ComponentName comp = sintent.getComponent(); 4122 if (comp == null) { 4123 ri = resolveIntent( 4124 sintent, 4125 specificTypes != null ? specificTypes[i] : null, 4126 flags, userId); 4127 if (ri == null) { 4128 continue; 4129 } 4130 if (ri == mResolveInfo) { 4131 // ACK! Must do something better with this. 4132 } 4133 ai = ri.activityInfo; 4134 comp = new ComponentName(ai.applicationInfo.packageName, 4135 ai.name); 4136 } else { 4137 ai = getActivityInfo(comp, flags, userId); 4138 if (ai == null) { 4139 continue; 4140 } 4141 } 4142 4143 // Look for any generic query activities that are duplicates 4144 // of this specific one, and remove them from the results. 4145 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4146 N = results.size(); 4147 int j; 4148 for (j=specificsPos; j<N; j++) { 4149 ResolveInfo sri = results.get(j); 4150 if ((sri.activityInfo.name.equals(comp.getClassName()) 4151 && sri.activityInfo.applicationInfo.packageName.equals( 4152 comp.getPackageName())) 4153 || (action != null && sri.filter.matchAction(action))) { 4154 results.remove(j); 4155 if (DEBUG_INTENT_MATCHING) Log.v( 4156 TAG, "Removing duplicate item from " + j 4157 + " due to specific " + specificsPos); 4158 if (ri == null) { 4159 ri = sri; 4160 } 4161 j--; 4162 N--; 4163 } 4164 } 4165 4166 // Add this specific item to its proper place. 4167 if (ri == null) { 4168 ri = new ResolveInfo(); 4169 ri.activityInfo = ai; 4170 } 4171 results.add(specificsPos, ri); 4172 ri.specificIndex = i; 4173 specificsPos++; 4174 } 4175 } 4176 4177 // Now we go through the remaining generic results and remove any 4178 // duplicate actions that are found here. 4179 N = results.size(); 4180 for (int i=specificsPos; i<N-1; i++) { 4181 final ResolveInfo rii = results.get(i); 4182 if (rii.filter == null) { 4183 continue; 4184 } 4185 4186 // Iterate over all of the actions of this result's intent 4187 // filter... typically this should be just one. 4188 final Iterator<String> it = rii.filter.actionsIterator(); 4189 if (it == null) { 4190 continue; 4191 } 4192 while (it.hasNext()) { 4193 final String action = it.next(); 4194 if (resultsAction != null && resultsAction.equals(action)) { 4195 // If this action was explicitly requested, then don't 4196 // remove things that have it. 4197 continue; 4198 } 4199 for (int j=i+1; j<N; j++) { 4200 final ResolveInfo rij = results.get(j); 4201 if (rij.filter != null && rij.filter.hasAction(action)) { 4202 results.remove(j); 4203 if (DEBUG_INTENT_MATCHING) Log.v( 4204 TAG, "Removing duplicate item from " + j 4205 + " due to action " + action + " at " + i); 4206 j--; 4207 N--; 4208 } 4209 } 4210 } 4211 4212 // If the caller didn't request filter information, drop it now 4213 // so we don't have to marshall/unmarshall it. 4214 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4215 rii.filter = null; 4216 } 4217 } 4218 4219 // Filter out the caller activity if so requested. 4220 if (caller != null) { 4221 N = results.size(); 4222 for (int i=0; i<N; i++) { 4223 ActivityInfo ainfo = results.get(i).activityInfo; 4224 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4225 && caller.getClassName().equals(ainfo.name)) { 4226 results.remove(i); 4227 break; 4228 } 4229 } 4230 } 4231 4232 // If the caller didn't request filter information, 4233 // drop them now so we don't have to 4234 // marshall/unmarshall it. 4235 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4236 N = results.size(); 4237 for (int i=0; i<N; i++) { 4238 results.get(i).filter = null; 4239 } 4240 } 4241 4242 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4243 return results; 4244 } 4245 4246 @Override 4247 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4248 int userId) { 4249 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4250 ComponentName comp = intent.getComponent(); 4251 if (comp == null) { 4252 if (intent.getSelector() != null) { 4253 intent = intent.getSelector(); 4254 comp = intent.getComponent(); 4255 } 4256 } 4257 if (comp != null) { 4258 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4259 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4260 if (ai != null) { 4261 ResolveInfo ri = new ResolveInfo(); 4262 ri.activityInfo = ai; 4263 list.add(ri); 4264 } 4265 return list; 4266 } 4267 4268 // reader 4269 synchronized (mPackages) { 4270 String pkgName = intent.getPackage(); 4271 if (pkgName == null) { 4272 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4273 } 4274 final PackageParser.Package pkg = mPackages.get(pkgName); 4275 if (pkg != null) { 4276 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4277 userId); 4278 } 4279 return null; 4280 } 4281 } 4282 4283 @Override 4284 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4285 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4286 if (!sUserManager.exists(userId)) return null; 4287 if (query != null) { 4288 if (query.size() >= 1) { 4289 // If there is more than one service with the same priority, 4290 // just arbitrarily pick the first one. 4291 return query.get(0); 4292 } 4293 } 4294 return null; 4295 } 4296 4297 @Override 4298 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4299 int userId) { 4300 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4301 ComponentName comp = intent.getComponent(); 4302 if (comp == null) { 4303 if (intent.getSelector() != null) { 4304 intent = intent.getSelector(); 4305 comp = intent.getComponent(); 4306 } 4307 } 4308 if (comp != null) { 4309 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4310 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4311 if (si != null) { 4312 final ResolveInfo ri = new ResolveInfo(); 4313 ri.serviceInfo = si; 4314 list.add(ri); 4315 } 4316 return list; 4317 } 4318 4319 // reader 4320 synchronized (mPackages) { 4321 String pkgName = intent.getPackage(); 4322 if (pkgName == null) { 4323 return mServices.queryIntent(intent, resolvedType, flags, userId); 4324 } 4325 final PackageParser.Package pkg = mPackages.get(pkgName); 4326 if (pkg != null) { 4327 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4328 userId); 4329 } 4330 return null; 4331 } 4332 } 4333 4334 @Override 4335 public List<ResolveInfo> queryIntentContentProviders( 4336 Intent intent, String resolvedType, int flags, int userId) { 4337 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4338 ComponentName comp = intent.getComponent(); 4339 if (comp == null) { 4340 if (intent.getSelector() != null) { 4341 intent = intent.getSelector(); 4342 comp = intent.getComponent(); 4343 } 4344 } 4345 if (comp != null) { 4346 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4347 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4348 if (pi != null) { 4349 final ResolveInfo ri = new ResolveInfo(); 4350 ri.providerInfo = pi; 4351 list.add(ri); 4352 } 4353 return list; 4354 } 4355 4356 // reader 4357 synchronized (mPackages) { 4358 String pkgName = intent.getPackage(); 4359 if (pkgName == null) { 4360 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4361 } 4362 final PackageParser.Package pkg = mPackages.get(pkgName); 4363 if (pkg != null) { 4364 return mProviders.queryIntentForPackage( 4365 intent, resolvedType, flags, pkg.providers, userId); 4366 } 4367 return null; 4368 } 4369 } 4370 4371 @Override 4372 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4373 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4374 4375 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4376 4377 // writer 4378 synchronized (mPackages) { 4379 ArrayList<PackageInfo> list; 4380 if (listUninstalled) { 4381 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4382 for (PackageSetting ps : mSettings.mPackages.values()) { 4383 PackageInfo pi; 4384 if (ps.pkg != null) { 4385 pi = generatePackageInfo(ps.pkg, flags, userId); 4386 } else { 4387 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4388 } 4389 if (pi != null) { 4390 list.add(pi); 4391 } 4392 } 4393 } else { 4394 list = new ArrayList<PackageInfo>(mPackages.size()); 4395 for (PackageParser.Package p : mPackages.values()) { 4396 PackageInfo pi = generatePackageInfo(p, flags, userId); 4397 if (pi != null) { 4398 list.add(pi); 4399 } 4400 } 4401 } 4402 4403 return new ParceledListSlice<PackageInfo>(list); 4404 } 4405 } 4406 4407 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4408 String[] permissions, boolean[] tmp, int flags, int userId) { 4409 int numMatch = 0; 4410 final PermissionsState permissionsState = ps.getPermissionsState(); 4411 for (int i=0; i<permissions.length; i++) { 4412 final String permission = permissions[i]; 4413 if (permissionsState.hasPermission(permission, userId)) { 4414 tmp[i] = true; 4415 numMatch++; 4416 } else { 4417 tmp[i] = false; 4418 } 4419 } 4420 if (numMatch == 0) { 4421 return; 4422 } 4423 PackageInfo pi; 4424 if (ps.pkg != null) { 4425 pi = generatePackageInfo(ps.pkg, flags, userId); 4426 } else { 4427 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4428 } 4429 // The above might return null in cases of uninstalled apps or install-state 4430 // skew across users/profiles. 4431 if (pi != null) { 4432 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4433 if (numMatch == permissions.length) { 4434 pi.requestedPermissions = permissions; 4435 } else { 4436 pi.requestedPermissions = new String[numMatch]; 4437 numMatch = 0; 4438 for (int i=0; i<permissions.length; i++) { 4439 if (tmp[i]) { 4440 pi.requestedPermissions[numMatch] = permissions[i]; 4441 numMatch++; 4442 } 4443 } 4444 } 4445 } 4446 list.add(pi); 4447 } 4448 } 4449 4450 @Override 4451 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4452 String[] permissions, int flags, int userId) { 4453 if (!sUserManager.exists(userId)) return null; 4454 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4455 4456 // writer 4457 synchronized (mPackages) { 4458 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4459 boolean[] tmpBools = new boolean[permissions.length]; 4460 if (listUninstalled) { 4461 for (PackageSetting ps : mSettings.mPackages.values()) { 4462 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4463 } 4464 } else { 4465 for (PackageParser.Package pkg : mPackages.values()) { 4466 PackageSetting ps = (PackageSetting)pkg.mExtras; 4467 if (ps != null) { 4468 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4469 userId); 4470 } 4471 } 4472 } 4473 4474 return new ParceledListSlice<PackageInfo>(list); 4475 } 4476 } 4477 4478 @Override 4479 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4480 if (!sUserManager.exists(userId)) return null; 4481 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4482 4483 // writer 4484 synchronized (mPackages) { 4485 ArrayList<ApplicationInfo> list; 4486 if (listUninstalled) { 4487 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4488 for (PackageSetting ps : mSettings.mPackages.values()) { 4489 ApplicationInfo ai; 4490 if (ps.pkg != null) { 4491 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4492 ps.readUserState(userId), userId); 4493 } else { 4494 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4495 } 4496 if (ai != null) { 4497 list.add(ai); 4498 } 4499 } 4500 } else { 4501 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4502 for (PackageParser.Package p : mPackages.values()) { 4503 if (p.mExtras != null) { 4504 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4505 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4506 if (ai != null) { 4507 list.add(ai); 4508 } 4509 } 4510 } 4511 } 4512 4513 return new ParceledListSlice<ApplicationInfo>(list); 4514 } 4515 } 4516 4517 public List<ApplicationInfo> getPersistentApplications(int flags) { 4518 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4519 4520 // reader 4521 synchronized (mPackages) { 4522 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4523 final int userId = UserHandle.getCallingUserId(); 4524 while (i.hasNext()) { 4525 final PackageParser.Package p = i.next(); 4526 if (p.applicationInfo != null 4527 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4528 && (!mSafeMode || isSystemApp(p))) { 4529 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4530 if (ps != null) { 4531 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4532 ps.readUserState(userId), userId); 4533 if (ai != null) { 4534 finalList.add(ai); 4535 } 4536 } 4537 } 4538 } 4539 } 4540 4541 return finalList; 4542 } 4543 4544 @Override 4545 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4546 if (!sUserManager.exists(userId)) return null; 4547 // reader 4548 synchronized (mPackages) { 4549 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4550 PackageSetting ps = provider != null 4551 ? mSettings.mPackages.get(provider.owner.packageName) 4552 : null; 4553 return ps != null 4554 && mSettings.isEnabledLPr(provider.info, flags, userId) 4555 && (!mSafeMode || (provider.info.applicationInfo.flags 4556 &ApplicationInfo.FLAG_SYSTEM) != 0) 4557 ? PackageParser.generateProviderInfo(provider, flags, 4558 ps.readUserState(userId), userId) 4559 : null; 4560 } 4561 } 4562 4563 /** 4564 * @deprecated 4565 */ 4566 @Deprecated 4567 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4568 // reader 4569 synchronized (mPackages) { 4570 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4571 .entrySet().iterator(); 4572 final int userId = UserHandle.getCallingUserId(); 4573 while (i.hasNext()) { 4574 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4575 PackageParser.Provider p = entry.getValue(); 4576 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4577 4578 if (ps != null && p.syncable 4579 && (!mSafeMode || (p.info.applicationInfo.flags 4580 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4581 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4582 ps.readUserState(userId), userId); 4583 if (info != null) { 4584 outNames.add(entry.getKey()); 4585 outInfo.add(info); 4586 } 4587 } 4588 } 4589 } 4590 } 4591 4592 @Override 4593 public List<ProviderInfo> queryContentProviders(String processName, 4594 int uid, int flags) { 4595 ArrayList<ProviderInfo> finalList = null; 4596 // reader 4597 synchronized (mPackages) { 4598 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4599 final int userId = processName != null ? 4600 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4601 while (i.hasNext()) { 4602 final PackageParser.Provider p = i.next(); 4603 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4604 if (ps != null && p.info.authority != null 4605 && (processName == null 4606 || (p.info.processName.equals(processName) 4607 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4608 && mSettings.isEnabledLPr(p.info, flags, userId) 4609 && (!mSafeMode 4610 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4611 if (finalList == null) { 4612 finalList = new ArrayList<ProviderInfo>(3); 4613 } 4614 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4615 ps.readUserState(userId), userId); 4616 if (info != null) { 4617 finalList.add(info); 4618 } 4619 } 4620 } 4621 } 4622 4623 if (finalList != null) { 4624 Collections.sort(finalList, mProviderInitOrderSorter); 4625 } 4626 4627 return finalList; 4628 } 4629 4630 @Override 4631 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4632 int flags) { 4633 // reader 4634 synchronized (mPackages) { 4635 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4636 return PackageParser.generateInstrumentationInfo(i, flags); 4637 } 4638 } 4639 4640 @Override 4641 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4642 int flags) { 4643 ArrayList<InstrumentationInfo> finalList = 4644 new ArrayList<InstrumentationInfo>(); 4645 4646 // reader 4647 synchronized (mPackages) { 4648 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4649 while (i.hasNext()) { 4650 final PackageParser.Instrumentation p = i.next(); 4651 if (targetPackage == null 4652 || targetPackage.equals(p.info.targetPackage)) { 4653 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4654 flags); 4655 if (ii != null) { 4656 finalList.add(ii); 4657 } 4658 } 4659 } 4660 } 4661 4662 return finalList; 4663 } 4664 4665 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4666 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4667 if (overlays == null) { 4668 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4669 return; 4670 } 4671 for (PackageParser.Package opkg : overlays.values()) { 4672 // Not much to do if idmap fails: we already logged the error 4673 // and we certainly don't want to abort installation of pkg simply 4674 // because an overlay didn't fit properly. For these reasons, 4675 // ignore the return value of createIdmapForPackagePairLI. 4676 createIdmapForPackagePairLI(pkg, opkg); 4677 } 4678 } 4679 4680 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4681 PackageParser.Package opkg) { 4682 if (!opkg.mTrustedOverlay) { 4683 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4684 opkg.baseCodePath + ": overlay not trusted"); 4685 return false; 4686 } 4687 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4688 if (overlaySet == null) { 4689 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4690 opkg.baseCodePath + " but target package has no known overlays"); 4691 return false; 4692 } 4693 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4694 // TODO: generate idmap for split APKs 4695 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4696 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4697 + opkg.baseCodePath); 4698 return false; 4699 } 4700 PackageParser.Package[] overlayArray = 4701 overlaySet.values().toArray(new PackageParser.Package[0]); 4702 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4703 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4704 return p1.mOverlayPriority - p2.mOverlayPriority; 4705 } 4706 }; 4707 Arrays.sort(overlayArray, cmp); 4708 4709 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4710 int i = 0; 4711 for (PackageParser.Package p : overlayArray) { 4712 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4713 } 4714 return true; 4715 } 4716 4717 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4718 final File[] files = dir.listFiles(); 4719 if (ArrayUtils.isEmpty(files)) { 4720 Log.d(TAG, "No files in app dir " + dir); 4721 return; 4722 } 4723 4724 if (DEBUG_PACKAGE_SCANNING) { 4725 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4726 + " flags=0x" + Integer.toHexString(parseFlags)); 4727 } 4728 4729 for (File file : files) { 4730 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4731 && !PackageInstallerService.isStageName(file.getName()); 4732 if (!isPackage) { 4733 // Ignore entries which are not packages 4734 continue; 4735 } 4736 try { 4737 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4738 scanFlags, currentTime, null); 4739 } catch (PackageManagerException e) { 4740 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4741 4742 // Delete invalid userdata apps 4743 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4744 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4745 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4746 if (file.isDirectory()) { 4747 mInstaller.rmPackageDir(file.getAbsolutePath()); 4748 } else { 4749 file.delete(); 4750 } 4751 } 4752 } 4753 } 4754 } 4755 4756 private static File getSettingsProblemFile() { 4757 File dataDir = Environment.getDataDirectory(); 4758 File systemDir = new File(dataDir, "system"); 4759 File fname = new File(systemDir, "uiderrors.txt"); 4760 return fname; 4761 } 4762 4763 static void reportSettingsProblem(int priority, String msg) { 4764 logCriticalInfo(priority, msg); 4765 } 4766 4767 static void logCriticalInfo(int priority, String msg) { 4768 Slog.println(priority, TAG, msg); 4769 EventLogTags.writePmCriticalInfo(msg); 4770 try { 4771 File fname = getSettingsProblemFile(); 4772 FileOutputStream out = new FileOutputStream(fname, true); 4773 PrintWriter pw = new FastPrintWriter(out); 4774 SimpleDateFormat formatter = new SimpleDateFormat(); 4775 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4776 pw.println(dateString + ": " + msg); 4777 pw.close(); 4778 FileUtils.setPermissions( 4779 fname.toString(), 4780 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4781 -1, -1); 4782 } catch (java.io.IOException e) { 4783 } 4784 } 4785 4786 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4787 PackageParser.Package pkg, File srcFile, int parseFlags) 4788 throws PackageManagerException { 4789 if (ps != null 4790 && ps.codePath.equals(srcFile) 4791 && ps.timeStamp == srcFile.lastModified() 4792 && !isCompatSignatureUpdateNeeded(pkg) 4793 && !isRecoverSignatureUpdateNeeded(pkg)) { 4794 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4795 if (ps.signatures.mSignatures != null 4796 && ps.signatures.mSignatures.length != 0 4797 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4798 // Optimization: reuse the existing cached certificates 4799 // if the package appears to be unchanged. 4800 pkg.mSignatures = ps.signatures.mSignatures; 4801 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4802 synchronized (mPackages) { 4803 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4804 } 4805 return; 4806 } 4807 4808 Slog.w(TAG, "PackageSetting for " + ps.name 4809 + " is missing signatures. Collecting certs again to recover them."); 4810 } else { 4811 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4812 } 4813 4814 try { 4815 pp.collectCertificates(pkg, parseFlags); 4816 pp.collectManifestDigest(pkg); 4817 } catch (PackageParserException e) { 4818 throw PackageManagerException.from(e); 4819 } 4820 } 4821 4822 /* 4823 * Scan a package and return the newly parsed package. 4824 * Returns null in case of errors and the error code is stored in mLastScanError 4825 */ 4826 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4827 long currentTime, UserHandle user) throws PackageManagerException { 4828 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4829 parseFlags |= mDefParseFlags; 4830 PackageParser pp = new PackageParser(); 4831 pp.setSeparateProcesses(mSeparateProcesses); 4832 pp.setOnlyCoreApps(mOnlyCore); 4833 pp.setDisplayMetrics(mMetrics); 4834 4835 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4836 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4837 } 4838 4839 final PackageParser.Package pkg; 4840 try { 4841 pkg = pp.parsePackage(scanFile, parseFlags); 4842 } catch (PackageParserException e) { 4843 throw PackageManagerException.from(e); 4844 } 4845 4846 PackageSetting ps = null; 4847 PackageSetting updatedPkg; 4848 // reader 4849 synchronized (mPackages) { 4850 // Look to see if we already know about this package. 4851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4853 // This package has been renamed to its original name. Let's 4854 // use that. 4855 ps = mSettings.peekPackageLPr(oldName); 4856 } 4857 // If there was no original package, see one for the real package name. 4858 if (ps == null) { 4859 ps = mSettings.peekPackageLPr(pkg.packageName); 4860 } 4861 // Check to see if this package could be hiding/updating a system 4862 // package. Must look for it either under the original or real 4863 // package name depending on our state. 4864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4866 } 4867 boolean updatedPkgBetter = false; 4868 // First check if this is a system package that may involve an update 4869 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4870 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4871 // it needs to drop FLAG_PRIVILEGED. 4872 if (locationIsPrivileged(scanFile)) { 4873 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4874 } else { 4875 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4876 } 4877 4878 if (ps != null && !ps.codePath.equals(scanFile)) { 4879 // The path has changed from what was last scanned... check the 4880 // version of the new path against what we have stored to determine 4881 // what to do. 4882 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4883 if (pkg.mVersionCode <= ps.versionCode) { 4884 // The system package has been updated and the code path does not match 4885 // Ignore entry. Skip it. 4886 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4887 + " ignored: updated version " + ps.versionCode 4888 + " better than this " + pkg.mVersionCode); 4889 if (!updatedPkg.codePath.equals(scanFile)) { 4890 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4891 + ps.name + " changing from " + updatedPkg.codePathString 4892 + " to " + scanFile); 4893 updatedPkg.codePath = scanFile; 4894 updatedPkg.codePathString = scanFile.toString(); 4895 updatedPkg.resourcePath = scanFile; 4896 updatedPkg.resourcePathString = scanFile.toString(); 4897 } 4898 updatedPkg.pkg = pkg; 4899 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4900 } else { 4901 // The current app on the system partition is better than 4902 // what we have updated to on the data partition; switch 4903 // back to the system partition version. 4904 // At this point, its safely assumed that package installation for 4905 // apps in system partition will go through. If not there won't be a working 4906 // version of the app 4907 // writer 4908 synchronized (mPackages) { 4909 // Just remove the loaded entries from package lists. 4910 mPackages.remove(ps.name); 4911 } 4912 4913 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4914 + " reverting from " + ps.codePathString 4915 + ": new version " + pkg.mVersionCode 4916 + " better than installed " + ps.versionCode); 4917 4918 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4919 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4920 getAppDexInstructionSets(ps)); 4921 synchronized (mInstallLock) { 4922 args.cleanUpResourcesLI(); 4923 } 4924 synchronized (mPackages) { 4925 mSettings.enableSystemPackageLPw(ps.name); 4926 } 4927 updatedPkgBetter = true; 4928 } 4929 } 4930 } 4931 4932 if (updatedPkg != null) { 4933 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4934 // initially 4935 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4936 4937 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4938 // flag set initially 4939 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4940 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4941 } 4942 } 4943 4944 // Verify certificates against what was last scanned 4945 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4946 4947 /* 4948 * A new system app appeared, but we already had a non-system one of the 4949 * same name installed earlier. 4950 */ 4951 boolean shouldHideSystemApp = false; 4952 if (updatedPkg == null && ps != null 4953 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4954 /* 4955 * Check to make sure the signatures match first. If they don't, 4956 * wipe the installed application and its data. 4957 */ 4958 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4959 != PackageManager.SIGNATURE_MATCH) { 4960 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4961 + " signatures don't match existing userdata copy; removing"); 4962 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4963 ps = null; 4964 } else { 4965 /* 4966 * If the newly-added system app is an older version than the 4967 * already installed version, hide it. It will be scanned later 4968 * and re-added like an update. 4969 */ 4970 if (pkg.mVersionCode <= ps.versionCode) { 4971 shouldHideSystemApp = true; 4972 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4973 + " but new version " + pkg.mVersionCode + " better than installed " 4974 + ps.versionCode + "; hiding system"); 4975 } else { 4976 /* 4977 * The newly found system app is a newer version that the 4978 * one previously installed. Simply remove the 4979 * already-installed application and replace it with our own 4980 * while keeping the application data. 4981 */ 4982 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4983 + " reverting from " + ps.codePathString + ": new version " 4984 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4985 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4986 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4987 getAppDexInstructionSets(ps)); 4988 synchronized (mInstallLock) { 4989 args.cleanUpResourcesLI(); 4990 } 4991 } 4992 } 4993 } 4994 4995 // The apk is forward locked (not public) if its code and resources 4996 // are kept in different files. (except for app in either system or 4997 // vendor path). 4998 // TODO grab this value from PackageSettings 4999 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5000 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5001 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5002 } 5003 } 5004 5005 // TODO: extend to support forward-locked splits 5006 String resourcePath = null; 5007 String baseResourcePath = null; 5008 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5009 if (ps != null && ps.resourcePathString != null) { 5010 resourcePath = ps.resourcePathString; 5011 baseResourcePath = ps.resourcePathString; 5012 } else { 5013 // Should not happen at all. Just log an error. 5014 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5015 } 5016 } else { 5017 resourcePath = pkg.codePath; 5018 baseResourcePath = pkg.baseCodePath; 5019 } 5020 5021 // Set application objects path explicitly. 5022 pkg.applicationInfo.setCodePath(pkg.codePath); 5023 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5024 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5025 pkg.applicationInfo.setResourcePath(resourcePath); 5026 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5027 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5028 5029 // Note that we invoke the following method only if we are about to unpack an application 5030 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5031 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5032 5033 /* 5034 * If the system app should be overridden by a previously installed 5035 * data, hide the system app now and let the /data/app scan pick it up 5036 * again. 5037 */ 5038 if (shouldHideSystemApp) { 5039 synchronized (mPackages) { 5040 /* 5041 * We have to grant systems permissions before we hide, because 5042 * grantPermissions will assume the package update is trying to 5043 * expand its permissions. 5044 */ 5045 grantPermissionsLPw(pkg, true, pkg.packageName); 5046 mSettings.disableSystemPackageLPw(pkg.packageName); 5047 } 5048 } 5049 5050 return scannedPkg; 5051 } 5052 5053 private static String fixProcessName(String defProcessName, 5054 String processName, int uid) { 5055 if (processName == null) { 5056 return defProcessName; 5057 } 5058 return processName; 5059 } 5060 5061 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5062 throws PackageManagerException { 5063 if (pkgSetting.signatures.mSignatures != null) { 5064 // Already existing package. Make sure signatures match 5065 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5066 == PackageManager.SIGNATURE_MATCH; 5067 if (!match) { 5068 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5069 == PackageManager.SIGNATURE_MATCH; 5070 } 5071 if (!match) { 5072 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5073 == PackageManager.SIGNATURE_MATCH; 5074 } 5075 if (!match) { 5076 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5077 + pkg.packageName + " signatures do not match the " 5078 + "previously installed version; ignoring!"); 5079 } 5080 } 5081 5082 // Check for shared user signatures 5083 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5084 // Already existing package. Make sure signatures match 5085 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5086 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5087 if (!match) { 5088 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5089 == PackageManager.SIGNATURE_MATCH; 5090 } 5091 if (!match) { 5092 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5093 == PackageManager.SIGNATURE_MATCH; 5094 } 5095 if (!match) { 5096 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5097 "Package " + pkg.packageName 5098 + " has no signatures that match those in shared user " 5099 + pkgSetting.sharedUser.name + "; ignoring!"); 5100 } 5101 } 5102 } 5103 5104 /** 5105 * Enforces that only the system UID or root's UID can call a method exposed 5106 * via Binder. 5107 * 5108 * @param message used as message if SecurityException is thrown 5109 * @throws SecurityException if the caller is not system or root 5110 */ 5111 private static final void enforceSystemOrRoot(String message) { 5112 final int uid = Binder.getCallingUid(); 5113 if (uid != Process.SYSTEM_UID && uid != 0) { 5114 throw new SecurityException(message); 5115 } 5116 } 5117 5118 @Override 5119 public void performBootDexOpt() { 5120 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5121 5122 // Before everything else, see whether we need to fstrim. 5123 try { 5124 IMountService ms = PackageHelper.getMountService(); 5125 if (ms != null) { 5126 final boolean isUpgrade = isUpgrade(); 5127 boolean doTrim = isUpgrade; 5128 if (doTrim) { 5129 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5130 } else { 5131 final long interval = android.provider.Settings.Global.getLong( 5132 mContext.getContentResolver(), 5133 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5134 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5135 if (interval > 0) { 5136 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5137 if (timeSinceLast > interval) { 5138 doTrim = true; 5139 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5140 + "; running immediately"); 5141 } 5142 } 5143 } 5144 if (doTrim) { 5145 if (!isFirstBoot()) { 5146 try { 5147 ActivityManagerNative.getDefault().showBootMessage( 5148 mContext.getResources().getString( 5149 R.string.android_upgrading_fstrim), true); 5150 } catch (RemoteException e) { 5151 } 5152 } 5153 ms.runMaintenance(); 5154 } 5155 } else { 5156 Slog.e(TAG, "Mount service unavailable!"); 5157 } 5158 } catch (RemoteException e) { 5159 // Can't happen; MountService is local 5160 } 5161 5162 final ArraySet<PackageParser.Package> pkgs; 5163 synchronized (mPackages) { 5164 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5165 } 5166 5167 if (pkgs != null) { 5168 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5169 // in case the device runs out of space. 5170 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5171 // Give priority to core apps. 5172 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5173 PackageParser.Package pkg = it.next(); 5174 if (pkg.coreApp) { 5175 if (DEBUG_DEXOPT) { 5176 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5177 } 5178 sortedPkgs.add(pkg); 5179 it.remove(); 5180 } 5181 } 5182 // Give priority to system apps that listen for pre boot complete. 5183 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5184 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5185 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5186 PackageParser.Package pkg = it.next(); 5187 if (pkgNames.contains(pkg.packageName)) { 5188 if (DEBUG_DEXOPT) { 5189 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5190 } 5191 sortedPkgs.add(pkg); 5192 it.remove(); 5193 } 5194 } 5195 // Give priority to system apps. 5196 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5197 PackageParser.Package pkg = it.next(); 5198 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5199 if (DEBUG_DEXOPT) { 5200 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5201 } 5202 sortedPkgs.add(pkg); 5203 it.remove(); 5204 } 5205 } 5206 // Give priority to updated system apps. 5207 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5208 PackageParser.Package pkg = it.next(); 5209 if (pkg.isUpdatedSystemApp()) { 5210 if (DEBUG_DEXOPT) { 5211 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5212 } 5213 sortedPkgs.add(pkg); 5214 it.remove(); 5215 } 5216 } 5217 // Give priority to apps that listen for boot complete. 5218 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5219 pkgNames = getPackageNamesForIntent(intent); 5220 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5221 PackageParser.Package pkg = it.next(); 5222 if (pkgNames.contains(pkg.packageName)) { 5223 if (DEBUG_DEXOPT) { 5224 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5225 } 5226 sortedPkgs.add(pkg); 5227 it.remove(); 5228 } 5229 } 5230 // Filter out packages that aren't recently used. 5231 filterRecentlyUsedApps(pkgs); 5232 // Add all remaining apps. 5233 for (PackageParser.Package pkg : pkgs) { 5234 if (DEBUG_DEXOPT) { 5235 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5236 } 5237 sortedPkgs.add(pkg); 5238 } 5239 5240 // If we want to be lazy, filter everything that wasn't recently used. 5241 if (mLazyDexOpt) { 5242 filterRecentlyUsedApps(sortedPkgs); 5243 } 5244 5245 int i = 0; 5246 int total = sortedPkgs.size(); 5247 File dataDir = Environment.getDataDirectory(); 5248 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5249 if (lowThreshold == 0) { 5250 throw new IllegalStateException("Invalid low memory threshold"); 5251 } 5252 for (PackageParser.Package pkg : sortedPkgs) { 5253 long usableSpace = dataDir.getUsableSpace(); 5254 if (usableSpace < lowThreshold) { 5255 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5256 break; 5257 } 5258 performBootDexOpt(pkg, ++i, total); 5259 } 5260 } 5261 } 5262 5263 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5264 // Filter out packages that aren't recently used. 5265 // 5266 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5267 // should do a full dexopt. 5268 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5269 int total = pkgs.size(); 5270 int skipped = 0; 5271 long now = System.currentTimeMillis(); 5272 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5273 PackageParser.Package pkg = i.next(); 5274 long then = pkg.mLastPackageUsageTimeInMills; 5275 if (then + mDexOptLRUThresholdInMills < now) { 5276 if (DEBUG_DEXOPT) { 5277 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5278 ((then == 0) ? "never" : new Date(then))); 5279 } 5280 i.remove(); 5281 skipped++; 5282 } 5283 } 5284 if (DEBUG_DEXOPT) { 5285 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5286 } 5287 } 5288 } 5289 5290 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5291 List<ResolveInfo> ris = null; 5292 try { 5293 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5294 intent, null, 0, UserHandle.USER_OWNER); 5295 } catch (RemoteException e) { 5296 } 5297 ArraySet<String> pkgNames = new ArraySet<String>(); 5298 if (ris != null) { 5299 for (ResolveInfo ri : ris) { 5300 pkgNames.add(ri.activityInfo.packageName); 5301 } 5302 } 5303 return pkgNames; 5304 } 5305 5306 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5307 if (DEBUG_DEXOPT) { 5308 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5309 } 5310 if (!isFirstBoot()) { 5311 try { 5312 ActivityManagerNative.getDefault().showBootMessage( 5313 mContext.getResources().getString(R.string.android_upgrading_apk, 5314 curr, total), true); 5315 } catch (RemoteException e) { 5316 } 5317 } 5318 PackageParser.Package p = pkg; 5319 synchronized (mInstallLock) { 5320 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5321 false /* force dex */, false /* defer */, true /* include dependencies */); 5322 } 5323 } 5324 5325 @Override 5326 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5327 return performDexOpt(packageName, instructionSet, false); 5328 } 5329 5330 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5331 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5332 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5333 if (!dexopt && !updateUsage) { 5334 // We aren't going to dexopt or update usage, so bail early. 5335 return false; 5336 } 5337 PackageParser.Package p; 5338 final String targetInstructionSet; 5339 synchronized (mPackages) { 5340 p = mPackages.get(packageName); 5341 if (p == null) { 5342 return false; 5343 } 5344 if (updateUsage) { 5345 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5346 } 5347 mPackageUsage.write(false); 5348 if (!dexopt) { 5349 // We aren't going to dexopt, so bail early. 5350 return false; 5351 } 5352 5353 targetInstructionSet = instructionSet != null ? instructionSet : 5354 getPrimaryInstructionSet(p.applicationInfo); 5355 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5356 return false; 5357 } 5358 } 5359 5360 synchronized (mInstallLock) { 5361 final String[] instructionSets = new String[] { targetInstructionSet }; 5362 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5363 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5364 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5365 } 5366 } 5367 5368 public ArraySet<String> getPackagesThatNeedDexOpt() { 5369 ArraySet<String> pkgs = null; 5370 synchronized (mPackages) { 5371 for (PackageParser.Package p : mPackages.values()) { 5372 if (DEBUG_DEXOPT) { 5373 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5374 } 5375 if (!p.mDexOptPerformed.isEmpty()) { 5376 continue; 5377 } 5378 if (pkgs == null) { 5379 pkgs = new ArraySet<String>(); 5380 } 5381 pkgs.add(p.packageName); 5382 } 5383 } 5384 return pkgs; 5385 } 5386 5387 public void shutdown() { 5388 mPackageUsage.write(true); 5389 } 5390 5391 @Override 5392 public void forceDexOpt(String packageName) { 5393 enforceSystemOrRoot("forceDexOpt"); 5394 5395 PackageParser.Package pkg; 5396 synchronized (mPackages) { 5397 pkg = mPackages.get(packageName); 5398 if (pkg == null) { 5399 throw new IllegalArgumentException("Missing package: " + packageName); 5400 } 5401 } 5402 5403 synchronized (mInstallLock) { 5404 final String[] instructionSets = new String[] { 5405 getPrimaryInstructionSet(pkg.applicationInfo) }; 5406 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5407 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5408 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5409 throw new IllegalStateException("Failed to dexopt: " + res); 5410 } 5411 } 5412 } 5413 5414 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5415 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5416 Slog.w(TAG, "Unable to update from " + oldPkg.name 5417 + " to " + newPkg.packageName 5418 + ": old package not in system partition"); 5419 return false; 5420 } else if (mPackages.get(oldPkg.name) != null) { 5421 Slog.w(TAG, "Unable to update from " + oldPkg.name 5422 + " to " + newPkg.packageName 5423 + ": old package still exists"); 5424 return false; 5425 } 5426 return true; 5427 } 5428 5429 private File getDataPathForPackage(String packageName, int userId) { 5430 /* 5431 * Until we fully support multiple users, return the directory we 5432 * previously would have. The PackageManagerTests will need to be 5433 * revised when this is changed back.. 5434 */ 5435 if (userId == 0) { 5436 return new File(mAppDataDir, packageName); 5437 } else { 5438 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5439 + File.separator + packageName); 5440 } 5441 } 5442 5443 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5444 int[] users = sUserManager.getUserIds(); 5445 int res = mInstaller.install(packageName, uid, uid, seinfo); 5446 if (res < 0) { 5447 return res; 5448 } 5449 for (int user : users) { 5450 if (user != 0) { 5451 res = mInstaller.createUserData(packageName, 5452 UserHandle.getUid(user, uid), user, seinfo); 5453 if (res < 0) { 5454 return res; 5455 } 5456 } 5457 } 5458 return res; 5459 } 5460 5461 private int removeDataDirsLI(String packageName) { 5462 int[] users = sUserManager.getUserIds(); 5463 int res = 0; 5464 for (int user : users) { 5465 int resInner = mInstaller.remove(packageName, user); 5466 if (resInner < 0) { 5467 res = resInner; 5468 } 5469 } 5470 5471 return res; 5472 } 5473 5474 private int deleteCodeCacheDirsLI(String packageName) { 5475 int[] users = sUserManager.getUserIds(); 5476 int res = 0; 5477 for (int user : users) { 5478 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5479 if (resInner < 0) { 5480 res = resInner; 5481 } 5482 } 5483 return res; 5484 } 5485 5486 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5487 PackageParser.Package changingLib) { 5488 if (file.path != null) { 5489 usesLibraryFiles.add(file.path); 5490 return; 5491 } 5492 PackageParser.Package p = mPackages.get(file.apk); 5493 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5494 // If we are doing this while in the middle of updating a library apk, 5495 // then we need to make sure to use that new apk for determining the 5496 // dependencies here. (We haven't yet finished committing the new apk 5497 // to the package manager state.) 5498 if (p == null || p.packageName.equals(changingLib.packageName)) { 5499 p = changingLib; 5500 } 5501 } 5502 if (p != null) { 5503 usesLibraryFiles.addAll(p.getAllCodePaths()); 5504 } 5505 } 5506 5507 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5508 PackageParser.Package changingLib) throws PackageManagerException { 5509 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5510 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5511 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5512 for (int i=0; i<N; i++) { 5513 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5514 if (file == null) { 5515 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5516 "Package " + pkg.packageName + " requires unavailable shared library " 5517 + pkg.usesLibraries.get(i) + "; failing!"); 5518 } 5519 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5520 } 5521 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5522 for (int i=0; i<N; i++) { 5523 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5524 if (file == null) { 5525 Slog.w(TAG, "Package " + pkg.packageName 5526 + " desires unavailable shared library " 5527 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5528 } else { 5529 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5530 } 5531 } 5532 N = usesLibraryFiles.size(); 5533 if (N > 0) { 5534 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5535 } else { 5536 pkg.usesLibraryFiles = null; 5537 } 5538 } 5539 } 5540 5541 private static boolean hasString(List<String> list, List<String> which) { 5542 if (list == null) { 5543 return false; 5544 } 5545 for (int i=list.size()-1; i>=0; i--) { 5546 for (int j=which.size()-1; j>=0; j--) { 5547 if (which.get(j).equals(list.get(i))) { 5548 return true; 5549 } 5550 } 5551 } 5552 return false; 5553 } 5554 5555 private void updateAllSharedLibrariesLPw() { 5556 for (PackageParser.Package pkg : mPackages.values()) { 5557 try { 5558 updateSharedLibrariesLPw(pkg, null); 5559 } catch (PackageManagerException e) { 5560 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5561 } 5562 } 5563 } 5564 5565 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5566 PackageParser.Package changingPkg) { 5567 ArrayList<PackageParser.Package> res = null; 5568 for (PackageParser.Package pkg : mPackages.values()) { 5569 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5570 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5571 if (res == null) { 5572 res = new ArrayList<PackageParser.Package>(); 5573 } 5574 res.add(pkg); 5575 try { 5576 updateSharedLibrariesLPw(pkg, changingPkg); 5577 } catch (PackageManagerException e) { 5578 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5579 } 5580 } 5581 } 5582 return res; 5583 } 5584 5585 /** 5586 * Derive the value of the {@code cpuAbiOverride} based on the provided 5587 * value and an optional stored value from the package settings. 5588 */ 5589 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5590 String cpuAbiOverride = null; 5591 5592 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5593 cpuAbiOverride = null; 5594 } else if (abiOverride != null) { 5595 cpuAbiOverride = abiOverride; 5596 } else if (settings != null) { 5597 cpuAbiOverride = settings.cpuAbiOverrideString; 5598 } 5599 5600 return cpuAbiOverride; 5601 } 5602 5603 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5604 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5605 boolean success = false; 5606 try { 5607 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5608 currentTime, user); 5609 success = true; 5610 return res; 5611 } finally { 5612 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5613 removeDataDirsLI(pkg.packageName); 5614 } 5615 } 5616 } 5617 5618 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5619 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5620 final File scanFile = new File(pkg.codePath); 5621 if (pkg.applicationInfo.getCodePath() == null || 5622 pkg.applicationInfo.getResourcePath() == null) { 5623 // Bail out. The resource and code paths haven't been set. 5624 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5625 "Code and resource paths haven't been set correctly"); 5626 } 5627 5628 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5629 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5630 } else { 5631 // Only allow system apps to be flagged as core apps. 5632 pkg.coreApp = false; 5633 } 5634 5635 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5636 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5637 } 5638 5639 if (mCustomResolverComponentName != null && 5640 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5641 setUpCustomResolverActivity(pkg); 5642 } 5643 5644 if (pkg.packageName.equals("android")) { 5645 synchronized (mPackages) { 5646 if (mAndroidApplication != null) { 5647 Slog.w(TAG, "*************************************************"); 5648 Slog.w(TAG, "Core android package being redefined. Skipping."); 5649 Slog.w(TAG, " file=" + scanFile); 5650 Slog.w(TAG, "*************************************************"); 5651 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5652 "Core android package being redefined. Skipping."); 5653 } 5654 5655 // Set up information for our fall-back user intent resolution activity. 5656 mPlatformPackage = pkg; 5657 pkg.mVersionCode = mSdkVersion; 5658 mAndroidApplication = pkg.applicationInfo; 5659 5660 if (!mResolverReplaced) { 5661 mResolveActivity.applicationInfo = mAndroidApplication; 5662 mResolveActivity.name = ResolverActivity.class.getName(); 5663 mResolveActivity.packageName = mAndroidApplication.packageName; 5664 mResolveActivity.processName = "system:ui"; 5665 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5666 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5667 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5668 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5669 mResolveActivity.exported = true; 5670 mResolveActivity.enabled = true; 5671 mResolveInfo.activityInfo = mResolveActivity; 5672 mResolveInfo.priority = 0; 5673 mResolveInfo.preferredOrder = 0; 5674 mResolveInfo.match = 0; 5675 mResolveComponentName = new ComponentName( 5676 mAndroidApplication.packageName, mResolveActivity.name); 5677 } 5678 } 5679 } 5680 5681 if (DEBUG_PACKAGE_SCANNING) { 5682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5683 Log.d(TAG, "Scanning package " + pkg.packageName); 5684 } 5685 5686 if (mPackages.containsKey(pkg.packageName) 5687 || mSharedLibraries.containsKey(pkg.packageName)) { 5688 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5689 "Application package " + pkg.packageName 5690 + " already installed. Skipping duplicate."); 5691 } 5692 5693 // If we're only installing presumed-existing packages, require that the 5694 // scanned APK is both already known and at the path previously established 5695 // for it. Previously unknown packages we pick up normally, but if we have an 5696 // a priori expectation about this package's install presence, enforce it. 5697 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5698 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5699 if (known != null) { 5700 if (DEBUG_PACKAGE_SCANNING) { 5701 Log.d(TAG, "Examining " + pkg.codePath 5702 + " and requiring known paths " + known.codePathString 5703 + " & " + known.resourcePathString); 5704 } 5705 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5706 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5707 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5708 "Application package " + pkg.packageName 5709 + " found at " + pkg.applicationInfo.getCodePath() 5710 + " but expected at " + known.codePathString + "; ignoring."); 5711 } 5712 } 5713 } 5714 5715 // Initialize package source and resource directories 5716 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5717 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5718 5719 SharedUserSetting suid = null; 5720 PackageSetting pkgSetting = null; 5721 5722 if (!isSystemApp(pkg)) { 5723 // Only system apps can use these features. 5724 pkg.mOriginalPackages = null; 5725 pkg.mRealPackage = null; 5726 pkg.mAdoptPermissions = null; 5727 } 5728 5729 // writer 5730 synchronized (mPackages) { 5731 if (pkg.mSharedUserId != null) { 5732 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5733 if (suid == null) { 5734 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5735 "Creating application package " + pkg.packageName 5736 + " for shared user failed"); 5737 } 5738 if (DEBUG_PACKAGE_SCANNING) { 5739 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5740 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5741 + "): packages=" + suid.packages); 5742 } 5743 } 5744 5745 // Check if we are renaming from an original package name. 5746 PackageSetting origPackage = null; 5747 String realName = null; 5748 if (pkg.mOriginalPackages != null) { 5749 // This package may need to be renamed to a previously 5750 // installed name. Let's check on that... 5751 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5752 if (pkg.mOriginalPackages.contains(renamed)) { 5753 // This package had originally been installed as the 5754 // original name, and we have already taken care of 5755 // transitioning to the new one. Just update the new 5756 // one to continue using the old name. 5757 realName = pkg.mRealPackage; 5758 if (!pkg.packageName.equals(renamed)) { 5759 // Callers into this function may have already taken 5760 // care of renaming the package; only do it here if 5761 // it is not already done. 5762 pkg.setPackageName(renamed); 5763 } 5764 5765 } else { 5766 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5767 if ((origPackage = mSettings.peekPackageLPr( 5768 pkg.mOriginalPackages.get(i))) != null) { 5769 // We do have the package already installed under its 5770 // original name... should we use it? 5771 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5772 // New package is not compatible with original. 5773 origPackage = null; 5774 continue; 5775 } else if (origPackage.sharedUser != null) { 5776 // Make sure uid is compatible between packages. 5777 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5778 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5779 + " to " + pkg.packageName + ": old uid " 5780 + origPackage.sharedUser.name 5781 + " differs from " + pkg.mSharedUserId); 5782 origPackage = null; 5783 continue; 5784 } 5785 } else { 5786 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5787 + pkg.packageName + " to old name " + origPackage.name); 5788 } 5789 break; 5790 } 5791 } 5792 } 5793 } 5794 5795 if (mTransferedPackages.contains(pkg.packageName)) { 5796 Slog.w(TAG, "Package " + pkg.packageName 5797 + " was transferred to another, but its .apk remains"); 5798 } 5799 5800 // Just create the setting, don't add it yet. For already existing packages 5801 // the PkgSetting exists already and doesn't have to be created. 5802 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5803 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5804 pkg.applicationInfo.primaryCpuAbi, 5805 pkg.applicationInfo.secondaryCpuAbi, 5806 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5807 user, false); 5808 if (pkgSetting == null) { 5809 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5810 "Creating application package " + pkg.packageName + " failed"); 5811 } 5812 5813 if (pkgSetting.origPackage != null) { 5814 // If we are first transitioning from an original package, 5815 // fix up the new package's name now. We need to do this after 5816 // looking up the package under its new name, so getPackageLP 5817 // can take care of fiddling things correctly. 5818 pkg.setPackageName(origPackage.name); 5819 5820 // File a report about this. 5821 String msg = "New package " + pkgSetting.realName 5822 + " renamed to replace old package " + pkgSetting.name; 5823 reportSettingsProblem(Log.WARN, msg); 5824 5825 // Make a note of it. 5826 mTransferedPackages.add(origPackage.name); 5827 5828 // No longer need to retain this. 5829 pkgSetting.origPackage = null; 5830 } 5831 5832 if (realName != null) { 5833 // Make a note of it. 5834 mTransferedPackages.add(pkg.packageName); 5835 } 5836 5837 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5839 } 5840 5841 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5842 // Check all shared libraries and map to their actual file path. 5843 // We only do this here for apps not on a system dir, because those 5844 // are the only ones that can fail an install due to this. We 5845 // will take care of the system apps by updating all of their 5846 // library paths after the scan is done. 5847 updateSharedLibrariesLPw(pkg, null); 5848 } 5849 5850 if (mFoundPolicyFile) { 5851 SELinuxMMAC.assignSeinfoValue(pkg); 5852 } 5853 5854 pkg.applicationInfo.uid = pkgSetting.appId; 5855 pkg.mExtras = pkgSetting; 5856 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5857 try { 5858 verifySignaturesLP(pkgSetting, pkg); 5859 // We just determined the app is signed correctly, so bring 5860 // over the latest parsed certs. 5861 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5862 } catch (PackageManagerException e) { 5863 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5864 throw e; 5865 } 5866 // The signature has changed, but this package is in the system 5867 // image... let's recover! 5868 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5869 // However... if this package is part of a shared user, but it 5870 // doesn't match the signature of the shared user, let's fail. 5871 // What this means is that you can't change the signatures 5872 // associated with an overall shared user, which doesn't seem all 5873 // that unreasonable. 5874 if (pkgSetting.sharedUser != null) { 5875 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5876 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5877 throw new PackageManagerException( 5878 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5879 "Signature mismatch for shared user : " 5880 + pkgSetting.sharedUser); 5881 } 5882 } 5883 // File a report about this. 5884 String msg = "System package " + pkg.packageName 5885 + " signature changed; retaining data."; 5886 reportSettingsProblem(Log.WARN, msg); 5887 } 5888 } else { 5889 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5890 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5891 + pkg.packageName + " upgrade keys do not match the " 5892 + "previously installed version"); 5893 } else { 5894 // We just determined the app is signed correctly, so bring 5895 // over the latest parsed certs. 5896 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5897 } 5898 } 5899 // Verify that this new package doesn't have any content providers 5900 // that conflict with existing packages. Only do this if the 5901 // package isn't already installed, since we don't want to break 5902 // things that are installed. 5903 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5904 final int N = pkg.providers.size(); 5905 int i; 5906 for (i=0; i<N; i++) { 5907 PackageParser.Provider p = pkg.providers.get(i); 5908 if (p.info.authority != null) { 5909 String names[] = p.info.authority.split(";"); 5910 for (int j = 0; j < names.length; j++) { 5911 if (mProvidersByAuthority.containsKey(names[j])) { 5912 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5913 final String otherPackageName = 5914 ((other != null && other.getComponentName() != null) ? 5915 other.getComponentName().getPackageName() : "?"); 5916 throw new PackageManagerException( 5917 INSTALL_FAILED_CONFLICTING_PROVIDER, 5918 "Can't install because provider name " + names[j] 5919 + " (in package " + pkg.applicationInfo.packageName 5920 + ") is already used by " + otherPackageName); 5921 } 5922 } 5923 } 5924 } 5925 } 5926 5927 if (pkg.mAdoptPermissions != null) { 5928 // This package wants to adopt ownership of permissions from 5929 // another package. 5930 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5931 final String origName = pkg.mAdoptPermissions.get(i); 5932 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5933 if (orig != null) { 5934 if (verifyPackageUpdateLPr(orig, pkg)) { 5935 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5936 + pkg.packageName); 5937 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5938 } 5939 } 5940 } 5941 } 5942 } 5943 5944 final String pkgName = pkg.packageName; 5945 5946 final long scanFileTime = scanFile.lastModified(); 5947 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5948 pkg.applicationInfo.processName = fixProcessName( 5949 pkg.applicationInfo.packageName, 5950 pkg.applicationInfo.processName, 5951 pkg.applicationInfo.uid); 5952 5953 File dataPath; 5954 if (mPlatformPackage == pkg) { 5955 // The system package is special. 5956 dataPath = new File(Environment.getDataDirectory(), "system"); 5957 5958 pkg.applicationInfo.dataDir = dataPath.getPath(); 5959 5960 } else { 5961 // This is a normal package, need to make its data directory. 5962 dataPath = getDataPathForPackage(pkg.packageName, 0); 5963 5964 boolean uidError = false; 5965 if (dataPath.exists()) { 5966 int currentUid = 0; 5967 try { 5968 StructStat stat = Os.stat(dataPath.getPath()); 5969 currentUid = stat.st_uid; 5970 } catch (ErrnoException e) { 5971 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5972 } 5973 5974 // If we have mismatched owners for the data path, we have a problem. 5975 if (currentUid != pkg.applicationInfo.uid) { 5976 boolean recovered = false; 5977 if (currentUid == 0) { 5978 // The directory somehow became owned by root. Wow. 5979 // This is probably because the system was stopped while 5980 // installd was in the middle of messing with its libs 5981 // directory. Ask installd to fix that. 5982 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5983 pkg.applicationInfo.uid); 5984 if (ret >= 0) { 5985 recovered = true; 5986 String msg = "Package " + pkg.packageName 5987 + " unexpectedly changed to uid 0; recovered to " + 5988 + pkg.applicationInfo.uid; 5989 reportSettingsProblem(Log.WARN, msg); 5990 } 5991 } 5992 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5993 || (scanFlags&SCAN_BOOTING) != 0)) { 5994 // If this is a system app, we can at least delete its 5995 // current data so the application will still work. 5996 int ret = removeDataDirsLI(pkgName); 5997 if (ret >= 0) { 5998 // TODO: Kill the processes first 5999 // Old data gone! 6000 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6001 ? "System package " : "Third party package "; 6002 String msg = prefix + pkg.packageName 6003 + " has changed from uid: " 6004 + currentUid + " to " 6005 + pkg.applicationInfo.uid + "; old data erased"; 6006 reportSettingsProblem(Log.WARN, msg); 6007 recovered = true; 6008 6009 // And now re-install the app. 6010 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6011 pkg.applicationInfo.seinfo); 6012 if (ret == -1) { 6013 // Ack should not happen! 6014 msg = prefix + pkg.packageName 6015 + " could not have data directory re-created after delete."; 6016 reportSettingsProblem(Log.WARN, msg); 6017 throw new PackageManagerException( 6018 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6019 } 6020 } 6021 if (!recovered) { 6022 mHasSystemUidErrors = true; 6023 } 6024 } else if (!recovered) { 6025 // If we allow this install to proceed, we will be broken. 6026 // Abort, abort! 6027 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6028 "scanPackageLI"); 6029 } 6030 if (!recovered) { 6031 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6032 + pkg.applicationInfo.uid + "/fs_" 6033 + currentUid; 6034 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6035 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6036 String msg = "Package " + pkg.packageName 6037 + " has mismatched uid: " 6038 + currentUid + " on disk, " 6039 + pkg.applicationInfo.uid + " in settings"; 6040 // writer 6041 synchronized (mPackages) { 6042 mSettings.mReadMessages.append(msg); 6043 mSettings.mReadMessages.append('\n'); 6044 uidError = true; 6045 if (!pkgSetting.uidError) { 6046 reportSettingsProblem(Log.ERROR, msg); 6047 } 6048 } 6049 } 6050 } 6051 pkg.applicationInfo.dataDir = dataPath.getPath(); 6052 if (mShouldRestoreconData) { 6053 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6054 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 6055 pkg.applicationInfo.uid); 6056 } 6057 } else { 6058 if (DEBUG_PACKAGE_SCANNING) { 6059 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6060 Log.v(TAG, "Want this data dir: " + dataPath); 6061 } 6062 //invoke installer to do the actual installation 6063 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 6064 pkg.applicationInfo.seinfo); 6065 if (ret < 0) { 6066 // Error from installer 6067 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6068 "Unable to create data dirs [errorCode=" + ret + "]"); 6069 } 6070 6071 if (dataPath.exists()) { 6072 pkg.applicationInfo.dataDir = dataPath.getPath(); 6073 } else { 6074 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6075 pkg.applicationInfo.dataDir = null; 6076 } 6077 } 6078 6079 pkgSetting.uidError = uidError; 6080 } 6081 6082 final String path = scanFile.getPath(); 6083 final String codePath = pkg.applicationInfo.getCodePath(); 6084 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6085 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6086 setBundledAppAbisAndRoots(pkg, pkgSetting); 6087 6088 // If we haven't found any native libraries for the app, check if it has 6089 // renderscript code. We'll need to force the app to 32 bit if it has 6090 // renderscript bitcode. 6091 if (pkg.applicationInfo.primaryCpuAbi == null 6092 && pkg.applicationInfo.secondaryCpuAbi == null 6093 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6094 NativeLibraryHelper.Handle handle = null; 6095 try { 6096 handle = NativeLibraryHelper.Handle.create(scanFile); 6097 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6098 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6099 } 6100 } catch (IOException ioe) { 6101 Slog.w(TAG, "Error scanning system app : " + ioe); 6102 } finally { 6103 IoUtils.closeQuietly(handle); 6104 } 6105 } 6106 6107 setNativeLibraryPaths(pkg); 6108 } else { 6109 // TODO: We can probably be smarter about this stuff. For installed apps, 6110 // we can calculate this information at install time once and for all. For 6111 // system apps, we can probably assume that this information doesn't change 6112 // after the first boot scan. As things stand, we do lots of unnecessary work. 6113 6114 // Give ourselves some initial paths; we'll come back for another 6115 // pass once we've determined ABI below. 6116 setNativeLibraryPaths(pkg); 6117 6118 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6119 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6120 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6121 6122 NativeLibraryHelper.Handle handle = null; 6123 try { 6124 handle = NativeLibraryHelper.Handle.create(scanFile); 6125 // TODO(multiArch): This can be null for apps that didn't go through the 6126 // usual installation process. We can calculate it again, like we 6127 // do during install time. 6128 // 6129 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6130 // unnecessary. 6131 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6132 6133 // Null out the abis so that they can be recalculated. 6134 pkg.applicationInfo.primaryCpuAbi = null; 6135 pkg.applicationInfo.secondaryCpuAbi = null; 6136 if (isMultiArch(pkg.applicationInfo)) { 6137 // Warn if we've set an abiOverride for multi-lib packages.. 6138 // By definition, we need to copy both 32 and 64 bit libraries for 6139 // such packages. 6140 if (pkg.cpuAbiOverride != null 6141 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6142 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6143 } 6144 6145 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6146 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6147 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6148 if (isAsec) { 6149 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6150 } else { 6151 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6152 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6153 useIsaSpecificSubdirs); 6154 } 6155 } 6156 6157 maybeThrowExceptionForMultiArchCopy( 6158 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6159 6160 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6161 if (isAsec) { 6162 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6163 } else { 6164 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6165 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6166 useIsaSpecificSubdirs); 6167 } 6168 } 6169 6170 maybeThrowExceptionForMultiArchCopy( 6171 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6172 6173 if (abi64 >= 0) { 6174 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6175 } 6176 6177 if (abi32 >= 0) { 6178 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6179 if (abi64 >= 0) { 6180 pkg.applicationInfo.secondaryCpuAbi = abi; 6181 } else { 6182 pkg.applicationInfo.primaryCpuAbi = abi; 6183 } 6184 } 6185 } else { 6186 String[] abiList = (cpuAbiOverride != null) ? 6187 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6188 6189 // Enable gross and lame hacks for apps that are built with old 6190 // SDK tools. We must scan their APKs for renderscript bitcode and 6191 // not launch them if it's present. Don't bother checking on devices 6192 // that don't have 64 bit support. 6193 boolean needsRenderScriptOverride = false; 6194 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6195 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6196 abiList = Build.SUPPORTED_32_BIT_ABIS; 6197 needsRenderScriptOverride = true; 6198 } 6199 6200 final int copyRet; 6201 if (isAsec) { 6202 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6203 } else { 6204 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6205 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6206 } 6207 6208 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6209 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6210 "Error unpackaging native libs for app, errorCode=" + copyRet); 6211 } 6212 6213 if (copyRet >= 0) { 6214 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6215 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6216 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6217 } else if (needsRenderScriptOverride) { 6218 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6219 } 6220 } 6221 } catch (IOException ioe) { 6222 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6223 } finally { 6224 IoUtils.closeQuietly(handle); 6225 } 6226 6227 // Now that we've calculated the ABIs and determined if it's an internal app, 6228 // we will go ahead and populate the nativeLibraryPath. 6229 setNativeLibraryPaths(pkg); 6230 6231 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6232 final int[] userIds = sUserManager.getUserIds(); 6233 synchronized (mInstallLock) { 6234 // Create a native library symlink only if we have native libraries 6235 // and if the native libraries are 32 bit libraries. We do not provide 6236 // this symlink for 64 bit libraries. 6237 if (pkg.applicationInfo.primaryCpuAbi != null && 6238 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6239 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6240 for (int userId : userIds) { 6241 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 6242 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6243 "Failed linking native library dir (user=" + userId + ")"); 6244 } 6245 } 6246 } 6247 } 6248 } 6249 6250 // This is a special case for the "system" package, where the ABI is 6251 // dictated by the zygote configuration (and init.rc). We should keep track 6252 // of this ABI so that we can deal with "normal" applications that run under 6253 // the same UID correctly. 6254 if (mPlatformPackage == pkg) { 6255 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6256 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6257 } 6258 6259 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6260 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6261 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6262 // Copy the derived override back to the parsed package, so that we can 6263 // update the package settings accordingly. 6264 pkg.cpuAbiOverride = cpuAbiOverride; 6265 6266 if (DEBUG_ABI_SELECTION) { 6267 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6268 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6269 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6270 } 6271 6272 // Push the derived path down into PackageSettings so we know what to 6273 // clean up at uninstall time. 6274 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6275 6276 if (DEBUG_ABI_SELECTION) { 6277 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6278 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6279 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6280 } 6281 6282 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6283 // We don't do this here during boot because we can do it all 6284 // at once after scanning all existing packages. 6285 // 6286 // We also do this *before* we perform dexopt on this package, so that 6287 // we can avoid redundant dexopts, and also to make sure we've got the 6288 // code and package path correct. 6289 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6290 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6291 } 6292 6293 if ((scanFlags & SCAN_NO_DEX) == 0) { 6294 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6295 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6296 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6297 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6298 } 6299 } 6300 if (mFactoryTest && pkg.requestedPermissions.contains( 6301 android.Manifest.permission.FACTORY_TEST)) { 6302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6303 } 6304 6305 ArrayList<PackageParser.Package> clientLibPkgs = null; 6306 6307 // writer 6308 synchronized (mPackages) { 6309 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6310 // Only system apps can add new shared libraries. 6311 if (pkg.libraryNames != null) { 6312 for (int i=0; i<pkg.libraryNames.size(); i++) { 6313 String name = pkg.libraryNames.get(i); 6314 boolean allowed = false; 6315 if (pkg.isUpdatedSystemApp()) { 6316 // New library entries can only be added through the 6317 // system image. This is important to get rid of a lot 6318 // of nasty edge cases: for example if we allowed a non- 6319 // system update of the app to add a library, then uninstalling 6320 // the update would make the library go away, and assumptions 6321 // we made such as through app install filtering would now 6322 // have allowed apps on the device which aren't compatible 6323 // with it. Better to just have the restriction here, be 6324 // conservative, and create many fewer cases that can negatively 6325 // impact the user experience. 6326 final PackageSetting sysPs = mSettings 6327 .getDisabledSystemPkgLPr(pkg.packageName); 6328 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6329 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6330 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6331 allowed = true; 6332 allowed = true; 6333 break; 6334 } 6335 } 6336 } 6337 } else { 6338 allowed = true; 6339 } 6340 if (allowed) { 6341 if (!mSharedLibraries.containsKey(name)) { 6342 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6343 } else if (!name.equals(pkg.packageName)) { 6344 Slog.w(TAG, "Package " + pkg.packageName + " library " 6345 + name + " already exists; skipping"); 6346 } 6347 } else { 6348 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6349 + name + " that is not declared on system image; skipping"); 6350 } 6351 } 6352 if ((scanFlags&SCAN_BOOTING) == 0) { 6353 // If we are not booting, we need to update any applications 6354 // that are clients of our shared library. If we are booting, 6355 // this will all be done once the scan is complete. 6356 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6357 } 6358 } 6359 } 6360 } 6361 6362 // We also need to dexopt any apps that are dependent on this library. Note that 6363 // if these fail, we should abort the install since installing the library will 6364 // result in some apps being broken. 6365 if (clientLibPkgs != null) { 6366 if ((scanFlags & SCAN_NO_DEX) == 0) { 6367 for (int i = 0; i < clientLibPkgs.size(); i++) { 6368 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6369 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6370 null /* instruction sets */, forceDex, 6371 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6372 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6373 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6374 "scanPackageLI failed to dexopt clientLibPkgs"); 6375 } 6376 } 6377 } 6378 } 6379 6380 // Request the ActivityManager to kill the process(only for existing packages) 6381 // so that we do not end up in a confused state while the user is still using the older 6382 // version of the application while the new one gets installed. 6383 if ((scanFlags & SCAN_REPLACING) != 0) { 6384 killApplication(pkg.applicationInfo.packageName, 6385 pkg.applicationInfo.uid, "update pkg"); 6386 } 6387 6388 // Also need to kill any apps that are dependent on the library. 6389 if (clientLibPkgs != null) { 6390 for (int i=0; i<clientLibPkgs.size(); i++) { 6391 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6392 killApplication(clientPkg.applicationInfo.packageName, 6393 clientPkg.applicationInfo.uid, "update lib"); 6394 } 6395 } 6396 6397 // writer 6398 synchronized (mPackages) { 6399 // We don't expect installation to fail beyond this point 6400 6401 // Add the new setting to mSettings 6402 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6403 // Add the new setting to mPackages 6404 mPackages.put(pkg.applicationInfo.packageName, pkg); 6405 // Make sure we don't accidentally delete its data. 6406 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6407 while (iter.hasNext()) { 6408 PackageCleanItem item = iter.next(); 6409 if (pkgName.equals(item.packageName)) { 6410 iter.remove(); 6411 } 6412 } 6413 6414 // Take care of first install / last update times. 6415 if (currentTime != 0) { 6416 if (pkgSetting.firstInstallTime == 0) { 6417 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6418 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6419 pkgSetting.lastUpdateTime = currentTime; 6420 } 6421 } else if (pkgSetting.firstInstallTime == 0) { 6422 // We need *something*. Take time time stamp of the file. 6423 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6424 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6425 if (scanFileTime != pkgSetting.timeStamp) { 6426 // A package on the system image has changed; consider this 6427 // to be an update. 6428 pkgSetting.lastUpdateTime = scanFileTime; 6429 } 6430 } 6431 6432 // Add the package's KeySets to the global KeySetManagerService 6433 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6434 try { 6435 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6436 if (pkg.mKeySetMapping != null) { 6437 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6438 if (pkg.mUpgradeKeySets != null) { 6439 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6440 } 6441 } 6442 } catch (NullPointerException e) { 6443 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6444 } catch (IllegalArgumentException e) { 6445 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6446 } 6447 6448 int N = pkg.providers.size(); 6449 StringBuilder r = null; 6450 int i; 6451 for (i=0; i<N; i++) { 6452 PackageParser.Provider p = pkg.providers.get(i); 6453 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6454 p.info.processName, pkg.applicationInfo.uid); 6455 mProviders.addProvider(p); 6456 p.syncable = p.info.isSyncable; 6457 if (p.info.authority != null) { 6458 String names[] = p.info.authority.split(";"); 6459 p.info.authority = null; 6460 for (int j = 0; j < names.length; j++) { 6461 if (j == 1 && p.syncable) { 6462 // We only want the first authority for a provider to possibly be 6463 // syncable, so if we already added this provider using a different 6464 // authority clear the syncable flag. We copy the provider before 6465 // changing it because the mProviders object contains a reference 6466 // to a provider that we don't want to change. 6467 // Only do this for the second authority since the resulting provider 6468 // object can be the same for all future authorities for this provider. 6469 p = new PackageParser.Provider(p); 6470 p.syncable = false; 6471 } 6472 if (!mProvidersByAuthority.containsKey(names[j])) { 6473 mProvidersByAuthority.put(names[j], p); 6474 if (p.info.authority == null) { 6475 p.info.authority = names[j]; 6476 } else { 6477 p.info.authority = p.info.authority + ";" + names[j]; 6478 } 6479 if (DEBUG_PACKAGE_SCANNING) { 6480 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6481 Log.d(TAG, "Registered content provider: " + names[j] 6482 + ", className = " + p.info.name + ", isSyncable = " 6483 + p.info.isSyncable); 6484 } 6485 } else { 6486 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6487 Slog.w(TAG, "Skipping provider name " + names[j] + 6488 " (in package " + pkg.applicationInfo.packageName + 6489 "): name already used by " 6490 + ((other != null && other.getComponentName() != null) 6491 ? other.getComponentName().getPackageName() : "?")); 6492 } 6493 } 6494 } 6495 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6496 if (r == null) { 6497 r = new StringBuilder(256); 6498 } else { 6499 r.append(' '); 6500 } 6501 r.append(p.info.name); 6502 } 6503 } 6504 if (r != null) { 6505 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6506 } 6507 6508 N = pkg.services.size(); 6509 r = null; 6510 for (i=0; i<N; i++) { 6511 PackageParser.Service s = pkg.services.get(i); 6512 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6513 s.info.processName, pkg.applicationInfo.uid); 6514 mServices.addService(s); 6515 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6516 if (r == null) { 6517 r = new StringBuilder(256); 6518 } else { 6519 r.append(' '); 6520 } 6521 r.append(s.info.name); 6522 } 6523 } 6524 if (r != null) { 6525 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6526 } 6527 6528 N = pkg.receivers.size(); 6529 r = null; 6530 for (i=0; i<N; i++) { 6531 PackageParser.Activity a = pkg.receivers.get(i); 6532 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6533 a.info.processName, pkg.applicationInfo.uid); 6534 mReceivers.addActivity(a, "receiver"); 6535 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6536 if (r == null) { 6537 r = new StringBuilder(256); 6538 } else { 6539 r.append(' '); 6540 } 6541 r.append(a.info.name); 6542 } 6543 } 6544 if (r != null) { 6545 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6546 } 6547 6548 N = pkg.activities.size(); 6549 r = null; 6550 for (i=0; i<N; i++) { 6551 PackageParser.Activity a = pkg.activities.get(i); 6552 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6553 a.info.processName, pkg.applicationInfo.uid); 6554 mActivities.addActivity(a, "activity"); 6555 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6556 if (r == null) { 6557 r = new StringBuilder(256); 6558 } else { 6559 r.append(' '); 6560 } 6561 r.append(a.info.name); 6562 } 6563 } 6564 if (r != null) { 6565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6566 } 6567 6568 N = pkg.permissionGroups.size(); 6569 r = null; 6570 for (i=0; i<N; i++) { 6571 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6572 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6573 if (cur == null) { 6574 mPermissionGroups.put(pg.info.name, pg); 6575 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6576 if (r == null) { 6577 r = new StringBuilder(256); 6578 } else { 6579 r.append(' '); 6580 } 6581 r.append(pg.info.name); 6582 } 6583 } else { 6584 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6585 + pg.info.packageName + " ignored: original from " 6586 + cur.info.packageName); 6587 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6588 if (r == null) { 6589 r = new StringBuilder(256); 6590 } else { 6591 r.append(' '); 6592 } 6593 r.append("DUP:"); 6594 r.append(pg.info.name); 6595 } 6596 } 6597 } 6598 if (r != null) { 6599 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6600 } 6601 6602 N = pkg.permissions.size(); 6603 r = null; 6604 for (i=0; i<N; i++) { 6605 PackageParser.Permission p = pkg.permissions.get(i); 6606 ArrayMap<String, BasePermission> permissionMap = 6607 p.tree ? mSettings.mPermissionTrees 6608 : mSettings.mPermissions; 6609 p.group = mPermissionGroups.get(p.info.group); 6610 if (p.info.group == null || p.group != null) { 6611 BasePermission bp = permissionMap.get(p.info.name); 6612 6613 // Allow system apps to redefine non-system permissions 6614 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6615 final boolean currentOwnerIsSystem = (bp.perm != null 6616 && isSystemApp(bp.perm.owner)); 6617 if (isSystemApp(p.owner)) { 6618 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6619 // It's a built-in permission and no owner, take ownership now 6620 bp.packageSetting = pkgSetting; 6621 bp.perm = p; 6622 bp.uid = pkg.applicationInfo.uid; 6623 bp.sourcePackage = p.info.packageName; 6624 } else if (!currentOwnerIsSystem) { 6625 String msg = "New decl " + p.owner + " of permission " 6626 + p.info.name + " is system; overriding " + bp.sourcePackage; 6627 reportSettingsProblem(Log.WARN, msg); 6628 bp = null; 6629 } 6630 } 6631 } 6632 6633 if (bp == null) { 6634 bp = new BasePermission(p.info.name, p.info.packageName, 6635 BasePermission.TYPE_NORMAL); 6636 permissionMap.put(p.info.name, bp); 6637 } 6638 6639 if (bp.perm == null) { 6640 if (bp.sourcePackage == null 6641 || bp.sourcePackage.equals(p.info.packageName)) { 6642 BasePermission tree = findPermissionTreeLP(p.info.name); 6643 if (tree == null 6644 || tree.sourcePackage.equals(p.info.packageName)) { 6645 bp.packageSetting = pkgSetting; 6646 bp.perm = p; 6647 bp.uid = pkg.applicationInfo.uid; 6648 bp.sourcePackage = p.info.packageName; 6649 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6650 if (r == null) { 6651 r = new StringBuilder(256); 6652 } else { 6653 r.append(' '); 6654 } 6655 r.append(p.info.name); 6656 } 6657 } else { 6658 Slog.w(TAG, "Permission " + p.info.name + " from package " 6659 + p.info.packageName + " ignored: base tree " 6660 + tree.name + " is from package " 6661 + tree.sourcePackage); 6662 } 6663 } else { 6664 Slog.w(TAG, "Permission " + p.info.name + " from package " 6665 + p.info.packageName + " ignored: original from " 6666 + bp.sourcePackage); 6667 } 6668 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6669 if (r == null) { 6670 r = new StringBuilder(256); 6671 } else { 6672 r.append(' '); 6673 } 6674 r.append("DUP:"); 6675 r.append(p.info.name); 6676 } 6677 if (bp.perm == p) { 6678 bp.protectionLevel = p.info.protectionLevel; 6679 } 6680 } else { 6681 Slog.w(TAG, "Permission " + p.info.name + " from package " 6682 + p.info.packageName + " ignored: no group " 6683 + p.group); 6684 } 6685 } 6686 if (r != null) { 6687 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6688 } 6689 6690 N = pkg.instrumentation.size(); 6691 r = null; 6692 for (i=0; i<N; i++) { 6693 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6694 a.info.packageName = pkg.applicationInfo.packageName; 6695 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6696 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6697 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6698 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6699 a.info.dataDir = pkg.applicationInfo.dataDir; 6700 6701 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6702 // need other information about the application, like the ABI and what not ? 6703 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6704 mInstrumentation.put(a.getComponentName(), a); 6705 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6706 if (r == null) { 6707 r = new StringBuilder(256); 6708 } else { 6709 r.append(' '); 6710 } 6711 r.append(a.info.name); 6712 } 6713 } 6714 if (r != null) { 6715 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6716 } 6717 6718 if (pkg.protectedBroadcasts != null) { 6719 N = pkg.protectedBroadcasts.size(); 6720 for (i=0; i<N; i++) { 6721 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6722 } 6723 } 6724 6725 pkgSetting.setTimeStamp(scanFileTime); 6726 6727 // Create idmap files for pairs of (packages, overlay packages). 6728 // Note: "android", ie framework-res.apk, is handled by native layers. 6729 if (pkg.mOverlayTarget != null) { 6730 // This is an overlay package. 6731 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6732 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6733 mOverlays.put(pkg.mOverlayTarget, 6734 new ArrayMap<String, PackageParser.Package>()); 6735 } 6736 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6737 map.put(pkg.packageName, pkg); 6738 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6739 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6740 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6741 "scanPackageLI failed to createIdmap"); 6742 } 6743 } 6744 } else if (mOverlays.containsKey(pkg.packageName) && 6745 !pkg.packageName.equals("android")) { 6746 // This is a regular package, with one or more known overlay packages. 6747 createIdmapsForPackageLI(pkg); 6748 } 6749 } 6750 6751 return pkg; 6752 } 6753 6754 /** 6755 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6756 * i.e, so that all packages can be run inside a single process if required. 6757 * 6758 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6759 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6760 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6761 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6762 * updating a package that belongs to a shared user. 6763 * 6764 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6765 * adds unnecessary complexity. 6766 */ 6767 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6768 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6769 String requiredInstructionSet = null; 6770 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6771 requiredInstructionSet = VMRuntime.getInstructionSet( 6772 scannedPackage.applicationInfo.primaryCpuAbi); 6773 } 6774 6775 PackageSetting requirer = null; 6776 for (PackageSetting ps : packagesForUser) { 6777 // If packagesForUser contains scannedPackage, we skip it. This will happen 6778 // when scannedPackage is an update of an existing package. Without this check, 6779 // we will never be able to change the ABI of any package belonging to a shared 6780 // user, even if it's compatible with other packages. 6781 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6782 if (ps.primaryCpuAbiString == null) { 6783 continue; 6784 } 6785 6786 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6787 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6788 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6789 // this but there's not much we can do. 6790 String errorMessage = "Instruction set mismatch, " 6791 + ((requirer == null) ? "[caller]" : requirer) 6792 + " requires " + requiredInstructionSet + " whereas " + ps 6793 + " requires " + instructionSet; 6794 Slog.w(TAG, errorMessage); 6795 } 6796 6797 if (requiredInstructionSet == null) { 6798 requiredInstructionSet = instructionSet; 6799 requirer = ps; 6800 } 6801 } 6802 } 6803 6804 if (requiredInstructionSet != null) { 6805 String adjustedAbi; 6806 if (requirer != null) { 6807 // requirer != null implies that either scannedPackage was null or that scannedPackage 6808 // did not require an ABI, in which case we have to adjust scannedPackage to match 6809 // the ABI of the set (which is the same as requirer's ABI) 6810 adjustedAbi = requirer.primaryCpuAbiString; 6811 if (scannedPackage != null) { 6812 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6813 } 6814 } else { 6815 // requirer == null implies that we're updating all ABIs in the set to 6816 // match scannedPackage. 6817 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6818 } 6819 6820 for (PackageSetting ps : packagesForUser) { 6821 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6822 if (ps.primaryCpuAbiString != null) { 6823 continue; 6824 } 6825 6826 ps.primaryCpuAbiString = adjustedAbi; 6827 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6828 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6829 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6830 6831 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6832 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6833 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6834 ps.primaryCpuAbiString = null; 6835 ps.pkg.applicationInfo.primaryCpuAbi = null; 6836 return; 6837 } else { 6838 mInstaller.rmdex(ps.codePathString, 6839 getDexCodeInstructionSet(getPreferredInstructionSet())); 6840 } 6841 } 6842 } 6843 } 6844 } 6845 } 6846 6847 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6848 synchronized (mPackages) { 6849 mResolverReplaced = true; 6850 // Set up information for custom user intent resolution activity. 6851 mResolveActivity.applicationInfo = pkg.applicationInfo; 6852 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6853 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6854 mResolveActivity.processName = pkg.applicationInfo.packageName; 6855 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6856 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6857 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6858 mResolveActivity.theme = 0; 6859 mResolveActivity.exported = true; 6860 mResolveActivity.enabled = true; 6861 mResolveInfo.activityInfo = mResolveActivity; 6862 mResolveInfo.priority = 0; 6863 mResolveInfo.preferredOrder = 0; 6864 mResolveInfo.match = 0; 6865 mResolveComponentName = mCustomResolverComponentName; 6866 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6867 mResolveComponentName); 6868 } 6869 } 6870 6871 private static String calculateBundledApkRoot(final String codePathString) { 6872 final File codePath = new File(codePathString); 6873 final File codeRoot; 6874 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6875 codeRoot = Environment.getRootDirectory(); 6876 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6877 codeRoot = Environment.getOemDirectory(); 6878 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6879 codeRoot = Environment.getVendorDirectory(); 6880 } else { 6881 // Unrecognized code path; take its top real segment as the apk root: 6882 // e.g. /something/app/blah.apk => /something 6883 try { 6884 File f = codePath.getCanonicalFile(); 6885 File parent = f.getParentFile(); // non-null because codePath is a file 6886 File tmp; 6887 while ((tmp = parent.getParentFile()) != null) { 6888 f = parent; 6889 parent = tmp; 6890 } 6891 codeRoot = f; 6892 Slog.w(TAG, "Unrecognized code path " 6893 + codePath + " - using " + codeRoot); 6894 } catch (IOException e) { 6895 // Can't canonicalize the code path -- shenanigans? 6896 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6897 return Environment.getRootDirectory().getPath(); 6898 } 6899 } 6900 return codeRoot.getPath(); 6901 } 6902 6903 /** 6904 * Derive and set the location of native libraries for the given package, 6905 * which varies depending on where and how the package was installed. 6906 */ 6907 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6908 final ApplicationInfo info = pkg.applicationInfo; 6909 final String codePath = pkg.codePath; 6910 final File codeFile = new File(codePath); 6911 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 6912 final boolean asecApp = info.isForwardLocked() || isExternal(info); 6913 6914 info.nativeLibraryRootDir = null; 6915 info.nativeLibraryRootRequiresIsa = false; 6916 info.nativeLibraryDir = null; 6917 info.secondaryNativeLibraryDir = null; 6918 6919 if (isApkFile(codeFile)) { 6920 // Monolithic install 6921 if (bundledApp) { 6922 // If "/system/lib64/apkname" exists, assume that is the per-package 6923 // native library directory to use; otherwise use "/system/lib/apkname". 6924 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6925 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6926 getPrimaryInstructionSet(info)); 6927 6928 // This is a bundled system app so choose the path based on the ABI. 6929 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6930 // is just the default path. 6931 final String apkName = deriveCodePathName(codePath); 6932 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6933 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6934 apkName).getAbsolutePath(); 6935 6936 if (info.secondaryCpuAbi != null) { 6937 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6938 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6939 secondaryLibDir, apkName).getAbsolutePath(); 6940 } 6941 } else if (asecApp) { 6942 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6943 .getAbsolutePath(); 6944 } else { 6945 final String apkName = deriveCodePathName(codePath); 6946 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6947 .getAbsolutePath(); 6948 } 6949 6950 info.nativeLibraryRootRequiresIsa = false; 6951 info.nativeLibraryDir = info.nativeLibraryRootDir; 6952 } else { 6953 // Cluster install 6954 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6955 info.nativeLibraryRootRequiresIsa = true; 6956 6957 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6958 getPrimaryInstructionSet(info)).getAbsolutePath(); 6959 6960 if (info.secondaryCpuAbi != null) { 6961 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6962 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6963 } 6964 } 6965 } 6966 6967 /** 6968 * Calculate the abis and roots for a bundled app. These can uniquely 6969 * be determined from the contents of the system partition, i.e whether 6970 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6971 * of this information, and instead assume that the system was built 6972 * sensibly. 6973 */ 6974 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6975 PackageSetting pkgSetting) { 6976 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6977 6978 // If "/system/lib64/apkname" exists, assume that is the per-package 6979 // native library directory to use; otherwise use "/system/lib/apkname". 6980 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6981 setBundledAppAbi(pkg, apkRoot, apkName); 6982 // pkgSetting might be null during rescan following uninstall of updates 6983 // to a bundled app, so accommodate that possibility. The settings in 6984 // that case will be established later from the parsed package. 6985 // 6986 // If the settings aren't null, sync them up with what we've just derived. 6987 // note that apkRoot isn't stored in the package settings. 6988 if (pkgSetting != null) { 6989 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6990 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6991 } 6992 } 6993 6994 /** 6995 * Deduces the ABI of a bundled app and sets the relevant fields on the 6996 * parsed pkg object. 6997 * 6998 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6999 * under which system libraries are installed. 7000 * @param apkName the name of the installed package. 7001 */ 7002 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7003 final File codeFile = new File(pkg.codePath); 7004 7005 final boolean has64BitLibs; 7006 final boolean has32BitLibs; 7007 if (isApkFile(codeFile)) { 7008 // Monolithic install 7009 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7010 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7011 } else { 7012 // Cluster install 7013 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7014 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7015 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7016 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7017 has64BitLibs = (new File(rootDir, isa)).exists(); 7018 } else { 7019 has64BitLibs = false; 7020 } 7021 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7022 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7023 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7024 has32BitLibs = (new File(rootDir, isa)).exists(); 7025 } else { 7026 has32BitLibs = false; 7027 } 7028 } 7029 7030 if (has64BitLibs && !has32BitLibs) { 7031 // The package has 64 bit libs, but not 32 bit libs. Its primary 7032 // ABI should be 64 bit. We can safely assume here that the bundled 7033 // native libraries correspond to the most preferred ABI in the list. 7034 7035 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7036 pkg.applicationInfo.secondaryCpuAbi = null; 7037 } else if (has32BitLibs && !has64BitLibs) { 7038 // The package has 32 bit libs but not 64 bit libs. Its primary 7039 // ABI should be 32 bit. 7040 7041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7042 pkg.applicationInfo.secondaryCpuAbi = null; 7043 } else if (has32BitLibs && has64BitLibs) { 7044 // The application has both 64 and 32 bit bundled libraries. We check 7045 // here that the app declares multiArch support, and warn if it doesn't. 7046 // 7047 // We will be lenient here and record both ABIs. The primary will be the 7048 // ABI that's higher on the list, i.e, a device that's configured to prefer 7049 // 64 bit apps will see a 64 bit primary ABI, 7050 7051 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7052 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7053 } 7054 7055 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7056 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7057 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7058 } else { 7059 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7060 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7061 } 7062 } else { 7063 pkg.applicationInfo.primaryCpuAbi = null; 7064 pkg.applicationInfo.secondaryCpuAbi = null; 7065 } 7066 } 7067 7068 private void killApplication(String pkgName, int appId, String reason) { 7069 // Request the ActivityManager to kill the process(only for existing packages) 7070 // so that we do not end up in a confused state while the user is still using the older 7071 // version of the application while the new one gets installed. 7072 IActivityManager am = ActivityManagerNative.getDefault(); 7073 if (am != null) { 7074 try { 7075 am.killApplicationWithAppId(pkgName, appId, reason); 7076 } catch (RemoteException e) { 7077 } 7078 } 7079 } 7080 7081 void removePackageLI(PackageSetting ps, boolean chatty) { 7082 if (DEBUG_INSTALL) { 7083 if (chatty) 7084 Log.d(TAG, "Removing package " + ps.name); 7085 } 7086 7087 // writer 7088 synchronized (mPackages) { 7089 mPackages.remove(ps.name); 7090 final PackageParser.Package pkg = ps.pkg; 7091 if (pkg != null) { 7092 cleanPackageDataStructuresLILPw(pkg, chatty); 7093 } 7094 } 7095 } 7096 7097 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7098 if (DEBUG_INSTALL) { 7099 if (chatty) 7100 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7101 } 7102 7103 // writer 7104 synchronized (mPackages) { 7105 mPackages.remove(pkg.applicationInfo.packageName); 7106 cleanPackageDataStructuresLILPw(pkg, chatty); 7107 } 7108 } 7109 7110 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7111 int N = pkg.providers.size(); 7112 StringBuilder r = null; 7113 int i; 7114 for (i=0; i<N; i++) { 7115 PackageParser.Provider p = pkg.providers.get(i); 7116 mProviders.removeProvider(p); 7117 if (p.info.authority == null) { 7118 7119 /* There was another ContentProvider with this authority when 7120 * this app was installed so this authority is null, 7121 * Ignore it as we don't have to unregister the provider. 7122 */ 7123 continue; 7124 } 7125 String names[] = p.info.authority.split(";"); 7126 for (int j = 0; j < names.length; j++) { 7127 if (mProvidersByAuthority.get(names[j]) == p) { 7128 mProvidersByAuthority.remove(names[j]); 7129 if (DEBUG_REMOVE) { 7130 if (chatty) 7131 Log.d(TAG, "Unregistered content provider: " + names[j] 7132 + ", className = " + p.info.name + ", isSyncable = " 7133 + p.info.isSyncable); 7134 } 7135 } 7136 } 7137 if (DEBUG_REMOVE && chatty) { 7138 if (r == null) { 7139 r = new StringBuilder(256); 7140 } else { 7141 r.append(' '); 7142 } 7143 r.append(p.info.name); 7144 } 7145 } 7146 if (r != null) { 7147 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7148 } 7149 7150 N = pkg.services.size(); 7151 r = null; 7152 for (i=0; i<N; i++) { 7153 PackageParser.Service s = pkg.services.get(i); 7154 mServices.removeService(s); 7155 if (chatty) { 7156 if (r == null) { 7157 r = new StringBuilder(256); 7158 } else { 7159 r.append(' '); 7160 } 7161 r.append(s.info.name); 7162 } 7163 } 7164 if (r != null) { 7165 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7166 } 7167 7168 N = pkg.receivers.size(); 7169 r = null; 7170 for (i=0; i<N; i++) { 7171 PackageParser.Activity a = pkg.receivers.get(i); 7172 mReceivers.removeActivity(a, "receiver"); 7173 if (DEBUG_REMOVE && chatty) { 7174 if (r == null) { 7175 r = new StringBuilder(256); 7176 } else { 7177 r.append(' '); 7178 } 7179 r.append(a.info.name); 7180 } 7181 } 7182 if (r != null) { 7183 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7184 } 7185 7186 N = pkg.activities.size(); 7187 r = null; 7188 for (i=0; i<N; i++) { 7189 PackageParser.Activity a = pkg.activities.get(i); 7190 mActivities.removeActivity(a, "activity"); 7191 if (DEBUG_REMOVE && chatty) { 7192 if (r == null) { 7193 r = new StringBuilder(256); 7194 } else { 7195 r.append(' '); 7196 } 7197 r.append(a.info.name); 7198 } 7199 } 7200 if (r != null) { 7201 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7202 } 7203 7204 N = pkg.permissions.size(); 7205 r = null; 7206 for (i=0; i<N; i++) { 7207 PackageParser.Permission p = pkg.permissions.get(i); 7208 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7209 if (bp == null) { 7210 bp = mSettings.mPermissionTrees.get(p.info.name); 7211 } 7212 if (bp != null && bp.perm == p) { 7213 bp.perm = null; 7214 if (DEBUG_REMOVE && chatty) { 7215 if (r == null) { 7216 r = new StringBuilder(256); 7217 } else { 7218 r.append(' '); 7219 } 7220 r.append(p.info.name); 7221 } 7222 } 7223 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7224 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7225 if (appOpPerms != null) { 7226 appOpPerms.remove(pkg.packageName); 7227 } 7228 } 7229 } 7230 if (r != null) { 7231 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7232 } 7233 7234 N = pkg.requestedPermissions.size(); 7235 r = null; 7236 for (i=0; i<N; i++) { 7237 String perm = pkg.requestedPermissions.get(i); 7238 BasePermission bp = mSettings.mPermissions.get(perm); 7239 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7240 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7241 if (appOpPerms != null) { 7242 appOpPerms.remove(pkg.packageName); 7243 if (appOpPerms.isEmpty()) { 7244 mAppOpPermissionPackages.remove(perm); 7245 } 7246 } 7247 } 7248 } 7249 if (r != null) { 7250 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7251 } 7252 7253 N = pkg.instrumentation.size(); 7254 r = null; 7255 for (i=0; i<N; i++) { 7256 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7257 mInstrumentation.remove(a.getComponentName()); 7258 if (DEBUG_REMOVE && chatty) { 7259 if (r == null) { 7260 r = new StringBuilder(256); 7261 } else { 7262 r.append(' '); 7263 } 7264 r.append(a.info.name); 7265 } 7266 } 7267 if (r != null) { 7268 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7269 } 7270 7271 r = null; 7272 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7273 // Only system apps can hold shared libraries. 7274 if (pkg.libraryNames != null) { 7275 for (i=0; i<pkg.libraryNames.size(); i++) { 7276 String name = pkg.libraryNames.get(i); 7277 SharedLibraryEntry cur = mSharedLibraries.get(name); 7278 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7279 mSharedLibraries.remove(name); 7280 if (DEBUG_REMOVE && chatty) { 7281 if (r == null) { 7282 r = new StringBuilder(256); 7283 } else { 7284 r.append(' '); 7285 } 7286 r.append(name); 7287 } 7288 } 7289 } 7290 } 7291 } 7292 if (r != null) { 7293 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7294 } 7295 } 7296 7297 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7298 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7299 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7300 return true; 7301 } 7302 } 7303 return false; 7304 } 7305 7306 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7307 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7308 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7309 7310 private void updatePermissionsLPw(String changingPkg, 7311 PackageParser.Package pkgInfo, int flags) { 7312 // Make sure there are no dangling permission trees. 7313 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7314 while (it.hasNext()) { 7315 final BasePermission bp = it.next(); 7316 if (bp.packageSetting == null) { 7317 // We may not yet have parsed the package, so just see if 7318 // we still know about its settings. 7319 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7320 } 7321 if (bp.packageSetting == null) { 7322 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7323 + " from package " + bp.sourcePackage); 7324 it.remove(); 7325 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7326 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7327 Slog.i(TAG, "Removing old permission tree: " + bp.name 7328 + " from package " + bp.sourcePackage); 7329 flags |= UPDATE_PERMISSIONS_ALL; 7330 it.remove(); 7331 } 7332 } 7333 } 7334 7335 // Make sure all dynamic permissions have been assigned to a package, 7336 // and make sure there are no dangling permissions. 7337 it = mSettings.mPermissions.values().iterator(); 7338 while (it.hasNext()) { 7339 final BasePermission bp = it.next(); 7340 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7341 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7342 + bp.name + " pkg=" + bp.sourcePackage 7343 + " info=" + bp.pendingInfo); 7344 if (bp.packageSetting == null && bp.pendingInfo != null) { 7345 final BasePermission tree = findPermissionTreeLP(bp.name); 7346 if (tree != null && tree.perm != null) { 7347 bp.packageSetting = tree.packageSetting; 7348 bp.perm = new PackageParser.Permission(tree.perm.owner, 7349 new PermissionInfo(bp.pendingInfo)); 7350 bp.perm.info.packageName = tree.perm.info.packageName; 7351 bp.perm.info.name = bp.name; 7352 bp.uid = tree.uid; 7353 } 7354 } 7355 } 7356 if (bp.packageSetting == null) { 7357 // We may not yet have parsed the package, so just see if 7358 // we still know about its settings. 7359 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7360 } 7361 if (bp.packageSetting == null) { 7362 Slog.w(TAG, "Removing dangling permission: " + bp.name 7363 + " from package " + bp.sourcePackage); 7364 it.remove(); 7365 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7366 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7367 Slog.i(TAG, "Removing old permission: " + bp.name 7368 + " from package " + bp.sourcePackage); 7369 flags |= UPDATE_PERMISSIONS_ALL; 7370 it.remove(); 7371 } 7372 } 7373 } 7374 7375 // Now update the permissions for all packages, in particular 7376 // replace the granted permissions of the system packages. 7377 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7378 for (PackageParser.Package pkg : mPackages.values()) { 7379 if (pkg != pkgInfo) { 7380 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7381 changingPkg); 7382 } 7383 } 7384 } 7385 7386 if (pkgInfo != null) { 7387 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7388 } 7389 } 7390 7391 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7392 String packageOfInterest) { 7393 // IMPORTANT: There are two types of permissions: install and runtime. 7394 // Install time permissions are granted when the app is installed to 7395 // all device users and users added in the future. Runtime permissions 7396 // are granted at runtime explicitly to specific users. Normal and signature 7397 // protected permissions are install time permissions. Dangerous permissions 7398 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7399 // otherwise they are runtime permissions. This function does not manage 7400 // runtime permissions except for the case an app targeting Lollipop MR1 7401 // being upgraded to target a newer SDK, in which case dangerous permissions 7402 // are transformed from install time to runtime ones. 7403 7404 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7405 if (ps == null) { 7406 return; 7407 } 7408 7409 PermissionsState permissionsState = ps.getPermissionsState(); 7410 PermissionsState origPermissions = permissionsState; 7411 7412 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7413 7414 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7415 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7416 7417 boolean changedInstallPermission = false; 7418 7419 if (replace) { 7420 ps.installPermissionsFixed = false; 7421 if (!ps.isSharedUser()) { 7422 origPermissions = new PermissionsState(permissionsState); 7423 permissionsState.reset(); 7424 } 7425 } 7426 7427 permissionsState.setGlobalGids(mGlobalGids); 7428 7429 final int N = pkg.requestedPermissions.size(); 7430 for (int i=0; i<N; i++) { 7431 final String name = pkg.requestedPermissions.get(i); 7432 final BasePermission bp = mSettings.mPermissions.get(name); 7433 7434 if (DEBUG_INSTALL) { 7435 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7436 } 7437 7438 if (bp == null || bp.packageSetting == null) { 7439 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7440 Slog.w(TAG, "Unknown permission " + name 7441 + " in package " + pkg.packageName); 7442 } 7443 continue; 7444 } 7445 7446 final String perm = bp.name; 7447 boolean allowedSig = false; 7448 int grant = GRANT_DENIED; 7449 7450 // Keep track of app op permissions. 7451 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7452 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7453 if (pkgs == null) { 7454 pkgs = new ArraySet<>(); 7455 mAppOpPermissionPackages.put(bp.name, pkgs); 7456 } 7457 pkgs.add(pkg.packageName); 7458 } 7459 7460 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7461 switch (level) { 7462 case PermissionInfo.PROTECTION_NORMAL: { 7463 // For all apps normal permissions are install time ones. 7464 grant = GRANT_INSTALL; 7465 } break; 7466 7467 case PermissionInfo.PROTECTION_DANGEROUS: { 7468 if (!RUNTIME_PERMISSIONS_ENABLED 7469 || pkg.applicationInfo.targetSdkVersion 7470 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7471 // For legacy apps dangerous permissions are install time ones. 7472 grant = GRANT_INSTALL; 7473 } else if (ps.isSystem()) { 7474 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7475 if (origPermissions.hasInstallPermission(bp.name)) { 7476 // If a system app had an install permission, then the app was 7477 // upgraded and we grant the permissions as runtime to all users. 7478 grant = GRANT_UPGRADE; 7479 upgradeUserIds = currentUserIds; 7480 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7481 // If users changed since the last permissions update for a 7482 // system app, we grant the permission as runtime to the new users. 7483 grant = GRANT_UPGRADE; 7484 upgradeUserIds = currentUserIds; 7485 for (int userId : updatedUserIds) { 7486 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7487 } 7488 } else { 7489 // Otherwise, we grant the permission as runtime if the app 7490 // already had it, i.e. we preserve runtime permissions. 7491 grant = GRANT_RUNTIME; 7492 } 7493 } else if (origPermissions.hasInstallPermission(bp.name)) { 7494 // For legacy apps that became modern, install becomes runtime. 7495 grant = GRANT_UPGRADE; 7496 upgradeUserIds = currentUserIds; 7497 } else if (replace) { 7498 // For upgraded modern apps keep runtime permissions unchanged. 7499 grant = GRANT_RUNTIME; 7500 } 7501 } break; 7502 7503 case PermissionInfo.PROTECTION_SIGNATURE: { 7504 // For all apps signature permissions are install time ones. 7505 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7506 if (allowedSig) { 7507 grant = GRANT_INSTALL; 7508 } 7509 } break; 7510 } 7511 7512 if (DEBUG_INSTALL) { 7513 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7514 } 7515 7516 if (grant != GRANT_DENIED) { 7517 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7518 // If this is an existing, non-system package, then 7519 // we can't add any new permissions to it. 7520 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7521 // Except... if this is a permission that was added 7522 // to the platform (note: need to only do this when 7523 // updating the platform). 7524 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7525 grant = GRANT_DENIED; 7526 } 7527 } 7528 } 7529 7530 switch (grant) { 7531 case GRANT_INSTALL: { 7532 // Grant an install permission. 7533 if (permissionsState.grantInstallPermission(bp) != 7534 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7535 changedInstallPermission = true; 7536 } 7537 } break; 7538 7539 case GRANT_RUNTIME: { 7540 // Grant previously granted runtime permissions. 7541 for (int userId : UserManagerService.getInstance().getUserIds()) { 7542 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7543 if (permissionsState.grantRuntimePermission(bp, userId) == 7544 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7545 // If we cannot put the permission as it was, we have to write. 7546 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7547 changedRuntimePermissionUserIds, userId); 7548 } 7549 } 7550 } 7551 } break; 7552 7553 case GRANT_UPGRADE: { 7554 // Grant runtime permissions for a previously held install permission. 7555 permissionsState.revokeInstallPermission(bp); 7556 for (int userId : upgradeUserIds) { 7557 if (permissionsState.grantRuntimePermission(bp, userId) != 7558 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7559 // If we granted the permission, we have to write. 7560 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7561 changedRuntimePermissionUserIds, userId); 7562 } 7563 } 7564 } break; 7565 7566 default: { 7567 if (packageOfInterest == null 7568 || packageOfInterest.equals(pkg.packageName)) { 7569 Slog.w(TAG, "Not granting permission " + perm 7570 + " to package " + pkg.packageName 7571 + " because it was previously installed without"); 7572 } 7573 } break; 7574 } 7575 } else { 7576 if (permissionsState.revokeInstallPermission(bp) != 7577 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7578 changedInstallPermission = true; 7579 Slog.i(TAG, "Un-granting permission " + perm 7580 + " from package " + pkg.packageName 7581 + " (protectionLevel=" + bp.protectionLevel 7582 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7583 + ")"); 7584 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7585 // Don't print warning for app op permissions, since it is fine for them 7586 // not to be granted, there is a UI for the user to decide. 7587 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7588 Slog.w(TAG, "Not granting permission " + perm 7589 + " to package " + pkg.packageName 7590 + " (protectionLevel=" + bp.protectionLevel 7591 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7592 + ")"); 7593 } 7594 } 7595 } 7596 } 7597 7598 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7599 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7600 // This is the first that we have heard about this package, so the 7601 // permissions we have now selected are fixed until explicitly 7602 // changed. 7603 ps.installPermissionsFixed = true; 7604 } 7605 7606 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7607 7608 // Persist the runtime permissions state for users with changes. 7609 if (RUNTIME_PERMISSIONS_ENABLED) { 7610 for (int userId : changedRuntimePermissionUserIds) { 7611 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7612 } 7613 } 7614 } 7615 7616 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7617 boolean allowed = false; 7618 final int NP = PackageParser.NEW_PERMISSIONS.length; 7619 for (int ip=0; ip<NP; ip++) { 7620 final PackageParser.NewPermissionInfo npi 7621 = PackageParser.NEW_PERMISSIONS[ip]; 7622 if (npi.name.equals(perm) 7623 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7624 allowed = true; 7625 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7626 + pkg.packageName); 7627 break; 7628 } 7629 } 7630 return allowed; 7631 } 7632 7633 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7634 BasePermission bp, PermissionsState origPermissions) { 7635 boolean allowed; 7636 allowed = (compareSignatures( 7637 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7638 == PackageManager.SIGNATURE_MATCH) 7639 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7640 == PackageManager.SIGNATURE_MATCH); 7641 if (!allowed && (bp.protectionLevel 7642 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7643 if (isSystemApp(pkg)) { 7644 // For updated system applications, a system permission 7645 // is granted only if it had been defined by the original application. 7646 if (pkg.isUpdatedSystemApp()) { 7647 final PackageSetting sysPs = mSettings 7648 .getDisabledSystemPkgLPr(pkg.packageName); 7649 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7650 // If the original was granted this permission, we take 7651 // that grant decision as read and propagate it to the 7652 // update. 7653 if (sysPs.isPrivileged()) { 7654 allowed = true; 7655 } 7656 } else { 7657 // The system apk may have been updated with an older 7658 // version of the one on the data partition, but which 7659 // granted a new system permission that it didn't have 7660 // before. In this case we do want to allow the app to 7661 // now get the new permission if the ancestral apk is 7662 // privileged to get it. 7663 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7664 for (int j=0; 7665 j<sysPs.pkg.requestedPermissions.size(); j++) { 7666 if (perm.equals( 7667 sysPs.pkg.requestedPermissions.get(j))) { 7668 allowed = true; 7669 break; 7670 } 7671 } 7672 } 7673 } 7674 } else { 7675 allowed = isPrivilegedApp(pkg); 7676 } 7677 } 7678 } 7679 if (!allowed && (bp.protectionLevel 7680 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7681 // For development permissions, a development permission 7682 // is granted only if it was already granted. 7683 allowed = origPermissions.hasInstallPermission(perm); 7684 } 7685 return allowed; 7686 } 7687 7688 final class ActivityIntentResolver 7689 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7690 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7691 boolean defaultOnly, int userId) { 7692 if (!sUserManager.exists(userId)) return null; 7693 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7694 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7695 } 7696 7697 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7698 int userId) { 7699 if (!sUserManager.exists(userId)) return null; 7700 mFlags = flags; 7701 return super.queryIntent(intent, resolvedType, 7702 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7703 } 7704 7705 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7706 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7707 if (!sUserManager.exists(userId)) return null; 7708 if (packageActivities == null) { 7709 return null; 7710 } 7711 mFlags = flags; 7712 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7713 final int N = packageActivities.size(); 7714 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7715 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7716 7717 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7718 for (int i = 0; i < N; ++i) { 7719 intentFilters = packageActivities.get(i).intents; 7720 if (intentFilters != null && intentFilters.size() > 0) { 7721 PackageParser.ActivityIntentInfo[] array = 7722 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7723 intentFilters.toArray(array); 7724 listCut.add(array); 7725 } 7726 } 7727 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7728 } 7729 7730 public final void addActivity(PackageParser.Activity a, String type) { 7731 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7732 mActivities.put(a.getComponentName(), a); 7733 if (DEBUG_SHOW_INFO) 7734 Log.v( 7735 TAG, " " + type + " " + 7736 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7737 if (DEBUG_SHOW_INFO) 7738 Log.v(TAG, " Class=" + a.info.name); 7739 final int NI = a.intents.size(); 7740 for (int j=0; j<NI; j++) { 7741 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7742 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7743 intent.setPriority(0); 7744 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7745 + a.className + " with priority > 0, forcing to 0"); 7746 } 7747 if (DEBUG_SHOW_INFO) { 7748 Log.v(TAG, " IntentFilter:"); 7749 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7750 } 7751 if (!intent.debugCheck()) { 7752 Log.w(TAG, "==> For Activity " + a.info.name); 7753 } 7754 addFilter(intent); 7755 } 7756 } 7757 7758 public final void removeActivity(PackageParser.Activity a, String type) { 7759 mActivities.remove(a.getComponentName()); 7760 if (DEBUG_SHOW_INFO) { 7761 Log.v(TAG, " " + type + " " 7762 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7763 : a.info.name) + ":"); 7764 Log.v(TAG, " Class=" + a.info.name); 7765 } 7766 final int NI = a.intents.size(); 7767 for (int j=0; j<NI; j++) { 7768 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7769 if (DEBUG_SHOW_INFO) { 7770 Log.v(TAG, " IntentFilter:"); 7771 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7772 } 7773 removeFilter(intent); 7774 } 7775 } 7776 7777 @Override 7778 protected boolean allowFilterResult( 7779 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7780 ActivityInfo filterAi = filter.activity.info; 7781 for (int i=dest.size()-1; i>=0; i--) { 7782 ActivityInfo destAi = dest.get(i).activityInfo; 7783 if (destAi.name == filterAi.name 7784 && destAi.packageName == filterAi.packageName) { 7785 return false; 7786 } 7787 } 7788 return true; 7789 } 7790 7791 @Override 7792 protected ActivityIntentInfo[] newArray(int size) { 7793 return new ActivityIntentInfo[size]; 7794 } 7795 7796 @Override 7797 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7798 if (!sUserManager.exists(userId)) return true; 7799 PackageParser.Package p = filter.activity.owner; 7800 if (p != null) { 7801 PackageSetting ps = (PackageSetting)p.mExtras; 7802 if (ps != null) { 7803 // System apps are never considered stopped for purposes of 7804 // filtering, because there may be no way for the user to 7805 // actually re-launch them. 7806 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7807 && ps.getStopped(userId); 7808 } 7809 } 7810 return false; 7811 } 7812 7813 @Override 7814 protected boolean isPackageForFilter(String packageName, 7815 PackageParser.ActivityIntentInfo info) { 7816 return packageName.equals(info.activity.owner.packageName); 7817 } 7818 7819 @Override 7820 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7821 int match, int userId) { 7822 if (!sUserManager.exists(userId)) return null; 7823 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7824 return null; 7825 } 7826 final PackageParser.Activity activity = info.activity; 7827 if (mSafeMode && (activity.info.applicationInfo.flags 7828 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7829 return null; 7830 } 7831 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7832 if (ps == null) { 7833 return null; 7834 } 7835 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7836 ps.readUserState(userId), userId); 7837 if (ai == null) { 7838 return null; 7839 } 7840 final ResolveInfo res = new ResolveInfo(); 7841 res.activityInfo = ai; 7842 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7843 res.filter = info; 7844 } 7845 if (info != null) { 7846 res.filterNeedsVerification = info.needsVerification(); 7847 } 7848 res.priority = info.getPriority(); 7849 res.preferredOrder = activity.owner.mPreferredOrder; 7850 //System.out.println("Result: " + res.activityInfo.className + 7851 // " = " + res.priority); 7852 res.match = match; 7853 res.isDefault = info.hasDefault; 7854 res.labelRes = info.labelRes; 7855 res.nonLocalizedLabel = info.nonLocalizedLabel; 7856 if (userNeedsBadging(userId)) { 7857 res.noResourceId = true; 7858 } else { 7859 res.icon = info.icon; 7860 } 7861 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7862 return res; 7863 } 7864 7865 @Override 7866 protected void sortResults(List<ResolveInfo> results) { 7867 Collections.sort(results, mResolvePrioritySorter); 7868 } 7869 7870 @Override 7871 protected void dumpFilter(PrintWriter out, String prefix, 7872 PackageParser.ActivityIntentInfo filter) { 7873 out.print(prefix); out.print( 7874 Integer.toHexString(System.identityHashCode(filter.activity))); 7875 out.print(' '); 7876 filter.activity.printComponentShortName(out); 7877 out.print(" filter "); 7878 out.println(Integer.toHexString(System.identityHashCode(filter))); 7879 } 7880 7881 @Override 7882 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7883 return filter.activity; 7884 } 7885 7886 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7887 PackageParser.Activity activity = (PackageParser.Activity)label; 7888 out.print(prefix); out.print( 7889 Integer.toHexString(System.identityHashCode(activity))); 7890 out.print(' '); 7891 activity.printComponentShortName(out); 7892 if (count > 1) { 7893 out.print(" ("); out.print(count); out.print(" filters)"); 7894 } 7895 out.println(); 7896 } 7897 7898// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7899// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7900// final List<ResolveInfo> retList = Lists.newArrayList(); 7901// while (i.hasNext()) { 7902// final ResolveInfo resolveInfo = i.next(); 7903// if (isEnabledLP(resolveInfo.activityInfo)) { 7904// retList.add(resolveInfo); 7905// } 7906// } 7907// return retList; 7908// } 7909 7910 // Keys are String (activity class name), values are Activity. 7911 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7912 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7913 private int mFlags; 7914 } 7915 7916 private final class ServiceIntentResolver 7917 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7918 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7919 boolean defaultOnly, int userId) { 7920 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7921 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7922 } 7923 7924 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7925 int userId) { 7926 if (!sUserManager.exists(userId)) return null; 7927 mFlags = flags; 7928 return super.queryIntent(intent, resolvedType, 7929 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7930 } 7931 7932 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7933 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7934 if (!sUserManager.exists(userId)) return null; 7935 if (packageServices == null) { 7936 return null; 7937 } 7938 mFlags = flags; 7939 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7940 final int N = packageServices.size(); 7941 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7942 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7943 7944 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7945 for (int i = 0; i < N; ++i) { 7946 intentFilters = packageServices.get(i).intents; 7947 if (intentFilters != null && intentFilters.size() > 0) { 7948 PackageParser.ServiceIntentInfo[] array = 7949 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7950 intentFilters.toArray(array); 7951 listCut.add(array); 7952 } 7953 } 7954 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7955 } 7956 7957 public final void addService(PackageParser.Service s) { 7958 mServices.put(s.getComponentName(), s); 7959 if (DEBUG_SHOW_INFO) { 7960 Log.v(TAG, " " 7961 + (s.info.nonLocalizedLabel != null 7962 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7963 Log.v(TAG, " Class=" + s.info.name); 7964 } 7965 final int NI = s.intents.size(); 7966 int j; 7967 for (j=0; j<NI; j++) { 7968 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7969 if (DEBUG_SHOW_INFO) { 7970 Log.v(TAG, " IntentFilter:"); 7971 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7972 } 7973 if (!intent.debugCheck()) { 7974 Log.w(TAG, "==> For Service " + s.info.name); 7975 } 7976 addFilter(intent); 7977 } 7978 } 7979 7980 public final void removeService(PackageParser.Service s) { 7981 mServices.remove(s.getComponentName()); 7982 if (DEBUG_SHOW_INFO) { 7983 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7984 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7985 Log.v(TAG, " Class=" + s.info.name); 7986 } 7987 final int NI = s.intents.size(); 7988 int j; 7989 for (j=0; j<NI; j++) { 7990 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7991 if (DEBUG_SHOW_INFO) { 7992 Log.v(TAG, " IntentFilter:"); 7993 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7994 } 7995 removeFilter(intent); 7996 } 7997 } 7998 7999 @Override 8000 protected boolean allowFilterResult( 8001 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8002 ServiceInfo filterSi = filter.service.info; 8003 for (int i=dest.size()-1; i>=0; i--) { 8004 ServiceInfo destAi = dest.get(i).serviceInfo; 8005 if (destAi.name == filterSi.name 8006 && destAi.packageName == filterSi.packageName) { 8007 return false; 8008 } 8009 } 8010 return true; 8011 } 8012 8013 @Override 8014 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8015 return new PackageParser.ServiceIntentInfo[size]; 8016 } 8017 8018 @Override 8019 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8020 if (!sUserManager.exists(userId)) return true; 8021 PackageParser.Package p = filter.service.owner; 8022 if (p != null) { 8023 PackageSetting ps = (PackageSetting)p.mExtras; 8024 if (ps != null) { 8025 // System apps are never considered stopped for purposes of 8026 // filtering, because there may be no way for the user to 8027 // actually re-launch them. 8028 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8029 && ps.getStopped(userId); 8030 } 8031 } 8032 return false; 8033 } 8034 8035 @Override 8036 protected boolean isPackageForFilter(String packageName, 8037 PackageParser.ServiceIntentInfo info) { 8038 return packageName.equals(info.service.owner.packageName); 8039 } 8040 8041 @Override 8042 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8043 int match, int userId) { 8044 if (!sUserManager.exists(userId)) return null; 8045 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8046 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8047 return null; 8048 } 8049 final PackageParser.Service service = info.service; 8050 if (mSafeMode && (service.info.applicationInfo.flags 8051 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8052 return null; 8053 } 8054 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8055 if (ps == null) { 8056 return null; 8057 } 8058 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8059 ps.readUserState(userId), userId); 8060 if (si == null) { 8061 return null; 8062 } 8063 final ResolveInfo res = new ResolveInfo(); 8064 res.serviceInfo = si; 8065 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8066 res.filter = filter; 8067 } 8068 res.priority = info.getPriority(); 8069 res.preferredOrder = service.owner.mPreferredOrder; 8070 res.match = match; 8071 res.isDefault = info.hasDefault; 8072 res.labelRes = info.labelRes; 8073 res.nonLocalizedLabel = info.nonLocalizedLabel; 8074 res.icon = info.icon; 8075 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8076 return res; 8077 } 8078 8079 @Override 8080 protected void sortResults(List<ResolveInfo> results) { 8081 Collections.sort(results, mResolvePrioritySorter); 8082 } 8083 8084 @Override 8085 protected void dumpFilter(PrintWriter out, String prefix, 8086 PackageParser.ServiceIntentInfo filter) { 8087 out.print(prefix); out.print( 8088 Integer.toHexString(System.identityHashCode(filter.service))); 8089 out.print(' '); 8090 filter.service.printComponentShortName(out); 8091 out.print(" filter "); 8092 out.println(Integer.toHexString(System.identityHashCode(filter))); 8093 } 8094 8095 @Override 8096 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8097 return filter.service; 8098 } 8099 8100 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8101 PackageParser.Service service = (PackageParser.Service)label; 8102 out.print(prefix); out.print( 8103 Integer.toHexString(System.identityHashCode(service))); 8104 out.print(' '); 8105 service.printComponentShortName(out); 8106 if (count > 1) { 8107 out.print(" ("); out.print(count); out.print(" filters)"); 8108 } 8109 out.println(); 8110 } 8111 8112// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8113// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8114// final List<ResolveInfo> retList = Lists.newArrayList(); 8115// while (i.hasNext()) { 8116// final ResolveInfo resolveInfo = (ResolveInfo) i; 8117// if (isEnabledLP(resolveInfo.serviceInfo)) { 8118// retList.add(resolveInfo); 8119// } 8120// } 8121// return retList; 8122// } 8123 8124 // Keys are String (activity class name), values are Activity. 8125 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8126 = new ArrayMap<ComponentName, PackageParser.Service>(); 8127 private int mFlags; 8128 }; 8129 8130 private final class ProviderIntentResolver 8131 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8133 boolean defaultOnly, int userId) { 8134 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8135 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8136 } 8137 8138 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8139 int userId) { 8140 if (!sUserManager.exists(userId)) 8141 return null; 8142 mFlags = flags; 8143 return super.queryIntent(intent, resolvedType, 8144 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8145 } 8146 8147 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8148 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8149 if (!sUserManager.exists(userId)) 8150 return null; 8151 if (packageProviders == null) { 8152 return null; 8153 } 8154 mFlags = flags; 8155 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8156 final int N = packageProviders.size(); 8157 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8158 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8159 8160 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8161 for (int i = 0; i < N; ++i) { 8162 intentFilters = packageProviders.get(i).intents; 8163 if (intentFilters != null && intentFilters.size() > 0) { 8164 PackageParser.ProviderIntentInfo[] array = 8165 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8166 intentFilters.toArray(array); 8167 listCut.add(array); 8168 } 8169 } 8170 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8171 } 8172 8173 public final void addProvider(PackageParser.Provider p) { 8174 if (mProviders.containsKey(p.getComponentName())) { 8175 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8176 return; 8177 } 8178 8179 mProviders.put(p.getComponentName(), p); 8180 if (DEBUG_SHOW_INFO) { 8181 Log.v(TAG, " " 8182 + (p.info.nonLocalizedLabel != null 8183 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8184 Log.v(TAG, " Class=" + p.info.name); 8185 } 8186 final int NI = p.intents.size(); 8187 int j; 8188 for (j = 0; j < NI; j++) { 8189 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8190 if (DEBUG_SHOW_INFO) { 8191 Log.v(TAG, " IntentFilter:"); 8192 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8193 } 8194 if (!intent.debugCheck()) { 8195 Log.w(TAG, "==> For Provider " + p.info.name); 8196 } 8197 addFilter(intent); 8198 } 8199 } 8200 8201 public final void removeProvider(PackageParser.Provider p) { 8202 mProviders.remove(p.getComponentName()); 8203 if (DEBUG_SHOW_INFO) { 8204 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8205 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8206 Log.v(TAG, " Class=" + p.info.name); 8207 } 8208 final int NI = p.intents.size(); 8209 int j; 8210 for (j = 0; j < NI; j++) { 8211 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8212 if (DEBUG_SHOW_INFO) { 8213 Log.v(TAG, " IntentFilter:"); 8214 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8215 } 8216 removeFilter(intent); 8217 } 8218 } 8219 8220 @Override 8221 protected boolean allowFilterResult( 8222 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8223 ProviderInfo filterPi = filter.provider.info; 8224 for (int i = dest.size() - 1; i >= 0; i--) { 8225 ProviderInfo destPi = dest.get(i).providerInfo; 8226 if (destPi.name == filterPi.name 8227 && destPi.packageName == filterPi.packageName) { 8228 return false; 8229 } 8230 } 8231 return true; 8232 } 8233 8234 @Override 8235 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8236 return new PackageParser.ProviderIntentInfo[size]; 8237 } 8238 8239 @Override 8240 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8241 if (!sUserManager.exists(userId)) 8242 return true; 8243 PackageParser.Package p = filter.provider.owner; 8244 if (p != null) { 8245 PackageSetting ps = (PackageSetting) p.mExtras; 8246 if (ps != null) { 8247 // System apps are never considered stopped for purposes of 8248 // filtering, because there may be no way for the user to 8249 // actually re-launch them. 8250 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8251 && ps.getStopped(userId); 8252 } 8253 } 8254 return false; 8255 } 8256 8257 @Override 8258 protected boolean isPackageForFilter(String packageName, 8259 PackageParser.ProviderIntentInfo info) { 8260 return packageName.equals(info.provider.owner.packageName); 8261 } 8262 8263 @Override 8264 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8265 int match, int userId) { 8266 if (!sUserManager.exists(userId)) 8267 return null; 8268 final PackageParser.ProviderIntentInfo info = filter; 8269 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8270 return null; 8271 } 8272 final PackageParser.Provider provider = info.provider; 8273 if (mSafeMode && (provider.info.applicationInfo.flags 8274 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8275 return null; 8276 } 8277 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8278 if (ps == null) { 8279 return null; 8280 } 8281 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8282 ps.readUserState(userId), userId); 8283 if (pi == null) { 8284 return null; 8285 } 8286 final ResolveInfo res = new ResolveInfo(); 8287 res.providerInfo = pi; 8288 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8289 res.filter = filter; 8290 } 8291 res.priority = info.getPriority(); 8292 res.preferredOrder = provider.owner.mPreferredOrder; 8293 res.match = match; 8294 res.isDefault = info.hasDefault; 8295 res.labelRes = info.labelRes; 8296 res.nonLocalizedLabel = info.nonLocalizedLabel; 8297 res.icon = info.icon; 8298 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8299 return res; 8300 } 8301 8302 @Override 8303 protected void sortResults(List<ResolveInfo> results) { 8304 Collections.sort(results, mResolvePrioritySorter); 8305 } 8306 8307 @Override 8308 protected void dumpFilter(PrintWriter out, String prefix, 8309 PackageParser.ProviderIntentInfo filter) { 8310 out.print(prefix); 8311 out.print( 8312 Integer.toHexString(System.identityHashCode(filter.provider))); 8313 out.print(' '); 8314 filter.provider.printComponentShortName(out); 8315 out.print(" filter "); 8316 out.println(Integer.toHexString(System.identityHashCode(filter))); 8317 } 8318 8319 @Override 8320 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8321 return filter.provider; 8322 } 8323 8324 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8325 PackageParser.Provider provider = (PackageParser.Provider)label; 8326 out.print(prefix); out.print( 8327 Integer.toHexString(System.identityHashCode(provider))); 8328 out.print(' '); 8329 provider.printComponentShortName(out); 8330 if (count > 1) { 8331 out.print(" ("); out.print(count); out.print(" filters)"); 8332 } 8333 out.println(); 8334 } 8335 8336 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8337 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8338 private int mFlags; 8339 }; 8340 8341 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8342 new Comparator<ResolveInfo>() { 8343 public int compare(ResolveInfo r1, ResolveInfo r2) { 8344 int v1 = r1.priority; 8345 int v2 = r2.priority; 8346 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8347 if (v1 != v2) { 8348 return (v1 > v2) ? -1 : 1; 8349 } 8350 v1 = r1.preferredOrder; 8351 v2 = r2.preferredOrder; 8352 if (v1 != v2) { 8353 return (v1 > v2) ? -1 : 1; 8354 } 8355 if (r1.isDefault != r2.isDefault) { 8356 return r1.isDefault ? -1 : 1; 8357 } 8358 v1 = r1.match; 8359 v2 = r2.match; 8360 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8361 if (v1 != v2) { 8362 return (v1 > v2) ? -1 : 1; 8363 } 8364 if (r1.system != r2.system) { 8365 return r1.system ? -1 : 1; 8366 } 8367 return 0; 8368 } 8369 }; 8370 8371 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8372 new Comparator<ProviderInfo>() { 8373 public int compare(ProviderInfo p1, ProviderInfo p2) { 8374 final int v1 = p1.initOrder; 8375 final int v2 = p2.initOrder; 8376 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8377 } 8378 }; 8379 8380 static final void sendPackageBroadcast(String action, String pkg, 8381 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8382 int[] userIds) { 8383 IActivityManager am = ActivityManagerNative.getDefault(); 8384 if (am != null) { 8385 try { 8386 if (userIds == null) { 8387 userIds = am.getRunningUserIds(); 8388 } 8389 for (int id : userIds) { 8390 final Intent intent = new Intent(action, 8391 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8392 if (extras != null) { 8393 intent.putExtras(extras); 8394 } 8395 if (targetPkg != null) { 8396 intent.setPackage(targetPkg); 8397 } 8398 // Modify the UID when posting to other users 8399 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8400 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8401 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8402 intent.putExtra(Intent.EXTRA_UID, uid); 8403 } 8404 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8406 if (DEBUG_BROADCASTS) { 8407 RuntimeException here = new RuntimeException("here"); 8408 here.fillInStackTrace(); 8409 Slog.d(TAG, "Sending to user " + id + ": " 8410 + intent.toShortString(false, true, false, false) 8411 + " " + intent.getExtras(), here); 8412 } 8413 am.broadcastIntent(null, intent, null, finishedReceiver, 8414 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8415 finishedReceiver != null, false, id); 8416 } 8417 } catch (RemoteException ex) { 8418 } 8419 } 8420 } 8421 8422 /** 8423 * Check if the external storage media is available. This is true if there 8424 * is a mounted external storage medium or if the external storage is 8425 * emulated. 8426 */ 8427 private boolean isExternalMediaAvailable() { 8428 return mMediaMounted || Environment.isExternalStorageEmulated(); 8429 } 8430 8431 @Override 8432 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8433 // writer 8434 synchronized (mPackages) { 8435 if (!isExternalMediaAvailable()) { 8436 // If the external storage is no longer mounted at this point, 8437 // the caller may not have been able to delete all of this 8438 // packages files and can not delete any more. Bail. 8439 return null; 8440 } 8441 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8442 if (lastPackage != null) { 8443 pkgs.remove(lastPackage); 8444 } 8445 if (pkgs.size() > 0) { 8446 return pkgs.get(0); 8447 } 8448 } 8449 return null; 8450 } 8451 8452 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8453 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8454 userId, andCode ? 1 : 0, packageName); 8455 if (mSystemReady) { 8456 msg.sendToTarget(); 8457 } else { 8458 if (mPostSystemReadyMessages == null) { 8459 mPostSystemReadyMessages = new ArrayList<>(); 8460 } 8461 mPostSystemReadyMessages.add(msg); 8462 } 8463 } 8464 8465 void startCleaningPackages() { 8466 // reader 8467 synchronized (mPackages) { 8468 if (!isExternalMediaAvailable()) { 8469 return; 8470 } 8471 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8472 return; 8473 } 8474 } 8475 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8476 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8477 IActivityManager am = ActivityManagerNative.getDefault(); 8478 if (am != null) { 8479 try { 8480 am.startService(null, intent, null, UserHandle.USER_OWNER); 8481 } catch (RemoteException e) { 8482 } 8483 } 8484 } 8485 8486 @Override 8487 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8488 int installFlags, String installerPackageName, VerificationParams verificationParams, 8489 String packageAbiOverride) { 8490 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8491 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8492 } 8493 8494 @Override 8495 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8496 int installFlags, String installerPackageName, VerificationParams verificationParams, 8497 String packageAbiOverride, int userId) { 8498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8499 8500 final int callingUid = Binder.getCallingUid(); 8501 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8502 8503 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8504 try { 8505 if (observer != null) { 8506 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8507 } 8508 } catch (RemoteException re) { 8509 } 8510 return; 8511 } 8512 8513 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8514 installFlags |= PackageManager.INSTALL_FROM_ADB; 8515 8516 } else { 8517 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8518 // about installerPackageName. 8519 8520 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8521 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8522 } 8523 8524 UserHandle user; 8525 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8526 user = UserHandle.ALL; 8527 } else { 8528 user = new UserHandle(userId); 8529 } 8530 8531 verificationParams.setInstallerUid(callingUid); 8532 8533 final File originFile = new File(originPath); 8534 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8535 8536 final Message msg = mHandler.obtainMessage(INIT_COPY); 8537 msg.obj = new InstallParams(origin, observer, installFlags, 8538 installerPackageName, null, verificationParams, user, packageAbiOverride); 8539 mHandler.sendMessage(msg); 8540 } 8541 8542 void installStage(String packageName, File stagedDir, String stagedCid, 8543 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8544 String installerPackageName, int installerUid, UserHandle user) { 8545 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8546 params.referrerUri, installerUid, null); 8547 8548 final OriginInfo origin; 8549 if (stagedDir != null) { 8550 origin = OriginInfo.fromStagedFile(stagedDir); 8551 } else { 8552 origin = OriginInfo.fromStagedContainer(stagedCid); 8553 } 8554 8555 final Message msg = mHandler.obtainMessage(INIT_COPY); 8556 msg.obj = new InstallParams(origin, observer, params.installFlags, 8557 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8558 mHandler.sendMessage(msg); 8559 } 8560 8561 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8562 Bundle extras = new Bundle(1); 8563 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8564 8565 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8566 packageName, extras, null, null, new int[] {userId}); 8567 try { 8568 IActivityManager am = ActivityManagerNative.getDefault(); 8569 final boolean isSystem = 8570 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8571 if (isSystem && am.isUserRunning(userId, false)) { 8572 // The just-installed/enabled app is bundled on the system, so presumed 8573 // to be able to run automatically without needing an explicit launch. 8574 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8575 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8576 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8577 .setPackage(packageName); 8578 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8579 android.app.AppOpsManager.OP_NONE, false, false, userId); 8580 } 8581 } catch (RemoteException e) { 8582 // shouldn't happen 8583 Slog.w(TAG, "Unable to bootstrap installed package", e); 8584 } 8585 } 8586 8587 @Override 8588 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8589 int userId) { 8590 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8591 PackageSetting pkgSetting; 8592 final int uid = Binder.getCallingUid(); 8593 enforceCrossUserPermission(uid, userId, true, true, 8594 "setApplicationHiddenSetting for user " + userId); 8595 8596 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8597 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8598 return false; 8599 } 8600 8601 long callingId = Binder.clearCallingIdentity(); 8602 try { 8603 boolean sendAdded = false; 8604 boolean sendRemoved = false; 8605 // writer 8606 synchronized (mPackages) { 8607 pkgSetting = mSettings.mPackages.get(packageName); 8608 if (pkgSetting == null) { 8609 return false; 8610 } 8611 if (pkgSetting.getHidden(userId) != hidden) { 8612 pkgSetting.setHidden(hidden, userId); 8613 mSettings.writePackageRestrictionsLPr(userId); 8614 if (hidden) { 8615 sendRemoved = true; 8616 } else { 8617 sendAdded = true; 8618 } 8619 } 8620 } 8621 if (sendAdded) { 8622 sendPackageAddedForUser(packageName, pkgSetting, userId); 8623 return true; 8624 } 8625 if (sendRemoved) { 8626 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8627 "hiding pkg"); 8628 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8629 } 8630 } finally { 8631 Binder.restoreCallingIdentity(callingId); 8632 } 8633 return false; 8634 } 8635 8636 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8637 int userId) { 8638 final PackageRemovedInfo info = new PackageRemovedInfo(); 8639 info.removedPackage = packageName; 8640 info.removedUsers = new int[] {userId}; 8641 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8642 info.sendBroadcast(false, false, false); 8643 } 8644 8645 /** 8646 * Returns true if application is not found or there was an error. Otherwise it returns 8647 * the hidden state of the package for the given user. 8648 */ 8649 @Override 8650 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8651 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8652 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8653 false, "getApplicationHidden for user " + userId); 8654 PackageSetting pkgSetting; 8655 long callingId = Binder.clearCallingIdentity(); 8656 try { 8657 // writer 8658 synchronized (mPackages) { 8659 pkgSetting = mSettings.mPackages.get(packageName); 8660 if (pkgSetting == null) { 8661 return true; 8662 } 8663 return pkgSetting.getHidden(userId); 8664 } 8665 } finally { 8666 Binder.restoreCallingIdentity(callingId); 8667 } 8668 } 8669 8670 /** 8671 * @hide 8672 */ 8673 @Override 8674 public int installExistingPackageAsUser(String packageName, int userId) { 8675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8676 null); 8677 PackageSetting pkgSetting; 8678 final int uid = Binder.getCallingUid(); 8679 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8680 + userId); 8681 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8682 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8683 } 8684 8685 long callingId = Binder.clearCallingIdentity(); 8686 try { 8687 boolean sendAdded = false; 8688 Bundle extras = new Bundle(1); 8689 8690 // writer 8691 synchronized (mPackages) { 8692 pkgSetting = mSettings.mPackages.get(packageName); 8693 if (pkgSetting == null) { 8694 return PackageManager.INSTALL_FAILED_INVALID_URI; 8695 } 8696 if (!pkgSetting.getInstalled(userId)) { 8697 pkgSetting.setInstalled(true, userId); 8698 pkgSetting.setHidden(false, userId); 8699 mSettings.writePackageRestrictionsLPr(userId); 8700 sendAdded = true; 8701 } 8702 } 8703 8704 if (sendAdded) { 8705 sendPackageAddedForUser(packageName, pkgSetting, userId); 8706 } 8707 } finally { 8708 Binder.restoreCallingIdentity(callingId); 8709 } 8710 8711 return PackageManager.INSTALL_SUCCEEDED; 8712 } 8713 8714 boolean isUserRestricted(int userId, String restrictionKey) { 8715 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8716 if (restrictions.getBoolean(restrictionKey, false)) { 8717 Log.w(TAG, "User is restricted: " + restrictionKey); 8718 return true; 8719 } 8720 return false; 8721 } 8722 8723 @Override 8724 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8725 mContext.enforceCallingOrSelfPermission( 8726 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8727 "Only package verification agents can verify applications"); 8728 8729 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8730 final PackageVerificationResponse response = new PackageVerificationResponse( 8731 verificationCode, Binder.getCallingUid()); 8732 msg.arg1 = id; 8733 msg.obj = response; 8734 mHandler.sendMessage(msg); 8735 } 8736 8737 @Override 8738 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8739 long millisecondsToDelay) { 8740 mContext.enforceCallingOrSelfPermission( 8741 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8742 "Only package verification agents can extend verification timeouts"); 8743 8744 final PackageVerificationState state = mPendingVerification.get(id); 8745 final PackageVerificationResponse response = new PackageVerificationResponse( 8746 verificationCodeAtTimeout, Binder.getCallingUid()); 8747 8748 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8749 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8750 } 8751 if (millisecondsToDelay < 0) { 8752 millisecondsToDelay = 0; 8753 } 8754 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8755 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8756 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8757 } 8758 8759 if ((state != null) && !state.timeoutExtended()) { 8760 state.extendTimeout(); 8761 8762 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8763 msg.arg1 = id; 8764 msg.obj = response; 8765 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8766 } 8767 } 8768 8769 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8770 int verificationCode, UserHandle user) { 8771 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8772 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8773 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8774 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8775 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8776 8777 mContext.sendBroadcastAsUser(intent, user, 8778 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8779 } 8780 8781 private ComponentName matchComponentForVerifier(String packageName, 8782 List<ResolveInfo> receivers) { 8783 ActivityInfo targetReceiver = null; 8784 8785 final int NR = receivers.size(); 8786 for (int i = 0; i < NR; i++) { 8787 final ResolveInfo info = receivers.get(i); 8788 if (info.activityInfo == null) { 8789 continue; 8790 } 8791 8792 if (packageName.equals(info.activityInfo.packageName)) { 8793 targetReceiver = info.activityInfo; 8794 break; 8795 } 8796 } 8797 8798 if (targetReceiver == null) { 8799 return null; 8800 } 8801 8802 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8803 } 8804 8805 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8806 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8807 if (pkgInfo.verifiers.length == 0) { 8808 return null; 8809 } 8810 8811 final int N = pkgInfo.verifiers.length; 8812 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8813 for (int i = 0; i < N; i++) { 8814 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8815 8816 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8817 receivers); 8818 if (comp == null) { 8819 continue; 8820 } 8821 8822 final int verifierUid = getUidForVerifier(verifierInfo); 8823 if (verifierUid == -1) { 8824 continue; 8825 } 8826 8827 if (DEBUG_VERIFY) { 8828 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8829 + " with the correct signature"); 8830 } 8831 sufficientVerifiers.add(comp); 8832 verificationState.addSufficientVerifier(verifierUid); 8833 } 8834 8835 return sufficientVerifiers; 8836 } 8837 8838 private int getUidForVerifier(VerifierInfo verifierInfo) { 8839 synchronized (mPackages) { 8840 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8841 if (pkg == null) { 8842 return -1; 8843 } else if (pkg.mSignatures.length != 1) { 8844 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8845 + " has more than one signature; ignoring"); 8846 return -1; 8847 } 8848 8849 /* 8850 * If the public key of the package's signature does not match 8851 * our expected public key, then this is a different package and 8852 * we should skip. 8853 */ 8854 8855 final byte[] expectedPublicKey; 8856 try { 8857 final Signature verifierSig = pkg.mSignatures[0]; 8858 final PublicKey publicKey = verifierSig.getPublicKey(); 8859 expectedPublicKey = publicKey.getEncoded(); 8860 } catch (CertificateException e) { 8861 return -1; 8862 } 8863 8864 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8865 8866 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8867 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8868 + " does not have the expected public key; ignoring"); 8869 return -1; 8870 } 8871 8872 return pkg.applicationInfo.uid; 8873 } 8874 } 8875 8876 @Override 8877 public void finishPackageInstall(int token) { 8878 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8879 8880 if (DEBUG_INSTALL) { 8881 Slog.v(TAG, "BM finishing package install for " + token); 8882 } 8883 8884 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8885 mHandler.sendMessage(msg); 8886 } 8887 8888 /** 8889 * Get the verification agent timeout. 8890 * 8891 * @return verification timeout in milliseconds 8892 */ 8893 private long getVerificationTimeout() { 8894 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8895 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8896 DEFAULT_VERIFICATION_TIMEOUT); 8897 } 8898 8899 /** 8900 * Get the default verification agent response code. 8901 * 8902 * @return default verification response code 8903 */ 8904 private int getDefaultVerificationResponse() { 8905 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8906 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8907 DEFAULT_VERIFICATION_RESPONSE); 8908 } 8909 8910 /** 8911 * Check whether or not package verification has been enabled. 8912 * 8913 * @return true if verification should be performed 8914 */ 8915 private boolean isVerificationEnabled(int userId, int installFlags) { 8916 if (!DEFAULT_VERIFY_ENABLE) { 8917 return false; 8918 } 8919 8920 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8921 8922 // Check if installing from ADB 8923 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8924 // Do not run verification in a test harness environment 8925 if (ActivityManager.isRunningInTestHarness()) { 8926 return false; 8927 } 8928 if (ensureVerifyAppsEnabled) { 8929 return true; 8930 } 8931 // Check if the developer does not want package verification for ADB installs 8932 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8933 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8934 return false; 8935 } 8936 } 8937 8938 if (ensureVerifyAppsEnabled) { 8939 return true; 8940 } 8941 8942 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8943 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8944 } 8945 8946 @Override 8947 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 8948 throws RemoteException { 8949 mContext.enforceCallingOrSelfPermission( 8950 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 8951 "Only intentfilter verification agents can verify applications"); 8952 8953 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 8954 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 8955 Binder.getCallingUid(), verificationCode, failedDomains); 8956 msg.arg1 = id; 8957 msg.obj = response; 8958 mHandler.sendMessage(msg); 8959 } 8960 8961 @Override 8962 public int getIntentVerificationStatus(String packageName, int userId) { 8963 synchronized (mPackages) { 8964 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 8965 } 8966 } 8967 8968 @Override 8969 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 8970 boolean result = false; 8971 synchronized (mPackages) { 8972 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 8973 } 8974 scheduleWritePackageRestrictionsLocked(userId); 8975 return result; 8976 } 8977 8978 @Override 8979 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 8980 synchronized (mPackages) { 8981 return mSettings.getIntentFilterVerificationsLPr(packageName); 8982 } 8983 } 8984 8985 @Override 8986 public List<IntentFilter> getAllIntentFilters(String packageName) { 8987 if (TextUtils.isEmpty(packageName)) { 8988 return Collections.<IntentFilter>emptyList(); 8989 } 8990 synchronized (mPackages) { 8991 PackageParser.Package pkg = mPackages.get(packageName); 8992 if (pkg == null || pkg.activities == null) { 8993 return Collections.<IntentFilter>emptyList(); 8994 } 8995 final int count = pkg.activities.size(); 8996 ArrayList<IntentFilter> result = new ArrayList<>(); 8997 for (int n=0; n<count; n++) { 8998 PackageParser.Activity activity = pkg.activities.get(n); 8999 if (activity.intents != null || activity.intents.size() > 0) { 9000 result.addAll(activity.intents); 9001 } 9002 } 9003 return result; 9004 } 9005 } 9006 9007 /** 9008 * Get the "allow unknown sources" setting. 9009 * 9010 * @return the current "allow unknown sources" setting 9011 */ 9012 private int getUnknownSourcesSettings() { 9013 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9014 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9015 -1); 9016 } 9017 9018 @Override 9019 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9020 final int uid = Binder.getCallingUid(); 9021 // writer 9022 synchronized (mPackages) { 9023 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9024 if (targetPackageSetting == null) { 9025 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9026 } 9027 9028 PackageSetting installerPackageSetting; 9029 if (installerPackageName != null) { 9030 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9031 if (installerPackageSetting == null) { 9032 throw new IllegalArgumentException("Unknown installer package: " 9033 + installerPackageName); 9034 } 9035 } else { 9036 installerPackageSetting = null; 9037 } 9038 9039 Signature[] callerSignature; 9040 Object obj = mSettings.getUserIdLPr(uid); 9041 if (obj != null) { 9042 if (obj instanceof SharedUserSetting) { 9043 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9044 } else if (obj instanceof PackageSetting) { 9045 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9046 } else { 9047 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9048 } 9049 } else { 9050 throw new SecurityException("Unknown calling uid " + uid); 9051 } 9052 9053 // Verify: can't set installerPackageName to a package that is 9054 // not signed with the same cert as the caller. 9055 if (installerPackageSetting != null) { 9056 if (compareSignatures(callerSignature, 9057 installerPackageSetting.signatures.mSignatures) 9058 != PackageManager.SIGNATURE_MATCH) { 9059 throw new SecurityException( 9060 "Caller does not have same cert as new installer package " 9061 + installerPackageName); 9062 } 9063 } 9064 9065 // Verify: if target already has an installer package, it must 9066 // be signed with the same cert as the caller. 9067 if (targetPackageSetting.installerPackageName != null) { 9068 PackageSetting setting = mSettings.mPackages.get( 9069 targetPackageSetting.installerPackageName); 9070 // If the currently set package isn't valid, then it's always 9071 // okay to change it. 9072 if (setting != null) { 9073 if (compareSignatures(callerSignature, 9074 setting.signatures.mSignatures) 9075 != PackageManager.SIGNATURE_MATCH) { 9076 throw new SecurityException( 9077 "Caller does not have same cert as old installer package " 9078 + targetPackageSetting.installerPackageName); 9079 } 9080 } 9081 } 9082 9083 // Okay! 9084 targetPackageSetting.installerPackageName = installerPackageName; 9085 scheduleWriteSettingsLocked(); 9086 } 9087 } 9088 9089 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9090 // Queue up an async operation since the package installation may take a little while. 9091 mHandler.post(new Runnable() { 9092 public void run() { 9093 mHandler.removeCallbacks(this); 9094 // Result object to be returned 9095 PackageInstalledInfo res = new PackageInstalledInfo(); 9096 res.returnCode = currentStatus; 9097 res.uid = -1; 9098 res.pkg = null; 9099 res.removedInfo = new PackageRemovedInfo(); 9100 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9101 args.doPreInstall(res.returnCode); 9102 synchronized (mInstallLock) { 9103 installPackageLI(args, res); 9104 } 9105 args.doPostInstall(res.returnCode, res.uid); 9106 } 9107 9108 // A restore should be performed at this point if (a) the install 9109 // succeeded, (b) the operation is not an update, and (c) the new 9110 // package has not opted out of backup participation. 9111 final boolean update = res.removedInfo.removedPackage != null; 9112 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9113 boolean doRestore = !update 9114 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9115 9116 // Set up the post-install work request bookkeeping. This will be used 9117 // and cleaned up by the post-install event handling regardless of whether 9118 // there's a restore pass performed. Token values are >= 1. 9119 int token; 9120 if (mNextInstallToken < 0) mNextInstallToken = 1; 9121 token = mNextInstallToken++; 9122 9123 PostInstallData data = new PostInstallData(args, res); 9124 mRunningInstalls.put(token, data); 9125 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9126 9127 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9128 // Pass responsibility to the Backup Manager. It will perform a 9129 // restore if appropriate, then pass responsibility back to the 9130 // Package Manager to run the post-install observer callbacks 9131 // and broadcasts. 9132 IBackupManager bm = IBackupManager.Stub.asInterface( 9133 ServiceManager.getService(Context.BACKUP_SERVICE)); 9134 if (bm != null) { 9135 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9136 + " to BM for possible restore"); 9137 try { 9138 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9139 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9140 } else { 9141 doRestore = false; 9142 } 9143 } catch (RemoteException e) { 9144 // can't happen; the backup manager is local 9145 } catch (Exception e) { 9146 Slog.e(TAG, "Exception trying to enqueue restore", e); 9147 doRestore = false; 9148 } 9149 } else { 9150 Slog.e(TAG, "Backup Manager not found!"); 9151 doRestore = false; 9152 } 9153 } 9154 9155 if (!doRestore) { 9156 // No restore possible, or the Backup Manager was mysteriously not 9157 // available -- just fire the post-install work request directly. 9158 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9159 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9160 mHandler.sendMessage(msg); 9161 } 9162 } 9163 }); 9164 } 9165 9166 private abstract class HandlerParams { 9167 private static final int MAX_RETRIES = 4; 9168 9169 /** 9170 * Number of times startCopy() has been attempted and had a non-fatal 9171 * error. 9172 */ 9173 private int mRetries = 0; 9174 9175 /** User handle for the user requesting the information or installation. */ 9176 private final UserHandle mUser; 9177 9178 HandlerParams(UserHandle user) { 9179 mUser = user; 9180 } 9181 9182 UserHandle getUser() { 9183 return mUser; 9184 } 9185 9186 final boolean startCopy() { 9187 boolean res; 9188 try { 9189 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9190 9191 if (++mRetries > MAX_RETRIES) { 9192 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9193 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9194 handleServiceError(); 9195 return false; 9196 } else { 9197 handleStartCopy(); 9198 res = true; 9199 } 9200 } catch (RemoteException e) { 9201 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9202 mHandler.sendEmptyMessage(MCS_RECONNECT); 9203 res = false; 9204 } 9205 handleReturnCode(); 9206 return res; 9207 } 9208 9209 final void serviceError() { 9210 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9211 handleServiceError(); 9212 handleReturnCode(); 9213 } 9214 9215 abstract void handleStartCopy() throws RemoteException; 9216 abstract void handleServiceError(); 9217 abstract void handleReturnCode(); 9218 } 9219 9220 class MeasureParams extends HandlerParams { 9221 private final PackageStats mStats; 9222 private boolean mSuccess; 9223 9224 private final IPackageStatsObserver mObserver; 9225 9226 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9227 super(new UserHandle(stats.userHandle)); 9228 mObserver = observer; 9229 mStats = stats; 9230 } 9231 9232 @Override 9233 public String toString() { 9234 return "MeasureParams{" 9235 + Integer.toHexString(System.identityHashCode(this)) 9236 + " " + mStats.packageName + "}"; 9237 } 9238 9239 @Override 9240 void handleStartCopy() throws RemoteException { 9241 synchronized (mInstallLock) { 9242 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9243 } 9244 9245 if (mSuccess) { 9246 final boolean mounted; 9247 if (Environment.isExternalStorageEmulated()) { 9248 mounted = true; 9249 } else { 9250 final String status = Environment.getExternalStorageState(); 9251 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9252 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9253 } 9254 9255 if (mounted) { 9256 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9257 9258 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9259 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9260 9261 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9262 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9263 9264 // Always subtract cache size, since it's a subdirectory 9265 mStats.externalDataSize -= mStats.externalCacheSize; 9266 9267 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9268 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9269 9270 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9271 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9272 } 9273 } 9274 } 9275 9276 @Override 9277 void handleReturnCode() { 9278 if (mObserver != null) { 9279 try { 9280 mObserver.onGetStatsCompleted(mStats, mSuccess); 9281 } catch (RemoteException e) { 9282 Slog.i(TAG, "Observer no longer exists."); 9283 } 9284 } 9285 } 9286 9287 @Override 9288 void handleServiceError() { 9289 Slog.e(TAG, "Could not measure application " + mStats.packageName 9290 + " external storage"); 9291 } 9292 } 9293 9294 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9295 throws RemoteException { 9296 long result = 0; 9297 for (File path : paths) { 9298 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9299 } 9300 return result; 9301 } 9302 9303 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9304 for (File path : paths) { 9305 try { 9306 mcs.clearDirectory(path.getAbsolutePath()); 9307 } catch (RemoteException e) { 9308 } 9309 } 9310 } 9311 9312 static class OriginInfo { 9313 /** 9314 * Location where install is coming from, before it has been 9315 * copied/renamed into place. This could be a single monolithic APK 9316 * file, or a cluster directory. This location may be untrusted. 9317 */ 9318 final File file; 9319 final String cid; 9320 9321 /** 9322 * Flag indicating that {@link #file} or {@link #cid} has already been 9323 * staged, meaning downstream users don't need to defensively copy the 9324 * contents. 9325 */ 9326 final boolean staged; 9327 9328 /** 9329 * Flag indicating that {@link #file} or {@link #cid} is an already 9330 * installed app that is being moved. 9331 */ 9332 final boolean existing; 9333 9334 final String resolvedPath; 9335 final File resolvedFile; 9336 9337 static OriginInfo fromNothing() { 9338 return new OriginInfo(null, null, false, false); 9339 } 9340 9341 static OriginInfo fromUntrustedFile(File file) { 9342 return new OriginInfo(file, null, false, false); 9343 } 9344 9345 static OriginInfo fromExistingFile(File file) { 9346 return new OriginInfo(file, null, false, true); 9347 } 9348 9349 static OriginInfo fromStagedFile(File file) { 9350 return new OriginInfo(file, null, true, false); 9351 } 9352 9353 static OriginInfo fromStagedContainer(String cid) { 9354 return new OriginInfo(null, cid, true, false); 9355 } 9356 9357 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9358 this.file = file; 9359 this.cid = cid; 9360 this.staged = staged; 9361 this.existing = existing; 9362 9363 if (cid != null) { 9364 resolvedPath = PackageHelper.getSdDir(cid); 9365 resolvedFile = new File(resolvedPath); 9366 } else if (file != null) { 9367 resolvedPath = file.getAbsolutePath(); 9368 resolvedFile = file; 9369 } else { 9370 resolvedPath = null; 9371 resolvedFile = null; 9372 } 9373 } 9374 } 9375 9376 class InstallParams extends HandlerParams { 9377 final OriginInfo origin; 9378 final IPackageInstallObserver2 observer; 9379 int installFlags; 9380 final String installerPackageName; 9381 final String volumeUuid; 9382 final VerificationParams verificationParams; 9383 private InstallArgs mArgs; 9384 private int mRet; 9385 final String packageAbiOverride; 9386 9387 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9388 String installerPackageName, String volumeUuid, 9389 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9390 super(user); 9391 this.origin = origin; 9392 this.observer = observer; 9393 this.installFlags = installFlags; 9394 this.installerPackageName = installerPackageName; 9395 this.volumeUuid = volumeUuid; 9396 this.verificationParams = verificationParams; 9397 this.packageAbiOverride = packageAbiOverride; 9398 } 9399 9400 @Override 9401 public String toString() { 9402 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9403 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9404 } 9405 9406 public ManifestDigest getManifestDigest() { 9407 if (verificationParams == null) { 9408 return null; 9409 } 9410 return verificationParams.getManifestDigest(); 9411 } 9412 9413 private int installLocationPolicy(PackageInfoLite pkgLite) { 9414 String packageName = pkgLite.packageName; 9415 int installLocation = pkgLite.installLocation; 9416 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9417 // reader 9418 synchronized (mPackages) { 9419 PackageParser.Package pkg = mPackages.get(packageName); 9420 if (pkg != null) { 9421 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9422 // Check for downgrading. 9423 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9424 try { 9425 checkDowngrade(pkg, pkgLite); 9426 } catch (PackageManagerException e) { 9427 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9428 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9429 } 9430 } 9431 // Check for updated system application. 9432 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9433 if (onSd) { 9434 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9435 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9436 } 9437 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9438 } else { 9439 if (onSd) { 9440 // Install flag overrides everything. 9441 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9442 } 9443 // If current upgrade specifies particular preference 9444 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9445 // Application explicitly specified internal. 9446 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9447 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9448 // App explictly prefers external. Let policy decide 9449 } else { 9450 // Prefer previous location 9451 if (isExternal(pkg)) { 9452 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9453 } 9454 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9455 } 9456 } 9457 } else { 9458 // Invalid install. Return error code 9459 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9460 } 9461 } 9462 } 9463 // All the special cases have been taken care of. 9464 // Return result based on recommended install location. 9465 if (onSd) { 9466 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9467 } 9468 return pkgLite.recommendedInstallLocation; 9469 } 9470 9471 /* 9472 * Invoke remote method to get package information and install 9473 * location values. Override install location based on default 9474 * policy if needed and then create install arguments based 9475 * on the install location. 9476 */ 9477 public void handleStartCopy() throws RemoteException { 9478 int ret = PackageManager.INSTALL_SUCCEEDED; 9479 9480 // If we're already staged, we've firmly committed to an install location 9481 if (origin.staged) { 9482 if (origin.file != null) { 9483 installFlags |= PackageManager.INSTALL_INTERNAL; 9484 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9485 } else if (origin.cid != null) { 9486 installFlags |= PackageManager.INSTALL_EXTERNAL; 9487 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9488 } else { 9489 throw new IllegalStateException("Invalid stage location"); 9490 } 9491 } 9492 9493 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9494 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9495 9496 PackageInfoLite pkgLite = null; 9497 9498 if (onInt && onSd) { 9499 // Check if both bits are set. 9500 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9501 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9502 } else { 9503 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9504 packageAbiOverride); 9505 9506 /* 9507 * If we have too little free space, try to free cache 9508 * before giving up. 9509 */ 9510 if (!origin.staged && pkgLite.recommendedInstallLocation 9511 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9512 // TODO: focus freeing disk space on the target device 9513 final StorageManager storage = StorageManager.from(mContext); 9514 final long lowThreshold = storage.getStorageLowBytes( 9515 Environment.getDataDirectory()); 9516 9517 final long sizeBytes = mContainerService.calculateInstalledSize( 9518 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9519 9520 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9521 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9522 installFlags, packageAbiOverride); 9523 } 9524 9525 /* 9526 * The cache free must have deleted the file we 9527 * downloaded to install. 9528 * 9529 * TODO: fix the "freeCache" call to not delete 9530 * the file we care about. 9531 */ 9532 if (pkgLite.recommendedInstallLocation 9533 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9534 pkgLite.recommendedInstallLocation 9535 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9536 } 9537 } 9538 } 9539 9540 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9541 int loc = pkgLite.recommendedInstallLocation; 9542 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9543 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9544 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9545 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9546 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9547 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9548 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9549 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9550 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9551 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9552 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9553 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9554 } else { 9555 // Override with defaults if needed. 9556 loc = installLocationPolicy(pkgLite); 9557 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9558 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9559 } else if (!onSd && !onInt) { 9560 // Override install location with flags 9561 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9562 // Set the flag to install on external media. 9563 installFlags |= PackageManager.INSTALL_EXTERNAL; 9564 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9565 } else { 9566 // Make sure the flag for installing on external 9567 // media is unset 9568 installFlags |= PackageManager.INSTALL_INTERNAL; 9569 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9570 } 9571 } 9572 } 9573 } 9574 9575 final InstallArgs args = createInstallArgs(this); 9576 mArgs = args; 9577 9578 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9579 /* 9580 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9581 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9582 */ 9583 int userIdentifier = getUser().getIdentifier(); 9584 if (userIdentifier == UserHandle.USER_ALL 9585 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9586 userIdentifier = UserHandle.USER_OWNER; 9587 } 9588 9589 /* 9590 * Determine if we have any installed package verifiers. If we 9591 * do, then we'll defer to them to verify the packages. 9592 */ 9593 final int requiredUid = mRequiredVerifierPackage == null ? -1 9594 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9595 if (!origin.existing && requiredUid != -1 9596 && isVerificationEnabled(userIdentifier, installFlags)) { 9597 final Intent verification = new Intent( 9598 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9599 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9600 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9601 PACKAGE_MIME_TYPE); 9602 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9603 9604 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9605 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9606 0 /* TODO: Which userId? */); 9607 9608 if (DEBUG_VERIFY) { 9609 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9610 + verification.toString() + " with " + pkgLite.verifiers.length 9611 + " optional verifiers"); 9612 } 9613 9614 final int verificationId = mPendingVerificationToken++; 9615 9616 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9617 9618 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9619 installerPackageName); 9620 9621 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9622 installFlags); 9623 9624 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9625 pkgLite.packageName); 9626 9627 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9628 pkgLite.versionCode); 9629 9630 if (verificationParams != null) { 9631 if (verificationParams.getVerificationURI() != null) { 9632 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9633 verificationParams.getVerificationURI()); 9634 } 9635 if (verificationParams.getOriginatingURI() != null) { 9636 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9637 verificationParams.getOriginatingURI()); 9638 } 9639 if (verificationParams.getReferrer() != null) { 9640 verification.putExtra(Intent.EXTRA_REFERRER, 9641 verificationParams.getReferrer()); 9642 } 9643 if (verificationParams.getOriginatingUid() >= 0) { 9644 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9645 verificationParams.getOriginatingUid()); 9646 } 9647 if (verificationParams.getInstallerUid() >= 0) { 9648 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9649 verificationParams.getInstallerUid()); 9650 } 9651 } 9652 9653 final PackageVerificationState verificationState = new PackageVerificationState( 9654 requiredUid, args); 9655 9656 mPendingVerification.append(verificationId, verificationState); 9657 9658 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9659 receivers, verificationState); 9660 9661 /* 9662 * If any sufficient verifiers were listed in the package 9663 * manifest, attempt to ask them. 9664 */ 9665 if (sufficientVerifiers != null) { 9666 final int N = sufficientVerifiers.size(); 9667 if (N == 0) { 9668 Slog.i(TAG, "Additional verifiers required, but none installed."); 9669 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9670 } else { 9671 for (int i = 0; i < N; i++) { 9672 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9673 9674 final Intent sufficientIntent = new Intent(verification); 9675 sufficientIntent.setComponent(verifierComponent); 9676 9677 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9678 } 9679 } 9680 } 9681 9682 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9683 mRequiredVerifierPackage, receivers); 9684 if (ret == PackageManager.INSTALL_SUCCEEDED 9685 && mRequiredVerifierPackage != null) { 9686 /* 9687 * Send the intent to the required verification agent, 9688 * but only start the verification timeout after the 9689 * target BroadcastReceivers have run. 9690 */ 9691 verification.setComponent(requiredVerifierComponent); 9692 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9693 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9694 new BroadcastReceiver() { 9695 @Override 9696 public void onReceive(Context context, Intent intent) { 9697 final Message msg = mHandler 9698 .obtainMessage(CHECK_PENDING_VERIFICATION); 9699 msg.arg1 = verificationId; 9700 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9701 } 9702 }, null, 0, null, null); 9703 9704 /* 9705 * We don't want the copy to proceed until verification 9706 * succeeds, so null out this field. 9707 */ 9708 mArgs = null; 9709 } 9710 } else { 9711 /* 9712 * No package verification is enabled, so immediately start 9713 * the remote call to initiate copy using temporary file. 9714 */ 9715 ret = args.copyApk(mContainerService, true); 9716 } 9717 } 9718 9719 mRet = ret; 9720 } 9721 9722 @Override 9723 void handleReturnCode() { 9724 // If mArgs is null, then MCS couldn't be reached. When it 9725 // reconnects, it will try again to install. At that point, this 9726 // will succeed. 9727 if (mArgs != null) { 9728 processPendingInstall(mArgs, mRet); 9729 } 9730 } 9731 9732 @Override 9733 void handleServiceError() { 9734 mArgs = createInstallArgs(this); 9735 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9736 } 9737 9738 public boolean isForwardLocked() { 9739 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9740 } 9741 } 9742 9743 /** 9744 * Used during creation of InstallArgs 9745 * 9746 * @param installFlags package installation flags 9747 * @return true if should be installed on external storage 9748 */ 9749 private static boolean installOnExternalAsec(int installFlags) { 9750 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9751 return false; 9752 } 9753 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9754 return true; 9755 } 9756 return false; 9757 } 9758 9759 /** 9760 * Used during creation of InstallArgs 9761 * 9762 * @param installFlags package installation flags 9763 * @return true if should be installed as forward locked 9764 */ 9765 private static boolean installForwardLocked(int installFlags) { 9766 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9767 } 9768 9769 private InstallArgs createInstallArgs(InstallParams params) { 9770 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9771 return new AsecInstallArgs(params); 9772 } else { 9773 return new FileInstallArgs(params); 9774 } 9775 } 9776 9777 /** 9778 * Create args that describe an existing installed package. Typically used 9779 * when cleaning up old installs, or used as a move source. 9780 */ 9781 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9782 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9783 final boolean isInAsec; 9784 if (installOnExternalAsec(installFlags)) { 9785 /* Apps on SD card are always in ASEC containers. */ 9786 isInAsec = true; 9787 } else if (installForwardLocked(installFlags) 9788 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9789 /* 9790 * Forward-locked apps are only in ASEC containers if they're the 9791 * new style 9792 */ 9793 isInAsec = true; 9794 } else { 9795 isInAsec = false; 9796 } 9797 9798 if (isInAsec) { 9799 return new AsecInstallArgs(codePath, instructionSets, 9800 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9801 } else { 9802 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9803 instructionSets); 9804 } 9805 } 9806 9807 static abstract class InstallArgs { 9808 /** @see InstallParams#origin */ 9809 final OriginInfo origin; 9810 9811 final IPackageInstallObserver2 observer; 9812 // Always refers to PackageManager flags only 9813 final int installFlags; 9814 final String installerPackageName; 9815 final String volumeUuid; 9816 final ManifestDigest manifestDigest; 9817 final UserHandle user; 9818 final String abiOverride; 9819 9820 // The list of instruction sets supported by this app. This is currently 9821 // only used during the rmdex() phase to clean up resources. We can get rid of this 9822 // if we move dex files under the common app path. 9823 /* nullable */ String[] instructionSets; 9824 9825 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9826 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9827 UserHandle user, String[] instructionSets, String abiOverride) { 9828 this.origin = origin; 9829 this.installFlags = installFlags; 9830 this.observer = observer; 9831 this.installerPackageName = installerPackageName; 9832 this.volumeUuid = volumeUuid; 9833 this.manifestDigest = manifestDigest; 9834 this.user = user; 9835 this.instructionSets = instructionSets; 9836 this.abiOverride = abiOverride; 9837 } 9838 9839 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9840 abstract int doPreInstall(int status); 9841 9842 /** 9843 * Rename package into final resting place. All paths on the given 9844 * scanned package should be updated to reflect the rename. 9845 */ 9846 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9847 abstract int doPostInstall(int status, int uid); 9848 9849 /** @see PackageSettingBase#codePathString */ 9850 abstract String getCodePath(); 9851 /** @see PackageSettingBase#resourcePathString */ 9852 abstract String getResourcePath(); 9853 abstract String getLegacyNativeLibraryPath(); 9854 9855 // Need installer lock especially for dex file removal. 9856 abstract void cleanUpResourcesLI(); 9857 abstract boolean doPostDeleteLI(boolean delete); 9858 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9859 9860 /** 9861 * Called before the source arguments are copied. This is used mostly 9862 * for MoveParams when it needs to read the source file to put it in the 9863 * destination. 9864 */ 9865 int doPreCopy() { 9866 return PackageManager.INSTALL_SUCCEEDED; 9867 } 9868 9869 /** 9870 * Called after the source arguments are copied. This is used mostly for 9871 * MoveParams when it needs to read the source file to put it in the 9872 * destination. 9873 * 9874 * @return 9875 */ 9876 int doPostCopy(int uid) { 9877 return PackageManager.INSTALL_SUCCEEDED; 9878 } 9879 9880 protected boolean isFwdLocked() { 9881 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9882 } 9883 9884 protected boolean isExternalAsec() { 9885 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9886 } 9887 9888 UserHandle getUser() { 9889 return user; 9890 } 9891 } 9892 9893 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 9894 if (!allCodePaths.isEmpty()) { 9895 if (instructionSets == null) { 9896 throw new IllegalStateException("instructionSet == null"); 9897 } 9898 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9899 for (String codePath : allCodePaths) { 9900 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9901 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9902 if (retCode < 0) { 9903 Slog.w(TAG, "Couldn't remove dex file for package: " 9904 + " at location " + codePath + ", retcode=" + retCode); 9905 // we don't consider this to be a failure of the core package deletion 9906 } 9907 } 9908 } 9909 } 9910 } 9911 9912 /** 9913 * Logic to handle installation of non-ASEC applications, including copying 9914 * and renaming logic. 9915 */ 9916 class FileInstallArgs extends InstallArgs { 9917 private File codeFile; 9918 private File resourceFile; 9919 private File legacyNativeLibraryPath; 9920 9921 // Example topology: 9922 // /data/app/com.example/base.apk 9923 // /data/app/com.example/split_foo.apk 9924 // /data/app/com.example/lib/arm/libfoo.so 9925 // /data/app/com.example/lib/arm64/libfoo.so 9926 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9927 9928 /** New install */ 9929 FileInstallArgs(InstallParams params) { 9930 super(params.origin, params.observer, params.installFlags, 9931 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 9932 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 9933 if (isFwdLocked()) { 9934 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9935 } 9936 } 9937 9938 /** Existing install */ 9939 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9940 String[] instructionSets) { 9941 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 9942 this.codeFile = (codePath != null) ? new File(codePath) : null; 9943 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9944 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9945 new File(legacyNativeLibraryPath) : null; 9946 } 9947 9948 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9949 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9950 isFwdLocked(), abiOverride); 9951 9952 final StorageManager storage = StorageManager.from(mContext); 9953 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9954 } 9955 9956 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9957 if (origin.staged) { 9958 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9959 codeFile = origin.file; 9960 resourceFile = origin.file; 9961 return PackageManager.INSTALL_SUCCEEDED; 9962 } 9963 9964 try { 9965 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 9966 codeFile = tempDir; 9967 resourceFile = tempDir; 9968 } catch (IOException e) { 9969 Slog.w(TAG, "Failed to create copy file: " + e); 9970 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9971 } 9972 9973 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9974 @Override 9975 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9976 if (!FileUtils.isValidExtFilename(name)) { 9977 throw new IllegalArgumentException("Invalid filename: " + name); 9978 } 9979 try { 9980 final File file = new File(codeFile, name); 9981 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9982 O_RDWR | O_CREAT, 0644); 9983 Os.chmod(file.getAbsolutePath(), 0644); 9984 return new ParcelFileDescriptor(fd); 9985 } catch (ErrnoException e) { 9986 throw new RemoteException("Failed to open: " + e.getMessage()); 9987 } 9988 } 9989 }; 9990 9991 int ret = PackageManager.INSTALL_SUCCEEDED; 9992 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9993 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9994 Slog.e(TAG, "Failed to copy package"); 9995 return ret; 9996 } 9997 9998 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9999 NativeLibraryHelper.Handle handle = null; 10000 try { 10001 handle = NativeLibraryHelper.Handle.create(codeFile); 10002 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10003 abiOverride); 10004 } catch (IOException e) { 10005 Slog.e(TAG, "Copying native libraries failed", e); 10006 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10007 } finally { 10008 IoUtils.closeQuietly(handle); 10009 } 10010 10011 return ret; 10012 } 10013 10014 int doPreInstall(int status) { 10015 if (status != PackageManager.INSTALL_SUCCEEDED) { 10016 cleanUp(); 10017 } 10018 return status; 10019 } 10020 10021 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10022 if (status != PackageManager.INSTALL_SUCCEEDED) { 10023 cleanUp(); 10024 return false; 10025 } else { 10026 final File targetDir = codeFile.getParentFile(); 10027 final File beforeCodeFile = codeFile; 10028 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10029 10030 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10031 try { 10032 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10033 } catch (ErrnoException e) { 10034 Slog.d(TAG, "Failed to rename", e); 10035 return false; 10036 } 10037 10038 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10039 Slog.d(TAG, "Failed to restorecon"); 10040 return false; 10041 } 10042 10043 // Reflect the rename internally 10044 codeFile = afterCodeFile; 10045 resourceFile = afterCodeFile; 10046 10047 // Reflect the rename in scanned details 10048 pkg.codePath = afterCodeFile.getAbsolutePath(); 10049 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10050 pkg.baseCodePath); 10051 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10052 pkg.splitCodePaths); 10053 10054 // Reflect the rename in app info 10055 pkg.applicationInfo.setCodePath(pkg.codePath); 10056 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10057 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10058 pkg.applicationInfo.setResourcePath(pkg.codePath); 10059 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10060 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10061 10062 return true; 10063 } 10064 } 10065 10066 int doPostInstall(int status, int uid) { 10067 if (status != PackageManager.INSTALL_SUCCEEDED) { 10068 cleanUp(); 10069 } 10070 return status; 10071 } 10072 10073 @Override 10074 String getCodePath() { 10075 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10076 } 10077 10078 @Override 10079 String getResourcePath() { 10080 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10081 } 10082 10083 @Override 10084 String getLegacyNativeLibraryPath() { 10085 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10086 } 10087 10088 private boolean cleanUp() { 10089 if (codeFile == null || !codeFile.exists()) { 10090 return false; 10091 } 10092 10093 if (codeFile.isDirectory()) { 10094 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10095 } else { 10096 codeFile.delete(); 10097 } 10098 10099 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10100 resourceFile.delete(); 10101 } 10102 10103 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10104 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10105 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10106 } 10107 legacyNativeLibraryPath.delete(); 10108 } 10109 10110 return true; 10111 } 10112 10113 void cleanUpResourcesLI() { 10114 // Try enumerating all code paths before deleting 10115 List<String> allCodePaths = Collections.EMPTY_LIST; 10116 if (codeFile != null && codeFile.exists()) { 10117 try { 10118 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10119 allCodePaths = pkg.getAllCodePaths(); 10120 } catch (PackageParserException e) { 10121 // Ignored; we tried our best 10122 } 10123 } 10124 10125 cleanUp(); 10126 removeDexFiles(allCodePaths, instructionSets); 10127 } 10128 10129 boolean doPostDeleteLI(boolean delete) { 10130 // XXX err, shouldn't we respect the delete flag? 10131 cleanUpResourcesLI(); 10132 return true; 10133 } 10134 } 10135 10136 private boolean isAsecExternal(String cid) { 10137 final String asecPath = PackageHelper.getSdFilesystem(cid); 10138 return !asecPath.startsWith(mAsecInternalPath); 10139 } 10140 10141 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10142 PackageManagerException { 10143 if (copyRet < 0) { 10144 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10145 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10146 throw new PackageManagerException(copyRet, message); 10147 } 10148 } 10149 } 10150 10151 /** 10152 * Extract the MountService "container ID" from the full code path of an 10153 * .apk. 10154 */ 10155 static String cidFromCodePath(String fullCodePath) { 10156 int eidx = fullCodePath.lastIndexOf("/"); 10157 String subStr1 = fullCodePath.substring(0, eidx); 10158 int sidx = subStr1.lastIndexOf("/"); 10159 return subStr1.substring(sidx+1, eidx); 10160 } 10161 10162 /** 10163 * Logic to handle installation of ASEC applications, including copying and 10164 * renaming logic. 10165 */ 10166 class AsecInstallArgs extends InstallArgs { 10167 static final String RES_FILE_NAME = "pkg.apk"; 10168 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10169 10170 String cid; 10171 String packagePath; 10172 String resourcePath; 10173 String legacyNativeLibraryDir; 10174 10175 /** New install */ 10176 AsecInstallArgs(InstallParams params) { 10177 super(params.origin, params.observer, params.installFlags, 10178 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10179 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10180 } 10181 10182 /** Existing install */ 10183 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10184 boolean isExternal, boolean isForwardLocked) { 10185 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10186 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10187 instructionSets, null); 10188 // Hackily pretend we're still looking at a full code path 10189 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10190 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10191 } 10192 10193 // Extract cid from fullCodePath 10194 int eidx = fullCodePath.lastIndexOf("/"); 10195 String subStr1 = fullCodePath.substring(0, eidx); 10196 int sidx = subStr1.lastIndexOf("/"); 10197 cid = subStr1.substring(sidx+1, eidx); 10198 setMountPath(subStr1); 10199 } 10200 10201 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10202 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10203 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10204 instructionSets, null); 10205 this.cid = cid; 10206 setMountPath(PackageHelper.getSdDir(cid)); 10207 } 10208 10209 void createCopyFile() { 10210 cid = mInstallerService.allocateExternalStageCidLegacy(); 10211 } 10212 10213 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10214 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10215 abiOverride); 10216 10217 final File target; 10218 if (isExternalAsec()) { 10219 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10220 } else { 10221 target = Environment.getDataDirectory(); 10222 } 10223 10224 final StorageManager storage = StorageManager.from(mContext); 10225 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10226 } 10227 10228 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10229 if (origin.staged) { 10230 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10231 cid = origin.cid; 10232 setMountPath(PackageHelper.getSdDir(cid)); 10233 return PackageManager.INSTALL_SUCCEEDED; 10234 } 10235 10236 if (temp) { 10237 createCopyFile(); 10238 } else { 10239 /* 10240 * Pre-emptively destroy the container since it's destroyed if 10241 * copying fails due to it existing anyway. 10242 */ 10243 PackageHelper.destroySdDir(cid); 10244 } 10245 10246 final String newMountPath = imcs.copyPackageToContainer( 10247 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10248 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10249 10250 if (newMountPath != null) { 10251 setMountPath(newMountPath); 10252 return PackageManager.INSTALL_SUCCEEDED; 10253 } else { 10254 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10255 } 10256 } 10257 10258 @Override 10259 String getCodePath() { 10260 return packagePath; 10261 } 10262 10263 @Override 10264 String getResourcePath() { 10265 return resourcePath; 10266 } 10267 10268 @Override 10269 String getLegacyNativeLibraryPath() { 10270 return legacyNativeLibraryDir; 10271 } 10272 10273 int doPreInstall(int status) { 10274 if (status != PackageManager.INSTALL_SUCCEEDED) { 10275 // Destroy container 10276 PackageHelper.destroySdDir(cid); 10277 } else { 10278 boolean mounted = PackageHelper.isContainerMounted(cid); 10279 if (!mounted) { 10280 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10281 Process.SYSTEM_UID); 10282 if (newMountPath != null) { 10283 setMountPath(newMountPath); 10284 } else { 10285 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10286 } 10287 } 10288 } 10289 return status; 10290 } 10291 10292 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10293 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10294 String newMountPath = null; 10295 if (PackageHelper.isContainerMounted(cid)) { 10296 // Unmount the container 10297 if (!PackageHelper.unMountSdDir(cid)) { 10298 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10299 return false; 10300 } 10301 } 10302 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10303 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10304 " which might be stale. Will try to clean up."); 10305 // Clean up the stale container and proceed to recreate. 10306 if (!PackageHelper.destroySdDir(newCacheId)) { 10307 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10308 return false; 10309 } 10310 // Successfully cleaned up stale container. Try to rename again. 10311 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10312 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10313 + " inspite of cleaning it up."); 10314 return false; 10315 } 10316 } 10317 if (!PackageHelper.isContainerMounted(newCacheId)) { 10318 Slog.w(TAG, "Mounting container " + newCacheId); 10319 newMountPath = PackageHelper.mountSdDir(newCacheId, 10320 getEncryptKey(), Process.SYSTEM_UID); 10321 } else { 10322 newMountPath = PackageHelper.getSdDir(newCacheId); 10323 } 10324 if (newMountPath == null) { 10325 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10326 return false; 10327 } 10328 Log.i(TAG, "Succesfully renamed " + cid + 10329 " to " + newCacheId + 10330 " at new path: " + newMountPath); 10331 cid = newCacheId; 10332 10333 final File beforeCodeFile = new File(packagePath); 10334 setMountPath(newMountPath); 10335 final File afterCodeFile = new File(packagePath); 10336 10337 // Reflect the rename in scanned details 10338 pkg.codePath = afterCodeFile.getAbsolutePath(); 10339 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10340 pkg.baseCodePath); 10341 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10342 pkg.splitCodePaths); 10343 10344 // Reflect the rename in app info 10345 pkg.applicationInfo.setCodePath(pkg.codePath); 10346 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10347 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10348 pkg.applicationInfo.setResourcePath(pkg.codePath); 10349 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10350 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10351 10352 return true; 10353 } 10354 10355 private void setMountPath(String mountPath) { 10356 final File mountFile = new File(mountPath); 10357 10358 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10359 if (monolithicFile.exists()) { 10360 packagePath = monolithicFile.getAbsolutePath(); 10361 if (isFwdLocked()) { 10362 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10363 } else { 10364 resourcePath = packagePath; 10365 } 10366 } else { 10367 packagePath = mountFile.getAbsolutePath(); 10368 resourcePath = packagePath; 10369 } 10370 10371 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10372 } 10373 10374 int doPostInstall(int status, int uid) { 10375 if (status != PackageManager.INSTALL_SUCCEEDED) { 10376 cleanUp(); 10377 } else { 10378 final int groupOwner; 10379 final String protectedFile; 10380 if (isFwdLocked()) { 10381 groupOwner = UserHandle.getSharedAppGid(uid); 10382 protectedFile = RES_FILE_NAME; 10383 } else { 10384 groupOwner = -1; 10385 protectedFile = null; 10386 } 10387 10388 if (uid < Process.FIRST_APPLICATION_UID 10389 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10390 Slog.e(TAG, "Failed to finalize " + cid); 10391 PackageHelper.destroySdDir(cid); 10392 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10393 } 10394 10395 boolean mounted = PackageHelper.isContainerMounted(cid); 10396 if (!mounted) { 10397 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10398 } 10399 } 10400 return status; 10401 } 10402 10403 private void cleanUp() { 10404 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10405 10406 // Destroy secure container 10407 PackageHelper.destroySdDir(cid); 10408 } 10409 10410 private List<String> getAllCodePaths() { 10411 final File codeFile = new File(getCodePath()); 10412 if (codeFile != null && codeFile.exists()) { 10413 try { 10414 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10415 return pkg.getAllCodePaths(); 10416 } catch (PackageParserException e) { 10417 // Ignored; we tried our best 10418 } 10419 } 10420 return Collections.EMPTY_LIST; 10421 } 10422 10423 void cleanUpResourcesLI() { 10424 // Enumerate all code paths before deleting 10425 cleanUpResourcesLI(getAllCodePaths()); 10426 } 10427 10428 private void cleanUpResourcesLI(List<String> allCodePaths) { 10429 cleanUp(); 10430 removeDexFiles(allCodePaths, instructionSets); 10431 } 10432 10433 10434 10435 String getPackageName() { 10436 return getAsecPackageName(cid); 10437 } 10438 10439 boolean doPostDeleteLI(boolean delete) { 10440 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10441 final List<String> allCodePaths = getAllCodePaths(); 10442 boolean mounted = PackageHelper.isContainerMounted(cid); 10443 if (mounted) { 10444 // Unmount first 10445 if (PackageHelper.unMountSdDir(cid)) { 10446 mounted = false; 10447 } 10448 } 10449 if (!mounted && delete) { 10450 cleanUpResourcesLI(allCodePaths); 10451 } 10452 return !mounted; 10453 } 10454 10455 @Override 10456 int doPreCopy() { 10457 if (isFwdLocked()) { 10458 if (!PackageHelper.fixSdPermissions(cid, 10459 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10460 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10461 } 10462 } 10463 10464 return PackageManager.INSTALL_SUCCEEDED; 10465 } 10466 10467 @Override 10468 int doPostCopy(int uid) { 10469 if (isFwdLocked()) { 10470 if (uid < Process.FIRST_APPLICATION_UID 10471 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10472 RES_FILE_NAME)) { 10473 Slog.e(TAG, "Failed to finalize " + cid); 10474 PackageHelper.destroySdDir(cid); 10475 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10476 } 10477 } 10478 10479 return PackageManager.INSTALL_SUCCEEDED; 10480 } 10481 } 10482 10483 static String getAsecPackageName(String packageCid) { 10484 int idx = packageCid.lastIndexOf("-"); 10485 if (idx == -1) { 10486 return packageCid; 10487 } 10488 return packageCid.substring(0, idx); 10489 } 10490 10491 // Utility method used to create code paths based on package name and available index. 10492 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10493 String idxStr = ""; 10494 int idx = 1; 10495 // Fall back to default value of idx=1 if prefix is not 10496 // part of oldCodePath 10497 if (oldCodePath != null) { 10498 String subStr = oldCodePath; 10499 // Drop the suffix right away 10500 if (suffix != null && subStr.endsWith(suffix)) { 10501 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10502 } 10503 // If oldCodePath already contains prefix find out the 10504 // ending index to either increment or decrement. 10505 int sidx = subStr.lastIndexOf(prefix); 10506 if (sidx != -1) { 10507 subStr = subStr.substring(sidx + prefix.length()); 10508 if (subStr != null) { 10509 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10510 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10511 } 10512 try { 10513 idx = Integer.parseInt(subStr); 10514 if (idx <= 1) { 10515 idx++; 10516 } else { 10517 idx--; 10518 } 10519 } catch(NumberFormatException e) { 10520 } 10521 } 10522 } 10523 } 10524 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10525 return prefix + idxStr; 10526 } 10527 10528 private File getNextCodePath(File targetDir, String packageName) { 10529 int suffix = 1; 10530 File result; 10531 do { 10532 result = new File(targetDir, packageName + "-" + suffix); 10533 suffix++; 10534 } while (result.exists()); 10535 return result; 10536 } 10537 10538 // Utility method that returns the relative package path with respect 10539 // to the installation directory. Like say for /data/data/com.test-1.apk 10540 // string com.test-1 is returned. 10541 static String deriveCodePathName(String codePath) { 10542 if (codePath == null) { 10543 return null; 10544 } 10545 final File codeFile = new File(codePath); 10546 final String name = codeFile.getName(); 10547 if (codeFile.isDirectory()) { 10548 return name; 10549 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10550 final int lastDot = name.lastIndexOf('.'); 10551 return name.substring(0, lastDot); 10552 } else { 10553 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10554 return null; 10555 } 10556 } 10557 10558 class PackageInstalledInfo { 10559 String name; 10560 int uid; 10561 // The set of users that originally had this package installed. 10562 int[] origUsers; 10563 // The set of users that now have this package installed. 10564 int[] newUsers; 10565 PackageParser.Package pkg; 10566 int returnCode; 10567 String returnMsg; 10568 PackageRemovedInfo removedInfo; 10569 10570 public void setError(int code, String msg) { 10571 returnCode = code; 10572 returnMsg = msg; 10573 Slog.w(TAG, msg); 10574 } 10575 10576 public void setError(String msg, PackageParserException e) { 10577 returnCode = e.error; 10578 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10579 Slog.w(TAG, msg, e); 10580 } 10581 10582 public void setError(String msg, PackageManagerException e) { 10583 returnCode = e.error; 10584 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10585 Slog.w(TAG, msg, e); 10586 } 10587 10588 // In some error cases we want to convey more info back to the observer 10589 String origPackage; 10590 String origPermission; 10591 } 10592 10593 /* 10594 * Install a non-existing package. 10595 */ 10596 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10597 UserHandle user, String installerPackageName, String volumeUuid, 10598 PackageInstalledInfo res) { 10599 // Remember this for later, in case we need to rollback this install 10600 String pkgName = pkg.packageName; 10601 10602 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10603 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10604 synchronized(mPackages) { 10605 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10606 // A package with the same name is already installed, though 10607 // it has been renamed to an older name. The package we 10608 // are trying to install should be installed as an update to 10609 // the existing one, but that has not been requested, so bail. 10610 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10611 + " without first uninstalling package running as " 10612 + mSettings.mRenamedPackages.get(pkgName)); 10613 return; 10614 } 10615 if (mPackages.containsKey(pkgName)) { 10616 // Don't allow installation over an existing package with the same name. 10617 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10618 + " without first uninstalling."); 10619 return; 10620 } 10621 } 10622 10623 try { 10624 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10625 System.currentTimeMillis(), user); 10626 10627 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10628 // delete the partially installed application. the data directory will have to be 10629 // restored if it was already existing 10630 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10631 // remove package from internal structures. Note that we want deletePackageX to 10632 // delete the package data and cache directories that it created in 10633 // scanPackageLocked, unless those directories existed before we even tried to 10634 // install. 10635 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10636 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10637 res.removedInfo, true); 10638 } 10639 10640 } catch (PackageManagerException e) { 10641 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10642 } 10643 } 10644 10645 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10646 // Upgrade keysets are being used. Determine if new package has a superset of the 10647 // required keys. 10648 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10649 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10650 for (int i = 0; i < upgradeKeySets.length; i++) { 10651 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10652 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10653 return true; 10654 } 10655 } 10656 return false; 10657 } 10658 10659 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10660 UserHandle user, String installerPackageName, String volumeUuid, 10661 PackageInstalledInfo res) { 10662 PackageParser.Package oldPackage; 10663 String pkgName = pkg.packageName; 10664 int[] allUsers; 10665 boolean[] perUserInstalled; 10666 10667 // First find the old package info and check signatures 10668 synchronized(mPackages) { 10669 oldPackage = mPackages.get(pkgName); 10670 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10671 PackageSetting ps = mSettings.mPackages.get(pkgName); 10672 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10673 // default to original signature matching 10674 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10675 != PackageManager.SIGNATURE_MATCH) { 10676 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10677 "New package has a different signature: " + pkgName); 10678 return; 10679 } 10680 } else { 10681 if(!checkUpgradeKeySetLP(ps, pkg)) { 10682 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10683 "New package not signed by keys specified by upgrade-keysets: " 10684 + pkgName); 10685 return; 10686 } 10687 } 10688 10689 // In case of rollback, remember per-user/profile install state 10690 allUsers = sUserManager.getUserIds(); 10691 perUserInstalled = new boolean[allUsers.length]; 10692 for (int i = 0; i < allUsers.length; i++) { 10693 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10694 } 10695 } 10696 10697 boolean sysPkg = (isSystemApp(oldPackage)); 10698 if (sysPkg) { 10699 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10700 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10701 } else { 10702 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10703 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10704 } 10705 } 10706 10707 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10708 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10709 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10710 String volumeUuid, PackageInstalledInfo res) { 10711 String pkgName = deletedPackage.packageName; 10712 boolean deletedPkg = true; 10713 boolean updatedSettings = false; 10714 10715 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10716 + deletedPackage); 10717 long origUpdateTime; 10718 if (pkg.mExtras != null) { 10719 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10720 } else { 10721 origUpdateTime = 0; 10722 } 10723 10724 // First delete the existing package while retaining the data directory 10725 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10726 res.removedInfo, true)) { 10727 // If the existing package wasn't successfully deleted 10728 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10729 deletedPkg = false; 10730 } else { 10731 // Successfully deleted the old package; proceed with replace. 10732 10733 // If deleted package lived in a container, give users a chance to 10734 // relinquish resources before killing. 10735 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10736 if (DEBUG_INSTALL) { 10737 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10738 } 10739 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10740 final ArrayList<String> pkgList = new ArrayList<String>(1); 10741 pkgList.add(deletedPackage.applicationInfo.packageName); 10742 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10743 } 10744 10745 deleteCodeCacheDirsLI(pkgName); 10746 try { 10747 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10748 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10749 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10750 perUserInstalled, res, user); 10751 updatedSettings = true; 10752 } catch (PackageManagerException e) { 10753 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10754 } 10755 } 10756 10757 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10758 // remove package from internal structures. Note that we want deletePackageX to 10759 // delete the package data and cache directories that it created in 10760 // scanPackageLocked, unless those directories existed before we even tried to 10761 // install. 10762 if(updatedSettings) { 10763 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10764 deletePackageLI( 10765 pkgName, null, true, allUsers, perUserInstalled, 10766 PackageManager.DELETE_KEEP_DATA, 10767 res.removedInfo, true); 10768 } 10769 // Since we failed to install the new package we need to restore the old 10770 // package that we deleted. 10771 if (deletedPkg) { 10772 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10773 File restoreFile = new File(deletedPackage.codePath); 10774 // Parse old package 10775 boolean oldExternal = isExternal(deletedPackage); 10776 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10777 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10778 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10779 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10780 try { 10781 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10782 } catch (PackageManagerException e) { 10783 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10784 + e.getMessage()); 10785 return; 10786 } 10787 // Restore of old package succeeded. Update permissions. 10788 // writer 10789 synchronized (mPackages) { 10790 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10791 UPDATE_PERMISSIONS_ALL); 10792 // can downgrade to reader 10793 mSettings.writeLPr(); 10794 } 10795 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10796 } 10797 } 10798 } 10799 10800 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10801 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10802 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10803 String volumeUuid, PackageInstalledInfo res) { 10804 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10805 + ", old=" + deletedPackage); 10806 boolean disabledSystem = false; 10807 boolean updatedSettings = false; 10808 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10809 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10810 != 0) { 10811 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10812 } 10813 String packageName = deletedPackage.packageName; 10814 if (packageName == null) { 10815 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10816 "Attempt to delete null packageName."); 10817 return; 10818 } 10819 PackageParser.Package oldPkg; 10820 PackageSetting oldPkgSetting; 10821 // reader 10822 synchronized (mPackages) { 10823 oldPkg = mPackages.get(packageName); 10824 oldPkgSetting = mSettings.mPackages.get(packageName); 10825 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10826 (oldPkgSetting == null)) { 10827 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10828 "Couldn't find package:" + packageName + " information"); 10829 return; 10830 } 10831 } 10832 10833 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10834 10835 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10836 res.removedInfo.removedPackage = packageName; 10837 // Remove existing system package 10838 removePackageLI(oldPkgSetting, true); 10839 // writer 10840 synchronized (mPackages) { 10841 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10842 if (!disabledSystem && deletedPackage != null) { 10843 // We didn't need to disable the .apk as a current system package, 10844 // which means we are replacing another update that is already 10845 // installed. We need to make sure to delete the older one's .apk. 10846 res.removedInfo.args = createInstallArgsForExisting(0, 10847 deletedPackage.applicationInfo.getCodePath(), 10848 deletedPackage.applicationInfo.getResourcePath(), 10849 deletedPackage.applicationInfo.nativeLibraryRootDir, 10850 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10851 } else { 10852 res.removedInfo.args = null; 10853 } 10854 } 10855 10856 // Successfully disabled the old package. Now proceed with re-installation 10857 deleteCodeCacheDirsLI(packageName); 10858 10859 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10860 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10861 10862 PackageParser.Package newPackage = null; 10863 try { 10864 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10865 if (newPackage.mExtras != null) { 10866 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10867 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10868 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10869 10870 // is the update attempting to change shared user? that isn't going to work... 10871 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10872 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10873 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10874 + " to " + newPkgSetting.sharedUser); 10875 updatedSettings = true; 10876 } 10877 } 10878 10879 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10880 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10881 perUserInstalled, res, user); 10882 updatedSettings = true; 10883 } 10884 10885 } catch (PackageManagerException e) { 10886 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10887 } 10888 10889 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10890 // Re installation failed. Restore old information 10891 // Remove new pkg information 10892 if (newPackage != null) { 10893 removeInstalledPackageLI(newPackage, true); 10894 } 10895 // Add back the old system package 10896 try { 10897 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10898 } catch (PackageManagerException e) { 10899 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10900 } 10901 // Restore the old system information in Settings 10902 synchronized (mPackages) { 10903 if (disabledSystem) { 10904 mSettings.enableSystemPackageLPw(packageName); 10905 } 10906 if (updatedSettings) { 10907 mSettings.setInstallerPackageName(packageName, 10908 oldPkgSetting.installerPackageName); 10909 } 10910 mSettings.writeLPr(); 10911 } 10912 } 10913 } 10914 10915 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10916 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 10917 UserHandle user) { 10918 String pkgName = newPackage.packageName; 10919 synchronized (mPackages) { 10920 //write settings. the installStatus will be incomplete at this stage. 10921 //note that the new package setting would have already been 10922 //added to mPackages. It hasn't been persisted yet. 10923 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10924 mSettings.writeLPr(); 10925 } 10926 10927 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10928 10929 synchronized (mPackages) { 10930 updatePermissionsLPw(newPackage.packageName, newPackage, 10931 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10932 ? UPDATE_PERMISSIONS_ALL : 0)); 10933 // For system-bundled packages, we assume that installing an upgraded version 10934 // of the package implies that the user actually wants to run that new code, 10935 // so we enable the package. 10936 PackageSetting ps = mSettings.mPackages.get(pkgName); 10937 if (ps != null) { 10938 if (isSystemApp(newPackage)) { 10939 // NB: implicit assumption that system package upgrades apply to all users 10940 if (DEBUG_INSTALL) { 10941 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10942 } 10943 if (res.origUsers != null) { 10944 for (int userHandle : res.origUsers) { 10945 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10946 userHandle, installerPackageName); 10947 } 10948 } 10949 // Also convey the prior install/uninstall state 10950 if (allUsers != null && perUserInstalled != null) { 10951 for (int i = 0; i < allUsers.length; i++) { 10952 if (DEBUG_INSTALL) { 10953 Slog.d(TAG, " user " + allUsers[i] 10954 + " => " + perUserInstalled[i]); 10955 } 10956 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10957 } 10958 // these install state changes will be persisted in the 10959 // upcoming call to mSettings.writeLPr(). 10960 } 10961 } 10962 // It's implied that when a user requests installation, they want the app to be 10963 // installed and enabled. 10964 int userId = user.getIdentifier(); 10965 if (userId != UserHandle.USER_ALL) { 10966 ps.setInstalled(true, userId); 10967 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 10968 } 10969 } 10970 res.name = pkgName; 10971 res.uid = newPackage.applicationInfo.uid; 10972 res.pkg = newPackage; 10973 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10974 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10975 mSettings.setVolumeUuid(pkgName, volumeUuid); 10976 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10977 //to update install status 10978 mSettings.writeLPr(); 10979 } 10980 } 10981 10982 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10983 final int installFlags = args.installFlags; 10984 final String installerPackageName = args.installerPackageName; 10985 final String volumeUuid = args.volumeUuid; 10986 final File tmpPackageFile = new File(args.getCodePath()); 10987 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10988 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 10989 || (args.volumeUuid != null)); 10990 boolean replace = false; 10991 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10992 // Result object to be returned 10993 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10994 10995 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10996 // Retrieve PackageSettings and parse package 10997 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10998 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10999 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11000 PackageParser pp = new PackageParser(); 11001 pp.setSeparateProcesses(mSeparateProcesses); 11002 pp.setDisplayMetrics(mMetrics); 11003 11004 final PackageParser.Package pkg; 11005 try { 11006 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11007 } catch (PackageParserException e) { 11008 res.setError("Failed parse during installPackageLI", e); 11009 return; 11010 } 11011 11012 // Mark that we have an install time CPU ABI override. 11013 pkg.cpuAbiOverride = args.abiOverride; 11014 11015 String pkgName = res.name = pkg.packageName; 11016 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11017 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11018 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11019 return; 11020 } 11021 } 11022 11023 try { 11024 pp.collectCertificates(pkg, parseFlags); 11025 pp.collectManifestDigest(pkg); 11026 } catch (PackageParserException e) { 11027 res.setError("Failed collect during installPackageLI", e); 11028 return; 11029 } 11030 11031 /* If the installer passed in a manifest digest, compare it now. */ 11032 if (args.manifestDigest != null) { 11033 if (DEBUG_INSTALL) { 11034 final String parsedManifest = pkg.manifestDigest == null ? "null" 11035 : pkg.manifestDigest.toString(); 11036 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11037 + parsedManifest); 11038 } 11039 11040 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11041 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11042 return; 11043 } 11044 } else if (DEBUG_INSTALL) { 11045 final String parsedManifest = pkg.manifestDigest == null 11046 ? "null" : pkg.manifestDigest.toString(); 11047 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11048 } 11049 11050 // Get rid of all references to package scan path via parser. 11051 pp = null; 11052 String oldCodePath = null; 11053 boolean systemApp = false; 11054 synchronized (mPackages) { 11055 // Check if installing already existing package 11056 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11057 String oldName = mSettings.mRenamedPackages.get(pkgName); 11058 if (pkg.mOriginalPackages != null 11059 && pkg.mOriginalPackages.contains(oldName) 11060 && mPackages.containsKey(oldName)) { 11061 // This package is derived from an original package, 11062 // and this device has been updating from that original 11063 // name. We must continue using the original name, so 11064 // rename the new package here. 11065 pkg.setPackageName(oldName); 11066 pkgName = pkg.packageName; 11067 replace = true; 11068 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11069 + oldName + " pkgName=" + pkgName); 11070 } else if (mPackages.containsKey(pkgName)) { 11071 // This package, under its official name, already exists 11072 // on the device; we should replace it. 11073 replace = true; 11074 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11075 } 11076 } 11077 11078 PackageSetting ps = mSettings.mPackages.get(pkgName); 11079 if (ps != null) { 11080 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11081 11082 // Quick sanity check that we're signed correctly if updating; 11083 // we'll check this again later when scanning, but we want to 11084 // bail early here before tripping over redefined permissions. 11085 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11086 try { 11087 verifySignaturesLP(ps, pkg); 11088 } catch (PackageManagerException e) { 11089 res.setError(e.error, e.getMessage()); 11090 return; 11091 } 11092 } else { 11093 if (!checkUpgradeKeySetLP(ps, pkg)) { 11094 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11095 + pkg.packageName + " upgrade keys do not match the " 11096 + "previously installed version"); 11097 return; 11098 } 11099 } 11100 11101 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11102 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11103 systemApp = (ps.pkg.applicationInfo.flags & 11104 ApplicationInfo.FLAG_SYSTEM) != 0; 11105 } 11106 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11107 } 11108 11109 // Check whether the newly-scanned package wants to define an already-defined perm 11110 int N = pkg.permissions.size(); 11111 for (int i = N-1; i >= 0; i--) { 11112 PackageParser.Permission perm = pkg.permissions.get(i); 11113 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11114 if (bp != null) { 11115 // If the defining package is signed with our cert, it's okay. This 11116 // also includes the "updating the same package" case, of course. 11117 // "updating same package" could also involve key-rotation. 11118 final boolean sigsOk; 11119 if (!bp.sourcePackage.equals(pkg.packageName) 11120 || !(bp.packageSetting instanceof PackageSetting) 11121 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11122 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11123 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11124 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11125 } else { 11126 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11127 } 11128 if (!sigsOk) { 11129 // If the owning package is the system itself, we log but allow 11130 // install to proceed; we fail the install on all other permission 11131 // redefinitions. 11132 if (!bp.sourcePackage.equals("android")) { 11133 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11134 + pkg.packageName + " attempting to redeclare permission " 11135 + perm.info.name + " already owned by " + bp.sourcePackage); 11136 res.origPermission = perm.info.name; 11137 res.origPackage = bp.sourcePackage; 11138 return; 11139 } else { 11140 Slog.w(TAG, "Package " + pkg.packageName 11141 + " attempting to redeclare system permission " 11142 + perm.info.name + "; ignoring new declaration"); 11143 pkg.permissions.remove(i); 11144 } 11145 } 11146 } 11147 } 11148 11149 } 11150 11151 if (systemApp && onExternal) { 11152 // Disable updates to system apps on sdcard 11153 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11154 "Cannot install updates to system apps on sdcard"); 11155 return; 11156 } 11157 11158 // Run dexopt before old package gets removed, to minimize time when app is not available 11159 int result = mPackageDexOptimizer 11160 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11161 false /* defer */, false /* inclDependencies */); 11162 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11163 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11164 return; 11165 } 11166 11167 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11168 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11169 return; 11170 } 11171 11172 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11173 11174 // Call with SCAN_NO_DEX, since dexopt has already been made 11175 if (replace) { 11176 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user, 11177 installerPackageName, volumeUuid, res); 11178 } else { 11179 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES 11180 | SCAN_NO_DEX, args.user, installerPackageName, volumeUuid, res); 11181 } 11182 synchronized (mPackages) { 11183 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11184 if (ps != null) { 11185 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11186 } 11187 } 11188 } 11189 11190 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11191 if (mIntentFilterVerifierComponent == null) { 11192 Slog.d(TAG, "No IntentFilter verification will not be done as " 11193 + "there is no IntentFilterVerifier available!"); 11194 return; 11195 } 11196 11197 final int verifierUid = getPackageUid( 11198 mIntentFilterVerifierComponent.getPackageName(), 11199 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11200 11201 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11202 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11203 msg.obj = pkg; 11204 msg.arg1 = userId; 11205 msg.arg2 = verifierUid; 11206 11207 mHandler.sendMessage(msg); 11208 } 11209 11210 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11211 PackageParser.Package pkg) { 11212 int size = pkg.activities.size(); 11213 if (size == 0) { 11214 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11215 return; 11216 } 11217 11218 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11219 + " Activities needs verification ..."); 11220 11221 final int verificationId = mIntentFilterVerificationToken++; 11222 int count = 0; 11223 final String packageName = pkg.packageName; 11224 ArrayList<String> allHosts = new ArrayList<>(); 11225 synchronized (mPackages) { 11226 for (PackageParser.Activity a : pkg.activities) { 11227 for (ActivityIntentInfo filter : a.intents) { 11228 boolean needFilterVerification = filter.needsVerification() && 11229 !filter.isVerified(); 11230 if (needFilterVerification && needNetworkVerificationLPr(filter)) { 11231 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11232 mIntentFilterVerifier.addOneIntentFilterVerification( 11233 verifierUid, userId, verificationId, filter, packageName); 11234 count++; 11235 } else { 11236 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11237 ArrayList<String> list = filter.getHostsList(); 11238 if (hasValidHosts(list)) { 11239 allHosts.addAll(list); 11240 } 11241 } 11242 } 11243 } 11244 } 11245 11246 if (count > 0) { 11247 mIntentFilterVerifier.startVerifications(userId); 11248 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11249 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11250 } else { 11251 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11252 if (allHosts.size() > 0 && hasDomainURLs(pkg) && 11253 mSettings.createIntentFilterVerificationIfNeededLPw( 11254 packageName, allHosts)) { 11255 scheduleWriteSettingsLocked(); 11256 } 11257 } 11258 } 11259 11260 private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) { 11261 final ComponentName cn = filter.activity.getComponentName(); 11262 final String packageName = cn.getPackageName(); 11263 11264 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11265 packageName); 11266 if (ivi == null) { 11267 return true; 11268 } 11269 int status = ivi.getStatus(); 11270 switch (status) { 11271 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11272 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11273 return true; 11274 11275 default: 11276 // Nothing to do 11277 return false; 11278 } 11279 } 11280 11281 private static boolean isMultiArch(PackageSetting ps) { 11282 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11283 } 11284 11285 private static boolean isMultiArch(ApplicationInfo info) { 11286 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11287 } 11288 11289 private static boolean isExternal(PackageParser.Package pkg) { 11290 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11291 } 11292 11293 private static boolean isExternal(PackageSetting ps) { 11294 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11295 } 11296 11297 private static boolean isExternal(ApplicationInfo info) { 11298 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11299 } 11300 11301 private static boolean isSystemApp(PackageParser.Package pkg) { 11302 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11303 } 11304 11305 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11306 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11307 } 11308 11309 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11310 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11311 } 11312 11313 private static boolean isSystemApp(PackageSetting ps) { 11314 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11315 } 11316 11317 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11318 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11319 } 11320 11321 private int packageFlagsToInstallFlags(PackageSetting ps) { 11322 int installFlags = 0; 11323 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11324 // This existing package was an external ASEC install when we have 11325 // the external flag without a UUID 11326 installFlags |= PackageManager.INSTALL_EXTERNAL; 11327 } 11328 if (ps.isForwardLocked()) { 11329 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11330 } 11331 return installFlags; 11332 } 11333 11334 private void deleteTempPackageFiles() { 11335 final FilenameFilter filter = new FilenameFilter() { 11336 public boolean accept(File dir, String name) { 11337 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11338 } 11339 }; 11340 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11341 file.delete(); 11342 } 11343 } 11344 11345 @Override 11346 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11347 int flags) { 11348 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11349 flags); 11350 } 11351 11352 @Override 11353 public void deletePackage(final String packageName, 11354 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11355 mContext.enforceCallingOrSelfPermission( 11356 android.Manifest.permission.DELETE_PACKAGES, null); 11357 final int uid = Binder.getCallingUid(); 11358 if (UserHandle.getUserId(uid) != userId) { 11359 mContext.enforceCallingPermission( 11360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11361 "deletePackage for user " + userId); 11362 } 11363 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11364 try { 11365 observer.onPackageDeleted(packageName, 11366 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11367 } catch (RemoteException re) { 11368 } 11369 return; 11370 } 11371 11372 boolean uninstallBlocked = false; 11373 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11374 int[] users = sUserManager.getUserIds(); 11375 for (int i = 0; i < users.length; ++i) { 11376 if (getBlockUninstallForUser(packageName, users[i])) { 11377 uninstallBlocked = true; 11378 break; 11379 } 11380 } 11381 } else { 11382 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11383 } 11384 if (uninstallBlocked) { 11385 try { 11386 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11387 null); 11388 } catch (RemoteException re) { 11389 } 11390 return; 11391 } 11392 11393 if (DEBUG_REMOVE) { 11394 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11395 } 11396 // Queue up an async operation since the package deletion may take a little while. 11397 mHandler.post(new Runnable() { 11398 public void run() { 11399 mHandler.removeCallbacks(this); 11400 final int returnCode = deletePackageX(packageName, userId, flags); 11401 if (observer != null) { 11402 try { 11403 observer.onPackageDeleted(packageName, returnCode, null); 11404 } catch (RemoteException e) { 11405 Log.i(TAG, "Observer no longer exists."); 11406 } //end catch 11407 } //end if 11408 } //end run 11409 }); 11410 } 11411 11412 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11413 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11414 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11415 try { 11416 if (dpm != null) { 11417 if (dpm.isDeviceOwner(packageName)) { 11418 return true; 11419 } 11420 int[] users; 11421 if (userId == UserHandle.USER_ALL) { 11422 users = sUserManager.getUserIds(); 11423 } else { 11424 users = new int[]{userId}; 11425 } 11426 for (int i = 0; i < users.length; ++i) { 11427 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11428 return true; 11429 } 11430 } 11431 } 11432 } catch (RemoteException e) { 11433 } 11434 return false; 11435 } 11436 11437 /** 11438 * This method is an internal method that could be get invoked either 11439 * to delete an installed package or to clean up a failed installation. 11440 * After deleting an installed package, a broadcast is sent to notify any 11441 * listeners that the package has been installed. For cleaning up a failed 11442 * installation, the broadcast is not necessary since the package's 11443 * installation wouldn't have sent the initial broadcast either 11444 * The key steps in deleting a package are 11445 * deleting the package information in internal structures like mPackages, 11446 * deleting the packages base directories through installd 11447 * updating mSettings to reflect current status 11448 * persisting settings for later use 11449 * sending a broadcast if necessary 11450 */ 11451 private int deletePackageX(String packageName, int userId, int flags) { 11452 final PackageRemovedInfo info = new PackageRemovedInfo(); 11453 final boolean res; 11454 11455 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11456 ? UserHandle.ALL : new UserHandle(userId); 11457 11458 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11459 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11460 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11461 } 11462 11463 boolean removedForAllUsers = false; 11464 boolean systemUpdate = false; 11465 11466 // for the uninstall-updates case and restricted profiles, remember the per- 11467 // userhandle installed state 11468 int[] allUsers; 11469 boolean[] perUserInstalled; 11470 synchronized (mPackages) { 11471 PackageSetting ps = mSettings.mPackages.get(packageName); 11472 allUsers = sUserManager.getUserIds(); 11473 perUserInstalled = new boolean[allUsers.length]; 11474 for (int i = 0; i < allUsers.length; i++) { 11475 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11476 } 11477 } 11478 11479 synchronized (mInstallLock) { 11480 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11481 res = deletePackageLI(packageName, removeForUser, 11482 true, allUsers, perUserInstalled, 11483 flags | REMOVE_CHATTY, info, true); 11484 systemUpdate = info.isRemovedPackageSystemUpdate; 11485 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11486 removedForAllUsers = true; 11487 } 11488 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11489 + " removedForAllUsers=" + removedForAllUsers); 11490 } 11491 11492 if (res) { 11493 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11494 11495 // If the removed package was a system update, the old system package 11496 // was re-enabled; we need to broadcast this information 11497 if (systemUpdate) { 11498 Bundle extras = new Bundle(1); 11499 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11500 ? info.removedAppId : info.uid); 11501 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11502 11503 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11504 extras, null, null, null); 11505 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11506 extras, null, null, null); 11507 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11508 null, packageName, null, null); 11509 } 11510 } 11511 // Force a gc here. 11512 Runtime.getRuntime().gc(); 11513 // Delete the resources here after sending the broadcast to let 11514 // other processes clean up before deleting resources. 11515 if (info.args != null) { 11516 synchronized (mInstallLock) { 11517 info.args.doPostDeleteLI(true); 11518 } 11519 } 11520 11521 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11522 } 11523 11524 static class PackageRemovedInfo { 11525 String removedPackage; 11526 int uid = -1; 11527 int removedAppId = -1; 11528 int[] removedUsers = null; 11529 boolean isRemovedPackageSystemUpdate = false; 11530 // Clean up resources deleted packages. 11531 InstallArgs args = null; 11532 11533 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11534 Bundle extras = new Bundle(1); 11535 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11536 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11537 if (replacing) { 11538 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11539 } 11540 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11541 if (removedPackage != null) { 11542 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11543 extras, null, null, removedUsers); 11544 if (fullRemove && !replacing) { 11545 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11546 extras, null, null, removedUsers); 11547 } 11548 } 11549 if (removedAppId >= 0) { 11550 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11551 removedUsers); 11552 } 11553 } 11554 } 11555 11556 /* 11557 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11558 * flag is not set, the data directory is removed as well. 11559 * make sure this flag is set for partially installed apps. If not its meaningless to 11560 * delete a partially installed application. 11561 */ 11562 private void removePackageDataLI(PackageSetting ps, 11563 int[] allUserHandles, boolean[] perUserInstalled, 11564 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11565 String packageName = ps.name; 11566 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11567 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11568 // Retrieve object to delete permissions for shared user later on 11569 final PackageSetting deletedPs; 11570 // reader 11571 synchronized (mPackages) { 11572 deletedPs = mSettings.mPackages.get(packageName); 11573 if (outInfo != null) { 11574 outInfo.removedPackage = packageName; 11575 outInfo.removedUsers = deletedPs != null 11576 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11577 : null; 11578 } 11579 } 11580 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11581 removeDataDirsLI(packageName); 11582 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11583 } 11584 // writer 11585 synchronized (mPackages) { 11586 if (deletedPs != null) { 11587 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11588 if (outInfo != null) { 11589 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11590 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11591 } 11592 updatePermissionsLPw(deletedPs.name, null, 0); 11593 if (deletedPs.sharedUser != null) { 11594 // Remove permissions associated with package. Since runtime 11595 // permissions are per user we have to kill the removed package 11596 // or packages running under the shared user of the removed 11597 // package if revoking the permissions requested only by the removed 11598 // package is successful and this causes a change in gids. 11599 for (int userId : UserManagerService.getInstance().getUserIds()) { 11600 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11601 userId); 11602 if (userIdToKill == UserHandle.USER_ALL 11603 || userIdToKill >= UserHandle.USER_OWNER) { 11604 // If gids changed for this user, kill all affected packages. 11605 mHandler.post(new Runnable() { 11606 @Override 11607 public void run() { 11608 // This has to happen with no lock held. 11609 killSettingPackagesForUser(deletedPs, userIdToKill, 11610 KILL_APP_REASON_GIDS_CHANGED); 11611 } 11612 }); 11613 break; 11614 } 11615 } 11616 } 11617 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11618 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11619 } 11620 // make sure to preserve per-user disabled state if this removal was just 11621 // a downgrade of a system app to the factory package 11622 if (allUserHandles != null && perUserInstalled != null) { 11623 if (DEBUG_REMOVE) { 11624 Slog.d(TAG, "Propagating install state across downgrade"); 11625 } 11626 for (int i = 0; i < allUserHandles.length; i++) { 11627 if (DEBUG_REMOVE) { 11628 Slog.d(TAG, " user " + allUserHandles[i] 11629 + " => " + perUserInstalled[i]); 11630 } 11631 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11632 } 11633 } 11634 } 11635 // can downgrade to reader 11636 if (writeSettings) { 11637 // Save settings now 11638 mSettings.writeLPr(); 11639 } 11640 } 11641 if (outInfo != null) { 11642 // A user ID was deleted here. Go through all users and remove it 11643 // from KeyStore. 11644 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11645 } 11646 } 11647 11648 static boolean locationIsPrivileged(File path) { 11649 try { 11650 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11651 .getCanonicalPath(); 11652 return path.getCanonicalPath().startsWith(privilegedAppDir); 11653 } catch (IOException e) { 11654 Slog.e(TAG, "Unable to access code path " + path); 11655 } 11656 return false; 11657 } 11658 11659 /* 11660 * Tries to delete system package. 11661 */ 11662 private boolean deleteSystemPackageLI(PackageSetting newPs, 11663 int[] allUserHandles, boolean[] perUserInstalled, 11664 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11665 final boolean applyUserRestrictions 11666 = (allUserHandles != null) && (perUserInstalled != null); 11667 PackageSetting disabledPs = null; 11668 // Confirm if the system package has been updated 11669 // An updated system app can be deleted. This will also have to restore 11670 // the system pkg from system partition 11671 // reader 11672 synchronized (mPackages) { 11673 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11674 } 11675 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11676 + " disabledPs=" + disabledPs); 11677 if (disabledPs == null) { 11678 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11679 return false; 11680 } else if (DEBUG_REMOVE) { 11681 Slog.d(TAG, "Deleting system pkg from data partition"); 11682 } 11683 if (DEBUG_REMOVE) { 11684 if (applyUserRestrictions) { 11685 Slog.d(TAG, "Remembering install states:"); 11686 for (int i = 0; i < allUserHandles.length; i++) { 11687 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11688 } 11689 } 11690 } 11691 // Delete the updated package 11692 outInfo.isRemovedPackageSystemUpdate = true; 11693 if (disabledPs.versionCode < newPs.versionCode) { 11694 // Delete data for downgrades 11695 flags &= ~PackageManager.DELETE_KEEP_DATA; 11696 } else { 11697 // Preserve data by setting flag 11698 flags |= PackageManager.DELETE_KEEP_DATA; 11699 } 11700 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11701 allUserHandles, perUserInstalled, outInfo, writeSettings); 11702 if (!ret) { 11703 return false; 11704 } 11705 // writer 11706 synchronized (mPackages) { 11707 // Reinstate the old system package 11708 mSettings.enableSystemPackageLPw(newPs.name); 11709 // Remove any native libraries from the upgraded package. 11710 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11711 } 11712 // Install the system package 11713 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11714 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11715 if (locationIsPrivileged(disabledPs.codePath)) { 11716 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11717 } 11718 11719 final PackageParser.Package newPkg; 11720 try { 11721 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11722 } catch (PackageManagerException e) { 11723 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11724 return false; 11725 } 11726 11727 // writer 11728 synchronized (mPackages) { 11729 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11730 updatePermissionsLPw(newPkg.packageName, newPkg, 11731 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11732 if (applyUserRestrictions) { 11733 if (DEBUG_REMOVE) { 11734 Slog.d(TAG, "Propagating install state across reinstall"); 11735 } 11736 for (int i = 0; i < allUserHandles.length; i++) { 11737 if (DEBUG_REMOVE) { 11738 Slog.d(TAG, " user " + allUserHandles[i] 11739 + " => " + perUserInstalled[i]); 11740 } 11741 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11742 } 11743 // Regardless of writeSettings we need to ensure that this restriction 11744 // state propagation is persisted 11745 mSettings.writeAllUsersPackageRestrictionsLPr(); 11746 } 11747 // can downgrade to reader here 11748 if (writeSettings) { 11749 mSettings.writeLPr(); 11750 } 11751 } 11752 return true; 11753 } 11754 11755 private boolean deleteInstalledPackageLI(PackageSetting ps, 11756 boolean deleteCodeAndResources, int flags, 11757 int[] allUserHandles, boolean[] perUserInstalled, 11758 PackageRemovedInfo outInfo, boolean writeSettings) { 11759 if (outInfo != null) { 11760 outInfo.uid = ps.appId; 11761 } 11762 11763 // Delete package data from internal structures and also remove data if flag is set 11764 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11765 11766 // Delete application code and resources 11767 if (deleteCodeAndResources && (outInfo != null)) { 11768 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11769 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11770 getAppDexInstructionSets(ps)); 11771 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11772 } 11773 return true; 11774 } 11775 11776 @Override 11777 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11778 int userId) { 11779 mContext.enforceCallingOrSelfPermission( 11780 android.Manifest.permission.DELETE_PACKAGES, null); 11781 synchronized (mPackages) { 11782 PackageSetting ps = mSettings.mPackages.get(packageName); 11783 if (ps == null) { 11784 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11785 return false; 11786 } 11787 if (!ps.getInstalled(userId)) { 11788 // Can't block uninstall for an app that is not installed or enabled. 11789 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11790 return false; 11791 } 11792 ps.setBlockUninstall(blockUninstall, userId); 11793 mSettings.writePackageRestrictionsLPr(userId); 11794 } 11795 return true; 11796 } 11797 11798 @Override 11799 public boolean getBlockUninstallForUser(String packageName, int userId) { 11800 synchronized (mPackages) { 11801 PackageSetting ps = mSettings.mPackages.get(packageName); 11802 if (ps == null) { 11803 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11804 return false; 11805 } 11806 return ps.getBlockUninstall(userId); 11807 } 11808 } 11809 11810 /* 11811 * This method handles package deletion in general 11812 */ 11813 private boolean deletePackageLI(String packageName, UserHandle user, 11814 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11815 int flags, PackageRemovedInfo outInfo, 11816 boolean writeSettings) { 11817 if (packageName == null) { 11818 Slog.w(TAG, "Attempt to delete null packageName."); 11819 return false; 11820 } 11821 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11822 PackageSetting ps; 11823 boolean dataOnly = false; 11824 int removeUser = -1; 11825 int appId = -1; 11826 synchronized (mPackages) { 11827 ps = mSettings.mPackages.get(packageName); 11828 if (ps == null) { 11829 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11830 return false; 11831 } 11832 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11833 && user.getIdentifier() != UserHandle.USER_ALL) { 11834 // The caller is asking that the package only be deleted for a single 11835 // user. To do this, we just mark its uninstalled state and delete 11836 // its data. If this is a system app, we only allow this to happen if 11837 // they have set the special DELETE_SYSTEM_APP which requests different 11838 // semantics than normal for uninstalling system apps. 11839 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11840 ps.setUserState(user.getIdentifier(), 11841 COMPONENT_ENABLED_STATE_DEFAULT, 11842 false, //installed 11843 true, //stopped 11844 true, //notLaunched 11845 false, //hidden 11846 null, null, null, 11847 false, // blockUninstall 11848 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 11849 if (!isSystemApp(ps)) { 11850 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11851 // Other user still have this package installed, so all 11852 // we need to do is clear this user's data and save that 11853 // it is uninstalled. 11854 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11855 removeUser = user.getIdentifier(); 11856 appId = ps.appId; 11857 mSettings.writePackageRestrictionsLPr(removeUser); 11858 } else { 11859 // We need to set it back to 'installed' so the uninstall 11860 // broadcasts will be sent correctly. 11861 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11862 ps.setInstalled(true, user.getIdentifier()); 11863 } 11864 } else { 11865 // This is a system app, so we assume that the 11866 // other users still have this package installed, so all 11867 // we need to do is clear this user's data and save that 11868 // it is uninstalled. 11869 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11870 removeUser = user.getIdentifier(); 11871 appId = ps.appId; 11872 mSettings.writePackageRestrictionsLPr(removeUser); 11873 } 11874 } 11875 } 11876 11877 if (removeUser >= 0) { 11878 // From above, we determined that we are deleting this only 11879 // for a single user. Continue the work here. 11880 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11881 if (outInfo != null) { 11882 outInfo.removedPackage = packageName; 11883 outInfo.removedAppId = appId; 11884 outInfo.removedUsers = new int[] {removeUser}; 11885 } 11886 mInstaller.clearUserData(packageName, removeUser); 11887 removeKeystoreDataIfNeeded(removeUser, appId); 11888 schedulePackageCleaning(packageName, removeUser, false); 11889 return true; 11890 } 11891 11892 if (dataOnly) { 11893 // Delete application data first 11894 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11895 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11896 return true; 11897 } 11898 11899 boolean ret = false; 11900 if (isSystemApp(ps)) { 11901 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11902 // When an updated system application is deleted we delete the existing resources as well and 11903 // fall back to existing code in system partition 11904 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11905 flags, outInfo, writeSettings); 11906 } else { 11907 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11908 // Kill application pre-emptively especially for apps on sd. 11909 killApplication(packageName, ps.appId, "uninstall pkg"); 11910 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11911 allUserHandles, perUserInstalled, 11912 outInfo, writeSettings); 11913 } 11914 11915 return ret; 11916 } 11917 11918 private final class ClearStorageConnection implements ServiceConnection { 11919 IMediaContainerService mContainerService; 11920 11921 @Override 11922 public void onServiceConnected(ComponentName name, IBinder service) { 11923 synchronized (this) { 11924 mContainerService = IMediaContainerService.Stub.asInterface(service); 11925 notifyAll(); 11926 } 11927 } 11928 11929 @Override 11930 public void onServiceDisconnected(ComponentName name) { 11931 } 11932 } 11933 11934 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11935 final boolean mounted; 11936 if (Environment.isExternalStorageEmulated()) { 11937 mounted = true; 11938 } else { 11939 final String status = Environment.getExternalStorageState(); 11940 11941 mounted = status.equals(Environment.MEDIA_MOUNTED) 11942 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11943 } 11944 11945 if (!mounted) { 11946 return; 11947 } 11948 11949 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11950 int[] users; 11951 if (userId == UserHandle.USER_ALL) { 11952 users = sUserManager.getUserIds(); 11953 } else { 11954 users = new int[] { userId }; 11955 } 11956 final ClearStorageConnection conn = new ClearStorageConnection(); 11957 if (mContext.bindServiceAsUser( 11958 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11959 try { 11960 for (int curUser : users) { 11961 long timeout = SystemClock.uptimeMillis() + 5000; 11962 synchronized (conn) { 11963 long now = SystemClock.uptimeMillis(); 11964 while (conn.mContainerService == null && now < timeout) { 11965 try { 11966 conn.wait(timeout - now); 11967 } catch (InterruptedException e) { 11968 } 11969 } 11970 } 11971 if (conn.mContainerService == null) { 11972 return; 11973 } 11974 11975 final UserEnvironment userEnv = new UserEnvironment(curUser); 11976 clearDirectory(conn.mContainerService, 11977 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11978 if (allData) { 11979 clearDirectory(conn.mContainerService, 11980 userEnv.buildExternalStorageAppDataDirs(packageName)); 11981 clearDirectory(conn.mContainerService, 11982 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11983 } 11984 } 11985 } finally { 11986 mContext.unbindService(conn); 11987 } 11988 } 11989 } 11990 11991 @Override 11992 public void clearApplicationUserData(final String packageName, 11993 final IPackageDataObserver observer, final int userId) { 11994 mContext.enforceCallingOrSelfPermission( 11995 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11996 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11997 // Queue up an async operation since the package deletion may take a little while. 11998 mHandler.post(new Runnable() { 11999 public void run() { 12000 mHandler.removeCallbacks(this); 12001 final boolean succeeded; 12002 synchronized (mInstallLock) { 12003 succeeded = clearApplicationUserDataLI(packageName, userId); 12004 } 12005 clearExternalStorageDataSync(packageName, userId, true); 12006 if (succeeded) { 12007 // invoke DeviceStorageMonitor's update method to clear any notifications 12008 DeviceStorageMonitorInternal 12009 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12010 if (dsm != null) { 12011 dsm.checkMemory(); 12012 } 12013 } 12014 if(observer != null) { 12015 try { 12016 observer.onRemoveCompleted(packageName, succeeded); 12017 } catch (RemoteException e) { 12018 Log.i(TAG, "Observer no longer exists."); 12019 } 12020 } //end if observer 12021 } //end run 12022 }); 12023 } 12024 12025 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12026 if (packageName == null) { 12027 Slog.w(TAG, "Attempt to delete null packageName."); 12028 return false; 12029 } 12030 12031 // Try finding details about the requested package 12032 PackageParser.Package pkg; 12033 synchronized (mPackages) { 12034 pkg = mPackages.get(packageName); 12035 if (pkg == null) { 12036 final PackageSetting ps = mSettings.mPackages.get(packageName); 12037 if (ps != null) { 12038 pkg = ps.pkg; 12039 } 12040 } 12041 } 12042 12043 if (pkg == null) { 12044 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12045 } 12046 12047 // Always delete data directories for package, even if we found no other 12048 // record of app. This helps users recover from UID mismatches without 12049 // resorting to a full data wipe. 12050 int retCode = mInstaller.clearUserData(packageName, userId); 12051 if (retCode < 0) { 12052 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12053 return false; 12054 } 12055 12056 if (pkg == null) { 12057 return false; 12058 } 12059 12060 if (pkg != null && pkg.applicationInfo != null) { 12061 final int appId = pkg.applicationInfo.uid; 12062 removeKeystoreDataIfNeeded(userId, appId); 12063 } 12064 12065 // Create a native library symlink only if we have native libraries 12066 // and if the native libraries are 32 bit libraries. We do not provide 12067 // this symlink for 64 bit libraries. 12068 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12069 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12070 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12071 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 12072 Slog.w(TAG, "Failed linking native library dir"); 12073 return false; 12074 } 12075 } 12076 12077 return true; 12078 } 12079 12080 /** 12081 * Remove entries from the keystore daemon. Will only remove it if the 12082 * {@code appId} is valid. 12083 */ 12084 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12085 if (appId < 0) { 12086 return; 12087 } 12088 12089 final KeyStore keyStore = KeyStore.getInstance(); 12090 if (keyStore != null) { 12091 if (userId == UserHandle.USER_ALL) { 12092 for (final int individual : sUserManager.getUserIds()) { 12093 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12094 } 12095 } else { 12096 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12097 } 12098 } else { 12099 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12100 } 12101 } 12102 12103 @Override 12104 public void deleteApplicationCacheFiles(final String packageName, 12105 final IPackageDataObserver observer) { 12106 mContext.enforceCallingOrSelfPermission( 12107 android.Manifest.permission.DELETE_CACHE_FILES, null); 12108 // Queue up an async operation since the package deletion may take a little while. 12109 final int userId = UserHandle.getCallingUserId(); 12110 mHandler.post(new Runnable() { 12111 public void run() { 12112 mHandler.removeCallbacks(this); 12113 final boolean succeded; 12114 synchronized (mInstallLock) { 12115 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12116 } 12117 clearExternalStorageDataSync(packageName, userId, false); 12118 if(observer != null) { 12119 try { 12120 observer.onRemoveCompleted(packageName, succeded); 12121 } catch (RemoteException e) { 12122 Log.i(TAG, "Observer no longer exists."); 12123 } 12124 } //end if observer 12125 } //end run 12126 }); 12127 } 12128 12129 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12130 if (packageName == null) { 12131 Slog.w(TAG, "Attempt to delete null packageName."); 12132 return false; 12133 } 12134 PackageParser.Package p; 12135 synchronized (mPackages) { 12136 p = mPackages.get(packageName); 12137 } 12138 if (p == null) { 12139 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12140 return false; 12141 } 12142 final ApplicationInfo applicationInfo = p.applicationInfo; 12143 if (applicationInfo == null) { 12144 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12145 return false; 12146 } 12147 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 12148 if (retCode < 0) { 12149 Slog.w(TAG, "Couldn't remove cache files for package: " 12150 + packageName + " u" + userId); 12151 return false; 12152 } 12153 return true; 12154 } 12155 12156 @Override 12157 public void getPackageSizeInfo(final String packageName, int userHandle, 12158 final IPackageStatsObserver observer) { 12159 mContext.enforceCallingOrSelfPermission( 12160 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12161 if (packageName == null) { 12162 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12163 } 12164 12165 PackageStats stats = new PackageStats(packageName, userHandle); 12166 12167 /* 12168 * Queue up an async operation since the package measurement may take a 12169 * little while. 12170 */ 12171 Message msg = mHandler.obtainMessage(INIT_COPY); 12172 msg.obj = new MeasureParams(stats, observer); 12173 mHandler.sendMessage(msg); 12174 } 12175 12176 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12177 PackageStats pStats) { 12178 if (packageName == null) { 12179 Slog.w(TAG, "Attempt to get size of null packageName."); 12180 return false; 12181 } 12182 PackageParser.Package p; 12183 boolean dataOnly = false; 12184 String libDirRoot = null; 12185 String asecPath = null; 12186 PackageSetting ps = null; 12187 synchronized (mPackages) { 12188 p = mPackages.get(packageName); 12189 ps = mSettings.mPackages.get(packageName); 12190 if(p == null) { 12191 dataOnly = true; 12192 if((ps == null) || (ps.pkg == null)) { 12193 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12194 return false; 12195 } 12196 p = ps.pkg; 12197 } 12198 if (ps != null) { 12199 libDirRoot = ps.legacyNativeLibraryPathString; 12200 } 12201 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12202 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12203 if (secureContainerId != null) { 12204 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12205 } 12206 } 12207 } 12208 String publicSrcDir = null; 12209 if(!dataOnly) { 12210 final ApplicationInfo applicationInfo = p.applicationInfo; 12211 if (applicationInfo == null) { 12212 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12213 return false; 12214 } 12215 if (p.isForwardLocked()) { 12216 publicSrcDir = applicationInfo.getBaseResourcePath(); 12217 } 12218 } 12219 // TODO: extend to measure size of split APKs 12220 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12221 // not just the first level. 12222 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12223 // just the primary. 12224 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12225 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 12226 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12227 if (res < 0) { 12228 return false; 12229 } 12230 12231 // Fix-up for forward-locked applications in ASEC containers. 12232 if (!isExternal(p)) { 12233 pStats.codeSize += pStats.externalCodeSize; 12234 pStats.externalCodeSize = 0L; 12235 } 12236 12237 return true; 12238 } 12239 12240 12241 @Override 12242 public void addPackageToPreferred(String packageName) { 12243 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12244 } 12245 12246 @Override 12247 public void removePackageFromPreferred(String packageName) { 12248 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12249 } 12250 12251 @Override 12252 public List<PackageInfo> getPreferredPackages(int flags) { 12253 return new ArrayList<PackageInfo>(); 12254 } 12255 12256 private int getUidTargetSdkVersionLockedLPr(int uid) { 12257 Object obj = mSettings.getUserIdLPr(uid); 12258 if (obj instanceof SharedUserSetting) { 12259 final SharedUserSetting sus = (SharedUserSetting) obj; 12260 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12261 final Iterator<PackageSetting> it = sus.packages.iterator(); 12262 while (it.hasNext()) { 12263 final PackageSetting ps = it.next(); 12264 if (ps.pkg != null) { 12265 int v = ps.pkg.applicationInfo.targetSdkVersion; 12266 if (v < vers) vers = v; 12267 } 12268 } 12269 return vers; 12270 } else if (obj instanceof PackageSetting) { 12271 final PackageSetting ps = (PackageSetting) obj; 12272 if (ps.pkg != null) { 12273 return ps.pkg.applicationInfo.targetSdkVersion; 12274 } 12275 } 12276 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12277 } 12278 12279 @Override 12280 public void addPreferredActivity(IntentFilter filter, int match, 12281 ComponentName[] set, ComponentName activity, int userId) { 12282 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12283 "Adding preferred"); 12284 } 12285 12286 private void addPreferredActivityInternal(IntentFilter filter, int match, 12287 ComponentName[] set, ComponentName activity, boolean always, int userId, 12288 String opname) { 12289 // writer 12290 int callingUid = Binder.getCallingUid(); 12291 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12292 if (filter.countActions() == 0) { 12293 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12294 return; 12295 } 12296 synchronized (mPackages) { 12297 if (mContext.checkCallingOrSelfPermission( 12298 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12299 != PackageManager.PERMISSION_GRANTED) { 12300 if (getUidTargetSdkVersionLockedLPr(callingUid) 12301 < Build.VERSION_CODES.FROYO) { 12302 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12303 + callingUid); 12304 return; 12305 } 12306 mContext.enforceCallingOrSelfPermission( 12307 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12308 } 12309 12310 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12311 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12312 + userId + ":"); 12313 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12314 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12315 scheduleWritePackageRestrictionsLocked(userId); 12316 } 12317 } 12318 12319 @Override 12320 public void replacePreferredActivity(IntentFilter filter, int match, 12321 ComponentName[] set, ComponentName activity, int userId) { 12322 if (filter.countActions() != 1) { 12323 throw new IllegalArgumentException( 12324 "replacePreferredActivity expects filter to have only 1 action."); 12325 } 12326 if (filter.countDataAuthorities() != 0 12327 || filter.countDataPaths() != 0 12328 || filter.countDataSchemes() > 1 12329 || filter.countDataTypes() != 0) { 12330 throw new IllegalArgumentException( 12331 "replacePreferredActivity expects filter to have no data authorities, " + 12332 "paths, or types; and at most one scheme."); 12333 } 12334 12335 final int callingUid = Binder.getCallingUid(); 12336 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12337 synchronized (mPackages) { 12338 if (mContext.checkCallingOrSelfPermission( 12339 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12340 != PackageManager.PERMISSION_GRANTED) { 12341 if (getUidTargetSdkVersionLockedLPr(callingUid) 12342 < Build.VERSION_CODES.FROYO) { 12343 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12344 + Binder.getCallingUid()); 12345 return; 12346 } 12347 mContext.enforceCallingOrSelfPermission( 12348 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12349 } 12350 12351 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12352 if (pir != null) { 12353 // Get all of the existing entries that exactly match this filter. 12354 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12355 if (existing != null && existing.size() == 1) { 12356 PreferredActivity cur = existing.get(0); 12357 if (DEBUG_PREFERRED) { 12358 Slog.i(TAG, "Checking replace of preferred:"); 12359 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12360 if (!cur.mPref.mAlways) { 12361 Slog.i(TAG, " -- CUR; not mAlways!"); 12362 } else { 12363 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12364 Slog.i(TAG, " -- CUR: mSet=" 12365 + Arrays.toString(cur.mPref.mSetComponents)); 12366 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12367 Slog.i(TAG, " -- NEW: mMatch=" 12368 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12369 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12370 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12371 } 12372 } 12373 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12374 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12375 && cur.mPref.sameSet(set)) { 12376 // Setting the preferred activity to what it happens to be already 12377 if (DEBUG_PREFERRED) { 12378 Slog.i(TAG, "Replacing with same preferred activity " 12379 + cur.mPref.mShortComponent + " for user " 12380 + userId + ":"); 12381 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12382 } 12383 return; 12384 } 12385 } 12386 12387 if (existing != null) { 12388 if (DEBUG_PREFERRED) { 12389 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12390 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12391 } 12392 for (int i = 0; i < existing.size(); i++) { 12393 PreferredActivity pa = existing.get(i); 12394 if (DEBUG_PREFERRED) { 12395 Slog.i(TAG, "Removing existing preferred activity " 12396 + pa.mPref.mComponent + ":"); 12397 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12398 } 12399 pir.removeFilter(pa); 12400 } 12401 } 12402 } 12403 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12404 "Replacing preferred"); 12405 } 12406 } 12407 12408 @Override 12409 public void clearPackagePreferredActivities(String packageName) { 12410 final int uid = Binder.getCallingUid(); 12411 // writer 12412 synchronized (mPackages) { 12413 PackageParser.Package pkg = mPackages.get(packageName); 12414 if (pkg == null || pkg.applicationInfo.uid != uid) { 12415 if (mContext.checkCallingOrSelfPermission( 12416 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12417 != PackageManager.PERMISSION_GRANTED) { 12418 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12419 < Build.VERSION_CODES.FROYO) { 12420 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12421 + Binder.getCallingUid()); 12422 return; 12423 } 12424 mContext.enforceCallingOrSelfPermission( 12425 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12426 } 12427 } 12428 12429 int user = UserHandle.getCallingUserId(); 12430 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12431 scheduleWritePackageRestrictionsLocked(user); 12432 } 12433 } 12434 } 12435 12436 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12437 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12438 ArrayList<PreferredActivity> removed = null; 12439 boolean changed = false; 12440 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12441 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12442 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12443 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12444 continue; 12445 } 12446 Iterator<PreferredActivity> it = pir.filterIterator(); 12447 while (it.hasNext()) { 12448 PreferredActivity pa = it.next(); 12449 // Mark entry for removal only if it matches the package name 12450 // and the entry is of type "always". 12451 if (packageName == null || 12452 (pa.mPref.mComponent.getPackageName().equals(packageName) 12453 && pa.mPref.mAlways)) { 12454 if (removed == null) { 12455 removed = new ArrayList<PreferredActivity>(); 12456 } 12457 removed.add(pa); 12458 } 12459 } 12460 if (removed != null) { 12461 for (int j=0; j<removed.size(); j++) { 12462 PreferredActivity pa = removed.get(j); 12463 pir.removeFilter(pa); 12464 } 12465 changed = true; 12466 } 12467 } 12468 return changed; 12469 } 12470 12471 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12472 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12473 if (userId == UserHandle.USER_ALL) { 12474 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12475 for (int oneUserId : sUserManager.getUserIds()) { 12476 scheduleWritePackageRestrictionsLocked(oneUserId); 12477 } 12478 } else { 12479 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12480 scheduleWritePackageRestrictionsLocked(userId); 12481 } 12482 } 12483 12484 @Override 12485 public void resetPreferredActivities(int userId) { 12486 /* TODO: Actually use userId. Why is it being passed in? */ 12487 mContext.enforceCallingOrSelfPermission( 12488 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12489 // writer 12490 synchronized (mPackages) { 12491 int user = UserHandle.getCallingUserId(); 12492 clearPackagePreferredActivitiesLPw(null, user); 12493 mSettings.readDefaultPreferredAppsLPw(this, user); 12494 scheduleWritePackageRestrictionsLocked(user); 12495 } 12496 } 12497 12498 @Override 12499 public int getPreferredActivities(List<IntentFilter> outFilters, 12500 List<ComponentName> outActivities, String packageName) { 12501 12502 int num = 0; 12503 final int userId = UserHandle.getCallingUserId(); 12504 // reader 12505 synchronized (mPackages) { 12506 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12507 if (pir != null) { 12508 final Iterator<PreferredActivity> it = pir.filterIterator(); 12509 while (it.hasNext()) { 12510 final PreferredActivity pa = it.next(); 12511 if (packageName == null 12512 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12513 && pa.mPref.mAlways)) { 12514 if (outFilters != null) { 12515 outFilters.add(new IntentFilter(pa)); 12516 } 12517 if (outActivities != null) { 12518 outActivities.add(pa.mPref.mComponent); 12519 } 12520 } 12521 } 12522 } 12523 } 12524 12525 return num; 12526 } 12527 12528 @Override 12529 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12530 int userId) { 12531 int callingUid = Binder.getCallingUid(); 12532 if (callingUid != Process.SYSTEM_UID) { 12533 throw new SecurityException( 12534 "addPersistentPreferredActivity can only be run by the system"); 12535 } 12536 if (filter.countActions() == 0) { 12537 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12538 return; 12539 } 12540 synchronized (mPackages) { 12541 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12542 " :"); 12543 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12544 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12545 new PersistentPreferredActivity(filter, activity)); 12546 scheduleWritePackageRestrictionsLocked(userId); 12547 } 12548 } 12549 12550 @Override 12551 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12552 int callingUid = Binder.getCallingUid(); 12553 if (callingUid != Process.SYSTEM_UID) { 12554 throw new SecurityException( 12555 "clearPackagePersistentPreferredActivities can only be run by the system"); 12556 } 12557 ArrayList<PersistentPreferredActivity> removed = null; 12558 boolean changed = false; 12559 synchronized (mPackages) { 12560 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12561 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12562 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12563 .valueAt(i); 12564 if (userId != thisUserId) { 12565 continue; 12566 } 12567 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12568 while (it.hasNext()) { 12569 PersistentPreferredActivity ppa = it.next(); 12570 // Mark entry for removal only if it matches the package name. 12571 if (ppa.mComponent.getPackageName().equals(packageName)) { 12572 if (removed == null) { 12573 removed = new ArrayList<PersistentPreferredActivity>(); 12574 } 12575 removed.add(ppa); 12576 } 12577 } 12578 if (removed != null) { 12579 for (int j=0; j<removed.size(); j++) { 12580 PersistentPreferredActivity ppa = removed.get(j); 12581 ppir.removeFilter(ppa); 12582 } 12583 changed = true; 12584 } 12585 } 12586 12587 if (changed) { 12588 scheduleWritePackageRestrictionsLocked(userId); 12589 } 12590 } 12591 } 12592 12593 /** 12594 * Non-Binder method, support for the backup/restore mechanism: write the 12595 * full set of preferred activities in its canonical XML format. Returns true 12596 * on success; false otherwise. 12597 */ 12598 @Override 12599 public byte[] getPreferredActivityBackup(int userId) { 12600 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12601 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12602 } 12603 12604 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12605 try { 12606 final XmlSerializer serializer = new FastXmlSerializer(); 12607 serializer.setOutput(dataStream, "utf-8"); 12608 serializer.startDocument(null, true); 12609 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12610 12611 synchronized (mPackages) { 12612 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12613 } 12614 12615 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12616 serializer.endDocument(); 12617 serializer.flush(); 12618 } catch (Exception e) { 12619 if (DEBUG_BACKUP) { 12620 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12621 } 12622 return null; 12623 } 12624 12625 return dataStream.toByteArray(); 12626 } 12627 12628 @Override 12629 public void restorePreferredActivities(byte[] backup, int userId) { 12630 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12631 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12632 } 12633 12634 try { 12635 final XmlPullParser parser = Xml.newPullParser(); 12636 parser.setInput(new ByteArrayInputStream(backup), null); 12637 12638 int type; 12639 while ((type = parser.next()) != XmlPullParser.START_TAG 12640 && type != XmlPullParser.END_DOCUMENT) { 12641 } 12642 if (type != XmlPullParser.START_TAG) { 12643 // oops didn't find a start tag?! 12644 if (DEBUG_BACKUP) { 12645 Slog.e(TAG, "Didn't find start tag during restore"); 12646 } 12647 return; 12648 } 12649 12650 // this is supposed to be TAG_PREFERRED_BACKUP 12651 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12652 if (DEBUG_BACKUP) { 12653 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12654 } 12655 return; 12656 } 12657 12658 // skip interfering stuff, then we're aligned with the backing implementation 12659 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12660 synchronized (mPackages) { 12661 mSettings.readPreferredActivitiesLPw(parser, userId); 12662 } 12663 } catch (Exception e) { 12664 if (DEBUG_BACKUP) { 12665 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12666 } 12667 } 12668 } 12669 12670 @Override 12671 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12672 int sourceUserId, int targetUserId, int flags) { 12673 mContext.enforceCallingOrSelfPermission( 12674 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12675 int callingUid = Binder.getCallingUid(); 12676 enforceOwnerRights(ownerPackage, callingUid); 12677 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12678 if (intentFilter.countActions() == 0) { 12679 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12680 return; 12681 } 12682 synchronized (mPackages) { 12683 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12684 ownerPackage, targetUserId, flags); 12685 CrossProfileIntentResolver resolver = 12686 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12687 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12688 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12689 if (existing != null) { 12690 int size = existing.size(); 12691 for (int i = 0; i < size; i++) { 12692 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12693 return; 12694 } 12695 } 12696 } 12697 resolver.addFilter(newFilter); 12698 scheduleWritePackageRestrictionsLocked(sourceUserId); 12699 } 12700 } 12701 12702 @Override 12703 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12704 mContext.enforceCallingOrSelfPermission( 12705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12706 int callingUid = Binder.getCallingUid(); 12707 enforceOwnerRights(ownerPackage, callingUid); 12708 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12709 synchronized (mPackages) { 12710 CrossProfileIntentResolver resolver = 12711 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12712 ArraySet<CrossProfileIntentFilter> set = 12713 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12714 for (CrossProfileIntentFilter filter : set) { 12715 if (filter.getOwnerPackage().equals(ownerPackage)) { 12716 resolver.removeFilter(filter); 12717 } 12718 } 12719 scheduleWritePackageRestrictionsLocked(sourceUserId); 12720 } 12721 } 12722 12723 // Enforcing that callingUid is owning pkg on userId 12724 private void enforceOwnerRights(String pkg, int callingUid) { 12725 // The system owns everything. 12726 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12727 return; 12728 } 12729 int callingUserId = UserHandle.getUserId(callingUid); 12730 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12731 if (pi == null) { 12732 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12733 + callingUserId); 12734 } 12735 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12736 throw new SecurityException("Calling uid " + callingUid 12737 + " does not own package " + pkg); 12738 } 12739 } 12740 12741 @Override 12742 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12743 Intent intent = new Intent(Intent.ACTION_MAIN); 12744 intent.addCategory(Intent.CATEGORY_HOME); 12745 12746 final int callingUserId = UserHandle.getCallingUserId(); 12747 List<ResolveInfo> list = queryIntentActivities(intent, null, 12748 PackageManager.GET_META_DATA, callingUserId); 12749 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12750 true, false, false, callingUserId); 12751 12752 allHomeCandidates.clear(); 12753 if (list != null) { 12754 for (ResolveInfo ri : list) { 12755 allHomeCandidates.add(ri); 12756 } 12757 } 12758 return (preferred == null || preferred.activityInfo == null) 12759 ? null 12760 : new ComponentName(preferred.activityInfo.packageName, 12761 preferred.activityInfo.name); 12762 } 12763 12764 @Override 12765 public void setApplicationEnabledSetting(String appPackageName, 12766 int newState, int flags, int userId, String callingPackage) { 12767 if (!sUserManager.exists(userId)) return; 12768 if (callingPackage == null) { 12769 callingPackage = Integer.toString(Binder.getCallingUid()); 12770 } 12771 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12772 } 12773 12774 @Override 12775 public void setComponentEnabledSetting(ComponentName componentName, 12776 int newState, int flags, int userId) { 12777 if (!sUserManager.exists(userId)) return; 12778 setEnabledSetting(componentName.getPackageName(), 12779 componentName.getClassName(), newState, flags, userId, null); 12780 } 12781 12782 private void setEnabledSetting(final String packageName, String className, int newState, 12783 final int flags, int userId, String callingPackage) { 12784 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12785 || newState == COMPONENT_ENABLED_STATE_ENABLED 12786 || newState == COMPONENT_ENABLED_STATE_DISABLED 12787 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12788 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12789 throw new IllegalArgumentException("Invalid new component state: " 12790 + newState); 12791 } 12792 PackageSetting pkgSetting; 12793 final int uid = Binder.getCallingUid(); 12794 final int permission = mContext.checkCallingOrSelfPermission( 12795 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12796 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12797 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12798 boolean sendNow = false; 12799 boolean isApp = (className == null); 12800 String componentName = isApp ? packageName : className; 12801 int packageUid = -1; 12802 ArrayList<String> components; 12803 12804 // writer 12805 synchronized (mPackages) { 12806 pkgSetting = mSettings.mPackages.get(packageName); 12807 if (pkgSetting == null) { 12808 if (className == null) { 12809 throw new IllegalArgumentException( 12810 "Unknown package: " + packageName); 12811 } 12812 throw new IllegalArgumentException( 12813 "Unknown component: " + packageName 12814 + "/" + className); 12815 } 12816 // Allow root and verify that userId is not being specified by a different user 12817 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12818 throw new SecurityException( 12819 "Permission Denial: attempt to change component state from pid=" 12820 + Binder.getCallingPid() 12821 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12822 } 12823 if (className == null) { 12824 // We're dealing with an application/package level state change 12825 if (pkgSetting.getEnabled(userId) == newState) { 12826 // Nothing to do 12827 return; 12828 } 12829 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12830 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12831 // Don't care about who enables an app. 12832 callingPackage = null; 12833 } 12834 pkgSetting.setEnabled(newState, userId, callingPackage); 12835 // pkgSetting.pkg.mSetEnabled = newState; 12836 } else { 12837 // We're dealing with a component level state change 12838 // First, verify that this is a valid class name. 12839 PackageParser.Package pkg = pkgSetting.pkg; 12840 if (pkg == null || !pkg.hasComponentClassName(className)) { 12841 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12842 throw new IllegalArgumentException("Component class " + className 12843 + " does not exist in " + packageName); 12844 } else { 12845 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12846 + className + " does not exist in " + packageName); 12847 } 12848 } 12849 switch (newState) { 12850 case COMPONENT_ENABLED_STATE_ENABLED: 12851 if (!pkgSetting.enableComponentLPw(className, userId)) { 12852 return; 12853 } 12854 break; 12855 case COMPONENT_ENABLED_STATE_DISABLED: 12856 if (!pkgSetting.disableComponentLPw(className, userId)) { 12857 return; 12858 } 12859 break; 12860 case COMPONENT_ENABLED_STATE_DEFAULT: 12861 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12862 return; 12863 } 12864 break; 12865 default: 12866 Slog.e(TAG, "Invalid new component state: " + newState); 12867 return; 12868 } 12869 } 12870 scheduleWritePackageRestrictionsLocked(userId); 12871 components = mPendingBroadcasts.get(userId, packageName); 12872 final boolean newPackage = components == null; 12873 if (newPackage) { 12874 components = new ArrayList<String>(); 12875 } 12876 if (!components.contains(componentName)) { 12877 components.add(componentName); 12878 } 12879 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12880 sendNow = true; 12881 // Purge entry from pending broadcast list if another one exists already 12882 // since we are sending one right away. 12883 mPendingBroadcasts.remove(userId, packageName); 12884 } else { 12885 if (newPackage) { 12886 mPendingBroadcasts.put(userId, packageName, components); 12887 } 12888 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12889 // Schedule a message 12890 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12891 } 12892 } 12893 } 12894 12895 long callingId = Binder.clearCallingIdentity(); 12896 try { 12897 if (sendNow) { 12898 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12899 sendPackageChangedBroadcast(packageName, 12900 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12901 } 12902 } finally { 12903 Binder.restoreCallingIdentity(callingId); 12904 } 12905 } 12906 12907 private void sendPackageChangedBroadcast(String packageName, 12908 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12909 if (DEBUG_INSTALL) 12910 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12911 + componentNames); 12912 Bundle extras = new Bundle(4); 12913 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12914 String nameList[] = new String[componentNames.size()]; 12915 componentNames.toArray(nameList); 12916 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12917 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12918 extras.putInt(Intent.EXTRA_UID, packageUid); 12919 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12920 new int[] {UserHandle.getUserId(packageUid)}); 12921 } 12922 12923 @Override 12924 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12925 if (!sUserManager.exists(userId)) return; 12926 final int uid = Binder.getCallingUid(); 12927 final int permission = mContext.checkCallingOrSelfPermission( 12928 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12929 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12930 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12931 // writer 12932 synchronized (mPackages) { 12933 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12934 uid, userId)) { 12935 scheduleWritePackageRestrictionsLocked(userId); 12936 } 12937 } 12938 } 12939 12940 @Override 12941 public String getInstallerPackageName(String packageName) { 12942 // reader 12943 synchronized (mPackages) { 12944 return mSettings.getInstallerPackageNameLPr(packageName); 12945 } 12946 } 12947 12948 @Override 12949 public int getApplicationEnabledSetting(String packageName, int userId) { 12950 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12951 int uid = Binder.getCallingUid(); 12952 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12953 // reader 12954 synchronized (mPackages) { 12955 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12956 } 12957 } 12958 12959 @Override 12960 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12961 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12962 int uid = Binder.getCallingUid(); 12963 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12964 // reader 12965 synchronized (mPackages) { 12966 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12967 } 12968 } 12969 12970 @Override 12971 public void enterSafeMode() { 12972 enforceSystemOrRoot("Only the system can request entering safe mode"); 12973 12974 if (!mSystemReady) { 12975 mSafeMode = true; 12976 } 12977 } 12978 12979 @Override 12980 public void systemReady() { 12981 mSystemReady = true; 12982 12983 // Read the compatibilty setting when the system is ready. 12984 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12985 mContext.getContentResolver(), 12986 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12987 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12988 if (DEBUG_SETTINGS) { 12989 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12990 } 12991 12992 synchronized (mPackages) { 12993 // Verify that all of the preferred activity components actually 12994 // exist. It is possible for applications to be updated and at 12995 // that point remove a previously declared activity component that 12996 // had been set as a preferred activity. We try to clean this up 12997 // the next time we encounter that preferred activity, but it is 12998 // possible for the user flow to never be able to return to that 12999 // situation so here we do a sanity check to make sure we haven't 13000 // left any junk around. 13001 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13002 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13003 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13004 removed.clear(); 13005 for (PreferredActivity pa : pir.filterSet()) { 13006 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13007 removed.add(pa); 13008 } 13009 } 13010 if (removed.size() > 0) { 13011 for (int r=0; r<removed.size(); r++) { 13012 PreferredActivity pa = removed.get(r); 13013 Slog.w(TAG, "Removing dangling preferred activity: " 13014 + pa.mPref.mComponent); 13015 pir.removeFilter(pa); 13016 } 13017 mSettings.writePackageRestrictionsLPr( 13018 mSettings.mPreferredActivities.keyAt(i)); 13019 } 13020 } 13021 } 13022 sUserManager.systemReady(); 13023 13024 // Kick off any messages waiting for system ready 13025 if (mPostSystemReadyMessages != null) { 13026 for (Message msg : mPostSystemReadyMessages) { 13027 msg.sendToTarget(); 13028 } 13029 mPostSystemReadyMessages = null; 13030 } 13031 13032 // Watch for external volumes that come and go over time 13033 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13034 storage.registerListener(mStorageListener); 13035 13036 mInstallerService.systemReady(); 13037 } 13038 13039 @Override 13040 public boolean isSafeMode() { 13041 return mSafeMode; 13042 } 13043 13044 @Override 13045 public boolean hasSystemUidErrors() { 13046 return mHasSystemUidErrors; 13047 } 13048 13049 static String arrayToString(int[] array) { 13050 StringBuffer buf = new StringBuffer(128); 13051 buf.append('['); 13052 if (array != null) { 13053 for (int i=0; i<array.length; i++) { 13054 if (i > 0) buf.append(", "); 13055 buf.append(array[i]); 13056 } 13057 } 13058 buf.append(']'); 13059 return buf.toString(); 13060 } 13061 13062 static class DumpState { 13063 public static final int DUMP_LIBS = 1 << 0; 13064 public static final int DUMP_FEATURES = 1 << 1; 13065 public static final int DUMP_RESOLVERS = 1 << 2; 13066 public static final int DUMP_PERMISSIONS = 1 << 3; 13067 public static final int DUMP_PACKAGES = 1 << 4; 13068 public static final int DUMP_SHARED_USERS = 1 << 5; 13069 public static final int DUMP_MESSAGES = 1 << 6; 13070 public static final int DUMP_PROVIDERS = 1 << 7; 13071 public static final int DUMP_VERIFIERS = 1 << 8; 13072 public static final int DUMP_PREFERRED = 1 << 9; 13073 public static final int DUMP_PREFERRED_XML = 1 << 10; 13074 public static final int DUMP_KEYSETS = 1 << 11; 13075 public static final int DUMP_VERSION = 1 << 12; 13076 public static final int DUMP_INSTALLS = 1 << 13; 13077 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13078 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13079 13080 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13081 13082 private int mTypes; 13083 13084 private int mOptions; 13085 13086 private boolean mTitlePrinted; 13087 13088 private SharedUserSetting mSharedUser; 13089 13090 public boolean isDumping(int type) { 13091 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13092 return true; 13093 } 13094 13095 return (mTypes & type) != 0; 13096 } 13097 13098 public void setDump(int type) { 13099 mTypes |= type; 13100 } 13101 13102 public boolean isOptionEnabled(int option) { 13103 return (mOptions & option) != 0; 13104 } 13105 13106 public void setOptionEnabled(int option) { 13107 mOptions |= option; 13108 } 13109 13110 public boolean onTitlePrinted() { 13111 final boolean printed = mTitlePrinted; 13112 mTitlePrinted = true; 13113 return printed; 13114 } 13115 13116 public boolean getTitlePrinted() { 13117 return mTitlePrinted; 13118 } 13119 13120 public void setTitlePrinted(boolean enabled) { 13121 mTitlePrinted = enabled; 13122 } 13123 13124 public SharedUserSetting getSharedUser() { 13125 return mSharedUser; 13126 } 13127 13128 public void setSharedUser(SharedUserSetting user) { 13129 mSharedUser = user; 13130 } 13131 } 13132 13133 @Override 13134 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13135 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13136 != PackageManager.PERMISSION_GRANTED) { 13137 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13138 + Binder.getCallingPid() 13139 + ", uid=" + Binder.getCallingUid() 13140 + " without permission " 13141 + android.Manifest.permission.DUMP); 13142 return; 13143 } 13144 13145 DumpState dumpState = new DumpState(); 13146 boolean fullPreferred = false; 13147 boolean checkin = false; 13148 13149 String packageName = null; 13150 13151 int opti = 0; 13152 while (opti < args.length) { 13153 String opt = args[opti]; 13154 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13155 break; 13156 } 13157 opti++; 13158 13159 if ("-a".equals(opt)) { 13160 // Right now we only know how to print all. 13161 } else if ("-h".equals(opt)) { 13162 pw.println("Package manager dump options:"); 13163 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13164 pw.println(" --checkin: dump for a checkin"); 13165 pw.println(" -f: print details of intent filters"); 13166 pw.println(" -h: print this help"); 13167 pw.println(" cmd may be one of:"); 13168 pw.println(" l[ibraries]: list known shared libraries"); 13169 pw.println(" f[ibraries]: list device features"); 13170 pw.println(" k[eysets]: print known keysets"); 13171 pw.println(" r[esolvers]: dump intent resolvers"); 13172 pw.println(" perm[issions]: dump permissions"); 13173 pw.println(" pref[erred]: print preferred package settings"); 13174 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13175 pw.println(" prov[iders]: dump content providers"); 13176 pw.println(" p[ackages]: dump installed packages"); 13177 pw.println(" s[hared-users]: dump shared user IDs"); 13178 pw.println(" m[essages]: print collected runtime messages"); 13179 pw.println(" v[erifiers]: print package verifier info"); 13180 pw.println(" version: print database version info"); 13181 pw.println(" write: write current settings now"); 13182 pw.println(" <package.name>: info about given package"); 13183 pw.println(" installs: details about install sessions"); 13184 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13185 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13186 return; 13187 } else if ("--checkin".equals(opt)) { 13188 checkin = true; 13189 } else if ("-f".equals(opt)) { 13190 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13191 } else { 13192 pw.println("Unknown argument: " + opt + "; use -h for help"); 13193 } 13194 } 13195 13196 // Is the caller requesting to dump a particular piece of data? 13197 if (opti < args.length) { 13198 String cmd = args[opti]; 13199 opti++; 13200 // Is this a package name? 13201 if ("android".equals(cmd) || cmd.contains(".")) { 13202 packageName = cmd; 13203 // When dumping a single package, we always dump all of its 13204 // filter information since the amount of data will be reasonable. 13205 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13206 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13207 dumpState.setDump(DumpState.DUMP_LIBS); 13208 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13209 dumpState.setDump(DumpState.DUMP_FEATURES); 13210 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13211 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13212 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13213 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13214 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13215 dumpState.setDump(DumpState.DUMP_PREFERRED); 13216 } else if ("preferred-xml".equals(cmd)) { 13217 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13218 if (opti < args.length && "--full".equals(args[opti])) { 13219 fullPreferred = true; 13220 opti++; 13221 } 13222 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13223 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13224 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13225 dumpState.setDump(DumpState.DUMP_PACKAGES); 13226 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13227 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13228 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13229 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13230 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13231 dumpState.setDump(DumpState.DUMP_MESSAGES); 13232 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13233 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13234 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13235 || "intent-filter-verifiers".equals(cmd)) { 13236 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13237 } else if ("version".equals(cmd)) { 13238 dumpState.setDump(DumpState.DUMP_VERSION); 13239 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13240 dumpState.setDump(DumpState.DUMP_KEYSETS); 13241 } else if ("installs".equals(cmd)) { 13242 dumpState.setDump(DumpState.DUMP_INSTALLS); 13243 } else if ("write".equals(cmd)) { 13244 synchronized (mPackages) { 13245 mSettings.writeLPr(); 13246 pw.println("Settings written."); 13247 return; 13248 } 13249 } 13250 } 13251 13252 if (checkin) { 13253 pw.println("vers,1"); 13254 } 13255 13256 // reader 13257 synchronized (mPackages) { 13258 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13259 if (!checkin) { 13260 if (dumpState.onTitlePrinted()) 13261 pw.println(); 13262 pw.println("Database versions:"); 13263 pw.print(" SDK Version:"); 13264 pw.print(" internal="); 13265 pw.print(mSettings.mInternalSdkPlatform); 13266 pw.print(" external="); 13267 pw.println(mSettings.mExternalSdkPlatform); 13268 pw.print(" DB Version:"); 13269 pw.print(" internal="); 13270 pw.print(mSettings.mInternalDatabaseVersion); 13271 pw.print(" external="); 13272 pw.println(mSettings.mExternalDatabaseVersion); 13273 } 13274 } 13275 13276 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13277 if (!checkin) { 13278 if (dumpState.onTitlePrinted()) 13279 pw.println(); 13280 pw.println("Verifiers:"); 13281 pw.print(" Required: "); 13282 pw.print(mRequiredVerifierPackage); 13283 pw.print(" (uid="); 13284 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13285 pw.println(")"); 13286 } else if (mRequiredVerifierPackage != null) { 13287 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13288 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13289 } 13290 } 13291 13292 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13293 packageName == null) { 13294 if (mIntentFilterVerifierComponent != null) { 13295 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13296 if (!checkin) { 13297 if (dumpState.onTitlePrinted()) 13298 pw.println(); 13299 pw.println("Intent Filter Verifier:"); 13300 pw.print(" Using: "); 13301 pw.print(verifierPackageName); 13302 pw.print(" (uid="); 13303 pw.print(getPackageUid(verifierPackageName, 0)); 13304 pw.println(")"); 13305 } else if (verifierPackageName != null) { 13306 pw.print("ifv,"); pw.print(verifierPackageName); 13307 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13308 } 13309 } else { 13310 pw.println(); 13311 pw.println("No Intent Filter Verifier available!"); 13312 } 13313 } 13314 13315 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13316 boolean printedHeader = false; 13317 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13318 while (it.hasNext()) { 13319 String name = it.next(); 13320 SharedLibraryEntry ent = mSharedLibraries.get(name); 13321 if (!checkin) { 13322 if (!printedHeader) { 13323 if (dumpState.onTitlePrinted()) 13324 pw.println(); 13325 pw.println("Libraries:"); 13326 printedHeader = true; 13327 } 13328 pw.print(" "); 13329 } else { 13330 pw.print("lib,"); 13331 } 13332 pw.print(name); 13333 if (!checkin) { 13334 pw.print(" -> "); 13335 } 13336 if (ent.path != null) { 13337 if (!checkin) { 13338 pw.print("(jar) "); 13339 pw.print(ent.path); 13340 } else { 13341 pw.print(",jar,"); 13342 pw.print(ent.path); 13343 } 13344 } else { 13345 if (!checkin) { 13346 pw.print("(apk) "); 13347 pw.print(ent.apk); 13348 } else { 13349 pw.print(",apk,"); 13350 pw.print(ent.apk); 13351 } 13352 } 13353 pw.println(); 13354 } 13355 } 13356 13357 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13358 if (dumpState.onTitlePrinted()) 13359 pw.println(); 13360 if (!checkin) { 13361 pw.println("Features:"); 13362 } 13363 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13364 while (it.hasNext()) { 13365 String name = it.next(); 13366 if (!checkin) { 13367 pw.print(" "); 13368 } else { 13369 pw.print("feat,"); 13370 } 13371 pw.println(name); 13372 } 13373 } 13374 13375 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13376 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13377 : "Activity Resolver Table:", " ", packageName, 13378 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13379 dumpState.setTitlePrinted(true); 13380 } 13381 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13382 : "Receiver Resolver Table:", " ", packageName, 13383 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13384 dumpState.setTitlePrinted(true); 13385 } 13386 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13387 : "Service Resolver Table:", " ", packageName, 13388 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13389 dumpState.setTitlePrinted(true); 13390 } 13391 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13392 : "Provider Resolver Table:", " ", packageName, 13393 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13394 dumpState.setTitlePrinted(true); 13395 } 13396 } 13397 13398 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13399 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13400 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13401 int user = mSettings.mPreferredActivities.keyAt(i); 13402 if (pir.dump(pw, 13403 dumpState.getTitlePrinted() 13404 ? "\nPreferred Activities User " + user + ":" 13405 : "Preferred Activities User " + user + ":", " ", 13406 packageName, true, false)) { 13407 dumpState.setTitlePrinted(true); 13408 } 13409 } 13410 } 13411 13412 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13413 pw.flush(); 13414 FileOutputStream fout = new FileOutputStream(fd); 13415 BufferedOutputStream str = new BufferedOutputStream(fout); 13416 XmlSerializer serializer = new FastXmlSerializer(); 13417 try { 13418 serializer.setOutput(str, "utf-8"); 13419 serializer.startDocument(null, true); 13420 serializer.setFeature( 13421 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13422 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13423 serializer.endDocument(); 13424 serializer.flush(); 13425 } catch (IllegalArgumentException e) { 13426 pw.println("Failed writing: " + e); 13427 } catch (IllegalStateException e) { 13428 pw.println("Failed writing: " + e); 13429 } catch (IOException e) { 13430 pw.println("Failed writing: " + e); 13431 } 13432 } 13433 13434 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13435 pw.println(); 13436 int count = mSettings.mPackages.size(); 13437 if (count == 0) { 13438 pw.println("No domain preferred apps!"); 13439 pw.println(); 13440 } else { 13441 final String prefix = " "; 13442 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13443 if (allPackageSettings.size() == 0) { 13444 pw.println("No domain preferred apps!"); 13445 pw.println(); 13446 } else { 13447 pw.println("Domain preferred apps status:"); 13448 pw.println(); 13449 count = 0; 13450 for (PackageSetting ps : allPackageSettings) { 13451 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13452 if (ivi == null || ivi.getPackageName() == null) continue; 13453 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13454 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13455 pw.println(prefix + "Status: " + ivi.getStatusString()); 13456 pw.println(); 13457 count++; 13458 } 13459 if (count == 0) { 13460 pw.println(prefix + "No domain preferred app status!"); 13461 pw.println(); 13462 } 13463 for (int userId : sUserManager.getUserIds()) { 13464 pw.println("Domain preferred apps for User " + userId + ":"); 13465 pw.println(); 13466 count = 0; 13467 for (PackageSetting ps : allPackageSettings) { 13468 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13469 if (ivi == null || ivi.getPackageName() == null) { 13470 continue; 13471 } 13472 final int status = ps.getDomainVerificationStatusForUser(userId); 13473 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13474 continue; 13475 } 13476 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13477 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13478 String statusStr = IntentFilterVerificationInfo. 13479 getStatusStringFromValue(status); 13480 pw.println(prefix + "Status: " + statusStr); 13481 pw.println(); 13482 count++; 13483 } 13484 if (count == 0) { 13485 pw.println(prefix + "No domain preferred apps!"); 13486 pw.println(); 13487 } 13488 } 13489 } 13490 } 13491 } 13492 13493 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13494 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13495 if (packageName == null) { 13496 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13497 if (iperm == 0) { 13498 if (dumpState.onTitlePrinted()) 13499 pw.println(); 13500 pw.println("AppOp Permissions:"); 13501 } 13502 pw.print(" AppOp Permission "); 13503 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13504 pw.println(":"); 13505 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13506 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13507 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13508 } 13509 } 13510 } 13511 } 13512 13513 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13514 boolean printedSomething = false; 13515 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13516 if (packageName != null && !packageName.equals(p.info.packageName)) { 13517 continue; 13518 } 13519 if (!printedSomething) { 13520 if (dumpState.onTitlePrinted()) 13521 pw.println(); 13522 pw.println("Registered ContentProviders:"); 13523 printedSomething = true; 13524 } 13525 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13526 pw.print(" "); pw.println(p.toString()); 13527 } 13528 printedSomething = false; 13529 for (Map.Entry<String, PackageParser.Provider> entry : 13530 mProvidersByAuthority.entrySet()) { 13531 PackageParser.Provider p = entry.getValue(); 13532 if (packageName != null && !packageName.equals(p.info.packageName)) { 13533 continue; 13534 } 13535 if (!printedSomething) { 13536 if (dumpState.onTitlePrinted()) 13537 pw.println(); 13538 pw.println("ContentProvider Authorities:"); 13539 printedSomething = true; 13540 } 13541 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13542 pw.print(" "); pw.println(p.toString()); 13543 if (p.info != null && p.info.applicationInfo != null) { 13544 final String appInfo = p.info.applicationInfo.toString(); 13545 pw.print(" applicationInfo="); pw.println(appInfo); 13546 } 13547 } 13548 } 13549 13550 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13551 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13552 } 13553 13554 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13555 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13556 } 13557 13558 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13559 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13560 } 13561 13562 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13563 // XXX should handle packageName != null by dumping only install data that 13564 // the given package is involved with. 13565 if (dumpState.onTitlePrinted()) pw.println(); 13566 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13567 } 13568 13569 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13570 if (dumpState.onTitlePrinted()) pw.println(); 13571 mSettings.dumpReadMessagesLPr(pw, dumpState); 13572 13573 pw.println(); 13574 pw.println("Package warning messages:"); 13575 BufferedReader in = null; 13576 String line = null; 13577 try { 13578 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13579 while ((line = in.readLine()) != null) { 13580 if (line.contains("ignored: updated version")) continue; 13581 pw.println(line); 13582 } 13583 } catch (IOException ignored) { 13584 } finally { 13585 IoUtils.closeQuietly(in); 13586 } 13587 } 13588 13589 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13590 BufferedReader in = null; 13591 String line = null; 13592 try { 13593 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13594 while ((line = in.readLine()) != null) { 13595 if (line.contains("ignored: updated version")) continue; 13596 pw.print("msg,"); 13597 pw.println(line); 13598 } 13599 } catch (IOException ignored) { 13600 } finally { 13601 IoUtils.closeQuietly(in); 13602 } 13603 } 13604 } 13605 } 13606 13607 // ------- apps on sdcard specific code ------- 13608 static final boolean DEBUG_SD_INSTALL = false; 13609 13610 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13611 13612 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13613 13614 private boolean mMediaMounted = false; 13615 13616 static String getEncryptKey() { 13617 try { 13618 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13619 SD_ENCRYPTION_KEYSTORE_NAME); 13620 if (sdEncKey == null) { 13621 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13622 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13623 if (sdEncKey == null) { 13624 Slog.e(TAG, "Failed to create encryption keys"); 13625 return null; 13626 } 13627 } 13628 return sdEncKey; 13629 } catch (NoSuchAlgorithmException nsae) { 13630 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13631 return null; 13632 } catch (IOException ioe) { 13633 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13634 return null; 13635 } 13636 } 13637 13638 /* 13639 * Update media status on PackageManager. 13640 */ 13641 @Override 13642 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13643 int callingUid = Binder.getCallingUid(); 13644 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13645 throw new SecurityException("Media status can only be updated by the system"); 13646 } 13647 // reader; this apparently protects mMediaMounted, but should probably 13648 // be a different lock in that case. 13649 synchronized (mPackages) { 13650 Log.i(TAG, "Updating external media status from " 13651 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13652 + (mediaStatus ? "mounted" : "unmounted")); 13653 if (DEBUG_SD_INSTALL) 13654 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13655 + ", mMediaMounted=" + mMediaMounted); 13656 if (mediaStatus == mMediaMounted) { 13657 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13658 : 0, -1); 13659 mHandler.sendMessage(msg); 13660 return; 13661 } 13662 mMediaMounted = mediaStatus; 13663 } 13664 // Queue up an async operation since the package installation may take a 13665 // little while. 13666 mHandler.post(new Runnable() { 13667 public void run() { 13668 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13669 } 13670 }); 13671 } 13672 13673 /** 13674 * Called by MountService when the initial ASECs to scan are available. 13675 * Should block until all the ASEC containers are finished being scanned. 13676 */ 13677 public void scanAvailableAsecs() { 13678 updateExternalMediaStatusInner(true, false, false); 13679 if (mShouldRestoreconData) { 13680 SELinuxMMAC.setRestoreconDone(); 13681 mShouldRestoreconData = false; 13682 } 13683 } 13684 13685 /* 13686 * Collect information of applications on external media, map them against 13687 * existing containers and update information based on current mount status. 13688 * Please note that we always have to report status if reportStatus has been 13689 * set to true especially when unloading packages. 13690 */ 13691 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13692 boolean externalStorage) { 13693 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13694 int[] uidArr = EmptyArray.INT; 13695 13696 final String[] list = PackageHelper.getSecureContainerList(); 13697 if (ArrayUtils.isEmpty(list)) { 13698 Log.i(TAG, "No secure containers found"); 13699 } else { 13700 // Process list of secure containers and categorize them 13701 // as active or stale based on their package internal state. 13702 13703 // reader 13704 synchronized (mPackages) { 13705 for (String cid : list) { 13706 // Leave stages untouched for now; installer service owns them 13707 if (PackageInstallerService.isStageName(cid)) continue; 13708 13709 if (DEBUG_SD_INSTALL) 13710 Log.i(TAG, "Processing container " + cid); 13711 String pkgName = getAsecPackageName(cid); 13712 if (pkgName == null) { 13713 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13714 continue; 13715 } 13716 if (DEBUG_SD_INSTALL) 13717 Log.i(TAG, "Looking for pkg : " + pkgName); 13718 13719 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13720 if (ps == null) { 13721 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13722 continue; 13723 } 13724 13725 /* 13726 * Skip packages that are not external if we're unmounting 13727 * external storage. 13728 */ 13729 if (externalStorage && !isMounted && !isExternal(ps)) { 13730 continue; 13731 } 13732 13733 final AsecInstallArgs args = new AsecInstallArgs(cid, 13734 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13735 // The package status is changed only if the code path 13736 // matches between settings and the container id. 13737 if (ps.codePathString != null 13738 && ps.codePathString.startsWith(args.getCodePath())) { 13739 if (DEBUG_SD_INSTALL) { 13740 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13741 + " at code path: " + ps.codePathString); 13742 } 13743 13744 // We do have a valid package installed on sdcard 13745 processCids.put(args, ps.codePathString); 13746 final int uid = ps.appId; 13747 if (uid != -1) { 13748 uidArr = ArrayUtils.appendInt(uidArr, uid); 13749 } 13750 } else { 13751 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13752 + ps.codePathString); 13753 } 13754 } 13755 } 13756 13757 Arrays.sort(uidArr); 13758 } 13759 13760 // Process packages with valid entries. 13761 if (isMounted) { 13762 if (DEBUG_SD_INSTALL) 13763 Log.i(TAG, "Loading packages"); 13764 loadMediaPackages(processCids, uidArr); 13765 startCleaningPackages(); 13766 mInstallerService.onSecureContainersAvailable(); 13767 } else { 13768 if (DEBUG_SD_INSTALL) 13769 Log.i(TAG, "Unloading packages"); 13770 unloadMediaPackages(processCids, uidArr, reportStatus); 13771 } 13772 } 13773 13774 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13775 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13776 final int size = infos.size(); 13777 final String[] packageNames = new String[size]; 13778 final int[] packageUids = new int[size]; 13779 for (int i = 0; i < size; i++) { 13780 final ApplicationInfo info = infos.get(i); 13781 packageNames[i] = info.packageName; 13782 packageUids[i] = info.uid; 13783 } 13784 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13785 finishedReceiver); 13786 } 13787 13788 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13789 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13790 sendResourcesChangedBroadcast(mediaStatus, replacing, 13791 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13792 } 13793 13794 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13795 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13796 int size = pkgList.length; 13797 if (size > 0) { 13798 // Send broadcasts here 13799 Bundle extras = new Bundle(); 13800 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13801 if (uidArr != null) { 13802 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13803 } 13804 if (replacing) { 13805 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13806 } 13807 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13808 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13809 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13810 } 13811 } 13812 13813 /* 13814 * Look at potentially valid container ids from processCids If package 13815 * information doesn't match the one on record or package scanning fails, 13816 * the cid is added to list of removeCids. We currently don't delete stale 13817 * containers. 13818 */ 13819 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13820 ArrayList<String> pkgList = new ArrayList<String>(); 13821 Set<AsecInstallArgs> keys = processCids.keySet(); 13822 13823 for (AsecInstallArgs args : keys) { 13824 String codePath = processCids.get(args); 13825 if (DEBUG_SD_INSTALL) 13826 Log.i(TAG, "Loading container : " + args.cid); 13827 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13828 try { 13829 // Make sure there are no container errors first. 13830 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13831 Slog.e(TAG, "Failed to mount cid : " + args.cid 13832 + " when installing from sdcard"); 13833 continue; 13834 } 13835 // Check code path here. 13836 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13837 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13838 + " does not match one in settings " + codePath); 13839 continue; 13840 } 13841 // Parse package 13842 int parseFlags = mDefParseFlags; 13843 if (args.isExternalAsec()) { 13844 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 13845 } 13846 if (args.isFwdLocked()) { 13847 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13848 } 13849 13850 synchronized (mInstallLock) { 13851 PackageParser.Package pkg = null; 13852 try { 13853 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13854 } catch (PackageManagerException e) { 13855 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13856 } 13857 // Scan the package 13858 if (pkg != null) { 13859 /* 13860 * TODO why is the lock being held? doPostInstall is 13861 * called in other places without the lock. This needs 13862 * to be straightened out. 13863 */ 13864 // writer 13865 synchronized (mPackages) { 13866 retCode = PackageManager.INSTALL_SUCCEEDED; 13867 pkgList.add(pkg.packageName); 13868 // Post process args 13869 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13870 pkg.applicationInfo.uid); 13871 } 13872 } else { 13873 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13874 } 13875 } 13876 13877 } finally { 13878 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13879 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13880 } 13881 } 13882 } 13883 // writer 13884 synchronized (mPackages) { 13885 // If the platform SDK has changed since the last time we booted, 13886 // we need to re-grant app permission to catch any new ones that 13887 // appear. This is really a hack, and means that apps can in some 13888 // cases get permissions that the user didn't initially explicitly 13889 // allow... it would be nice to have some better way to handle 13890 // this situation. 13891 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13892 if (regrantPermissions) 13893 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13894 + mSdkVersion + "; regranting permissions for external storage"); 13895 mSettings.mExternalSdkPlatform = mSdkVersion; 13896 13897 // Make sure group IDs have been assigned, and any permission 13898 // changes in other apps are accounted for 13899 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13900 | (regrantPermissions 13901 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13902 : 0)); 13903 13904 mSettings.updateExternalDatabaseVersion(); 13905 13906 // can downgrade to reader 13907 // Persist settings 13908 mSettings.writeLPr(); 13909 } 13910 // Send a broadcast to let everyone know we are done processing 13911 if (pkgList.size() > 0) { 13912 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13913 } 13914 } 13915 13916 /* 13917 * Utility method to unload a list of specified containers 13918 */ 13919 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13920 // Just unmount all valid containers. 13921 for (AsecInstallArgs arg : cidArgs) { 13922 synchronized (mInstallLock) { 13923 arg.doPostDeleteLI(false); 13924 } 13925 } 13926 } 13927 13928 /* 13929 * Unload packages mounted on external media. This involves deleting package 13930 * data from internal structures, sending broadcasts about diabled packages, 13931 * gc'ing to free up references, unmounting all secure containers 13932 * corresponding to packages on external media, and posting a 13933 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13934 * that we always have to post this message if status has been requested no 13935 * matter what. 13936 */ 13937 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13938 final boolean reportStatus) { 13939 if (DEBUG_SD_INSTALL) 13940 Log.i(TAG, "unloading media packages"); 13941 ArrayList<String> pkgList = new ArrayList<String>(); 13942 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13943 final Set<AsecInstallArgs> keys = processCids.keySet(); 13944 for (AsecInstallArgs args : keys) { 13945 String pkgName = args.getPackageName(); 13946 if (DEBUG_SD_INSTALL) 13947 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13948 // Delete package internally 13949 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13950 synchronized (mInstallLock) { 13951 boolean res = deletePackageLI(pkgName, null, false, null, null, 13952 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13953 if (res) { 13954 pkgList.add(pkgName); 13955 } else { 13956 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13957 failedList.add(args); 13958 } 13959 } 13960 } 13961 13962 // reader 13963 synchronized (mPackages) { 13964 // We didn't update the settings after removing each package; 13965 // write them now for all packages. 13966 mSettings.writeLPr(); 13967 } 13968 13969 // We have to absolutely send UPDATED_MEDIA_STATUS only 13970 // after confirming that all the receivers processed the ordered 13971 // broadcast when packages get disabled, force a gc to clean things up. 13972 // and unload all the containers. 13973 if (pkgList.size() > 0) { 13974 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13975 new IIntentReceiver.Stub() { 13976 public void performReceive(Intent intent, int resultCode, String data, 13977 Bundle extras, boolean ordered, boolean sticky, 13978 int sendingUser) throws RemoteException { 13979 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13980 reportStatus ? 1 : 0, 1, keys); 13981 mHandler.sendMessage(msg); 13982 } 13983 }); 13984 } else { 13985 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13986 keys); 13987 mHandler.sendMessage(msg); 13988 } 13989 } 13990 13991 private void loadPrivatePackages(VolumeInfo vol) { 13992 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 13993 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 13994 synchronized (mPackages) { 13995 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 13996 for (PackageSetting ps : packages) { 13997 synchronized (mInstallLock) { 13998 final PackageParser.Package pkg; 13999 try { 14000 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14001 loaded.add(pkg.applicationInfo); 14002 } catch (PackageManagerException e) { 14003 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14004 } 14005 } 14006 } 14007 14008 // TODO: regrant any permissions that changed based since original install 14009 14010 mSettings.writeLPr(); 14011 } 14012 14013 Slog.d(TAG, "Loaded packages " + loaded); 14014 sendResourcesChangedBroadcast(true, false, loaded, null); 14015 } 14016 14017 private void unloadPrivatePackages(VolumeInfo vol) { 14018 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14019 synchronized (mPackages) { 14020 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14021 for (PackageSetting ps : packages) { 14022 if (ps.pkg == null) continue; 14023 synchronized (mInstallLock) { 14024 final ApplicationInfo info = ps.pkg.applicationInfo; 14025 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14026 if (deletePackageLI(ps.name, null, false, null, null, 14027 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14028 unloaded.add(info); 14029 } else { 14030 Slog.w(TAG, "Failed to unload " + ps.codePath); 14031 } 14032 } 14033 } 14034 14035 mSettings.writeLPr(); 14036 } 14037 14038 Slog.d(TAG, "Unloaded packages " + unloaded); 14039 sendResourcesChangedBroadcast(false, false, unloaded, null); 14040 } 14041 14042 @Override 14043 public void movePackage(final String packageName, final IPackageMoveObserver observer, 14044 final int flags) { 14045 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14046 14047 final int installFlags; 14048 if ((flags & MOVE_INTERNAL) != 0) { 14049 installFlags = INSTALL_INTERNAL; 14050 } else if ((flags & MOVE_EXTERNAL_MEDIA) != 0) { 14051 installFlags = INSTALL_EXTERNAL; 14052 } else { 14053 throw new IllegalArgumentException("Unsupported move flags " + flags); 14054 } 14055 14056 try { 14057 movePackageInternal(packageName, null, installFlags, false, observer); 14058 } catch (PackageManagerException e) { 14059 Slog.d(TAG, "Failed to move " + packageName, e); 14060 try { 14061 observer.packageMoved(packageName, e.error); 14062 } catch (RemoteException ignored) { 14063 } 14064 } 14065 } 14066 14067 @Override 14068 public void movePackageAndData(final String packageName, final String volumeUuid, 14069 final IPackageMoveObserver observer) { 14070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14071 try { 14072 movePackageInternal(packageName, volumeUuid, INSTALL_INTERNAL, true, observer); 14073 } catch (PackageManagerException e) { 14074 Slog.d(TAG, "Failed to move " + packageName, e); 14075 try { 14076 observer.packageMoved(packageName, e.error); 14077 } catch (RemoteException ignored) { 14078 } 14079 } 14080 } 14081 14082 private void movePackageInternal(final String packageName, String volumeUuid, int installFlags, 14083 boolean andData, final IPackageMoveObserver observer) throws PackageManagerException { 14084 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14085 14086 File codeFile = null; 14087 String installerPackageName = null; 14088 String packageAbiOverride = null; 14089 14090 // TOOD: move app private data before installing 14091 14092 // reader 14093 synchronized (mPackages) { 14094 final PackageParser.Package pkg = mPackages.get(packageName); 14095 final PackageSetting ps = mSettings.mPackages.get(packageName); 14096 if (pkg == null || ps == null) { 14097 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14098 } 14099 14100 if (pkg.applicationInfo.isSystemApp()) { 14101 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14102 "Cannot move system application"); 14103 } else if (pkg.mOperationPending) { 14104 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14105 "Attempt to move package which has pending operations"); 14106 } 14107 14108 // TODO: yell if already in desired location 14109 14110 pkg.mOperationPending = true; 14111 14112 codeFile = new File(pkg.codePath); 14113 installerPackageName = ps.installerPackageName; 14114 packageAbiOverride = ps.cpuAbiOverrideString; 14115 } 14116 14117 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14118 @Override 14119 public void onUserActionRequired(Intent intent) throws RemoteException { 14120 throw new IllegalStateException(); 14121 } 14122 14123 @Override 14124 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14125 Bundle extras) throws RemoteException { 14126 Slog.d(TAG, "Install result for move: " 14127 + PackageManager.installStatusToString(returnCode, msg)); 14128 14129 // We usually have a new package now after the install, but if 14130 // we failed we need to clear the pending flag on the original 14131 // package object. 14132 synchronized (mPackages) { 14133 final PackageParser.Package pkg = mPackages.get(packageName); 14134 if (pkg != null) { 14135 pkg.mOperationPending = false; 14136 } 14137 } 14138 14139 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14140 switch (status) { 14141 case PackageInstaller.STATUS_SUCCESS: 14142 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 14143 break; 14144 case PackageInstaller.STATUS_FAILURE_STORAGE: 14145 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14146 break; 14147 default: 14148 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14149 break; 14150 } 14151 } 14152 }; 14153 14154 // Treat a move like reinstalling an existing app, which ensures that we 14155 // process everythign uniformly, like unpacking native libraries. 14156 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14157 14158 final Message msg = mHandler.obtainMessage(INIT_COPY); 14159 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14160 msg.obj = new InstallParams(origin, installObserver, installFlags, 14161 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14162 mHandler.sendMessage(msg); 14163 } 14164 14165 @Override 14166 public boolean setInstallLocation(int loc) { 14167 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14168 null); 14169 if (getInstallLocation() == loc) { 14170 return true; 14171 } 14172 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14173 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14174 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14175 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14176 return true; 14177 } 14178 return false; 14179 } 14180 14181 @Override 14182 public int getInstallLocation() { 14183 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14184 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14185 PackageHelper.APP_INSTALL_AUTO); 14186 } 14187 14188 /** Called by UserManagerService */ 14189 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14190 mDirtyUsers.remove(userHandle); 14191 mSettings.removeUserLPw(userHandle); 14192 mPendingBroadcasts.remove(userHandle); 14193 if (mInstaller != null) { 14194 // Technically, we shouldn't be doing this with the package lock 14195 // held. However, this is very rare, and there is already so much 14196 // other disk I/O going on, that we'll let it slide for now. 14197 mInstaller.removeUserDataDirs(userHandle); 14198 } 14199 mUserNeedsBadging.delete(userHandle); 14200 removeUnusedPackagesLILPw(userManager, userHandle); 14201 } 14202 14203 /** 14204 * We're removing userHandle and would like to remove any downloaded packages 14205 * that are no longer in use by any other user. 14206 * @param userHandle the user being removed 14207 */ 14208 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14209 final boolean DEBUG_CLEAN_APKS = false; 14210 int [] users = userManager.getUserIdsLPr(); 14211 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14212 while (psit.hasNext()) { 14213 PackageSetting ps = psit.next(); 14214 if (ps.pkg == null) { 14215 continue; 14216 } 14217 final String packageName = ps.pkg.packageName; 14218 // Skip over if system app 14219 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14220 continue; 14221 } 14222 if (DEBUG_CLEAN_APKS) { 14223 Slog.i(TAG, "Checking package " + packageName); 14224 } 14225 boolean keep = false; 14226 for (int i = 0; i < users.length; i++) { 14227 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14228 keep = true; 14229 if (DEBUG_CLEAN_APKS) { 14230 Slog.i(TAG, " Keeping package " + packageName + " for user " 14231 + users[i]); 14232 } 14233 break; 14234 } 14235 } 14236 if (!keep) { 14237 if (DEBUG_CLEAN_APKS) { 14238 Slog.i(TAG, " Removing package " + packageName); 14239 } 14240 mHandler.post(new Runnable() { 14241 public void run() { 14242 deletePackageX(packageName, userHandle, 0); 14243 } //end run 14244 }); 14245 } 14246 } 14247 } 14248 14249 /** Called by UserManagerService */ 14250 void createNewUserLILPw(int userHandle, File path) { 14251 if (mInstaller != null) { 14252 mInstaller.createUserConfig(userHandle); 14253 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14254 } 14255 } 14256 14257 void newUserCreatedLILPw(int userHandle) { 14258 // Adding a user requires updating runtime permissions for system apps. 14259 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14260 } 14261 14262 @Override 14263 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14264 mContext.enforceCallingOrSelfPermission( 14265 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14266 "Only package verification agents can read the verifier device identity"); 14267 14268 synchronized (mPackages) { 14269 return mSettings.getVerifierDeviceIdentityLPw(); 14270 } 14271 } 14272 14273 @Override 14274 public void setPermissionEnforced(String permission, boolean enforced) { 14275 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14276 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14277 synchronized (mPackages) { 14278 if (mSettings.mReadExternalStorageEnforced == null 14279 || mSettings.mReadExternalStorageEnforced != enforced) { 14280 mSettings.mReadExternalStorageEnforced = enforced; 14281 mSettings.writeLPr(); 14282 } 14283 } 14284 // kill any non-foreground processes so we restart them and 14285 // grant/revoke the GID. 14286 final IActivityManager am = ActivityManagerNative.getDefault(); 14287 if (am != null) { 14288 final long token = Binder.clearCallingIdentity(); 14289 try { 14290 am.killProcessesBelowForeground("setPermissionEnforcement"); 14291 } catch (RemoteException e) { 14292 } finally { 14293 Binder.restoreCallingIdentity(token); 14294 } 14295 } 14296 } else { 14297 throw new IllegalArgumentException("No selective enforcement for " + permission); 14298 } 14299 } 14300 14301 @Override 14302 @Deprecated 14303 public boolean isPermissionEnforced(String permission) { 14304 return true; 14305 } 14306 14307 @Override 14308 public boolean isStorageLow() { 14309 final long token = Binder.clearCallingIdentity(); 14310 try { 14311 final DeviceStorageMonitorInternal 14312 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14313 if (dsm != null) { 14314 return dsm.isMemoryLow(); 14315 } else { 14316 return false; 14317 } 14318 } finally { 14319 Binder.restoreCallingIdentity(token); 14320 } 14321 } 14322 14323 @Override 14324 public IPackageInstaller getPackageInstaller() { 14325 return mInstallerService; 14326 } 14327 14328 private boolean userNeedsBadging(int userId) { 14329 int index = mUserNeedsBadging.indexOfKey(userId); 14330 if (index < 0) { 14331 final UserInfo userInfo; 14332 final long token = Binder.clearCallingIdentity(); 14333 try { 14334 userInfo = sUserManager.getUserInfo(userId); 14335 } finally { 14336 Binder.restoreCallingIdentity(token); 14337 } 14338 final boolean b; 14339 if (userInfo != null && userInfo.isManagedProfile()) { 14340 b = true; 14341 } else { 14342 b = false; 14343 } 14344 mUserNeedsBadging.put(userId, b); 14345 return b; 14346 } 14347 return mUserNeedsBadging.valueAt(index); 14348 } 14349 14350 @Override 14351 public KeySet getKeySetByAlias(String packageName, String alias) { 14352 if (packageName == null || alias == null) { 14353 return null; 14354 } 14355 synchronized(mPackages) { 14356 final PackageParser.Package pkg = mPackages.get(packageName); 14357 if (pkg == null) { 14358 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14359 throw new IllegalArgumentException("Unknown package: " + packageName); 14360 } 14361 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14362 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14363 } 14364 } 14365 14366 @Override 14367 public KeySet getSigningKeySet(String packageName) { 14368 if (packageName == null) { 14369 return null; 14370 } 14371 synchronized(mPackages) { 14372 final PackageParser.Package pkg = mPackages.get(packageName); 14373 if (pkg == null) { 14374 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14375 throw new IllegalArgumentException("Unknown package: " + packageName); 14376 } 14377 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14378 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14379 throw new SecurityException("May not access signing KeySet of other apps."); 14380 } 14381 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14382 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14383 } 14384 } 14385 14386 @Override 14387 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14388 if (packageName == null || ks == null) { 14389 return false; 14390 } 14391 synchronized(mPackages) { 14392 final PackageParser.Package pkg = mPackages.get(packageName); 14393 if (pkg == null) { 14394 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14395 throw new IllegalArgumentException("Unknown package: " + packageName); 14396 } 14397 IBinder ksh = ks.getToken(); 14398 if (ksh instanceof KeySetHandle) { 14399 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14400 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14401 } 14402 return false; 14403 } 14404 } 14405 14406 @Override 14407 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14408 if (packageName == null || ks == null) { 14409 return false; 14410 } 14411 synchronized(mPackages) { 14412 final PackageParser.Package pkg = mPackages.get(packageName); 14413 if (pkg == null) { 14414 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14415 throw new IllegalArgumentException("Unknown package: " + packageName); 14416 } 14417 IBinder ksh = ks.getToken(); 14418 if (ksh instanceof KeySetHandle) { 14419 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14420 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14421 } 14422 return false; 14423 } 14424 } 14425 14426 public void getUsageStatsIfNoPackageUsageInfo() { 14427 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14428 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14429 if (usm == null) { 14430 throw new IllegalStateException("UsageStatsManager must be initialized"); 14431 } 14432 long now = System.currentTimeMillis(); 14433 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14434 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14435 String packageName = entry.getKey(); 14436 PackageParser.Package pkg = mPackages.get(packageName); 14437 if (pkg == null) { 14438 continue; 14439 } 14440 UsageStats usage = entry.getValue(); 14441 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14442 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14443 } 14444 } 14445 } 14446 14447 /** 14448 * Check and throw if the given before/after packages would be considered a 14449 * downgrade. 14450 */ 14451 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14452 throws PackageManagerException { 14453 if (after.versionCode < before.mVersionCode) { 14454 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14455 "Update version code " + after.versionCode + " is older than current " 14456 + before.mVersionCode); 14457 } else if (after.versionCode == before.mVersionCode) { 14458 if (after.baseRevisionCode < before.baseRevisionCode) { 14459 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14460 "Update base revision code " + after.baseRevisionCode 14461 + " is older than current " + before.baseRevisionCode); 14462 } 14463 14464 if (!ArrayUtils.isEmpty(after.splitNames)) { 14465 for (int i = 0; i < after.splitNames.length; i++) { 14466 final String splitName = after.splitNames[i]; 14467 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14468 if (j != -1) { 14469 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14470 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14471 "Update split " + splitName + " revision code " 14472 + after.splitRevisionCodes[i] + " is older than current " 14473 + before.splitRevisionCodes[j]); 14474 } 14475 } 14476 } 14477 } 14478 } 14479 } 14480} 14481