PackageManagerService.java revision 7d1a9d056261fdf304215c9b53b7cc4f4422e1db
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.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.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 android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 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.SparseIntArray; 178import android.util.Xml; 179import android.view.Display; 180 181import dalvik.system.DexFile; 182import dalvik.system.VMRuntime; 183 184import libcore.io.IoUtils; 185import libcore.util.EmptyArray; 186 187import com.android.internal.R; 188import com.android.internal.app.IMediaContainerService; 189import com.android.internal.app.ResolverActivity; 190import com.android.internal.content.NativeLibraryHelper; 191import com.android.internal.content.PackageHelper; 192import com.android.internal.os.IParcelFileDescriptorFactory; 193import com.android.internal.os.SomeArgs; 194import com.android.internal.util.ArrayUtils; 195import com.android.internal.util.FastPrintWriter; 196import com.android.internal.util.FastXmlSerializer; 197import com.android.internal.util.IndentingPrintWriter; 198import com.android.internal.util.Preconditions; 199import com.android.server.EventLogTags; 200import com.android.server.FgThread; 201import com.android.server.IntentResolver; 202import com.android.server.LocalServices; 203import com.android.server.ServiceThread; 204import com.android.server.SystemConfig; 205import com.android.server.Watchdog; 206import com.android.server.pm.Settings.DatabaseVersion; 207import com.android.server.storage.DeviceStorageMonitorInternal; 208 209import org.xmlpull.v1.XmlPullParser; 210import org.xmlpull.v1.XmlSerializer; 211 212import java.io.BufferedInputStream; 213import java.io.BufferedOutputStream; 214import java.io.BufferedReader; 215import java.io.ByteArrayInputStream; 216import java.io.ByteArrayOutputStream; 217import java.io.File; 218import java.io.FileDescriptor; 219import java.io.FileNotFoundException; 220import java.io.FileOutputStream; 221import java.io.FileReader; 222import java.io.FilenameFilter; 223import java.io.IOException; 224import java.io.InputStream; 225import java.io.PrintWriter; 226import java.nio.charset.StandardCharsets; 227import java.security.NoSuchAlgorithmException; 228import java.security.PublicKey; 229import java.security.cert.CertificateEncodingException; 230import java.security.cert.CertificateException; 231import java.text.SimpleDateFormat; 232import java.util.ArrayList; 233import java.util.Arrays; 234import java.util.Collection; 235import java.util.Collections; 236import java.util.Comparator; 237import java.util.Date; 238import java.util.Iterator; 239import java.util.List; 240import java.util.Map; 241import java.util.Objects; 242import java.util.Set; 243import java.util.concurrent.atomic.AtomicBoolean; 244import java.util.concurrent.atomic.AtomicInteger; 245import java.util.concurrent.atomic.AtomicLong; 246 247/** 248 * Keep track of all those .apks everywhere. 249 * 250 * This is very central to the platform's security; please run the unit 251 * tests whenever making modifications here: 252 * 253mmm frameworks/base/tests/AndroidTests 254adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 255adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 256 * 257 * {@hide} 258 */ 259public class PackageManagerService extends IPackageManager.Stub { 260 static final String TAG = "PackageManager"; 261 static final boolean DEBUG_SETTINGS = false; 262 static final boolean DEBUG_PREFERRED = false; 263 static final boolean DEBUG_UPGRADE = false; 264 private static final boolean DEBUG_BACKUP = true; 265 private static final boolean DEBUG_INSTALL = false; 266 private static final boolean DEBUG_REMOVE = false; 267 private static final boolean DEBUG_BROADCASTS = false; 268 private static final boolean DEBUG_SHOW_INFO = false; 269 private static final boolean DEBUG_PACKAGE_INFO = false; 270 private static final boolean DEBUG_INTENT_MATCHING = false; 271 private static final boolean DEBUG_PACKAGE_SCANNING = false; 272 private static final boolean DEBUG_VERIFY = false; 273 private static final boolean DEBUG_DEXOPT = false; 274 private static final boolean DEBUG_ABI_SELECTION = false; 275 276 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 277 278 private static final int RADIO_UID = Process.PHONE_UID; 279 private static final int LOG_UID = Process.LOG_UID; 280 private static final int NFC_UID = Process.NFC_UID; 281 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 282 private static final int SHELL_UID = Process.SHELL_UID; 283 284 // Cap the size of permission trees that 3rd party apps can define 285 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 286 287 // Suffix used during package installation when copying/moving 288 // package apks to install directory. 289 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 290 291 static final int SCAN_NO_DEX = 1<<1; 292 static final int SCAN_FORCE_DEX = 1<<2; 293 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 294 static final int SCAN_NEW_INSTALL = 1<<4; 295 static final int SCAN_NO_PATHS = 1<<5; 296 static final int SCAN_UPDATE_TIME = 1<<6; 297 static final int SCAN_DEFER_DEX = 1<<7; 298 static final int SCAN_BOOTING = 1<<8; 299 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 300 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 301 static final int SCAN_REPLACING = 1<<11; 302 static final int SCAN_REQUIRE_KNOWN = 1<<12; 303 304 static final int REMOVE_CHATTY = 1<<16; 305 306 /** 307 * Timeout (in milliseconds) after which the watchdog should declare that 308 * our handler thread is wedged. The usual default for such things is one 309 * minute but we sometimes do very lengthy I/O operations on this thread, 310 * such as installing multi-gigabyte applications, so ours needs to be longer. 311 */ 312 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 313 314 /** 315 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 316 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 317 * settings entry if available, otherwise we use the hardcoded default. If it's been 318 * more than this long since the last fstrim, we force one during the boot sequence. 319 * 320 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 321 * one gets run at the next available charging+idle time. This final mandatory 322 * no-fstrim check kicks in only of the other scheduling criteria is never met. 323 */ 324 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 325 326 /** 327 * Whether verification is enabled by default. 328 */ 329 private static final boolean DEFAULT_VERIFY_ENABLE = true; 330 331 /** 332 * The default maximum time to wait for the verification agent to return in 333 * milliseconds. 334 */ 335 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 336 337 /** 338 * The default response for package verification timeout. 339 * 340 * This can be either PackageManager.VERIFICATION_ALLOW or 341 * PackageManager.VERIFICATION_REJECT. 342 */ 343 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 344 345 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 346 347 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 348 DEFAULT_CONTAINER_PACKAGE, 349 "com.android.defcontainer.DefaultContainerService"); 350 351 private static final String KILL_APP_REASON_GIDS_CHANGED = 352 "permission grant or revoke changed gids"; 353 354 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 355 "permissions revoked"; 356 357 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 358 359 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 360 361 /** Permission grant: not grant the permission. */ 362 private static final int GRANT_DENIED = 1; 363 364 /** Permission grant: grant the permission as an install permission. */ 365 private static final int GRANT_INSTALL = 2; 366 367 /** Permission grant: grant the permission as a runtime one. */ 368 private static final int GRANT_RUNTIME = 3; 369 370 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 371 private static final int GRANT_UPGRADE = 4; 372 373 final ServiceThread mHandlerThread; 374 375 final PackageHandler mHandler; 376 377 /** 378 * Messages for {@link #mHandler} that need to wait for system ready before 379 * being dispatched. 380 */ 381 private ArrayList<Message> mPostSystemReadyMessages; 382 383 final int mSdkVersion = Build.VERSION.SDK_INT; 384 385 final Context mContext; 386 final boolean mFactoryTest; 387 final boolean mOnlyCore; 388 final boolean mLazyDexOpt; 389 final long mDexOptLRUThresholdInMills; 390 final DisplayMetrics mMetrics; 391 final int mDefParseFlags; 392 final String[] mSeparateProcesses; 393 final boolean mIsUpgrade; 394 395 // This is where all application persistent data goes. 396 final File mAppDataDir; 397 398 // This is where all application persistent data goes for secondary users. 399 final File mUserAppDataDir; 400 401 /** The location for ASEC container files on internal storage. */ 402 final String mAsecInternalPath; 403 404 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 405 // LOCK HELD. Can be called with mInstallLock held. 406 final Installer mInstaller; 407 408 /** Directory where installed third-party apps stored */ 409 final File mAppInstallDir; 410 411 /** 412 * Directory to which applications installed internally have their 413 * 32 bit native libraries copied. 414 */ 415 private File mAppLib32InstallDir; 416 417 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 418 // apps. 419 final File mDrmAppPrivateInstallDir; 420 421 // ---------------------------------------------------------------- 422 423 // Lock for state used when installing and doing other long running 424 // operations. Methods that must be called with this lock held have 425 // the suffix "LI". 426 final Object mInstallLock = new Object(); 427 428 // ---------------------------------------------------------------- 429 430 // Keys are String (package name), values are Package. This also serves 431 // as the lock for the global state. Methods that must be called with 432 // this lock held have the prefix "LP". 433 final ArrayMap<String, PackageParser.Package> mPackages = 434 new ArrayMap<String, PackageParser.Package>(); 435 436 // Tracks available target package names -> overlay package paths. 437 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 438 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 439 440 final Settings mSettings; 441 boolean mRestoredSettings; 442 443 // System configuration read by SystemConfig. 444 final int[] mGlobalGids; 445 final SparseArray<ArraySet<String>> mSystemPermissions; 446 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 447 448 // If mac_permissions.xml was found for seinfo labeling. 449 boolean mFoundPolicyFile; 450 451 // If a recursive restorecon of /data/data/<pkg> is needed. 452 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 453 454 public static final class SharedLibraryEntry { 455 public final String path; 456 public final String apk; 457 458 SharedLibraryEntry(String _path, String _apk) { 459 path = _path; 460 apk = _apk; 461 } 462 } 463 464 // Currently known shared libraries. 465 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 466 new ArrayMap<String, SharedLibraryEntry>(); 467 468 // All available activities, for your resolving pleasure. 469 final ActivityIntentResolver mActivities = 470 new ActivityIntentResolver(); 471 472 // All available receivers, for your resolving pleasure. 473 final ActivityIntentResolver mReceivers = 474 new ActivityIntentResolver(); 475 476 // All available services, for your resolving pleasure. 477 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 478 479 // All available providers, for your resolving pleasure. 480 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 481 482 // Mapping from provider base names (first directory in content URI codePath) 483 // to the provider information. 484 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 485 new ArrayMap<String, PackageParser.Provider>(); 486 487 // Mapping from instrumentation class names to info about them. 488 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 489 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 490 491 // Mapping from permission names to info about them. 492 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 493 new ArrayMap<String, PackageParser.PermissionGroup>(); 494 495 // Packages whose data we have transfered into another package, thus 496 // should no longer exist. 497 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 498 499 // Broadcast actions that are only available to the system. 500 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 501 502 /** List of packages waiting for verification. */ 503 final SparseArray<PackageVerificationState> mPendingVerification 504 = new SparseArray<PackageVerificationState>(); 505 506 /** Set of packages associated with each app op permission. */ 507 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 508 509 final PackageInstallerService mInstallerService; 510 511 private final PackageDexOptimizer mPackageDexOptimizer; 512 513 private AtomicInteger mNextMoveId = new AtomicInteger(); 514 private final MoveCallbacks mMoveCallbacks; 515 516 // Cache of users who need badging. 517 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 518 519 /** Token for keys in mPendingVerification. */ 520 private int mPendingVerificationToken = 0; 521 522 volatile boolean mSystemReady; 523 volatile boolean mSafeMode; 524 volatile boolean mHasSystemUidErrors; 525 526 ApplicationInfo mAndroidApplication; 527 final ActivityInfo mResolveActivity = new ActivityInfo(); 528 final ResolveInfo mResolveInfo = new ResolveInfo(); 529 ComponentName mResolveComponentName; 530 PackageParser.Package mPlatformPackage; 531 ComponentName mCustomResolverComponentName; 532 533 boolean mResolverReplaced = false; 534 535 private final ComponentName mIntentFilterVerifierComponent; 536 private int mIntentFilterVerificationToken = 0; 537 538 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 539 = new SparseArray<IntentFilterVerificationState>(); 540 541 private interface IntentFilterVerifier<T extends IntentFilter> { 542 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 543 T filter, String packageName); 544 void startVerifications(int userId); 545 void receiveVerificationResponse(int verificationId); 546 } 547 548 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 549 private Context mContext; 550 private ComponentName mIntentFilterVerifierComponent; 551 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 552 553 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 554 mContext = context; 555 mIntentFilterVerifierComponent = verifierComponent; 556 } 557 558 private String getDefaultScheme() { 559 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 560 return IntentFilter.SCHEME_HTTP; 561 } 562 563 @Override 564 public void startVerifications(int userId) { 565 // Launch verifications requests 566 int count = mCurrentIntentFilterVerifications.size(); 567 for (int n=0; n<count; n++) { 568 int verificationId = mCurrentIntentFilterVerifications.get(n); 569 final IntentFilterVerificationState ivs = 570 mIntentFilterVerificationStates.get(verificationId); 571 572 String packageName = ivs.getPackageName(); 573 574 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 575 final int filterCount = filters.size(); 576 ArraySet<String> domainsSet = new ArraySet<>(); 577 for (int m=0; m<filterCount; m++) { 578 PackageParser.ActivityIntentInfo filter = filters.get(m); 579 domainsSet.addAll(filter.getHostsList()); 580 } 581 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 582 synchronized (mPackages) { 583 if (mSettings.createIntentFilterVerificationIfNeededLPw( 584 packageName, domainsList) != null) { 585 scheduleWriteSettingsLocked(); 586 } 587 } 588 sendVerificationRequest(userId, verificationId, ivs); 589 } 590 mCurrentIntentFilterVerifications.clear(); 591 } 592 593 private void sendVerificationRequest(int userId, int verificationId, 594 IntentFilterVerificationState ivs) { 595 596 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 597 verificationIntent.putExtra( 598 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 599 verificationId); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 602 getDefaultScheme()); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 605 ivs.getHostsString()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 608 ivs.getPackageName()); 609 verificationIntent.setComponent(mIntentFilterVerifierComponent); 610 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 611 612 UserHandle user = new UserHandle(userId); 613 mContext.sendBroadcastAsUser(verificationIntent, user); 614 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 615 } 616 617 public void receiveVerificationResponse(int verificationId) { 618 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 619 620 final boolean verified = ivs.isVerified(); 621 622 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 623 final int count = filters.size(); 624 for (int n=0; n<count; n++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(n); 626 filter.setVerified(verified); 627 628 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 629 + verified + " and hosts:" + ivs.getHostsString()); 630 } 631 632 mIntentFilterVerificationStates.remove(verificationId); 633 634 final String packageName = ivs.getPackageName(); 635 IntentFilterVerificationInfo ivi = null; 636 637 synchronized (mPackages) { 638 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 639 } 640 if (ivi == null) { 641 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 642 + verificationId + " packageName:" + packageName); 643 return; 644 } 645 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 646 + verificationId); 647 648 synchronized (mPackages) { 649 if (verified) { 650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 651 } else { 652 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 653 } 654 scheduleWriteSettingsLocked(); 655 656 final int userId = ivs.getUserId(); 657 if (userId != UserHandle.USER_ALL) { 658 final int userStatus = 659 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 660 661 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 662 boolean needUpdate = false; 663 664 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 665 // already been set by the User thru the Disambiguation dialog 666 switch (userStatus) { 667 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 668 if (verified) { 669 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 670 } else { 671 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 672 } 673 needUpdate = true; 674 break; 675 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 needUpdate = true; 680 } 681 break; 682 683 default: 684 // Nothing to do 685 } 686 687 if (needUpdate) { 688 mSettings.updateIntentFilterVerificationStatusLPw( 689 packageName, updatedStatus, userId); 690 scheduleWritePackageRestrictionsLocked(userId); 691 } 692 } 693 } 694 } 695 696 @Override 697 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 698 ActivityIntentInfo filter, String packageName) { 699 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 700 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 701 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 702 return false; 703 } 704 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 705 if (ivs == null) { 706 ivs = createDomainVerificationState(verifierId, userId, verificationId, 707 packageName); 708 } 709 if (!hasValidDomains(filter)) { 710 return false; 711 } 712 ivs.addFilter(filter); 713 return true; 714 } 715 716 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 717 int userId, int verificationId, String packageName) { 718 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 719 verifierId, userId, packageName); 720 ivs.setPendingState(); 721 synchronized (mPackages) { 722 mIntentFilterVerificationStates.append(verificationId, ivs); 723 mCurrentIntentFilterVerifications.add(verificationId); 724 } 725 return ivs; 726 } 727 } 728 729 private static boolean hasValidDomains(ActivityIntentInfo filter) { 730 return hasValidDomains(filter, true); 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 734 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 735 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 736 if (!hasHTTPorHTTPS) { 737 if (logging) { 738 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 739 } 740 return false; 741 } 742 return true; 743 } 744 745 private IntentFilterVerifier mIntentFilterVerifier; 746 747 // Set of pending broadcasts for aggregating enable/disable of components. 748 static class PendingPackageBroadcasts { 749 // for each user id, a map of <package name -> components within that package> 750 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 751 752 public PendingPackageBroadcasts() { 753 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 754 } 755 756 public ArrayList<String> get(int userId, String packageName) { 757 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 758 return packages.get(packageName); 759 } 760 761 public void put(int userId, String packageName, ArrayList<String> components) { 762 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 763 packages.put(packageName, components); 764 } 765 766 public void remove(int userId, String packageName) { 767 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 768 if (packages != null) { 769 packages.remove(packageName); 770 } 771 } 772 773 public void remove(int userId) { 774 mUidMap.remove(userId); 775 } 776 777 public int userIdCount() { 778 return mUidMap.size(); 779 } 780 781 public int userIdAt(int n) { 782 return mUidMap.keyAt(n); 783 } 784 785 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 786 return mUidMap.get(userId); 787 } 788 789 public int size() { 790 // total number of pending broadcast entries across all userIds 791 int num = 0; 792 for (int i = 0; i< mUidMap.size(); i++) { 793 num += mUidMap.valueAt(i).size(); 794 } 795 return num; 796 } 797 798 public void clear() { 799 mUidMap.clear(); 800 } 801 802 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 803 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 804 if (map == null) { 805 map = new ArrayMap<String, ArrayList<String>>(); 806 mUidMap.put(userId, map); 807 } 808 return map; 809 } 810 } 811 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 812 813 // Service Connection to remote media container service to copy 814 // package uri's from external media onto secure containers 815 // or internal storage. 816 private IMediaContainerService mContainerService = null; 817 818 static final int SEND_PENDING_BROADCAST = 1; 819 static final int MCS_BOUND = 3; 820 static final int END_COPY = 4; 821 static final int INIT_COPY = 5; 822 static final int MCS_UNBIND = 6; 823 static final int START_CLEANING_PACKAGE = 7; 824 static final int FIND_INSTALL_LOC = 8; 825 static final int POST_INSTALL = 9; 826 static final int MCS_RECONNECT = 10; 827 static final int MCS_GIVE_UP = 11; 828 static final int UPDATED_MEDIA_STATUS = 12; 829 static final int WRITE_SETTINGS = 13; 830 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 831 static final int PACKAGE_VERIFIED = 15; 832 static final int CHECK_PENDING_VERIFICATION = 16; 833 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 834 static final int INTENT_FILTER_VERIFIED = 18; 835 836 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 837 838 // Delay time in millisecs 839 static final int BROADCAST_DELAY = 10 * 1000; 840 841 static UserManagerService sUserManager; 842 843 // Stores a list of users whose package restrictions file needs to be updated 844 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 845 846 final private DefaultContainerConnection mDefContainerConn = 847 new DefaultContainerConnection(); 848 class DefaultContainerConnection implements ServiceConnection { 849 public void onServiceConnected(ComponentName name, IBinder service) { 850 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 851 IMediaContainerService imcs = 852 IMediaContainerService.Stub.asInterface(service); 853 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 854 } 855 856 public void onServiceDisconnected(ComponentName name) { 857 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 858 } 859 }; 860 861 // Recordkeeping of restore-after-install operations that are currently in flight 862 // between the Package Manager and the Backup Manager 863 class PostInstallData { 864 public InstallArgs args; 865 public PackageInstalledInfo res; 866 867 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 868 args = _a; 869 res = _r; 870 } 871 }; 872 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 873 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 874 875 // backup/restore of preferred activity state 876 private static final String TAG_PREFERRED_BACKUP = "pa"; 877 878 private final String mRequiredVerifierPackage; 879 880 private final PackageUsage mPackageUsage = new PackageUsage(); 881 882 private class PackageUsage { 883 private static final int WRITE_INTERVAL 884 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 885 886 private final Object mFileLock = new Object(); 887 private final AtomicLong mLastWritten = new AtomicLong(0); 888 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 889 890 private boolean mIsHistoricalPackageUsageAvailable = true; 891 892 boolean isHistoricalPackageUsageAvailable() { 893 return mIsHistoricalPackageUsageAvailable; 894 } 895 896 void write(boolean force) { 897 if (force) { 898 writeInternal(); 899 return; 900 } 901 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 902 && !DEBUG_DEXOPT) { 903 return; 904 } 905 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 906 new Thread("PackageUsage_DiskWriter") { 907 @Override 908 public void run() { 909 try { 910 writeInternal(); 911 } finally { 912 mBackgroundWriteRunning.set(false); 913 } 914 } 915 }.start(); 916 } 917 } 918 919 private void writeInternal() { 920 synchronized (mPackages) { 921 synchronized (mFileLock) { 922 AtomicFile file = getFile(); 923 FileOutputStream f = null; 924 try { 925 f = file.startWrite(); 926 BufferedOutputStream out = new BufferedOutputStream(f); 927 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 928 StringBuilder sb = new StringBuilder(); 929 for (PackageParser.Package pkg : mPackages.values()) { 930 if (pkg.mLastPackageUsageTimeInMills == 0) { 931 continue; 932 } 933 sb.setLength(0); 934 sb.append(pkg.packageName); 935 sb.append(' '); 936 sb.append((long)pkg.mLastPackageUsageTimeInMills); 937 sb.append('\n'); 938 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 939 } 940 out.flush(); 941 file.finishWrite(f); 942 } catch (IOException e) { 943 if (f != null) { 944 file.failWrite(f); 945 } 946 Log.e(TAG, "Failed to write package usage times", e); 947 } 948 } 949 } 950 mLastWritten.set(SystemClock.elapsedRealtime()); 951 } 952 953 void readLP() { 954 synchronized (mFileLock) { 955 AtomicFile file = getFile(); 956 BufferedInputStream in = null; 957 try { 958 in = new BufferedInputStream(file.openRead()); 959 StringBuffer sb = new StringBuffer(); 960 while (true) { 961 String packageName = readToken(in, sb, ' '); 962 if (packageName == null) { 963 break; 964 } 965 String timeInMillisString = readToken(in, sb, '\n'); 966 if (timeInMillisString == null) { 967 throw new IOException("Failed to find last usage time for package " 968 + packageName); 969 } 970 PackageParser.Package pkg = mPackages.get(packageName); 971 if (pkg == null) { 972 continue; 973 } 974 long timeInMillis; 975 try { 976 timeInMillis = Long.parseLong(timeInMillisString.toString()); 977 } catch (NumberFormatException e) { 978 throw new IOException("Failed to parse " + timeInMillisString 979 + " as a long.", e); 980 } 981 pkg.mLastPackageUsageTimeInMills = timeInMillis; 982 } 983 } catch (FileNotFoundException expected) { 984 mIsHistoricalPackageUsageAvailable = false; 985 } catch (IOException e) { 986 Log.w(TAG, "Failed to read package usage times", e); 987 } finally { 988 IoUtils.closeQuietly(in); 989 } 990 } 991 mLastWritten.set(SystemClock.elapsedRealtime()); 992 } 993 994 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 995 throws IOException { 996 sb.setLength(0); 997 while (true) { 998 int ch = in.read(); 999 if (ch == -1) { 1000 if (sb.length() == 0) { 1001 return null; 1002 } 1003 throw new IOException("Unexpected EOF"); 1004 } 1005 if (ch == endOfToken) { 1006 return sb.toString(); 1007 } 1008 sb.append((char)ch); 1009 } 1010 } 1011 1012 private AtomicFile getFile() { 1013 File dataDir = Environment.getDataDirectory(); 1014 File systemDir = new File(dataDir, "system"); 1015 File fname = new File(systemDir, "package-usage.list"); 1016 return new AtomicFile(fname); 1017 } 1018 } 1019 1020 class PackageHandler extends Handler { 1021 private boolean mBound = false; 1022 final ArrayList<HandlerParams> mPendingInstalls = 1023 new ArrayList<HandlerParams>(); 1024 1025 private boolean connectToService() { 1026 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1027 " DefaultContainerService"); 1028 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1029 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1030 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1031 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1033 mBound = true; 1034 return true; 1035 } 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 return false; 1038 } 1039 1040 private void disconnectService() { 1041 mContainerService = null; 1042 mBound = false; 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1044 mContext.unbindService(mDefContainerConn); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 } 1047 1048 PackageHandler(Looper looper) { 1049 super(looper); 1050 } 1051 1052 public void handleMessage(Message msg) { 1053 try { 1054 doHandleMessage(msg); 1055 } finally { 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 } 1059 1060 void doHandleMessage(Message msg) { 1061 switch (msg.what) { 1062 case INIT_COPY: { 1063 HandlerParams params = (HandlerParams) msg.obj; 1064 int idx = mPendingInstalls.size(); 1065 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1066 // If a bind was already initiated we dont really 1067 // need to do anything. The pending install 1068 // will be processed later on. 1069 if (!mBound) { 1070 // If this is the only one pending we might 1071 // have to bind to the service again. 1072 if (!connectToService()) { 1073 Slog.e(TAG, "Failed to bind to media container service"); 1074 params.serviceError(); 1075 return; 1076 } else { 1077 // Once we bind to the service, the first 1078 // pending request will be processed. 1079 mPendingInstalls.add(idx, params); 1080 } 1081 } else { 1082 mPendingInstalls.add(idx, params); 1083 // Already bound to the service. Just make 1084 // sure we trigger off processing the first request. 1085 if (idx == 0) { 1086 mHandler.sendEmptyMessage(MCS_BOUND); 1087 } 1088 } 1089 break; 1090 } 1091 case MCS_BOUND: { 1092 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1093 if (msg.obj != null) { 1094 mContainerService = (IMediaContainerService) msg.obj; 1095 } 1096 if (mContainerService == null) { 1097 // Something seriously wrong. Bail out 1098 Slog.e(TAG, "Cannot bind to media container service"); 1099 for (HandlerParams params : mPendingInstalls) { 1100 // Indicate service bind error 1101 params.serviceError(); 1102 } 1103 mPendingInstalls.clear(); 1104 } else if (mPendingInstalls.size() > 0) { 1105 HandlerParams params = mPendingInstalls.get(0); 1106 if (params != null) { 1107 if (params.startCopy()) { 1108 // We are done... look for more work or to 1109 // go idle. 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, 1111 "Checking for more work or unbind..."); 1112 // Delete pending install 1113 if (mPendingInstalls.size() > 0) { 1114 mPendingInstalls.remove(0); 1115 } 1116 if (mPendingInstalls.size() == 0) { 1117 if (mBound) { 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Posting delayed MCS_UNBIND"); 1120 removeMessages(MCS_UNBIND); 1121 Message ubmsg = obtainMessage(MCS_UNBIND); 1122 // Unbind after a little delay, to avoid 1123 // continual thrashing. 1124 sendMessageDelayed(ubmsg, 10000); 1125 } 1126 } else { 1127 // There are more pending requests in queue. 1128 // Just post MCS_BOUND message to trigger processing 1129 // of next pending install. 1130 if (DEBUG_SD_INSTALL) Log.i(TAG, 1131 "Posting MCS_BOUND for next work"); 1132 mHandler.sendEmptyMessage(MCS_BOUND); 1133 } 1134 } 1135 } 1136 } else { 1137 // Should never happen ideally. 1138 Slog.w(TAG, "Empty queue"); 1139 } 1140 break; 1141 } 1142 case MCS_RECONNECT: { 1143 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1144 if (mPendingInstalls.size() > 0) { 1145 if (mBound) { 1146 disconnectService(); 1147 } 1148 if (!connectToService()) { 1149 Slog.e(TAG, "Failed to bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } 1156 } 1157 break; 1158 } 1159 case MCS_UNBIND: { 1160 // If there is no actual work left, then time to unbind. 1161 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1162 1163 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1164 if (mBound) { 1165 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1166 1167 disconnectService(); 1168 } 1169 } else if (mPendingInstalls.size() > 0) { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 1176 break; 1177 } 1178 case MCS_GIVE_UP: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1180 mPendingInstalls.remove(0); 1181 break; 1182 } 1183 case SEND_PENDING_BROADCAST: { 1184 String packages[]; 1185 ArrayList<String> components[]; 1186 int size = 0; 1187 int uids[]; 1188 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1189 synchronized (mPackages) { 1190 if (mPendingBroadcasts == null) { 1191 return; 1192 } 1193 size = mPendingBroadcasts.size(); 1194 if (size <= 0) { 1195 // Nothing to be done. Just return 1196 return; 1197 } 1198 packages = new String[size]; 1199 components = new ArrayList[size]; 1200 uids = new int[size]; 1201 int i = 0; // filling out the above arrays 1202 1203 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1204 int packageUserId = mPendingBroadcasts.userIdAt(n); 1205 Iterator<Map.Entry<String, ArrayList<String>>> it 1206 = mPendingBroadcasts.packagesForUserId(packageUserId) 1207 .entrySet().iterator(); 1208 while (it.hasNext() && i < size) { 1209 Map.Entry<String, ArrayList<String>> ent = it.next(); 1210 packages[i] = ent.getKey(); 1211 components[i] = ent.getValue(); 1212 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1213 uids[i] = (ps != null) 1214 ? UserHandle.getUid(packageUserId, ps.appId) 1215 : -1; 1216 i++; 1217 } 1218 } 1219 size = i; 1220 mPendingBroadcasts.clear(); 1221 } 1222 // Send broadcasts 1223 for (int i = 0; i < size; i++) { 1224 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 break; 1228 } 1229 case START_CLEANING_PACKAGE: { 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 final String packageName = (String)msg.obj; 1232 final int userId = msg.arg1; 1233 final boolean andCode = msg.arg2 != 0; 1234 synchronized (mPackages) { 1235 if (userId == UserHandle.USER_ALL) { 1236 int[] users = sUserManager.getUserIds(); 1237 for (int user : users) { 1238 mSettings.addPackageToCleanLPw( 1239 new PackageCleanItem(user, packageName, andCode)); 1240 } 1241 } else { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(userId, packageName, andCode)); 1244 } 1245 } 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 startCleaningPackages(); 1248 } break; 1249 case POST_INSTALL: { 1250 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1251 PostInstallData data = mRunningInstalls.get(msg.arg1); 1252 mRunningInstalls.delete(msg.arg1); 1253 boolean deleteOld = false; 1254 1255 if (data != null) { 1256 InstallArgs args = data.args; 1257 PackageInstalledInfo res = data.res; 1258 1259 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1260 res.removedInfo.sendBroadcast(false, true, false); 1261 Bundle extras = new Bundle(1); 1262 extras.putInt(Intent.EXTRA_UID, res.uid); 1263 1264 // Now that we successfully installed the package, grant runtime 1265 // permissions if requested before broadcasting the install. 1266 if ((args.installFlags 1267 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1268 grantRequestedRuntimePermissions(res.pkg, 1269 args.user.getIdentifier()); 1270 } 1271 1272 // Determine the set of users who are adding this 1273 // package for the first time vs. those who are seeing 1274 // an update. 1275 int[] firstUsers; 1276 int[] updateUsers = new int[0]; 1277 if (res.origUsers == null || res.origUsers.length == 0) { 1278 firstUsers = res.newUsers; 1279 } else { 1280 firstUsers = new int[0]; 1281 for (int i=0; i<res.newUsers.length; i++) { 1282 int user = res.newUsers[i]; 1283 boolean isNew = true; 1284 for (int j=0; j<res.origUsers.length; j++) { 1285 if (res.origUsers[j] == user) { 1286 isNew = false; 1287 break; 1288 } 1289 } 1290 if (isNew) { 1291 int[] newFirst = new int[firstUsers.length+1]; 1292 System.arraycopy(firstUsers, 0, newFirst, 0, 1293 firstUsers.length); 1294 newFirst[firstUsers.length] = user; 1295 firstUsers = newFirst; 1296 } else { 1297 int[] newUpdate = new int[updateUsers.length+1]; 1298 System.arraycopy(updateUsers, 0, newUpdate, 0, 1299 updateUsers.length); 1300 newUpdate[updateUsers.length] = user; 1301 updateUsers = newUpdate; 1302 } 1303 } 1304 } 1305 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1306 res.pkg.applicationInfo.packageName, 1307 extras, null, null, firstUsers); 1308 final boolean update = res.removedInfo.removedPackage != null; 1309 if (update) { 1310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1311 } 1312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1313 res.pkg.applicationInfo.packageName, 1314 extras, null, null, updateUsers); 1315 if (update) { 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1320 null, null, 1321 res.pkg.applicationInfo.packageName, null, updateUsers); 1322 1323 // treat asec-hosted packages like removable media on upgrade 1324 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1325 if (DEBUG_INSTALL) { 1326 Slog.i(TAG, "upgrading pkg " + res.pkg 1327 + " is ASEC-hosted -> AVAILABLE"); 1328 } 1329 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1330 ArrayList<String> pkgList = new ArrayList<String>(1); 1331 pkgList.add(res.pkg.applicationInfo.packageName); 1332 sendResourcesChangedBroadcast(true, true, 1333 pkgList,uidArray, null); 1334 } 1335 } 1336 if (res.removedInfo.args != null) { 1337 // Remove the replaced package's older resources safely now 1338 deleteOld = true; 1339 } 1340 1341 // Log current value of "unknown sources" setting 1342 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1343 getUnknownSourcesSettings()); 1344 } 1345 // Force a gc to clear up things 1346 Runtime.getRuntime().gc(); 1347 // We delete after a gc for applications on sdcard. 1348 if (deleteOld) { 1349 synchronized (mInstallLock) { 1350 res.removedInfo.args.doPostDeleteLI(true); 1351 } 1352 } 1353 if (args.observer != null) { 1354 try { 1355 Bundle extras = extrasForInstallResult(res); 1356 args.observer.onPackageInstalled(res.name, res.returnCode, 1357 res.returnMsg, extras); 1358 } catch (RemoteException e) { 1359 Slog.i(TAG, "Observer no longer exists."); 1360 } 1361 } 1362 } else { 1363 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1364 } 1365 } break; 1366 case UPDATED_MEDIA_STATUS: { 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1368 boolean reportStatus = msg.arg1 == 1; 1369 boolean doGc = msg.arg2 == 1; 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1371 if (doGc) { 1372 // Force a gc to clear up stale containers. 1373 Runtime.getRuntime().gc(); 1374 } 1375 if (msg.obj != null) { 1376 @SuppressWarnings("unchecked") 1377 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1379 // Unload containers 1380 unloadAllContainers(args); 1381 } 1382 if (reportStatus) { 1383 try { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1385 PackageHelper.getMountService().finishMediaUpdate(); 1386 } catch (RemoteException e) { 1387 Log.e(TAG, "MountService not running?"); 1388 } 1389 } 1390 } break; 1391 case WRITE_SETTINGS: { 1392 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1393 synchronized (mPackages) { 1394 removeMessages(WRITE_SETTINGS); 1395 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1396 mSettings.writeLPr(); 1397 mDirtyUsers.clear(); 1398 } 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } break; 1401 case WRITE_PACKAGE_RESTRICTIONS: { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1403 synchronized (mPackages) { 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 for (int userId : mDirtyUsers) { 1406 mSettings.writePackageRestrictionsLPr(userId); 1407 } 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case CHECK_PENDING_VERIFICATION: { 1413 final int verificationId = msg.arg1; 1414 final PackageVerificationState state = mPendingVerification.get(verificationId); 1415 1416 if ((state != null) && !state.timeoutExtended()) { 1417 final InstallArgs args = state.getInstallArgs(); 1418 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1419 1420 Slog.i(TAG, "Verification timed out for " + originUri); 1421 mPendingVerification.remove(verificationId); 1422 1423 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1424 1425 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1426 Slog.i(TAG, "Continuing with installation of " + originUri); 1427 state.setVerifierResponse(Binder.getCallingUid(), 1428 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1429 broadcastPackageVerified(verificationId, originUri, 1430 PackageManager.VERIFICATION_ALLOW, 1431 state.getInstallArgs().getUser()); 1432 try { 1433 ret = args.copyApk(mContainerService, true); 1434 } catch (RemoteException e) { 1435 Slog.e(TAG, "Could not contact the ContainerService"); 1436 } 1437 } else { 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_REJECT, 1440 state.getInstallArgs().getUser()); 1441 } 1442 1443 processPendingInstall(args, ret); 1444 mHandler.sendEmptyMessage(MCS_UNBIND); 1445 } 1446 break; 1447 } 1448 case PACKAGE_VERIFIED: { 1449 final int verificationId = msg.arg1; 1450 1451 final PackageVerificationState state = mPendingVerification.get(verificationId); 1452 if (state == null) { 1453 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1454 break; 1455 } 1456 1457 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1458 1459 state.setVerifierResponse(response.callerUid, response.code); 1460 1461 if (state.isVerificationComplete()) { 1462 mPendingVerification.remove(verificationId); 1463 1464 final InstallArgs args = state.getInstallArgs(); 1465 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1466 1467 int ret; 1468 if (state.isInstallAllowed()) { 1469 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1470 broadcastPackageVerified(verificationId, originUri, 1471 response.code, state.getInstallArgs().getUser()); 1472 try { 1473 ret = args.copyApk(mContainerService, true); 1474 } catch (RemoteException e) { 1475 Slog.e(TAG, "Could not contact the ContainerService"); 1476 } 1477 } else { 1478 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1479 } 1480 1481 processPendingInstall(args, ret); 1482 1483 mHandler.sendEmptyMessage(MCS_UNBIND); 1484 } 1485 1486 break; 1487 } 1488 case START_INTENT_FILTER_VERIFICATIONS: { 1489 int userId = msg.arg1; 1490 int verifierUid = msg.arg2; 1491 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1492 1493 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1494 break; 1495 } 1496 case INTENT_FILTER_VERIFIED: { 1497 final int verificationId = msg.arg1; 1498 1499 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1500 verificationId); 1501 if (state == null) { 1502 Slog.w(TAG, "Invalid IntentFilter verification token " 1503 + verificationId + " received"); 1504 break; 1505 } 1506 1507 final int userId = state.getUserId(); 1508 1509 Slog.d(TAG, "Processing IntentFilter verification with token:" 1510 + verificationId + " and userId:" + userId); 1511 1512 final IntentFilterVerificationResponse response = 1513 (IntentFilterVerificationResponse) msg.obj; 1514 1515 state.setVerifierResponse(response.callerUid, response.code); 1516 1517 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1518 + " and userId:" + userId 1519 + " is settings verifier response with response code:" 1520 + response.code); 1521 1522 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1523 Slog.d(TAG, "Domains failing verification: " 1524 + response.getFailedDomainsString()); 1525 } 1526 1527 if (state.isVerificationComplete()) { 1528 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1529 } else { 1530 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1531 + " was not said to be complete"); 1532 } 1533 1534 break; 1535 } 1536 } 1537 } 1538 } 1539 1540 private StorageEventListener mStorageListener = new StorageEventListener() { 1541 @Override 1542 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1543 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1544 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1545 // TODO: ensure that private directories exist for all active users 1546 // TODO: remove user data whose serial number doesn't match 1547 loadPrivatePackages(vol); 1548 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1549 unloadPrivatePackages(vol); 1550 } 1551 } 1552 1553 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1554 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1555 updateExternalMediaStatus(true, false); 1556 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1557 updateExternalMediaStatus(false, false); 1558 } 1559 } 1560 } 1561 }; 1562 1563 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1564 if (userId >= UserHandle.USER_OWNER) { 1565 grantRequestedRuntimePermissionsForUser(pkg, userId); 1566 } else if (userId == UserHandle.USER_ALL) { 1567 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1568 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1569 } 1570 } 1571 } 1572 1573 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1574 SettingBase sb = (SettingBase) pkg.mExtras; 1575 if (sb == null) { 1576 return; 1577 } 1578 1579 PermissionsState permissionsState = sb.getPermissionsState(); 1580 1581 for (String permission : pkg.requestedPermissions) { 1582 BasePermission bp = mSettings.mPermissions.get(permission); 1583 if (bp != null && bp.isRuntime()) { 1584 permissionsState.grantRuntimePermission(bp, userId); 1585 } 1586 } 1587 } 1588 1589 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1590 Bundle extras = null; 1591 switch (res.returnCode) { 1592 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1593 extras = new Bundle(); 1594 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1595 res.origPermission); 1596 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1597 res.origPackage); 1598 break; 1599 } 1600 } 1601 return extras; 1602 } 1603 1604 void scheduleWriteSettingsLocked() { 1605 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1606 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1607 } 1608 } 1609 1610 void scheduleWritePackageRestrictionsLocked(int userId) { 1611 if (!sUserManager.exists(userId)) return; 1612 mDirtyUsers.add(userId); 1613 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1614 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1615 } 1616 } 1617 1618 public static PackageManagerService main(Context context, Installer installer, 1619 boolean factoryTest, boolean onlyCore) { 1620 PackageManagerService m = new PackageManagerService(context, installer, 1621 factoryTest, onlyCore); 1622 ServiceManager.addService("package", m); 1623 return m; 1624 } 1625 1626 static String[] splitString(String str, char sep) { 1627 int count = 1; 1628 int i = 0; 1629 while ((i=str.indexOf(sep, i)) >= 0) { 1630 count++; 1631 i++; 1632 } 1633 1634 String[] res = new String[count]; 1635 i=0; 1636 count = 0; 1637 int lastI=0; 1638 while ((i=str.indexOf(sep, i)) >= 0) { 1639 res[count] = str.substring(lastI, i); 1640 count++; 1641 i++; 1642 lastI = i; 1643 } 1644 res[count] = str.substring(lastI, str.length()); 1645 return res; 1646 } 1647 1648 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1649 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1650 Context.DISPLAY_SERVICE); 1651 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1652 } 1653 1654 public PackageManagerService(Context context, Installer installer, 1655 boolean factoryTest, boolean onlyCore) { 1656 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1657 SystemClock.uptimeMillis()); 1658 1659 if (mSdkVersion <= 0) { 1660 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1661 } 1662 1663 mContext = context; 1664 mFactoryTest = factoryTest; 1665 mOnlyCore = onlyCore; 1666 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1667 mMetrics = new DisplayMetrics(); 1668 mSettings = new Settings(mPackages); 1669 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1670 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1671 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1672 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1673 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1674 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1675 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1676 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1677 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1678 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1679 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1680 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1681 1682 // TODO: add a property to control this? 1683 long dexOptLRUThresholdInMinutes; 1684 if (mLazyDexOpt) { 1685 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1686 } else { 1687 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1688 } 1689 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1690 1691 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1692 if (separateProcesses != null && separateProcesses.length() > 0) { 1693 if ("*".equals(separateProcesses)) { 1694 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1695 mSeparateProcesses = null; 1696 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1697 } else { 1698 mDefParseFlags = 0; 1699 mSeparateProcesses = separateProcesses.split(","); 1700 Slog.w(TAG, "Running with debug.separate_processes: " 1701 + separateProcesses); 1702 } 1703 } else { 1704 mDefParseFlags = 0; 1705 mSeparateProcesses = null; 1706 } 1707 1708 mInstaller = installer; 1709 mPackageDexOptimizer = new PackageDexOptimizer(this); 1710 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1711 1712 getDefaultDisplayMetrics(context, mMetrics); 1713 1714 SystemConfig systemConfig = SystemConfig.getInstance(); 1715 mGlobalGids = systemConfig.getGlobalGids(); 1716 mSystemPermissions = systemConfig.getSystemPermissions(); 1717 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1718 1719 synchronized (mInstallLock) { 1720 // writer 1721 synchronized (mPackages) { 1722 mHandlerThread = new ServiceThread(TAG, 1723 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1724 mHandlerThread.start(); 1725 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1726 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1727 1728 File dataDir = Environment.getDataDirectory(); 1729 mAppDataDir = new File(dataDir, "data"); 1730 mAppInstallDir = new File(dataDir, "app"); 1731 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1732 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1733 mUserAppDataDir = new File(dataDir, "user"); 1734 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1735 1736 sUserManager = new UserManagerService(context, this, 1737 mInstallLock, mPackages); 1738 1739 // Propagate permission configuration in to package manager. 1740 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1741 = systemConfig.getPermissions(); 1742 for (int i=0; i<permConfig.size(); i++) { 1743 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1744 BasePermission bp = mSettings.mPermissions.get(perm.name); 1745 if (bp == null) { 1746 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1747 mSettings.mPermissions.put(perm.name, bp); 1748 } 1749 if (perm.gids != null) { 1750 bp.setGids(perm.gids, perm.perUser); 1751 } 1752 } 1753 1754 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1755 for (int i=0; i<libConfig.size(); i++) { 1756 mSharedLibraries.put(libConfig.keyAt(i), 1757 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1758 } 1759 1760 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1761 1762 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1763 mSdkVersion, mOnlyCore); 1764 1765 String customResolverActivity = Resources.getSystem().getString( 1766 R.string.config_customResolverActivity); 1767 if (TextUtils.isEmpty(customResolverActivity)) { 1768 customResolverActivity = null; 1769 } else { 1770 mCustomResolverComponentName = ComponentName.unflattenFromString( 1771 customResolverActivity); 1772 } 1773 1774 long startTime = SystemClock.uptimeMillis(); 1775 1776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1777 startTime); 1778 1779 // Set flag to monitor and not change apk file paths when 1780 // scanning install directories. 1781 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1782 1783 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1784 1785 /** 1786 * Add everything in the in the boot class path to the 1787 * list of process files because dexopt will have been run 1788 * if necessary during zygote startup. 1789 */ 1790 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1791 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1792 1793 if (bootClassPath != null) { 1794 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1795 for (String element : bootClassPathElements) { 1796 alreadyDexOpted.add(element); 1797 } 1798 } else { 1799 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1800 } 1801 1802 if (systemServerClassPath != null) { 1803 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1804 for (String element : systemServerClassPathElements) { 1805 alreadyDexOpted.add(element); 1806 } 1807 } else { 1808 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1809 } 1810 1811 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1812 final String[] dexCodeInstructionSets = 1813 getDexCodeInstructionSets( 1814 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1815 1816 /** 1817 * Ensure all external libraries have had dexopt run on them. 1818 */ 1819 if (mSharedLibraries.size() > 0) { 1820 // NOTE: For now, we're compiling these system "shared libraries" 1821 // (and framework jars) into all available architectures. It's possible 1822 // to compile them only when we come across an app that uses them (there's 1823 // already logic for that in scanPackageLI) but that adds some complexity. 1824 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1825 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1826 final String lib = libEntry.path; 1827 if (lib == null) { 1828 continue; 1829 } 1830 1831 try { 1832 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1833 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1834 alreadyDexOpted.add(lib); 1835 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1836 } 1837 } catch (FileNotFoundException e) { 1838 Slog.w(TAG, "Library not found: " + lib); 1839 } catch (IOException e) { 1840 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1841 + e.getMessage()); 1842 } 1843 } 1844 } 1845 } 1846 1847 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1848 1849 // Gross hack for now: we know this file doesn't contain any 1850 // code, so don't dexopt it to avoid the resulting log spew. 1851 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1852 1853 // Gross hack for now: we know this file is only part of 1854 // the boot class path for art, so don't dexopt it to 1855 // avoid the resulting log spew. 1856 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1857 1858 /** 1859 * And there are a number of commands implemented in Java, which 1860 * we currently need to do the dexopt on so that they can be 1861 * run from a non-root shell. 1862 */ 1863 String[] frameworkFiles = frameworkDir.list(); 1864 if (frameworkFiles != null) { 1865 // TODO: We could compile these only for the most preferred ABI. We should 1866 // first double check that the dex files for these commands are not referenced 1867 // by other system apps. 1868 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1869 for (int i=0; i<frameworkFiles.length; i++) { 1870 File libPath = new File(frameworkDir, frameworkFiles[i]); 1871 String path = libPath.getPath(); 1872 // Skip the file if we already did it. 1873 if (alreadyDexOpted.contains(path)) { 1874 continue; 1875 } 1876 // Skip the file if it is not a type we want to dexopt. 1877 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1878 continue; 1879 } 1880 try { 1881 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1882 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1883 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1884 } 1885 } catch (FileNotFoundException e) { 1886 Slog.w(TAG, "Jar not found: " + path); 1887 } catch (IOException e) { 1888 Slog.w(TAG, "Exception reading jar: " + path, e); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Collect vendor overlay packages. 1895 // (Do this before scanning any apps.) 1896 // For security and version matching reason, only consider 1897 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1898 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1899 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1900 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1901 1902 // Find base frameworks (resource packages without code). 1903 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1904 | PackageParser.PARSE_IS_SYSTEM_DIR 1905 | PackageParser.PARSE_IS_PRIVILEGED, 1906 scanFlags | SCAN_NO_DEX, 0); 1907 1908 // Collected privileged system packages. 1909 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1910 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1911 | PackageParser.PARSE_IS_SYSTEM_DIR 1912 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1913 1914 // Collect ordinary system packages. 1915 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1916 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1917 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1918 1919 // Collect all vendor packages. 1920 File vendorAppDir = new File("/vendor/app"); 1921 try { 1922 vendorAppDir = vendorAppDir.getCanonicalFile(); 1923 } catch (IOException e) { 1924 // failed to look up canonical path, continue with original one 1925 } 1926 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1927 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1928 1929 // Collect all OEM packages. 1930 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1931 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1935 mInstaller.moveFiles(); 1936 1937 // Prune any system packages that no longer exist. 1938 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1939 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1940 if (!mOnlyCore) { 1941 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1942 while (psit.hasNext()) { 1943 PackageSetting ps = psit.next(); 1944 1945 /* 1946 * If this is not a system app, it can't be a 1947 * disable system app. 1948 */ 1949 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1950 continue; 1951 } 1952 1953 /* 1954 * If the package is scanned, it's not erased. 1955 */ 1956 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1957 if (scannedPkg != null) { 1958 /* 1959 * If the system app is both scanned and in the 1960 * disabled packages list, then it must have been 1961 * added via OTA. Remove it from the currently 1962 * scanned package so the previously user-installed 1963 * application can be scanned. 1964 */ 1965 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1966 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1967 + ps.name + "; removing system app. Last known codePath=" 1968 + ps.codePathString + ", installStatus=" + ps.installStatus 1969 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1970 + scannedPkg.mVersionCode); 1971 removePackageLI(ps, true); 1972 expectingBetter.put(ps.name, ps.codePath); 1973 } 1974 1975 continue; 1976 } 1977 1978 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1979 psit.remove(); 1980 logCriticalInfo(Log.WARN, "System package " + ps.name 1981 + " no longer exists; wiping its data"); 1982 removeDataDirsLI(null, ps.name); 1983 } else { 1984 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1985 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1986 possiblyDeletedUpdatedSystemApps.add(ps.name); 1987 } 1988 } 1989 } 1990 } 1991 1992 //look for any incomplete package installations 1993 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1994 //clean up list 1995 for(int i = 0; i < deletePkgsList.size(); i++) { 1996 //clean up here 1997 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1998 } 1999 //delete tmp files 2000 deleteTempPackageFiles(); 2001 2002 // Remove any shared userIDs that have no associated packages 2003 mSettings.pruneSharedUsersLPw(); 2004 2005 if (!mOnlyCore) { 2006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2007 SystemClock.uptimeMillis()); 2008 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2009 2010 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2011 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2012 2013 /** 2014 * Remove disable package settings for any updated system 2015 * apps that were removed via an OTA. If they're not a 2016 * previously-updated app, remove them completely. 2017 * Otherwise, just revoke their system-level permissions. 2018 */ 2019 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2020 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2021 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2022 2023 String msg; 2024 if (deletedPkg == null) { 2025 msg = "Updated system package " + deletedAppName 2026 + " no longer exists; wiping its data"; 2027 removeDataDirsLI(null, deletedAppName); 2028 } else { 2029 msg = "Updated system app + " + deletedAppName 2030 + " no longer present; removing system privileges for " 2031 + deletedAppName; 2032 2033 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2034 2035 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2036 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2037 } 2038 logCriticalInfo(Log.WARN, msg); 2039 } 2040 2041 /** 2042 * Make sure all system apps that we expected to appear on 2043 * the userdata partition actually showed up. If they never 2044 * appeared, crawl back and revive the system version. 2045 */ 2046 for (int i = 0; i < expectingBetter.size(); i++) { 2047 final String packageName = expectingBetter.keyAt(i); 2048 if (!mPackages.containsKey(packageName)) { 2049 final File scanFile = expectingBetter.valueAt(i); 2050 2051 logCriticalInfo(Log.WARN, "Expected better " + packageName 2052 + " but never showed up; reverting to system"); 2053 2054 final int reparseFlags; 2055 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2056 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2057 | PackageParser.PARSE_IS_SYSTEM_DIR 2058 | PackageParser.PARSE_IS_PRIVILEGED; 2059 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2060 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2061 | PackageParser.PARSE_IS_SYSTEM_DIR; 2062 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2063 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2064 | PackageParser.PARSE_IS_SYSTEM_DIR; 2065 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2066 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR; 2068 } else { 2069 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2070 continue; 2071 } 2072 2073 mSettings.enableSystemPackageLPw(packageName); 2074 2075 try { 2076 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2077 } catch (PackageManagerException e) { 2078 Slog.e(TAG, "Failed to parse original system package: " 2079 + e.getMessage()); 2080 } 2081 } 2082 } 2083 } 2084 2085 // Now that we know all of the shared libraries, update all clients to have 2086 // the correct library paths. 2087 updateAllSharedLibrariesLPw(); 2088 2089 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2090 // NOTE: We ignore potential failures here during a system scan (like 2091 // the rest of the commands above) because there's precious little we 2092 // can do about it. A settings error is reported, though. 2093 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2094 false /* force dexopt */, false /* defer dexopt */); 2095 } 2096 2097 // Now that we know all the packages we are keeping, 2098 // read and update their last usage times. 2099 mPackageUsage.readLP(); 2100 2101 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2102 SystemClock.uptimeMillis()); 2103 Slog.i(TAG, "Time to scan packages: " 2104 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2105 + " seconds"); 2106 2107 // If the platform SDK has changed since the last time we booted, 2108 // we need to re-grant app permission to catch any new ones that 2109 // appear. This is really a hack, and means that apps can in some 2110 // cases get permissions that the user didn't initially explicitly 2111 // allow... it would be nice to have some better way to handle 2112 // this situation. 2113 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2114 != mSdkVersion; 2115 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2116 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2117 + "; regranting permissions for internal storage"); 2118 mSettings.mInternalSdkPlatform = mSdkVersion; 2119 2120 // For now runtime permissions are toggled via a system property. 2121 if (!RUNTIME_PERMISSIONS_ENABLED) { 2122 // Remove the runtime permissions state if the feature 2123 // was disabled by flipping the system property. 2124 mSettings.deleteRuntimePermissionsFiles(); 2125 } 2126 2127 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2128 | (regrantPermissions 2129 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2130 : 0)); 2131 2132 // If this is the first boot, and it is a normal boot, then 2133 // we need to initialize the default preferred apps. 2134 if (!mRestoredSettings && !onlyCore) { 2135 mSettings.readDefaultPreferredAppsLPw(this, 0); 2136 } 2137 2138 // If this is first boot after an OTA, and a normal boot, then 2139 // we need to clear code cache directories. 2140 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2141 if (mIsUpgrade && !onlyCore) { 2142 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2143 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2144 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2145 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2146 } 2147 mSettings.mFingerprint = Build.FINGERPRINT; 2148 } 2149 2150 primeDomainVerificationsLPw(false); 2151 checkDefaultBrowser(); 2152 2153 // All the changes are done during package scanning. 2154 mSettings.updateInternalDatabaseVersion(); 2155 2156 // can downgrade to reader 2157 mSettings.writeLPr(); 2158 2159 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2160 SystemClock.uptimeMillis()); 2161 2162 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2163 2164 mInstallerService = new PackageInstallerService(context, this); 2165 2166 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2167 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2168 mIntentFilterVerifierComponent); 2169 2170 } // synchronized (mPackages) 2171 } // synchronized (mInstallLock) 2172 2173 // Now after opening every single application zip, make sure they 2174 // are all flushed. Not really needed, but keeps things nice and 2175 // tidy. 2176 Runtime.getRuntime().gc(); 2177 } 2178 2179 @Override 2180 public boolean isFirstBoot() { 2181 return !mRestoredSettings; 2182 } 2183 2184 @Override 2185 public boolean isOnlyCoreApps() { 2186 return mOnlyCore; 2187 } 2188 2189 @Override 2190 public boolean isUpgrade() { 2191 return mIsUpgrade; 2192 } 2193 2194 private String getRequiredVerifierLPr() { 2195 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2196 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2197 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2198 2199 String requiredVerifier = null; 2200 2201 final int N = receivers.size(); 2202 for (int i = 0; i < N; i++) { 2203 final ResolveInfo info = receivers.get(i); 2204 2205 if (info.activityInfo == null) { 2206 continue; 2207 } 2208 2209 final String packageName = info.activityInfo.packageName; 2210 2211 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2212 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2213 continue; 2214 } 2215 2216 if (requiredVerifier != null) { 2217 throw new RuntimeException("There can be only one required verifier"); 2218 } 2219 2220 requiredVerifier = packageName; 2221 } 2222 2223 return requiredVerifier; 2224 } 2225 2226 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2227 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2228 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2229 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2230 2231 ComponentName verifierComponentName = null; 2232 2233 int priority = -1000; 2234 final int N = receivers.size(); 2235 for (int i = 0; i < N; i++) { 2236 final ResolveInfo info = receivers.get(i); 2237 2238 if (info.activityInfo == null) { 2239 continue; 2240 } 2241 2242 final String packageName = info.activityInfo.packageName; 2243 2244 final PackageSetting ps = mSettings.mPackages.get(packageName); 2245 if (ps == null) { 2246 continue; 2247 } 2248 2249 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2250 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2251 continue; 2252 } 2253 2254 // Select the IntentFilterVerifier with the highest priority 2255 if (priority < info.priority) { 2256 priority = info.priority; 2257 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2258 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2259 " with priority: " + info.priority); 2260 } 2261 } 2262 2263 return verifierComponentName; 2264 } 2265 2266 private void primeDomainVerificationsLPw(boolean logging) { 2267 Slog.d(TAG, "Start priming domain verifications"); 2268 boolean updated = false; 2269 ArraySet<String> allHostsSet = new ArraySet<>(); 2270 for (PackageParser.Package pkg : mPackages.values()) { 2271 final String packageName = pkg.packageName; 2272 if (!hasDomainURLs(pkg)) { 2273 if (logging) { 2274 Slog.d(TAG, "No priming domain verifications for " + 2275 "package with no domain URLs: " + packageName); 2276 } 2277 continue; 2278 } 2279 if (!pkg.isSystemApp()) { 2280 if (logging) { 2281 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2282 packageName); 2283 } 2284 continue; 2285 } 2286 for (PackageParser.Activity a : pkg.activities) { 2287 for (ActivityIntentInfo filter : a.intents) { 2288 if (hasValidDomains(filter, false)) { 2289 allHostsSet.addAll(filter.getHostsList()); 2290 } 2291 } 2292 } 2293 if (allHostsSet.size() == 0) { 2294 allHostsSet.add("*"); 2295 } 2296 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2297 IntentFilterVerificationInfo ivi = 2298 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2299 if (ivi != null) { 2300 // We will always log this 2301 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2302 " with hosts:" + ivi.getDomainsString()); 2303 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2304 updated = true; 2305 } 2306 else { 2307 if (logging) { 2308 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2309 } 2310 } 2311 allHostsSet.clear(); 2312 } 2313 if (updated) { 2314 if (logging) { 2315 Slog.d(TAG, "Will need to write primed domain verifications"); 2316 } 2317 } 2318 Slog.d(TAG, "End priming domain verifications"); 2319 } 2320 2321 private void checkDefaultBrowser() { 2322 final int myUserId = UserHandle.myUserId(); 2323 final String packageName = getDefaultBrowserPackageName(myUserId); 2324 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2325 if (info == null) { 2326 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2327 packageName); 2328 setDefaultBrowserPackageName(null, myUserId); 2329 } 2330 } 2331 2332 @Override 2333 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2334 throws RemoteException { 2335 try { 2336 return super.onTransact(code, data, reply, flags); 2337 } catch (RuntimeException e) { 2338 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2339 Slog.wtf(TAG, "Package Manager Crash", e); 2340 } 2341 throw e; 2342 } 2343 } 2344 2345 void cleanupInstallFailedPackage(PackageSetting ps) { 2346 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2347 2348 removeDataDirsLI(ps.volumeUuid, ps.name); 2349 if (ps.codePath != null) { 2350 if (ps.codePath.isDirectory()) { 2351 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2352 } else { 2353 ps.codePath.delete(); 2354 } 2355 } 2356 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2357 if (ps.resourcePath.isDirectory()) { 2358 FileUtils.deleteContents(ps.resourcePath); 2359 } 2360 ps.resourcePath.delete(); 2361 } 2362 mSettings.removePackageLPw(ps.name); 2363 } 2364 2365 static int[] appendInts(int[] cur, int[] add) { 2366 if (add == null) return cur; 2367 if (cur == null) return add; 2368 final int N = add.length; 2369 for (int i=0; i<N; i++) { 2370 cur = appendInt(cur, add[i]); 2371 } 2372 return cur; 2373 } 2374 2375 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2376 if (!sUserManager.exists(userId)) return null; 2377 final PackageSetting ps = (PackageSetting) p.mExtras; 2378 if (ps == null) { 2379 return null; 2380 } 2381 2382 final PermissionsState permissionsState = ps.getPermissionsState(); 2383 2384 final int[] gids = permissionsState.computeGids(userId); 2385 final Set<String> permissions = permissionsState.getPermissions(userId); 2386 final PackageUserState state = ps.readUserState(userId); 2387 2388 return PackageParser.generatePackageInfo(p, gids, flags, 2389 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2390 } 2391 2392 @Override 2393 public boolean isPackageAvailable(String packageName, int userId) { 2394 if (!sUserManager.exists(userId)) return false; 2395 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2396 synchronized (mPackages) { 2397 PackageParser.Package p = mPackages.get(packageName); 2398 if (p != null) { 2399 final PackageSetting ps = (PackageSetting) p.mExtras; 2400 if (ps != null) { 2401 final PackageUserState state = ps.readUserState(userId); 2402 if (state != null) { 2403 return PackageParser.isAvailable(state); 2404 } 2405 } 2406 } 2407 } 2408 return false; 2409 } 2410 2411 @Override 2412 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2413 if (!sUserManager.exists(userId)) return null; 2414 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2415 // reader 2416 synchronized (mPackages) { 2417 PackageParser.Package p = mPackages.get(packageName); 2418 if (DEBUG_PACKAGE_INFO) 2419 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2420 if (p != null) { 2421 return generatePackageInfo(p, flags, userId); 2422 } 2423 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2424 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2425 } 2426 } 2427 return null; 2428 } 2429 2430 @Override 2431 public String[] currentToCanonicalPackageNames(String[] names) { 2432 String[] out = new String[names.length]; 2433 // reader 2434 synchronized (mPackages) { 2435 for (int i=names.length-1; i>=0; i--) { 2436 PackageSetting ps = mSettings.mPackages.get(names[i]); 2437 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2438 } 2439 } 2440 return out; 2441 } 2442 2443 @Override 2444 public String[] canonicalToCurrentPackageNames(String[] names) { 2445 String[] out = new String[names.length]; 2446 // reader 2447 synchronized (mPackages) { 2448 for (int i=names.length-1; i>=0; i--) { 2449 String cur = mSettings.mRenamedPackages.get(names[i]); 2450 out[i] = cur != null ? cur : names[i]; 2451 } 2452 } 2453 return out; 2454 } 2455 2456 @Override 2457 public int getPackageUid(String packageName, int userId) { 2458 if (!sUserManager.exists(userId)) return -1; 2459 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2460 2461 // reader 2462 synchronized (mPackages) { 2463 PackageParser.Package p = mPackages.get(packageName); 2464 if(p != null) { 2465 return UserHandle.getUid(userId, p.applicationInfo.uid); 2466 } 2467 PackageSetting ps = mSettings.mPackages.get(packageName); 2468 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2469 return -1; 2470 } 2471 p = ps.pkg; 2472 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2473 } 2474 } 2475 2476 @Override 2477 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2478 if (!sUserManager.exists(userId)) { 2479 return null; 2480 } 2481 2482 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2483 "getPackageGids"); 2484 2485 // reader 2486 synchronized (mPackages) { 2487 PackageParser.Package p = mPackages.get(packageName); 2488 if (DEBUG_PACKAGE_INFO) { 2489 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2490 } 2491 if (p != null) { 2492 PackageSetting ps = (PackageSetting) p.mExtras; 2493 return ps.getPermissionsState().computeGids(userId); 2494 } 2495 } 2496 2497 return null; 2498 } 2499 2500 static PermissionInfo generatePermissionInfo( 2501 BasePermission bp, int flags) { 2502 if (bp.perm != null) { 2503 return PackageParser.generatePermissionInfo(bp.perm, flags); 2504 } 2505 PermissionInfo pi = new PermissionInfo(); 2506 pi.name = bp.name; 2507 pi.packageName = bp.sourcePackage; 2508 pi.nonLocalizedLabel = bp.name; 2509 pi.protectionLevel = bp.protectionLevel; 2510 return pi; 2511 } 2512 2513 @Override 2514 public PermissionInfo getPermissionInfo(String name, int flags) { 2515 // reader 2516 synchronized (mPackages) { 2517 final BasePermission p = mSettings.mPermissions.get(name); 2518 if (p != null) { 2519 return generatePermissionInfo(p, flags); 2520 } 2521 return null; 2522 } 2523 } 2524 2525 @Override 2526 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2527 // reader 2528 synchronized (mPackages) { 2529 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2530 for (BasePermission p : mSettings.mPermissions.values()) { 2531 if (group == null) { 2532 if (p.perm == null || p.perm.info.group == null) { 2533 out.add(generatePermissionInfo(p, flags)); 2534 } 2535 } else { 2536 if (p.perm != null && group.equals(p.perm.info.group)) { 2537 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2538 } 2539 } 2540 } 2541 2542 if (out.size() > 0) { 2543 return out; 2544 } 2545 return mPermissionGroups.containsKey(group) ? out : null; 2546 } 2547 } 2548 2549 @Override 2550 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2551 // reader 2552 synchronized (mPackages) { 2553 return PackageParser.generatePermissionGroupInfo( 2554 mPermissionGroups.get(name), flags); 2555 } 2556 } 2557 2558 @Override 2559 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2560 // reader 2561 synchronized (mPackages) { 2562 final int N = mPermissionGroups.size(); 2563 ArrayList<PermissionGroupInfo> out 2564 = new ArrayList<PermissionGroupInfo>(N); 2565 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2566 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2567 } 2568 return out; 2569 } 2570 } 2571 2572 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2573 int userId) { 2574 if (!sUserManager.exists(userId)) return null; 2575 PackageSetting ps = mSettings.mPackages.get(packageName); 2576 if (ps != null) { 2577 if (ps.pkg == null) { 2578 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2579 flags, userId); 2580 if (pInfo != null) { 2581 return pInfo.applicationInfo; 2582 } 2583 return null; 2584 } 2585 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2586 ps.readUserState(userId), userId); 2587 } 2588 return null; 2589 } 2590 2591 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2592 int userId) { 2593 if (!sUserManager.exists(userId)) return null; 2594 PackageSetting ps = mSettings.mPackages.get(packageName); 2595 if (ps != null) { 2596 PackageParser.Package pkg = ps.pkg; 2597 if (pkg == null) { 2598 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2599 return null; 2600 } 2601 // Only data remains, so we aren't worried about code paths 2602 pkg = new PackageParser.Package(packageName); 2603 pkg.applicationInfo.packageName = packageName; 2604 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2605 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2606 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2607 packageName, userId).getAbsolutePath(); 2608 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2609 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2610 } 2611 return generatePackageInfo(pkg, flags, userId); 2612 } 2613 return null; 2614 } 2615 2616 @Override 2617 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2618 if (!sUserManager.exists(userId)) return null; 2619 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2620 // writer 2621 synchronized (mPackages) { 2622 PackageParser.Package p = mPackages.get(packageName); 2623 if (DEBUG_PACKAGE_INFO) Log.v( 2624 TAG, "getApplicationInfo " + packageName 2625 + ": " + p); 2626 if (p != null) { 2627 PackageSetting ps = mSettings.mPackages.get(packageName); 2628 if (ps == null) return null; 2629 // Note: isEnabledLP() does not apply here - always return info 2630 return PackageParser.generateApplicationInfo( 2631 p, flags, ps.readUserState(userId), userId); 2632 } 2633 if ("android".equals(packageName)||"system".equals(packageName)) { 2634 return mAndroidApplication; 2635 } 2636 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2637 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2638 } 2639 } 2640 return null; 2641 } 2642 2643 @Override 2644 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2645 final IPackageDataObserver observer) { 2646 mContext.enforceCallingOrSelfPermission( 2647 android.Manifest.permission.CLEAR_APP_CACHE, null); 2648 // Queue up an async operation since clearing cache may take a little while. 2649 mHandler.post(new Runnable() { 2650 public void run() { 2651 mHandler.removeCallbacks(this); 2652 int retCode = -1; 2653 synchronized (mInstallLock) { 2654 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2655 if (retCode < 0) { 2656 Slog.w(TAG, "Couldn't clear application caches"); 2657 } 2658 } 2659 if (observer != null) { 2660 try { 2661 observer.onRemoveCompleted(null, (retCode >= 0)); 2662 } catch (RemoteException e) { 2663 Slog.w(TAG, "RemoveException when invoking call back"); 2664 } 2665 } 2666 } 2667 }); 2668 } 2669 2670 @Override 2671 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2672 final IntentSender pi) { 2673 mContext.enforceCallingOrSelfPermission( 2674 android.Manifest.permission.CLEAR_APP_CACHE, null); 2675 // Queue up an async operation since clearing cache may take a little while. 2676 mHandler.post(new Runnable() { 2677 public void run() { 2678 mHandler.removeCallbacks(this); 2679 int retCode = -1; 2680 synchronized (mInstallLock) { 2681 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2682 if (retCode < 0) { 2683 Slog.w(TAG, "Couldn't clear application caches"); 2684 } 2685 } 2686 if(pi != null) { 2687 try { 2688 // Callback via pending intent 2689 int code = (retCode >= 0) ? 1 : 0; 2690 pi.sendIntent(null, code, null, 2691 null, null); 2692 } catch (SendIntentException e1) { 2693 Slog.i(TAG, "Failed to send pending intent"); 2694 } 2695 } 2696 } 2697 }); 2698 } 2699 2700 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2701 synchronized (mInstallLock) { 2702 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2703 throw new IOException("Failed to free enough space"); 2704 } 2705 } 2706 } 2707 2708 @Override 2709 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2710 if (!sUserManager.exists(userId)) return null; 2711 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2712 synchronized (mPackages) { 2713 PackageParser.Activity a = mActivities.mActivities.get(component); 2714 2715 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2716 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2717 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2718 if (ps == null) return null; 2719 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2720 userId); 2721 } 2722 if (mResolveComponentName.equals(component)) { 2723 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2724 new PackageUserState(), userId); 2725 } 2726 } 2727 return null; 2728 } 2729 2730 @Override 2731 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2732 String resolvedType) { 2733 synchronized (mPackages) { 2734 PackageParser.Activity a = mActivities.mActivities.get(component); 2735 if (a == null) { 2736 return false; 2737 } 2738 for (int i=0; i<a.intents.size(); i++) { 2739 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2740 intent.getData(), intent.getCategories(), TAG) >= 0) { 2741 return true; 2742 } 2743 } 2744 return false; 2745 } 2746 } 2747 2748 @Override 2749 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2750 if (!sUserManager.exists(userId)) return null; 2751 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2752 synchronized (mPackages) { 2753 PackageParser.Activity a = mReceivers.mActivities.get(component); 2754 if (DEBUG_PACKAGE_INFO) Log.v( 2755 TAG, "getReceiverInfo " + component + ": " + a); 2756 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2757 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2758 if (ps == null) return null; 2759 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2760 userId); 2761 } 2762 } 2763 return null; 2764 } 2765 2766 @Override 2767 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2768 if (!sUserManager.exists(userId)) return null; 2769 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2770 synchronized (mPackages) { 2771 PackageParser.Service s = mServices.mServices.get(component); 2772 if (DEBUG_PACKAGE_INFO) Log.v( 2773 TAG, "getServiceInfo " + component + ": " + s); 2774 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2775 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2776 if (ps == null) return null; 2777 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2778 userId); 2779 } 2780 } 2781 return null; 2782 } 2783 2784 @Override 2785 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2786 if (!sUserManager.exists(userId)) return null; 2787 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2788 synchronized (mPackages) { 2789 PackageParser.Provider p = mProviders.mProviders.get(component); 2790 if (DEBUG_PACKAGE_INFO) Log.v( 2791 TAG, "getProviderInfo " + component + ": " + p); 2792 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2793 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2794 if (ps == null) return null; 2795 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2796 userId); 2797 } 2798 } 2799 return null; 2800 } 2801 2802 @Override 2803 public String[] getSystemSharedLibraryNames() { 2804 Set<String> libSet; 2805 synchronized (mPackages) { 2806 libSet = mSharedLibraries.keySet(); 2807 int size = libSet.size(); 2808 if (size > 0) { 2809 String[] libs = new String[size]; 2810 libSet.toArray(libs); 2811 return libs; 2812 } 2813 } 2814 return null; 2815 } 2816 2817 /** 2818 * @hide 2819 */ 2820 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2821 synchronized (mPackages) { 2822 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2823 if (lib != null && lib.apk != null) { 2824 return mPackages.get(lib.apk); 2825 } 2826 } 2827 return null; 2828 } 2829 2830 @Override 2831 public FeatureInfo[] getSystemAvailableFeatures() { 2832 Collection<FeatureInfo> featSet; 2833 synchronized (mPackages) { 2834 featSet = mAvailableFeatures.values(); 2835 int size = featSet.size(); 2836 if (size > 0) { 2837 FeatureInfo[] features = new FeatureInfo[size+1]; 2838 featSet.toArray(features); 2839 FeatureInfo fi = new FeatureInfo(); 2840 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2841 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2842 features[size] = fi; 2843 return features; 2844 } 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public boolean hasSystemFeature(String name) { 2851 synchronized (mPackages) { 2852 return mAvailableFeatures.containsKey(name); 2853 } 2854 } 2855 2856 private void checkValidCaller(int uid, int userId) { 2857 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2858 return; 2859 2860 throw new SecurityException("Caller uid=" + uid 2861 + " is not privileged to communicate with user=" + userId); 2862 } 2863 2864 @Override 2865 public int checkPermission(String permName, String pkgName, int userId) { 2866 if (!sUserManager.exists(userId)) { 2867 return PackageManager.PERMISSION_DENIED; 2868 } 2869 2870 synchronized (mPackages) { 2871 final PackageParser.Package p = mPackages.get(pkgName); 2872 if (p != null && p.mExtras != null) { 2873 final PackageSetting ps = (PackageSetting) p.mExtras; 2874 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2875 return PackageManager.PERMISSION_GRANTED; 2876 } 2877 } 2878 } 2879 2880 return PackageManager.PERMISSION_DENIED; 2881 } 2882 2883 @Override 2884 public int checkUidPermission(String permName, int uid) { 2885 final int userId = UserHandle.getUserId(uid); 2886 2887 if (!sUserManager.exists(userId)) { 2888 return PackageManager.PERMISSION_DENIED; 2889 } 2890 2891 synchronized (mPackages) { 2892 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2893 if (obj != null) { 2894 final SettingBase ps = (SettingBase) obj; 2895 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2896 return PackageManager.PERMISSION_GRANTED; 2897 } 2898 } else { 2899 ArraySet<String> perms = mSystemPermissions.get(uid); 2900 if (perms != null && perms.contains(permName)) { 2901 return PackageManager.PERMISSION_GRANTED; 2902 } 2903 } 2904 } 2905 2906 return PackageManager.PERMISSION_DENIED; 2907 } 2908 2909 /** 2910 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2911 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2912 * @param checkShell TODO(yamasani): 2913 * @param message the message to log on security exception 2914 */ 2915 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2916 boolean checkShell, String message) { 2917 if (userId < 0) { 2918 throw new IllegalArgumentException("Invalid userId " + userId); 2919 } 2920 if (checkShell) { 2921 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2922 } 2923 if (userId == UserHandle.getUserId(callingUid)) return; 2924 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2925 if (requireFullPermission) { 2926 mContext.enforceCallingOrSelfPermission( 2927 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2928 } else { 2929 try { 2930 mContext.enforceCallingOrSelfPermission( 2931 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2932 } catch (SecurityException se) { 2933 mContext.enforceCallingOrSelfPermission( 2934 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2935 } 2936 } 2937 } 2938 } 2939 2940 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2941 if (callingUid == Process.SHELL_UID) { 2942 if (userHandle >= 0 2943 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2944 throw new SecurityException("Shell does not have permission to access user " 2945 + userHandle); 2946 } else if (userHandle < 0) { 2947 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2948 + Debug.getCallers(3)); 2949 } 2950 } 2951 } 2952 2953 private BasePermission findPermissionTreeLP(String permName) { 2954 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2955 if (permName.startsWith(bp.name) && 2956 permName.length() > bp.name.length() && 2957 permName.charAt(bp.name.length()) == '.') { 2958 return bp; 2959 } 2960 } 2961 return null; 2962 } 2963 2964 private BasePermission checkPermissionTreeLP(String permName) { 2965 if (permName != null) { 2966 BasePermission bp = findPermissionTreeLP(permName); 2967 if (bp != null) { 2968 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2969 return bp; 2970 } 2971 throw new SecurityException("Calling uid " 2972 + Binder.getCallingUid() 2973 + " is not allowed to add to permission tree " 2974 + bp.name + " owned by uid " + bp.uid); 2975 } 2976 } 2977 throw new SecurityException("No permission tree found for " + permName); 2978 } 2979 2980 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2981 if (s1 == null) { 2982 return s2 == null; 2983 } 2984 if (s2 == null) { 2985 return false; 2986 } 2987 if (s1.getClass() != s2.getClass()) { 2988 return false; 2989 } 2990 return s1.equals(s2); 2991 } 2992 2993 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2994 if (pi1.icon != pi2.icon) return false; 2995 if (pi1.logo != pi2.logo) return false; 2996 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2997 if (!compareStrings(pi1.name, pi2.name)) return false; 2998 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2999 // We'll take care of setting this one. 3000 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3001 // These are not currently stored in settings. 3002 //if (!compareStrings(pi1.group, pi2.group)) return false; 3003 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3004 //if (pi1.labelRes != pi2.labelRes) return false; 3005 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3006 return true; 3007 } 3008 3009 int permissionInfoFootprint(PermissionInfo info) { 3010 int size = info.name.length(); 3011 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3012 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3013 return size; 3014 } 3015 3016 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3017 int size = 0; 3018 for (BasePermission perm : mSettings.mPermissions.values()) { 3019 if (perm.uid == tree.uid) { 3020 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3021 } 3022 } 3023 return size; 3024 } 3025 3026 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3027 // We calculate the max size of permissions defined by this uid and throw 3028 // if that plus the size of 'info' would exceed our stated maximum. 3029 if (tree.uid != Process.SYSTEM_UID) { 3030 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3031 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3032 throw new SecurityException("Permission tree size cap exceeded"); 3033 } 3034 } 3035 } 3036 3037 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3038 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3039 throw new SecurityException("Label must be specified in permission"); 3040 } 3041 BasePermission tree = checkPermissionTreeLP(info.name); 3042 BasePermission bp = mSettings.mPermissions.get(info.name); 3043 boolean added = bp == null; 3044 boolean changed = true; 3045 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3046 if (added) { 3047 enforcePermissionCapLocked(info, tree); 3048 bp = new BasePermission(info.name, tree.sourcePackage, 3049 BasePermission.TYPE_DYNAMIC); 3050 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3051 throw new SecurityException( 3052 "Not allowed to modify non-dynamic permission " 3053 + info.name); 3054 } else { 3055 if (bp.protectionLevel == fixedLevel 3056 && bp.perm.owner.equals(tree.perm.owner) 3057 && bp.uid == tree.uid 3058 && comparePermissionInfos(bp.perm.info, info)) { 3059 changed = false; 3060 } 3061 } 3062 bp.protectionLevel = fixedLevel; 3063 info = new PermissionInfo(info); 3064 info.protectionLevel = fixedLevel; 3065 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3066 bp.perm.info.packageName = tree.perm.info.packageName; 3067 bp.uid = tree.uid; 3068 if (added) { 3069 mSettings.mPermissions.put(info.name, bp); 3070 } 3071 if (changed) { 3072 if (!async) { 3073 mSettings.writeLPr(); 3074 } else { 3075 scheduleWriteSettingsLocked(); 3076 } 3077 } 3078 return added; 3079 } 3080 3081 @Override 3082 public boolean addPermission(PermissionInfo info) { 3083 synchronized (mPackages) { 3084 return addPermissionLocked(info, false); 3085 } 3086 } 3087 3088 @Override 3089 public boolean addPermissionAsync(PermissionInfo info) { 3090 synchronized (mPackages) { 3091 return addPermissionLocked(info, true); 3092 } 3093 } 3094 3095 @Override 3096 public void removePermission(String name) { 3097 synchronized (mPackages) { 3098 checkPermissionTreeLP(name); 3099 BasePermission bp = mSettings.mPermissions.get(name); 3100 if (bp != null) { 3101 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3102 throw new SecurityException( 3103 "Not allowed to modify non-dynamic permission " 3104 + name); 3105 } 3106 mSettings.mPermissions.remove(name); 3107 mSettings.writeLPr(); 3108 } 3109 } 3110 } 3111 3112 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3113 BasePermission bp) { 3114 int index = pkg.requestedPermissions.indexOf(bp.name); 3115 if (index == -1) { 3116 throw new SecurityException("Package " + pkg.packageName 3117 + " has not requested permission " + bp.name); 3118 } 3119 if (!bp.isRuntime()) { 3120 throw new SecurityException("Permission " + bp.name 3121 + " is not a changeable permission type"); 3122 } 3123 } 3124 3125 @Override 3126 public boolean grantPermission(String packageName, String name, int userId) { 3127 if (!RUNTIME_PERMISSIONS_ENABLED) { 3128 return false; 3129 } 3130 3131 if (!sUserManager.exists(userId)) { 3132 return false; 3133 } 3134 3135 mContext.enforceCallingOrSelfPermission( 3136 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3137 "grantPermission"); 3138 3139 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3140 "grantPermission"); 3141 3142 boolean gidsChanged = false; 3143 final SettingBase sb; 3144 3145 synchronized (mPackages) { 3146 final PackageParser.Package pkg = mPackages.get(packageName); 3147 if (pkg == null) { 3148 throw new IllegalArgumentException("Unknown package: " + packageName); 3149 } 3150 3151 final BasePermission bp = mSettings.mPermissions.get(name); 3152 if (bp == null) { 3153 throw new IllegalArgumentException("Unknown permission: " + name); 3154 } 3155 3156 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3157 3158 sb = (SettingBase) pkg.mExtras; 3159 if (sb == null) { 3160 throw new IllegalArgumentException("Unknown package: " + packageName); 3161 } 3162 3163 final PermissionsState permissionsState = sb.getPermissionsState(); 3164 3165 final int result = permissionsState.grantRuntimePermission(bp, userId); 3166 switch (result) { 3167 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3168 return false; 3169 } 3170 3171 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3172 gidsChanged = true; 3173 } break; 3174 } 3175 3176 // Not critical if that is lost - app has to request again. 3177 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3178 } 3179 3180 if (gidsChanged) { 3181 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3182 } 3183 3184 return true; 3185 } 3186 3187 @Override 3188 public boolean revokePermission(String packageName, String name, int userId) { 3189 if (!RUNTIME_PERMISSIONS_ENABLED) { 3190 return false; 3191 } 3192 3193 if (!sUserManager.exists(userId)) { 3194 return false; 3195 } 3196 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3199 "revokePermission"); 3200 3201 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3202 "revokePermission"); 3203 3204 final SettingBase sb; 3205 3206 synchronized (mPackages) { 3207 final PackageParser.Package pkg = mPackages.get(packageName); 3208 if (pkg == null) { 3209 throw new IllegalArgumentException("Unknown package: " + packageName); 3210 } 3211 3212 final BasePermission bp = mSettings.mPermissions.get(name); 3213 if (bp == null) { 3214 throw new IllegalArgumentException("Unknown permission: " + name); 3215 } 3216 3217 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3218 3219 sb = (SettingBase) pkg.mExtras; 3220 if (sb == null) { 3221 throw new IllegalArgumentException("Unknown package: " + packageName); 3222 } 3223 3224 final PermissionsState permissionsState = sb.getPermissionsState(); 3225 3226 if (permissionsState.revokeRuntimePermission(bp, userId) == 3227 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3228 return false; 3229 } 3230 3231 // Critical, after this call all should never have the permission. 3232 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3233 } 3234 3235 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3236 3237 return true; 3238 } 3239 3240 @Override 3241 public boolean isProtectedBroadcast(String actionName) { 3242 synchronized (mPackages) { 3243 return mProtectedBroadcasts.contains(actionName); 3244 } 3245 } 3246 3247 @Override 3248 public int checkSignatures(String pkg1, String pkg2) { 3249 synchronized (mPackages) { 3250 final PackageParser.Package p1 = mPackages.get(pkg1); 3251 final PackageParser.Package p2 = mPackages.get(pkg2); 3252 if (p1 == null || p1.mExtras == null 3253 || p2 == null || p2.mExtras == null) { 3254 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3255 } 3256 return compareSignatures(p1.mSignatures, p2.mSignatures); 3257 } 3258 } 3259 3260 @Override 3261 public int checkUidSignatures(int uid1, int uid2) { 3262 // Map to base uids. 3263 uid1 = UserHandle.getAppId(uid1); 3264 uid2 = UserHandle.getAppId(uid2); 3265 // reader 3266 synchronized (mPackages) { 3267 Signature[] s1; 3268 Signature[] s2; 3269 Object obj = mSettings.getUserIdLPr(uid1); 3270 if (obj != null) { 3271 if (obj instanceof SharedUserSetting) { 3272 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3273 } else if (obj instanceof PackageSetting) { 3274 s1 = ((PackageSetting)obj).signatures.mSignatures; 3275 } else { 3276 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3277 } 3278 } else { 3279 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3280 } 3281 obj = mSettings.getUserIdLPr(uid2); 3282 if (obj != null) { 3283 if (obj instanceof SharedUserSetting) { 3284 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3285 } else if (obj instanceof PackageSetting) { 3286 s2 = ((PackageSetting)obj).signatures.mSignatures; 3287 } else { 3288 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3289 } 3290 } else { 3291 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3292 } 3293 return compareSignatures(s1, s2); 3294 } 3295 } 3296 3297 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3298 final long identity = Binder.clearCallingIdentity(); 3299 try { 3300 if (sb instanceof SharedUserSetting) { 3301 SharedUserSetting sus = (SharedUserSetting) sb; 3302 final int packageCount = sus.packages.size(); 3303 for (int i = 0; i < packageCount; i++) { 3304 PackageSetting susPs = sus.packages.valueAt(i); 3305 if (userId == UserHandle.USER_ALL) { 3306 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3307 } else { 3308 final int uid = UserHandle.getUid(userId, susPs.appId); 3309 killUid(uid, reason); 3310 } 3311 } 3312 } else if (sb instanceof PackageSetting) { 3313 PackageSetting ps = (PackageSetting) sb; 3314 if (userId == UserHandle.USER_ALL) { 3315 killApplication(ps.pkg.packageName, ps.appId, reason); 3316 } else { 3317 final int uid = UserHandle.getUid(userId, ps.appId); 3318 killUid(uid, reason); 3319 } 3320 } 3321 } finally { 3322 Binder.restoreCallingIdentity(identity); 3323 } 3324 } 3325 3326 private static void killUid(int uid, String reason) { 3327 IActivityManager am = ActivityManagerNative.getDefault(); 3328 if (am != null) { 3329 try { 3330 am.killUid(uid, reason); 3331 } catch (RemoteException e) { 3332 /* ignore - same process */ 3333 } 3334 } 3335 } 3336 3337 /** 3338 * Compares two sets of signatures. Returns: 3339 * <br /> 3340 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3341 * <br /> 3342 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3343 * <br /> 3344 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3345 * <br /> 3346 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3347 * <br /> 3348 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3349 */ 3350 static int compareSignatures(Signature[] s1, Signature[] s2) { 3351 if (s1 == null) { 3352 return s2 == null 3353 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3354 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3355 } 3356 3357 if (s2 == null) { 3358 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3359 } 3360 3361 if (s1.length != s2.length) { 3362 return PackageManager.SIGNATURE_NO_MATCH; 3363 } 3364 3365 // Since both signature sets are of size 1, we can compare without HashSets. 3366 if (s1.length == 1) { 3367 return s1[0].equals(s2[0]) ? 3368 PackageManager.SIGNATURE_MATCH : 3369 PackageManager.SIGNATURE_NO_MATCH; 3370 } 3371 3372 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3373 for (Signature sig : s1) { 3374 set1.add(sig); 3375 } 3376 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3377 for (Signature sig : s2) { 3378 set2.add(sig); 3379 } 3380 // Make sure s2 contains all signatures in s1. 3381 if (set1.equals(set2)) { 3382 return PackageManager.SIGNATURE_MATCH; 3383 } 3384 return PackageManager.SIGNATURE_NO_MATCH; 3385 } 3386 3387 /** 3388 * If the database version for this type of package (internal storage or 3389 * external storage) is less than the version where package signatures 3390 * were updated, return true. 3391 */ 3392 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3393 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3394 DatabaseVersion.SIGNATURE_END_ENTITY)) 3395 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3396 DatabaseVersion.SIGNATURE_END_ENTITY)); 3397 } 3398 3399 /** 3400 * Used for backward compatibility to make sure any packages with 3401 * certificate chains get upgraded to the new style. {@code existingSigs} 3402 * will be in the old format (since they were stored on disk from before the 3403 * system upgrade) and {@code scannedSigs} will be in the newer format. 3404 */ 3405 private int compareSignaturesCompat(PackageSignatures existingSigs, 3406 PackageParser.Package scannedPkg) { 3407 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3408 return PackageManager.SIGNATURE_NO_MATCH; 3409 } 3410 3411 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3412 for (Signature sig : existingSigs.mSignatures) { 3413 existingSet.add(sig); 3414 } 3415 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3416 for (Signature sig : scannedPkg.mSignatures) { 3417 try { 3418 Signature[] chainSignatures = sig.getChainSignatures(); 3419 for (Signature chainSig : chainSignatures) { 3420 scannedCompatSet.add(chainSig); 3421 } 3422 } catch (CertificateEncodingException e) { 3423 scannedCompatSet.add(sig); 3424 } 3425 } 3426 /* 3427 * Make sure the expanded scanned set contains all signatures in the 3428 * existing one. 3429 */ 3430 if (scannedCompatSet.equals(existingSet)) { 3431 // Migrate the old signatures to the new scheme. 3432 existingSigs.assignSignatures(scannedPkg.mSignatures); 3433 // The new KeySets will be re-added later in the scanning process. 3434 synchronized (mPackages) { 3435 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3436 } 3437 return PackageManager.SIGNATURE_MATCH; 3438 } 3439 return PackageManager.SIGNATURE_NO_MATCH; 3440 } 3441 3442 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3443 if (isExternal(scannedPkg)) { 3444 return mSettings.isExternalDatabaseVersionOlderThan( 3445 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3446 } else { 3447 return mSettings.isInternalDatabaseVersionOlderThan( 3448 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3449 } 3450 } 3451 3452 private int compareSignaturesRecover(PackageSignatures existingSigs, 3453 PackageParser.Package scannedPkg) { 3454 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3455 return PackageManager.SIGNATURE_NO_MATCH; 3456 } 3457 3458 String msg = null; 3459 try { 3460 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3461 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3462 + scannedPkg.packageName); 3463 return PackageManager.SIGNATURE_MATCH; 3464 } 3465 } catch (CertificateException e) { 3466 msg = e.getMessage(); 3467 } 3468 3469 logCriticalInfo(Log.INFO, 3470 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3471 return PackageManager.SIGNATURE_NO_MATCH; 3472 } 3473 3474 @Override 3475 public String[] getPackagesForUid(int uid) { 3476 uid = UserHandle.getAppId(uid); 3477 // reader 3478 synchronized (mPackages) { 3479 Object obj = mSettings.getUserIdLPr(uid); 3480 if (obj instanceof SharedUserSetting) { 3481 final SharedUserSetting sus = (SharedUserSetting) obj; 3482 final int N = sus.packages.size(); 3483 final String[] res = new String[N]; 3484 final Iterator<PackageSetting> it = sus.packages.iterator(); 3485 int i = 0; 3486 while (it.hasNext()) { 3487 res[i++] = it.next().name; 3488 } 3489 return res; 3490 } else if (obj instanceof PackageSetting) { 3491 final PackageSetting ps = (PackageSetting) obj; 3492 return new String[] { ps.name }; 3493 } 3494 } 3495 return null; 3496 } 3497 3498 @Override 3499 public String getNameForUid(int uid) { 3500 // reader 3501 synchronized (mPackages) { 3502 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3503 if (obj instanceof SharedUserSetting) { 3504 final SharedUserSetting sus = (SharedUserSetting) obj; 3505 return sus.name + ":" + sus.userId; 3506 } else if (obj instanceof PackageSetting) { 3507 final PackageSetting ps = (PackageSetting) obj; 3508 return ps.name; 3509 } 3510 } 3511 return null; 3512 } 3513 3514 @Override 3515 public int getUidForSharedUser(String sharedUserName) { 3516 if(sharedUserName == null) { 3517 return -1; 3518 } 3519 // reader 3520 synchronized (mPackages) { 3521 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3522 if (suid == null) { 3523 return -1; 3524 } 3525 return suid.userId; 3526 } 3527 } 3528 3529 @Override 3530 public int getFlagsForUid(int uid) { 3531 synchronized (mPackages) { 3532 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3533 if (obj instanceof SharedUserSetting) { 3534 final SharedUserSetting sus = (SharedUserSetting) obj; 3535 return sus.pkgFlags; 3536 } else if (obj instanceof PackageSetting) { 3537 final PackageSetting ps = (PackageSetting) obj; 3538 return ps.pkgFlags; 3539 } 3540 } 3541 return 0; 3542 } 3543 3544 @Override 3545 public int getPrivateFlagsForUid(int uid) { 3546 synchronized (mPackages) { 3547 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3548 if (obj instanceof SharedUserSetting) { 3549 final SharedUserSetting sus = (SharedUserSetting) obj; 3550 return sus.pkgPrivateFlags; 3551 } else if (obj instanceof PackageSetting) { 3552 final PackageSetting ps = (PackageSetting) obj; 3553 return ps.pkgPrivateFlags; 3554 } 3555 } 3556 return 0; 3557 } 3558 3559 @Override 3560 public boolean isUidPrivileged(int uid) { 3561 uid = UserHandle.getAppId(uid); 3562 // reader 3563 synchronized (mPackages) { 3564 Object obj = mSettings.getUserIdLPr(uid); 3565 if (obj instanceof SharedUserSetting) { 3566 final SharedUserSetting sus = (SharedUserSetting) obj; 3567 final Iterator<PackageSetting> it = sus.packages.iterator(); 3568 while (it.hasNext()) { 3569 if (it.next().isPrivileged()) { 3570 return true; 3571 } 3572 } 3573 } else if (obj instanceof PackageSetting) { 3574 final PackageSetting ps = (PackageSetting) obj; 3575 return ps.isPrivileged(); 3576 } 3577 } 3578 return false; 3579 } 3580 3581 @Override 3582 public String[] getAppOpPermissionPackages(String permissionName) { 3583 synchronized (mPackages) { 3584 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3585 if (pkgs == null) { 3586 return null; 3587 } 3588 return pkgs.toArray(new String[pkgs.size()]); 3589 } 3590 } 3591 3592 @Override 3593 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3594 int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return null; 3596 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3597 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3598 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3599 } 3600 3601 @Override 3602 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3603 IntentFilter filter, int match, ComponentName activity) { 3604 final int userId = UserHandle.getCallingUserId(); 3605 if (DEBUG_PREFERRED) { 3606 Log.v(TAG, "setLastChosenActivity intent=" + intent 3607 + " resolvedType=" + resolvedType 3608 + " flags=" + flags 3609 + " filter=" + filter 3610 + " match=" + match 3611 + " activity=" + activity); 3612 filter.dump(new PrintStreamPrinter(System.out), " "); 3613 } 3614 intent.setComponent(null); 3615 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3616 // Find any earlier preferred or last chosen entries and nuke them 3617 findPreferredActivity(intent, resolvedType, 3618 flags, query, 0, false, true, false, userId); 3619 // Add the new activity as the last chosen for this filter 3620 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3621 "Setting last chosen"); 3622 } 3623 3624 @Override 3625 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3626 final int userId = UserHandle.getCallingUserId(); 3627 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3628 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3629 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3630 false, false, false, userId); 3631 } 3632 3633 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3634 int flags, List<ResolveInfo> query, int userId) { 3635 if (query != null) { 3636 final int N = query.size(); 3637 if (N == 1) { 3638 return query.get(0); 3639 } else if (N > 1) { 3640 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3641 // If there is more than one activity with the same priority, 3642 // then let the user decide between them. 3643 ResolveInfo r0 = query.get(0); 3644 ResolveInfo r1 = query.get(1); 3645 if (DEBUG_INTENT_MATCHING || debug) { 3646 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3647 + r1.activityInfo.name + "=" + r1.priority); 3648 } 3649 // If the first activity has a higher priority, or a different 3650 // default, then it is always desireable to pick it. 3651 if (r0.priority != r1.priority 3652 || r0.preferredOrder != r1.preferredOrder 3653 || r0.isDefault != r1.isDefault) { 3654 return query.get(0); 3655 } 3656 // If we have saved a preference for a preferred activity for 3657 // this Intent, use that. 3658 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3659 flags, query, r0.priority, true, false, debug, userId); 3660 if (ri != null) { 3661 return ri; 3662 } 3663 if (userId != 0) { 3664 ri = new ResolveInfo(mResolveInfo); 3665 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3666 ri.activityInfo.applicationInfo = new ApplicationInfo( 3667 ri.activityInfo.applicationInfo); 3668 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3669 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3670 return ri; 3671 } 3672 return mResolveInfo; 3673 } 3674 } 3675 return null; 3676 } 3677 3678 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3679 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3680 final int N = query.size(); 3681 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3682 .get(userId); 3683 // Get the list of persistent preferred activities that handle the intent 3684 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3685 List<PersistentPreferredActivity> pprefs = ppir != null 3686 ? ppir.queryIntent(intent, resolvedType, 3687 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3688 : null; 3689 if (pprefs != null && pprefs.size() > 0) { 3690 final int M = pprefs.size(); 3691 for (int i=0; i<M; i++) { 3692 final PersistentPreferredActivity ppa = pprefs.get(i); 3693 if (DEBUG_PREFERRED || debug) { 3694 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3695 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3696 + "\n component=" + ppa.mComponent); 3697 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3698 } 3699 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3700 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3701 if (DEBUG_PREFERRED || debug) { 3702 Slog.v(TAG, "Found persistent preferred activity:"); 3703 if (ai != null) { 3704 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3705 } else { 3706 Slog.v(TAG, " null"); 3707 } 3708 } 3709 if (ai == null) { 3710 // This previously registered persistent preferred activity 3711 // component is no longer known. Ignore it and do NOT remove it. 3712 continue; 3713 } 3714 for (int j=0; j<N; j++) { 3715 final ResolveInfo ri = query.get(j); 3716 if (!ri.activityInfo.applicationInfo.packageName 3717 .equals(ai.applicationInfo.packageName)) { 3718 continue; 3719 } 3720 if (!ri.activityInfo.name.equals(ai.name)) { 3721 continue; 3722 } 3723 // Found a persistent preference that can handle the intent. 3724 if (DEBUG_PREFERRED || debug) { 3725 Slog.v(TAG, "Returning persistent preferred activity: " + 3726 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3727 } 3728 return ri; 3729 } 3730 } 3731 } 3732 return null; 3733 } 3734 3735 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3736 List<ResolveInfo> query, int priority, boolean always, 3737 boolean removeMatches, boolean debug, int userId) { 3738 if (!sUserManager.exists(userId)) return null; 3739 // writer 3740 synchronized (mPackages) { 3741 if (intent.getSelector() != null) { 3742 intent = intent.getSelector(); 3743 } 3744 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3745 3746 // Try to find a matching persistent preferred activity. 3747 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3748 debug, userId); 3749 3750 // If a persistent preferred activity matched, use it. 3751 if (pri != null) { 3752 return pri; 3753 } 3754 3755 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3756 // Get the list of preferred activities that handle the intent 3757 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3758 List<PreferredActivity> prefs = pir != null 3759 ? pir.queryIntent(intent, resolvedType, 3760 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3761 : null; 3762 if (prefs != null && prefs.size() > 0) { 3763 boolean changed = false; 3764 try { 3765 // First figure out how good the original match set is. 3766 // We will only allow preferred activities that came 3767 // from the same match quality. 3768 int match = 0; 3769 3770 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3771 3772 final int N = query.size(); 3773 for (int j=0; j<N; j++) { 3774 final ResolveInfo ri = query.get(j); 3775 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3776 + ": 0x" + Integer.toHexString(match)); 3777 if (ri.match > match) { 3778 match = ri.match; 3779 } 3780 } 3781 3782 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3783 + Integer.toHexString(match)); 3784 3785 match &= IntentFilter.MATCH_CATEGORY_MASK; 3786 final int M = prefs.size(); 3787 for (int i=0; i<M; i++) { 3788 final PreferredActivity pa = prefs.get(i); 3789 if (DEBUG_PREFERRED || debug) { 3790 Slog.v(TAG, "Checking PreferredActivity ds=" 3791 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3792 + "\n component=" + pa.mPref.mComponent); 3793 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3794 } 3795 if (pa.mPref.mMatch != match) { 3796 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3797 + Integer.toHexString(pa.mPref.mMatch)); 3798 continue; 3799 } 3800 // If it's not an "always" type preferred activity and that's what we're 3801 // looking for, skip it. 3802 if (always && !pa.mPref.mAlways) { 3803 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3804 continue; 3805 } 3806 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3807 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3808 if (DEBUG_PREFERRED || debug) { 3809 Slog.v(TAG, "Found preferred activity:"); 3810 if (ai != null) { 3811 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3812 } else { 3813 Slog.v(TAG, " null"); 3814 } 3815 } 3816 if (ai == null) { 3817 // This previously registered preferred activity 3818 // component is no longer known. Most likely an update 3819 // to the app was installed and in the new version this 3820 // component no longer exists. Clean it up by removing 3821 // it from the preferred activities list, and skip it. 3822 Slog.w(TAG, "Removing dangling preferred activity: " 3823 + pa.mPref.mComponent); 3824 pir.removeFilter(pa); 3825 changed = true; 3826 continue; 3827 } 3828 for (int j=0; j<N; j++) { 3829 final ResolveInfo ri = query.get(j); 3830 if (!ri.activityInfo.applicationInfo.packageName 3831 .equals(ai.applicationInfo.packageName)) { 3832 continue; 3833 } 3834 if (!ri.activityInfo.name.equals(ai.name)) { 3835 continue; 3836 } 3837 3838 if (removeMatches) { 3839 pir.removeFilter(pa); 3840 changed = true; 3841 if (DEBUG_PREFERRED) { 3842 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3843 } 3844 break; 3845 } 3846 3847 // Okay we found a previously set preferred or last chosen app. 3848 // If the result set is different from when this 3849 // was created, we need to clear it and re-ask the 3850 // user their preference, if we're looking for an "always" type entry. 3851 if (always && !pa.mPref.sameSet(query)) { 3852 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3853 + intent + " type " + resolvedType); 3854 if (DEBUG_PREFERRED) { 3855 Slog.v(TAG, "Removing preferred activity since set changed " 3856 + pa.mPref.mComponent); 3857 } 3858 pir.removeFilter(pa); 3859 // Re-add the filter as a "last chosen" entry (!always) 3860 PreferredActivity lastChosen = new PreferredActivity( 3861 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3862 pir.addFilter(lastChosen); 3863 changed = true; 3864 return null; 3865 } 3866 3867 // Yay! Either the set matched or we're looking for the last chosen 3868 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3869 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3870 return ri; 3871 } 3872 } 3873 } finally { 3874 if (changed) { 3875 if (DEBUG_PREFERRED) { 3876 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3877 } 3878 scheduleWritePackageRestrictionsLocked(userId); 3879 } 3880 } 3881 } 3882 } 3883 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3884 return null; 3885 } 3886 3887 /* 3888 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3889 */ 3890 @Override 3891 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3892 int targetUserId) { 3893 mContext.enforceCallingOrSelfPermission( 3894 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3895 List<CrossProfileIntentFilter> matches = 3896 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3897 if (matches != null) { 3898 int size = matches.size(); 3899 for (int i = 0; i < size; i++) { 3900 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3901 } 3902 } 3903 return false; 3904 } 3905 3906 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3907 String resolvedType, int userId) { 3908 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3909 if (resolver != null) { 3910 return resolver.queryIntent(intent, resolvedType, false, userId); 3911 } 3912 return null; 3913 } 3914 3915 @Override 3916 public List<ResolveInfo> queryIntentActivities(Intent intent, 3917 String resolvedType, int flags, int userId) { 3918 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3919 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3920 ComponentName comp = intent.getComponent(); 3921 if (comp == null) { 3922 if (intent.getSelector() != null) { 3923 intent = intent.getSelector(); 3924 comp = intent.getComponent(); 3925 } 3926 } 3927 3928 if (comp != null) { 3929 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3930 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3931 if (ai != null) { 3932 final ResolveInfo ri = new ResolveInfo(); 3933 ri.activityInfo = ai; 3934 list.add(ri); 3935 } 3936 return list; 3937 } 3938 3939 // reader 3940 synchronized (mPackages) { 3941 final String pkgName = intent.getPackage(); 3942 if (pkgName == null) { 3943 List<CrossProfileIntentFilter> matchingFilters = 3944 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3945 // Check for results that need to skip the current profile. 3946 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3947 resolvedType, flags, userId); 3948 if (resolveInfo != null) { 3949 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3950 result.add(resolveInfo); 3951 return filterIfNotPrimaryUser(result, userId); 3952 } 3953 // Check for cross profile results. 3954 resolveInfo = queryCrossProfileIntents( 3955 matchingFilters, intent, resolvedType, flags, userId); 3956 3957 // Check for results in the current profile. 3958 List<ResolveInfo> result = mActivities.queryIntent( 3959 intent, resolvedType, flags, userId); 3960 if (resolveInfo != null) { 3961 result.add(resolveInfo); 3962 Collections.sort(result, mResolvePrioritySorter); 3963 } 3964 result = filterIfNotPrimaryUser(result, userId); 3965 if (result.size() > 1 && hasWebURI(intent)) { 3966 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3967 } 3968 return result; 3969 } 3970 final PackageParser.Package pkg = mPackages.get(pkgName); 3971 if (pkg != null) { 3972 return filterIfNotPrimaryUser( 3973 mActivities.queryIntentForPackage( 3974 intent, resolvedType, flags, pkg.activities, userId), 3975 userId); 3976 } 3977 return new ArrayList<ResolveInfo>(); 3978 } 3979 } 3980 3981 /** 3982 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3983 * 3984 * @return filtered list 3985 */ 3986 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3987 if (userId == UserHandle.USER_OWNER) { 3988 return resolveInfos; 3989 } 3990 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3991 ResolveInfo info = resolveInfos.get(i); 3992 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3993 resolveInfos.remove(i); 3994 } 3995 } 3996 return resolveInfos; 3997 } 3998 3999 private static boolean hasWebURI(Intent intent) { 4000 if (intent.getData() == null) { 4001 return false; 4002 } 4003 final String scheme = intent.getScheme(); 4004 if (TextUtils.isEmpty(scheme)) { 4005 return false; 4006 } 4007 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4008 } 4009 4010 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4011 int flags, List<ResolveInfo> candidates) { 4012 if (DEBUG_PREFERRED) { 4013 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4014 candidates.size()); 4015 } 4016 4017 final int userId = UserHandle.getCallingUserId(); 4018 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4019 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4020 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4021 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4022 4023 synchronized (mPackages) { 4024 final int count = candidates.size(); 4025 // First, try to use the domain prefered App 4026 for (int n=0; n<count; n++) { 4027 ResolveInfo info = candidates.get(n); 4028 String packageName = info.activityInfo.packageName; 4029 PackageSetting ps = mSettings.mPackages.get(packageName); 4030 if (ps != null) { 4031 // Add to the special match all list (Browser use case) 4032 if (info.handleAllWebDataURI) { 4033 matchAllList.add(info); 4034 continue; 4035 } 4036 // Try to get the status from User settings first 4037 int status = getDomainVerificationStatusLPr(ps, userId); 4038 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4039 result.add(info); 4040 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4041 neverList.add(info); 4042 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4043 undefinedList.add(info); 4044 } 4045 } 4046 } 4047 // If there is nothing selected, add all candidates and remove the ones that the User 4048 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4049 // also remove any Browser Apps ones. 4050 // If there is still none after this pass, add all undefined one and Browser Apps and 4051 // let the User decide with the Disambiguation dialog if there are several ones. 4052 if (result.size() == 0) { 4053 result.addAll(candidates); 4054 } 4055 result.removeAll(neverList); 4056 result.removeAll(matchAllList); 4057 if (result.size() == 0) { 4058 result.addAll(undefinedList); 4059 if ((flags & MATCH_ALL) != 0) { 4060 result.addAll(matchAllList); 4061 } else { 4062 // Try to add the Default Browser if we can 4063 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4064 UserHandle.myUserId()); 4065 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4066 boolean defaultBrowserFound = false; 4067 final int browserCount = matchAllList.size(); 4068 for (int n=0; n<browserCount; n++) { 4069 ResolveInfo browser = matchAllList.get(n); 4070 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4071 result.add(browser); 4072 defaultBrowserFound = true; 4073 break; 4074 } 4075 } 4076 if (!defaultBrowserFound) { 4077 result.addAll(matchAllList); 4078 } 4079 } else { 4080 result.addAll(matchAllList); 4081 } 4082 } 4083 } 4084 } 4085 if (DEBUG_PREFERRED) { 4086 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4087 result.size()); 4088 } 4089 return result; 4090 } 4091 4092 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4093 int status = ps.getDomainVerificationStatusForUser(userId); 4094 // if none available, get the master status 4095 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4096 if (ps.getIntentFilterVerificationInfo() != null) { 4097 status = ps.getIntentFilterVerificationInfo().getStatus(); 4098 } 4099 } 4100 return status; 4101 } 4102 4103 private ResolveInfo querySkipCurrentProfileIntents( 4104 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4105 int flags, int sourceUserId) { 4106 if (matchingFilters != null) { 4107 int size = matchingFilters.size(); 4108 for (int i = 0; i < size; i ++) { 4109 CrossProfileIntentFilter filter = matchingFilters.get(i); 4110 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4111 // Checking if there are activities in the target user that can handle the 4112 // intent. 4113 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4114 flags, sourceUserId); 4115 if (resolveInfo != null) { 4116 return resolveInfo; 4117 } 4118 } 4119 } 4120 } 4121 return null; 4122 } 4123 4124 // Return matching ResolveInfo if any for skip current profile intent filters. 4125 private ResolveInfo queryCrossProfileIntents( 4126 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4127 int flags, int sourceUserId) { 4128 if (matchingFilters != null) { 4129 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4130 // match the same intent. For performance reasons, it is better not to 4131 // run queryIntent twice for the same userId 4132 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4133 int size = matchingFilters.size(); 4134 for (int i = 0; i < size; i++) { 4135 CrossProfileIntentFilter filter = matchingFilters.get(i); 4136 int targetUserId = filter.getTargetUserId(); 4137 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4138 && !alreadyTriedUserIds.get(targetUserId)) { 4139 // Checking if there are activities in the target user that can handle the 4140 // intent. 4141 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4142 flags, sourceUserId); 4143 if (resolveInfo != null) return resolveInfo; 4144 alreadyTriedUserIds.put(targetUserId, true); 4145 } 4146 } 4147 } 4148 return null; 4149 } 4150 4151 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4152 String resolvedType, int flags, int sourceUserId) { 4153 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4154 resolvedType, flags, filter.getTargetUserId()); 4155 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4156 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4157 } 4158 return null; 4159 } 4160 4161 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4162 int sourceUserId, int targetUserId) { 4163 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4164 String className; 4165 if (targetUserId == UserHandle.USER_OWNER) { 4166 className = FORWARD_INTENT_TO_USER_OWNER; 4167 } else { 4168 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4169 } 4170 ComponentName forwardingActivityComponentName = new ComponentName( 4171 mAndroidApplication.packageName, className); 4172 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4173 sourceUserId); 4174 if (targetUserId == UserHandle.USER_OWNER) { 4175 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4176 forwardingResolveInfo.noResourceId = true; 4177 } 4178 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4179 forwardingResolveInfo.priority = 0; 4180 forwardingResolveInfo.preferredOrder = 0; 4181 forwardingResolveInfo.match = 0; 4182 forwardingResolveInfo.isDefault = true; 4183 forwardingResolveInfo.filter = filter; 4184 forwardingResolveInfo.targetUserId = targetUserId; 4185 return forwardingResolveInfo; 4186 } 4187 4188 @Override 4189 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4190 Intent[] specifics, String[] specificTypes, Intent intent, 4191 String resolvedType, int flags, int userId) { 4192 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4193 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4194 false, "query intent activity options"); 4195 final String resultsAction = intent.getAction(); 4196 4197 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4198 | PackageManager.GET_RESOLVED_FILTER, userId); 4199 4200 if (DEBUG_INTENT_MATCHING) { 4201 Log.v(TAG, "Query " + intent + ": " + results); 4202 } 4203 4204 int specificsPos = 0; 4205 int N; 4206 4207 // todo: note that the algorithm used here is O(N^2). This 4208 // isn't a problem in our current environment, but if we start running 4209 // into situations where we have more than 5 or 10 matches then this 4210 // should probably be changed to something smarter... 4211 4212 // First we go through and resolve each of the specific items 4213 // that were supplied, taking care of removing any corresponding 4214 // duplicate items in the generic resolve list. 4215 if (specifics != null) { 4216 for (int i=0; i<specifics.length; i++) { 4217 final Intent sintent = specifics[i]; 4218 if (sintent == null) { 4219 continue; 4220 } 4221 4222 if (DEBUG_INTENT_MATCHING) { 4223 Log.v(TAG, "Specific #" + i + ": " + sintent); 4224 } 4225 4226 String action = sintent.getAction(); 4227 if (resultsAction != null && resultsAction.equals(action)) { 4228 // If this action was explicitly requested, then don't 4229 // remove things that have it. 4230 action = null; 4231 } 4232 4233 ResolveInfo ri = null; 4234 ActivityInfo ai = null; 4235 4236 ComponentName comp = sintent.getComponent(); 4237 if (comp == null) { 4238 ri = resolveIntent( 4239 sintent, 4240 specificTypes != null ? specificTypes[i] : null, 4241 flags, userId); 4242 if (ri == null) { 4243 continue; 4244 } 4245 if (ri == mResolveInfo) { 4246 // ACK! Must do something better with this. 4247 } 4248 ai = ri.activityInfo; 4249 comp = new ComponentName(ai.applicationInfo.packageName, 4250 ai.name); 4251 } else { 4252 ai = getActivityInfo(comp, flags, userId); 4253 if (ai == null) { 4254 continue; 4255 } 4256 } 4257 4258 // Look for any generic query activities that are duplicates 4259 // of this specific one, and remove them from the results. 4260 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4261 N = results.size(); 4262 int j; 4263 for (j=specificsPos; j<N; j++) { 4264 ResolveInfo sri = results.get(j); 4265 if ((sri.activityInfo.name.equals(comp.getClassName()) 4266 && sri.activityInfo.applicationInfo.packageName.equals( 4267 comp.getPackageName())) 4268 || (action != null && sri.filter.matchAction(action))) { 4269 results.remove(j); 4270 if (DEBUG_INTENT_MATCHING) Log.v( 4271 TAG, "Removing duplicate item from " + j 4272 + " due to specific " + specificsPos); 4273 if (ri == null) { 4274 ri = sri; 4275 } 4276 j--; 4277 N--; 4278 } 4279 } 4280 4281 // Add this specific item to its proper place. 4282 if (ri == null) { 4283 ri = new ResolveInfo(); 4284 ri.activityInfo = ai; 4285 } 4286 results.add(specificsPos, ri); 4287 ri.specificIndex = i; 4288 specificsPos++; 4289 } 4290 } 4291 4292 // Now we go through the remaining generic results and remove any 4293 // duplicate actions that are found here. 4294 N = results.size(); 4295 for (int i=specificsPos; i<N-1; i++) { 4296 final ResolveInfo rii = results.get(i); 4297 if (rii.filter == null) { 4298 continue; 4299 } 4300 4301 // Iterate over all of the actions of this result's intent 4302 // filter... typically this should be just one. 4303 final Iterator<String> it = rii.filter.actionsIterator(); 4304 if (it == null) { 4305 continue; 4306 } 4307 while (it.hasNext()) { 4308 final String action = it.next(); 4309 if (resultsAction != null && resultsAction.equals(action)) { 4310 // If this action was explicitly requested, then don't 4311 // remove things that have it. 4312 continue; 4313 } 4314 for (int j=i+1; j<N; j++) { 4315 final ResolveInfo rij = results.get(j); 4316 if (rij.filter != null && rij.filter.hasAction(action)) { 4317 results.remove(j); 4318 if (DEBUG_INTENT_MATCHING) Log.v( 4319 TAG, "Removing duplicate item from " + j 4320 + " due to action " + action + " at " + i); 4321 j--; 4322 N--; 4323 } 4324 } 4325 } 4326 4327 // If the caller didn't request filter information, drop it now 4328 // so we don't have to marshall/unmarshall it. 4329 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4330 rii.filter = null; 4331 } 4332 } 4333 4334 // Filter out the caller activity if so requested. 4335 if (caller != null) { 4336 N = results.size(); 4337 for (int i=0; i<N; i++) { 4338 ActivityInfo ainfo = results.get(i).activityInfo; 4339 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4340 && caller.getClassName().equals(ainfo.name)) { 4341 results.remove(i); 4342 break; 4343 } 4344 } 4345 } 4346 4347 // If the caller didn't request filter information, 4348 // drop them now so we don't have to 4349 // marshall/unmarshall it. 4350 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4351 N = results.size(); 4352 for (int i=0; i<N; i++) { 4353 results.get(i).filter = null; 4354 } 4355 } 4356 4357 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4358 return results; 4359 } 4360 4361 @Override 4362 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4363 int userId) { 4364 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4365 ComponentName comp = intent.getComponent(); 4366 if (comp == null) { 4367 if (intent.getSelector() != null) { 4368 intent = intent.getSelector(); 4369 comp = intent.getComponent(); 4370 } 4371 } 4372 if (comp != null) { 4373 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4374 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4375 if (ai != null) { 4376 ResolveInfo ri = new ResolveInfo(); 4377 ri.activityInfo = ai; 4378 list.add(ri); 4379 } 4380 return list; 4381 } 4382 4383 // reader 4384 synchronized (mPackages) { 4385 String pkgName = intent.getPackage(); 4386 if (pkgName == null) { 4387 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4388 } 4389 final PackageParser.Package pkg = mPackages.get(pkgName); 4390 if (pkg != null) { 4391 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4392 userId); 4393 } 4394 return null; 4395 } 4396 } 4397 4398 @Override 4399 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4400 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4401 if (!sUserManager.exists(userId)) return null; 4402 if (query != null) { 4403 if (query.size() >= 1) { 4404 // If there is more than one service with the same priority, 4405 // just arbitrarily pick the first one. 4406 return query.get(0); 4407 } 4408 } 4409 return null; 4410 } 4411 4412 @Override 4413 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4414 int userId) { 4415 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4416 ComponentName comp = intent.getComponent(); 4417 if (comp == null) { 4418 if (intent.getSelector() != null) { 4419 intent = intent.getSelector(); 4420 comp = intent.getComponent(); 4421 } 4422 } 4423 if (comp != null) { 4424 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4425 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4426 if (si != null) { 4427 final ResolveInfo ri = new ResolveInfo(); 4428 ri.serviceInfo = si; 4429 list.add(ri); 4430 } 4431 return list; 4432 } 4433 4434 // reader 4435 synchronized (mPackages) { 4436 String pkgName = intent.getPackage(); 4437 if (pkgName == null) { 4438 return mServices.queryIntent(intent, resolvedType, flags, userId); 4439 } 4440 final PackageParser.Package pkg = mPackages.get(pkgName); 4441 if (pkg != null) { 4442 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4443 userId); 4444 } 4445 return null; 4446 } 4447 } 4448 4449 @Override 4450 public List<ResolveInfo> queryIntentContentProviders( 4451 Intent intent, String resolvedType, int flags, int userId) { 4452 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4453 ComponentName comp = intent.getComponent(); 4454 if (comp == null) { 4455 if (intent.getSelector() != null) { 4456 intent = intent.getSelector(); 4457 comp = intent.getComponent(); 4458 } 4459 } 4460 if (comp != null) { 4461 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4462 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4463 if (pi != null) { 4464 final ResolveInfo ri = new ResolveInfo(); 4465 ri.providerInfo = pi; 4466 list.add(ri); 4467 } 4468 return list; 4469 } 4470 4471 // reader 4472 synchronized (mPackages) { 4473 String pkgName = intent.getPackage(); 4474 if (pkgName == null) { 4475 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4476 } 4477 final PackageParser.Package pkg = mPackages.get(pkgName); 4478 if (pkg != null) { 4479 return mProviders.queryIntentForPackage( 4480 intent, resolvedType, flags, pkg.providers, userId); 4481 } 4482 return null; 4483 } 4484 } 4485 4486 @Override 4487 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4488 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4489 4490 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4491 4492 // writer 4493 synchronized (mPackages) { 4494 ArrayList<PackageInfo> list; 4495 if (listUninstalled) { 4496 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4497 for (PackageSetting ps : mSettings.mPackages.values()) { 4498 PackageInfo pi; 4499 if (ps.pkg != null) { 4500 pi = generatePackageInfo(ps.pkg, flags, userId); 4501 } else { 4502 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4503 } 4504 if (pi != null) { 4505 list.add(pi); 4506 } 4507 } 4508 } else { 4509 list = new ArrayList<PackageInfo>(mPackages.size()); 4510 for (PackageParser.Package p : mPackages.values()) { 4511 PackageInfo pi = generatePackageInfo(p, flags, userId); 4512 if (pi != null) { 4513 list.add(pi); 4514 } 4515 } 4516 } 4517 4518 return new ParceledListSlice<PackageInfo>(list); 4519 } 4520 } 4521 4522 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4523 String[] permissions, boolean[] tmp, int flags, int userId) { 4524 int numMatch = 0; 4525 final PermissionsState permissionsState = ps.getPermissionsState(); 4526 for (int i=0; i<permissions.length; i++) { 4527 final String permission = permissions[i]; 4528 if (permissionsState.hasPermission(permission, userId)) { 4529 tmp[i] = true; 4530 numMatch++; 4531 } else { 4532 tmp[i] = false; 4533 } 4534 } 4535 if (numMatch == 0) { 4536 return; 4537 } 4538 PackageInfo pi; 4539 if (ps.pkg != null) { 4540 pi = generatePackageInfo(ps.pkg, flags, userId); 4541 } else { 4542 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4543 } 4544 // The above might return null in cases of uninstalled apps or install-state 4545 // skew across users/profiles. 4546 if (pi != null) { 4547 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4548 if (numMatch == permissions.length) { 4549 pi.requestedPermissions = permissions; 4550 } else { 4551 pi.requestedPermissions = new String[numMatch]; 4552 numMatch = 0; 4553 for (int i=0; i<permissions.length; i++) { 4554 if (tmp[i]) { 4555 pi.requestedPermissions[numMatch] = permissions[i]; 4556 numMatch++; 4557 } 4558 } 4559 } 4560 } 4561 list.add(pi); 4562 } 4563 } 4564 4565 @Override 4566 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4567 String[] permissions, int flags, int userId) { 4568 if (!sUserManager.exists(userId)) return null; 4569 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4570 4571 // writer 4572 synchronized (mPackages) { 4573 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4574 boolean[] tmpBools = new boolean[permissions.length]; 4575 if (listUninstalled) { 4576 for (PackageSetting ps : mSettings.mPackages.values()) { 4577 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4578 } 4579 } else { 4580 for (PackageParser.Package pkg : mPackages.values()) { 4581 PackageSetting ps = (PackageSetting)pkg.mExtras; 4582 if (ps != null) { 4583 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4584 userId); 4585 } 4586 } 4587 } 4588 4589 return new ParceledListSlice<PackageInfo>(list); 4590 } 4591 } 4592 4593 @Override 4594 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4595 if (!sUserManager.exists(userId)) return null; 4596 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4597 4598 // writer 4599 synchronized (mPackages) { 4600 ArrayList<ApplicationInfo> list; 4601 if (listUninstalled) { 4602 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4603 for (PackageSetting ps : mSettings.mPackages.values()) { 4604 ApplicationInfo ai; 4605 if (ps.pkg != null) { 4606 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4607 ps.readUserState(userId), userId); 4608 } else { 4609 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4610 } 4611 if (ai != null) { 4612 list.add(ai); 4613 } 4614 } 4615 } else { 4616 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4617 for (PackageParser.Package p : mPackages.values()) { 4618 if (p.mExtras != null) { 4619 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4620 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4621 if (ai != null) { 4622 list.add(ai); 4623 } 4624 } 4625 } 4626 } 4627 4628 return new ParceledListSlice<ApplicationInfo>(list); 4629 } 4630 } 4631 4632 public List<ApplicationInfo> getPersistentApplications(int flags) { 4633 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4634 4635 // reader 4636 synchronized (mPackages) { 4637 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4638 final int userId = UserHandle.getCallingUserId(); 4639 while (i.hasNext()) { 4640 final PackageParser.Package p = i.next(); 4641 if (p.applicationInfo != null 4642 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4643 && (!mSafeMode || isSystemApp(p))) { 4644 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4645 if (ps != null) { 4646 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4647 ps.readUserState(userId), userId); 4648 if (ai != null) { 4649 finalList.add(ai); 4650 } 4651 } 4652 } 4653 } 4654 } 4655 4656 return finalList; 4657 } 4658 4659 @Override 4660 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4661 if (!sUserManager.exists(userId)) return null; 4662 // reader 4663 synchronized (mPackages) { 4664 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4665 PackageSetting ps = provider != null 4666 ? mSettings.mPackages.get(provider.owner.packageName) 4667 : null; 4668 return ps != null 4669 && mSettings.isEnabledLPr(provider.info, flags, userId) 4670 && (!mSafeMode || (provider.info.applicationInfo.flags 4671 &ApplicationInfo.FLAG_SYSTEM) != 0) 4672 ? PackageParser.generateProviderInfo(provider, flags, 4673 ps.readUserState(userId), userId) 4674 : null; 4675 } 4676 } 4677 4678 /** 4679 * @deprecated 4680 */ 4681 @Deprecated 4682 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4683 // reader 4684 synchronized (mPackages) { 4685 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4686 .entrySet().iterator(); 4687 final int userId = UserHandle.getCallingUserId(); 4688 while (i.hasNext()) { 4689 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4690 PackageParser.Provider p = entry.getValue(); 4691 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4692 4693 if (ps != null && p.syncable 4694 && (!mSafeMode || (p.info.applicationInfo.flags 4695 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4696 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4697 ps.readUserState(userId), userId); 4698 if (info != null) { 4699 outNames.add(entry.getKey()); 4700 outInfo.add(info); 4701 } 4702 } 4703 } 4704 } 4705 } 4706 4707 @Override 4708 public List<ProviderInfo> queryContentProviders(String processName, 4709 int uid, int flags) { 4710 ArrayList<ProviderInfo> finalList = null; 4711 // reader 4712 synchronized (mPackages) { 4713 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4714 final int userId = processName != null ? 4715 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4716 while (i.hasNext()) { 4717 final PackageParser.Provider p = i.next(); 4718 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4719 if (ps != null && p.info.authority != null 4720 && (processName == null 4721 || (p.info.processName.equals(processName) 4722 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4723 && mSettings.isEnabledLPr(p.info, flags, userId) 4724 && (!mSafeMode 4725 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4726 if (finalList == null) { 4727 finalList = new ArrayList<ProviderInfo>(3); 4728 } 4729 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4730 ps.readUserState(userId), userId); 4731 if (info != null) { 4732 finalList.add(info); 4733 } 4734 } 4735 } 4736 } 4737 4738 if (finalList != null) { 4739 Collections.sort(finalList, mProviderInitOrderSorter); 4740 } 4741 4742 return finalList; 4743 } 4744 4745 @Override 4746 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4747 int flags) { 4748 // reader 4749 synchronized (mPackages) { 4750 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4751 return PackageParser.generateInstrumentationInfo(i, flags); 4752 } 4753 } 4754 4755 @Override 4756 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4757 int flags) { 4758 ArrayList<InstrumentationInfo> finalList = 4759 new ArrayList<InstrumentationInfo>(); 4760 4761 // reader 4762 synchronized (mPackages) { 4763 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4764 while (i.hasNext()) { 4765 final PackageParser.Instrumentation p = i.next(); 4766 if (targetPackage == null 4767 || targetPackage.equals(p.info.targetPackage)) { 4768 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4769 flags); 4770 if (ii != null) { 4771 finalList.add(ii); 4772 } 4773 } 4774 } 4775 } 4776 4777 return finalList; 4778 } 4779 4780 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4781 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4782 if (overlays == null) { 4783 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4784 return; 4785 } 4786 for (PackageParser.Package opkg : overlays.values()) { 4787 // Not much to do if idmap fails: we already logged the error 4788 // and we certainly don't want to abort installation of pkg simply 4789 // because an overlay didn't fit properly. For these reasons, 4790 // ignore the return value of createIdmapForPackagePairLI. 4791 createIdmapForPackagePairLI(pkg, opkg); 4792 } 4793 } 4794 4795 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4796 PackageParser.Package opkg) { 4797 if (!opkg.mTrustedOverlay) { 4798 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4799 opkg.baseCodePath + ": overlay not trusted"); 4800 return false; 4801 } 4802 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4803 if (overlaySet == null) { 4804 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4805 opkg.baseCodePath + " but target package has no known overlays"); 4806 return false; 4807 } 4808 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4809 // TODO: generate idmap for split APKs 4810 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4811 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4812 + opkg.baseCodePath); 4813 return false; 4814 } 4815 PackageParser.Package[] overlayArray = 4816 overlaySet.values().toArray(new PackageParser.Package[0]); 4817 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4818 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4819 return p1.mOverlayPriority - p2.mOverlayPriority; 4820 } 4821 }; 4822 Arrays.sort(overlayArray, cmp); 4823 4824 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4825 int i = 0; 4826 for (PackageParser.Package p : overlayArray) { 4827 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4828 } 4829 return true; 4830 } 4831 4832 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4833 final File[] files = dir.listFiles(); 4834 if (ArrayUtils.isEmpty(files)) { 4835 Log.d(TAG, "No files in app dir " + dir); 4836 return; 4837 } 4838 4839 if (DEBUG_PACKAGE_SCANNING) { 4840 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4841 + " flags=0x" + Integer.toHexString(parseFlags)); 4842 } 4843 4844 for (File file : files) { 4845 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4846 && !PackageInstallerService.isStageName(file.getName()); 4847 if (!isPackage) { 4848 // Ignore entries which are not packages 4849 continue; 4850 } 4851 try { 4852 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4853 scanFlags, currentTime, null); 4854 } catch (PackageManagerException e) { 4855 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4856 4857 // Delete invalid userdata apps 4858 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4859 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4860 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4861 if (file.isDirectory()) { 4862 mInstaller.rmPackageDir(file.getAbsolutePath()); 4863 } else { 4864 file.delete(); 4865 } 4866 } 4867 } 4868 } 4869 } 4870 4871 private static File getSettingsProblemFile() { 4872 File dataDir = Environment.getDataDirectory(); 4873 File systemDir = new File(dataDir, "system"); 4874 File fname = new File(systemDir, "uiderrors.txt"); 4875 return fname; 4876 } 4877 4878 static void reportSettingsProblem(int priority, String msg) { 4879 logCriticalInfo(priority, msg); 4880 } 4881 4882 static void logCriticalInfo(int priority, String msg) { 4883 Slog.println(priority, TAG, msg); 4884 EventLogTags.writePmCriticalInfo(msg); 4885 try { 4886 File fname = getSettingsProblemFile(); 4887 FileOutputStream out = new FileOutputStream(fname, true); 4888 PrintWriter pw = new FastPrintWriter(out); 4889 SimpleDateFormat formatter = new SimpleDateFormat(); 4890 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4891 pw.println(dateString + ": " + msg); 4892 pw.close(); 4893 FileUtils.setPermissions( 4894 fname.toString(), 4895 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4896 -1, -1); 4897 } catch (java.io.IOException e) { 4898 } 4899 } 4900 4901 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4902 PackageParser.Package pkg, File srcFile, int parseFlags) 4903 throws PackageManagerException { 4904 if (ps != null 4905 && ps.codePath.equals(srcFile) 4906 && ps.timeStamp == srcFile.lastModified() 4907 && !isCompatSignatureUpdateNeeded(pkg) 4908 && !isRecoverSignatureUpdateNeeded(pkg)) { 4909 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4910 if (ps.signatures.mSignatures != null 4911 && ps.signatures.mSignatures.length != 0 4912 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4913 // Optimization: reuse the existing cached certificates 4914 // if the package appears to be unchanged. 4915 pkg.mSignatures = ps.signatures.mSignatures; 4916 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4917 synchronized (mPackages) { 4918 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4919 } 4920 return; 4921 } 4922 4923 Slog.w(TAG, "PackageSetting for " + ps.name 4924 + " is missing signatures. Collecting certs again to recover them."); 4925 } else { 4926 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4927 } 4928 4929 try { 4930 pp.collectCertificates(pkg, parseFlags); 4931 pp.collectManifestDigest(pkg); 4932 } catch (PackageParserException e) { 4933 throw PackageManagerException.from(e); 4934 } 4935 } 4936 4937 /* 4938 * Scan a package and return the newly parsed package. 4939 * Returns null in case of errors and the error code is stored in mLastScanError 4940 */ 4941 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4942 long currentTime, UserHandle user) throws PackageManagerException { 4943 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4944 parseFlags |= mDefParseFlags; 4945 PackageParser pp = new PackageParser(); 4946 pp.setSeparateProcesses(mSeparateProcesses); 4947 pp.setOnlyCoreApps(mOnlyCore); 4948 pp.setDisplayMetrics(mMetrics); 4949 4950 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4951 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4952 } 4953 4954 final PackageParser.Package pkg; 4955 try { 4956 pkg = pp.parsePackage(scanFile, parseFlags); 4957 } catch (PackageParserException e) { 4958 throw PackageManagerException.from(e); 4959 } 4960 4961 PackageSetting ps = null; 4962 PackageSetting updatedPkg; 4963 // reader 4964 synchronized (mPackages) { 4965 // Look to see if we already know about this package. 4966 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4967 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4968 // This package has been renamed to its original name. Let's 4969 // use that. 4970 ps = mSettings.peekPackageLPr(oldName); 4971 } 4972 // If there was no original package, see one for the real package name. 4973 if (ps == null) { 4974 ps = mSettings.peekPackageLPr(pkg.packageName); 4975 } 4976 // Check to see if this package could be hiding/updating a system 4977 // package. Must look for it either under the original or real 4978 // package name depending on our state. 4979 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4980 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4981 } 4982 boolean updatedPkgBetter = false; 4983 // First check if this is a system package that may involve an update 4984 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4985 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4986 // it needs to drop FLAG_PRIVILEGED. 4987 if (locationIsPrivileged(scanFile)) { 4988 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4989 } else { 4990 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4991 } 4992 4993 if (ps != null && !ps.codePath.equals(scanFile)) { 4994 // The path has changed from what was last scanned... check the 4995 // version of the new path against what we have stored to determine 4996 // what to do. 4997 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4998 if (pkg.mVersionCode <= ps.versionCode) { 4999 // The system package has been updated and the code path does not match 5000 // Ignore entry. Skip it. 5001 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5002 + " ignored: updated version " + ps.versionCode 5003 + " better than this " + pkg.mVersionCode); 5004 if (!updatedPkg.codePath.equals(scanFile)) { 5005 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5006 + ps.name + " changing from " + updatedPkg.codePathString 5007 + " to " + scanFile); 5008 updatedPkg.codePath = scanFile; 5009 updatedPkg.codePathString = scanFile.toString(); 5010 updatedPkg.resourcePath = scanFile; 5011 updatedPkg.resourcePathString = scanFile.toString(); 5012 } 5013 updatedPkg.pkg = pkg; 5014 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5015 } else { 5016 // The current app on the system partition is better than 5017 // what we have updated to on the data partition; switch 5018 // back to the system partition version. 5019 // At this point, its safely assumed that package installation for 5020 // apps in system partition will go through. If not there won't be a working 5021 // version of the app 5022 // writer 5023 synchronized (mPackages) { 5024 // Just remove the loaded entries from package lists. 5025 mPackages.remove(ps.name); 5026 } 5027 5028 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5029 + " reverting from " + ps.codePathString 5030 + ": new version " + pkg.mVersionCode 5031 + " better than installed " + ps.versionCode); 5032 5033 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5034 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5035 getAppDexInstructionSets(ps)); 5036 synchronized (mInstallLock) { 5037 args.cleanUpResourcesLI(); 5038 } 5039 synchronized (mPackages) { 5040 mSettings.enableSystemPackageLPw(ps.name); 5041 } 5042 updatedPkgBetter = true; 5043 } 5044 } 5045 } 5046 5047 if (updatedPkg != null) { 5048 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5049 // initially 5050 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5051 5052 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5053 // flag set initially 5054 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5055 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5056 } 5057 } 5058 5059 // Verify certificates against what was last scanned 5060 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5061 5062 /* 5063 * A new system app appeared, but we already had a non-system one of the 5064 * same name installed earlier. 5065 */ 5066 boolean shouldHideSystemApp = false; 5067 if (updatedPkg == null && ps != null 5068 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5069 /* 5070 * Check to make sure the signatures match first. If they don't, 5071 * wipe the installed application and its data. 5072 */ 5073 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5074 != PackageManager.SIGNATURE_MATCH) { 5075 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5076 + " signatures don't match existing userdata copy; removing"); 5077 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5078 ps = null; 5079 } else { 5080 /* 5081 * If the newly-added system app is an older version than the 5082 * already installed version, hide it. It will be scanned later 5083 * and re-added like an update. 5084 */ 5085 if (pkg.mVersionCode <= ps.versionCode) { 5086 shouldHideSystemApp = true; 5087 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5088 + " but new version " + pkg.mVersionCode + " better than installed " 5089 + ps.versionCode + "; hiding system"); 5090 } else { 5091 /* 5092 * The newly found system app is a newer version that the 5093 * one previously installed. Simply remove the 5094 * already-installed application and replace it with our own 5095 * while keeping the application data. 5096 */ 5097 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5098 + " reverting from " + ps.codePathString + ": new version " 5099 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5100 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5101 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 5102 getAppDexInstructionSets(ps)); 5103 synchronized (mInstallLock) { 5104 args.cleanUpResourcesLI(); 5105 } 5106 } 5107 } 5108 } 5109 5110 // The apk is forward locked (not public) if its code and resources 5111 // are kept in different files. (except for app in either system or 5112 // vendor path). 5113 // TODO grab this value from PackageSettings 5114 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5115 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5116 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5117 } 5118 } 5119 5120 // TODO: extend to support forward-locked splits 5121 String resourcePath = null; 5122 String baseResourcePath = null; 5123 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5124 if (ps != null && ps.resourcePathString != null) { 5125 resourcePath = ps.resourcePathString; 5126 baseResourcePath = ps.resourcePathString; 5127 } else { 5128 // Should not happen at all. Just log an error. 5129 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5130 } 5131 } else { 5132 resourcePath = pkg.codePath; 5133 baseResourcePath = pkg.baseCodePath; 5134 } 5135 5136 // Set application objects path explicitly. 5137 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5138 pkg.applicationInfo.setCodePath(pkg.codePath); 5139 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5140 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5141 pkg.applicationInfo.setResourcePath(resourcePath); 5142 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5143 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5144 5145 // Note that we invoke the following method only if we are about to unpack an application 5146 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5147 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5148 5149 /* 5150 * If the system app should be overridden by a previously installed 5151 * data, hide the system app now and let the /data/app scan pick it up 5152 * again. 5153 */ 5154 if (shouldHideSystemApp) { 5155 synchronized (mPackages) { 5156 /* 5157 * We have to grant systems permissions before we hide, because 5158 * grantPermissions will assume the package update is trying to 5159 * expand its permissions. 5160 */ 5161 grantPermissionsLPw(pkg, true, pkg.packageName); 5162 mSettings.disableSystemPackageLPw(pkg.packageName); 5163 } 5164 } 5165 5166 return scannedPkg; 5167 } 5168 5169 private static String fixProcessName(String defProcessName, 5170 String processName, int uid) { 5171 if (processName == null) { 5172 return defProcessName; 5173 } 5174 return processName; 5175 } 5176 5177 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5178 throws PackageManagerException { 5179 if (pkgSetting.signatures.mSignatures != null) { 5180 // Already existing package. Make sure signatures match 5181 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5182 == PackageManager.SIGNATURE_MATCH; 5183 if (!match) { 5184 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5185 == PackageManager.SIGNATURE_MATCH; 5186 } 5187 if (!match) { 5188 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5189 == PackageManager.SIGNATURE_MATCH; 5190 } 5191 if (!match) { 5192 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5193 + pkg.packageName + " signatures do not match the " 5194 + "previously installed version; ignoring!"); 5195 } 5196 } 5197 5198 // Check for shared user signatures 5199 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5200 // Already existing package. Make sure signatures match 5201 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5202 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5203 if (!match) { 5204 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5205 == PackageManager.SIGNATURE_MATCH; 5206 } 5207 if (!match) { 5208 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5209 == PackageManager.SIGNATURE_MATCH; 5210 } 5211 if (!match) { 5212 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5213 "Package " + pkg.packageName 5214 + " has no signatures that match those in shared user " 5215 + pkgSetting.sharedUser.name + "; ignoring!"); 5216 } 5217 } 5218 } 5219 5220 /** 5221 * Enforces that only the system UID or root's UID can call a method exposed 5222 * via Binder. 5223 * 5224 * @param message used as message if SecurityException is thrown 5225 * @throws SecurityException if the caller is not system or root 5226 */ 5227 private static final void enforceSystemOrRoot(String message) { 5228 final int uid = Binder.getCallingUid(); 5229 if (uid != Process.SYSTEM_UID && uid != 0) { 5230 throw new SecurityException(message); 5231 } 5232 } 5233 5234 @Override 5235 public void performBootDexOpt() { 5236 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5237 5238 // Before everything else, see whether we need to fstrim. 5239 try { 5240 IMountService ms = PackageHelper.getMountService(); 5241 if (ms != null) { 5242 final boolean isUpgrade = isUpgrade(); 5243 boolean doTrim = isUpgrade; 5244 if (doTrim) { 5245 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5246 } else { 5247 final long interval = android.provider.Settings.Global.getLong( 5248 mContext.getContentResolver(), 5249 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5250 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5251 if (interval > 0) { 5252 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5253 if (timeSinceLast > interval) { 5254 doTrim = true; 5255 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5256 + "; running immediately"); 5257 } 5258 } 5259 } 5260 if (doTrim) { 5261 if (!isFirstBoot()) { 5262 try { 5263 ActivityManagerNative.getDefault().showBootMessage( 5264 mContext.getResources().getString( 5265 R.string.android_upgrading_fstrim), true); 5266 } catch (RemoteException e) { 5267 } 5268 } 5269 ms.runMaintenance(); 5270 } 5271 } else { 5272 Slog.e(TAG, "Mount service unavailable!"); 5273 } 5274 } catch (RemoteException e) { 5275 // Can't happen; MountService is local 5276 } 5277 5278 final ArraySet<PackageParser.Package> pkgs; 5279 synchronized (mPackages) { 5280 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5281 } 5282 5283 if (pkgs != null) { 5284 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5285 // in case the device runs out of space. 5286 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5287 // Give priority to core apps. 5288 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5289 PackageParser.Package pkg = it.next(); 5290 if (pkg.coreApp) { 5291 if (DEBUG_DEXOPT) { 5292 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5293 } 5294 sortedPkgs.add(pkg); 5295 it.remove(); 5296 } 5297 } 5298 // Give priority to system apps that listen for pre boot complete. 5299 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5300 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5301 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5302 PackageParser.Package pkg = it.next(); 5303 if (pkgNames.contains(pkg.packageName)) { 5304 if (DEBUG_DEXOPT) { 5305 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5306 } 5307 sortedPkgs.add(pkg); 5308 it.remove(); 5309 } 5310 } 5311 // Give priority to system apps. 5312 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5313 PackageParser.Package pkg = it.next(); 5314 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5315 if (DEBUG_DEXOPT) { 5316 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5317 } 5318 sortedPkgs.add(pkg); 5319 it.remove(); 5320 } 5321 } 5322 // Give priority to updated system apps. 5323 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5324 PackageParser.Package pkg = it.next(); 5325 if (pkg.isUpdatedSystemApp()) { 5326 if (DEBUG_DEXOPT) { 5327 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5328 } 5329 sortedPkgs.add(pkg); 5330 it.remove(); 5331 } 5332 } 5333 // Give priority to apps that listen for boot complete. 5334 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5335 pkgNames = getPackageNamesForIntent(intent); 5336 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5337 PackageParser.Package pkg = it.next(); 5338 if (pkgNames.contains(pkg.packageName)) { 5339 if (DEBUG_DEXOPT) { 5340 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5341 } 5342 sortedPkgs.add(pkg); 5343 it.remove(); 5344 } 5345 } 5346 // Filter out packages that aren't recently used. 5347 filterRecentlyUsedApps(pkgs); 5348 // Add all remaining apps. 5349 for (PackageParser.Package pkg : pkgs) { 5350 if (DEBUG_DEXOPT) { 5351 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5352 } 5353 sortedPkgs.add(pkg); 5354 } 5355 5356 // If we want to be lazy, filter everything that wasn't recently used. 5357 if (mLazyDexOpt) { 5358 filterRecentlyUsedApps(sortedPkgs); 5359 } 5360 5361 int i = 0; 5362 int total = sortedPkgs.size(); 5363 File dataDir = Environment.getDataDirectory(); 5364 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5365 if (lowThreshold == 0) { 5366 throw new IllegalStateException("Invalid low memory threshold"); 5367 } 5368 for (PackageParser.Package pkg : sortedPkgs) { 5369 long usableSpace = dataDir.getUsableSpace(); 5370 if (usableSpace < lowThreshold) { 5371 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5372 break; 5373 } 5374 performBootDexOpt(pkg, ++i, total); 5375 } 5376 } 5377 } 5378 5379 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5380 // Filter out packages that aren't recently used. 5381 // 5382 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5383 // should do a full dexopt. 5384 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5385 int total = pkgs.size(); 5386 int skipped = 0; 5387 long now = System.currentTimeMillis(); 5388 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5389 PackageParser.Package pkg = i.next(); 5390 long then = pkg.mLastPackageUsageTimeInMills; 5391 if (then + mDexOptLRUThresholdInMills < now) { 5392 if (DEBUG_DEXOPT) { 5393 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5394 ((then == 0) ? "never" : new Date(then))); 5395 } 5396 i.remove(); 5397 skipped++; 5398 } 5399 } 5400 if (DEBUG_DEXOPT) { 5401 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5402 } 5403 } 5404 } 5405 5406 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5407 List<ResolveInfo> ris = null; 5408 try { 5409 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5410 intent, null, 0, UserHandle.USER_OWNER); 5411 } catch (RemoteException e) { 5412 } 5413 ArraySet<String> pkgNames = new ArraySet<String>(); 5414 if (ris != null) { 5415 for (ResolveInfo ri : ris) { 5416 pkgNames.add(ri.activityInfo.packageName); 5417 } 5418 } 5419 return pkgNames; 5420 } 5421 5422 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5423 if (DEBUG_DEXOPT) { 5424 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5425 } 5426 if (!isFirstBoot()) { 5427 try { 5428 ActivityManagerNative.getDefault().showBootMessage( 5429 mContext.getResources().getString(R.string.android_upgrading_apk, 5430 curr, total), true); 5431 } catch (RemoteException e) { 5432 } 5433 } 5434 PackageParser.Package p = pkg; 5435 synchronized (mInstallLock) { 5436 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5437 false /* force dex */, false /* defer */, true /* include dependencies */); 5438 } 5439 } 5440 5441 @Override 5442 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5443 return performDexOpt(packageName, instructionSet, false); 5444 } 5445 5446 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5447 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5448 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5449 if (!dexopt && !updateUsage) { 5450 // We aren't going to dexopt or update usage, so bail early. 5451 return false; 5452 } 5453 PackageParser.Package p; 5454 final String targetInstructionSet; 5455 synchronized (mPackages) { 5456 p = mPackages.get(packageName); 5457 if (p == null) { 5458 return false; 5459 } 5460 if (updateUsage) { 5461 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5462 } 5463 mPackageUsage.write(false); 5464 if (!dexopt) { 5465 // We aren't going to dexopt, so bail early. 5466 return false; 5467 } 5468 5469 targetInstructionSet = instructionSet != null ? instructionSet : 5470 getPrimaryInstructionSet(p.applicationInfo); 5471 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5472 return false; 5473 } 5474 } 5475 5476 synchronized (mInstallLock) { 5477 final String[] instructionSets = new String[] { targetInstructionSet }; 5478 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5479 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5480 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5481 } 5482 } 5483 5484 public ArraySet<String> getPackagesThatNeedDexOpt() { 5485 ArraySet<String> pkgs = null; 5486 synchronized (mPackages) { 5487 for (PackageParser.Package p : mPackages.values()) { 5488 if (DEBUG_DEXOPT) { 5489 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5490 } 5491 if (!p.mDexOptPerformed.isEmpty()) { 5492 continue; 5493 } 5494 if (pkgs == null) { 5495 pkgs = new ArraySet<String>(); 5496 } 5497 pkgs.add(p.packageName); 5498 } 5499 } 5500 return pkgs; 5501 } 5502 5503 public void shutdown() { 5504 mPackageUsage.write(true); 5505 } 5506 5507 @Override 5508 public void forceDexOpt(String packageName) { 5509 enforceSystemOrRoot("forceDexOpt"); 5510 5511 PackageParser.Package pkg; 5512 synchronized (mPackages) { 5513 pkg = mPackages.get(packageName); 5514 if (pkg == null) { 5515 throw new IllegalArgumentException("Missing package: " + packageName); 5516 } 5517 } 5518 5519 synchronized (mInstallLock) { 5520 final String[] instructionSets = new String[] { 5521 getPrimaryInstructionSet(pkg.applicationInfo) }; 5522 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5523 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5524 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5525 throw new IllegalStateException("Failed to dexopt: " + res); 5526 } 5527 } 5528 } 5529 5530 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5531 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5532 Slog.w(TAG, "Unable to update from " + oldPkg.name 5533 + " to " + newPkg.packageName 5534 + ": old package not in system partition"); 5535 return false; 5536 } else if (mPackages.get(oldPkg.name) != null) { 5537 Slog.w(TAG, "Unable to update from " + oldPkg.name 5538 + " to " + newPkg.packageName 5539 + ": old package still exists"); 5540 return false; 5541 } 5542 return true; 5543 } 5544 5545 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5546 int[] users = sUserManager.getUserIds(); 5547 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5548 if (res < 0) { 5549 return res; 5550 } 5551 for (int user : users) { 5552 if (user != 0) { 5553 res = mInstaller.createUserData(volumeUuid, packageName, 5554 UserHandle.getUid(user, uid), user, seinfo); 5555 if (res < 0) { 5556 return res; 5557 } 5558 } 5559 } 5560 return res; 5561 } 5562 5563 private int removeDataDirsLI(String volumeUuid, String packageName) { 5564 int[] users = sUserManager.getUserIds(); 5565 int res = 0; 5566 for (int user : users) { 5567 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5568 if (resInner < 0) { 5569 res = resInner; 5570 } 5571 } 5572 5573 return res; 5574 } 5575 5576 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5577 int[] users = sUserManager.getUserIds(); 5578 int res = 0; 5579 for (int user : users) { 5580 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5581 if (resInner < 0) { 5582 res = resInner; 5583 } 5584 } 5585 return res; 5586 } 5587 5588 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5589 PackageParser.Package changingLib) { 5590 if (file.path != null) { 5591 usesLibraryFiles.add(file.path); 5592 return; 5593 } 5594 PackageParser.Package p = mPackages.get(file.apk); 5595 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5596 // If we are doing this while in the middle of updating a library apk, 5597 // then we need to make sure to use that new apk for determining the 5598 // dependencies here. (We haven't yet finished committing the new apk 5599 // to the package manager state.) 5600 if (p == null || p.packageName.equals(changingLib.packageName)) { 5601 p = changingLib; 5602 } 5603 } 5604 if (p != null) { 5605 usesLibraryFiles.addAll(p.getAllCodePaths()); 5606 } 5607 } 5608 5609 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5610 PackageParser.Package changingLib) throws PackageManagerException { 5611 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5612 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5613 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5614 for (int i=0; i<N; i++) { 5615 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5616 if (file == null) { 5617 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5618 "Package " + pkg.packageName + " requires unavailable shared library " 5619 + pkg.usesLibraries.get(i) + "; failing!"); 5620 } 5621 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5622 } 5623 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5624 for (int i=0; i<N; i++) { 5625 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5626 if (file == null) { 5627 Slog.w(TAG, "Package " + pkg.packageName 5628 + " desires unavailable shared library " 5629 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5630 } else { 5631 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5632 } 5633 } 5634 N = usesLibraryFiles.size(); 5635 if (N > 0) { 5636 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5637 } else { 5638 pkg.usesLibraryFiles = null; 5639 } 5640 } 5641 } 5642 5643 private static boolean hasString(List<String> list, List<String> which) { 5644 if (list == null) { 5645 return false; 5646 } 5647 for (int i=list.size()-1; i>=0; i--) { 5648 for (int j=which.size()-1; j>=0; j--) { 5649 if (which.get(j).equals(list.get(i))) { 5650 return true; 5651 } 5652 } 5653 } 5654 return false; 5655 } 5656 5657 private void updateAllSharedLibrariesLPw() { 5658 for (PackageParser.Package pkg : mPackages.values()) { 5659 try { 5660 updateSharedLibrariesLPw(pkg, null); 5661 } catch (PackageManagerException e) { 5662 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5663 } 5664 } 5665 } 5666 5667 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5668 PackageParser.Package changingPkg) { 5669 ArrayList<PackageParser.Package> res = null; 5670 for (PackageParser.Package pkg : mPackages.values()) { 5671 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5672 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5673 if (res == null) { 5674 res = new ArrayList<PackageParser.Package>(); 5675 } 5676 res.add(pkg); 5677 try { 5678 updateSharedLibrariesLPw(pkg, changingPkg); 5679 } catch (PackageManagerException e) { 5680 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5681 } 5682 } 5683 } 5684 return res; 5685 } 5686 5687 /** 5688 * Derive the value of the {@code cpuAbiOverride} based on the provided 5689 * value and an optional stored value from the package settings. 5690 */ 5691 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5692 String cpuAbiOverride = null; 5693 5694 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5695 cpuAbiOverride = null; 5696 } else if (abiOverride != null) { 5697 cpuAbiOverride = abiOverride; 5698 } else if (settings != null) { 5699 cpuAbiOverride = settings.cpuAbiOverrideString; 5700 } 5701 5702 return cpuAbiOverride; 5703 } 5704 5705 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5706 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5707 boolean success = false; 5708 try { 5709 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5710 currentTime, user); 5711 success = true; 5712 return res; 5713 } finally { 5714 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5715 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5716 } 5717 } 5718 } 5719 5720 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5721 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5722 final File scanFile = new File(pkg.codePath); 5723 if (pkg.applicationInfo.getCodePath() == null || 5724 pkg.applicationInfo.getResourcePath() == null) { 5725 // Bail out. The resource and code paths haven't been set. 5726 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5727 "Code and resource paths haven't been set correctly"); 5728 } 5729 5730 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5731 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5732 } else { 5733 // Only allow system apps to be flagged as core apps. 5734 pkg.coreApp = false; 5735 } 5736 5737 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5738 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5739 } 5740 5741 if (mCustomResolverComponentName != null && 5742 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5743 setUpCustomResolverActivity(pkg); 5744 } 5745 5746 if (pkg.packageName.equals("android")) { 5747 synchronized (mPackages) { 5748 if (mAndroidApplication != null) { 5749 Slog.w(TAG, "*************************************************"); 5750 Slog.w(TAG, "Core android package being redefined. Skipping."); 5751 Slog.w(TAG, " file=" + scanFile); 5752 Slog.w(TAG, "*************************************************"); 5753 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5754 "Core android package being redefined. Skipping."); 5755 } 5756 5757 // Set up information for our fall-back user intent resolution activity. 5758 mPlatformPackage = pkg; 5759 pkg.mVersionCode = mSdkVersion; 5760 mAndroidApplication = pkg.applicationInfo; 5761 5762 if (!mResolverReplaced) { 5763 mResolveActivity.applicationInfo = mAndroidApplication; 5764 mResolveActivity.name = ResolverActivity.class.getName(); 5765 mResolveActivity.packageName = mAndroidApplication.packageName; 5766 mResolveActivity.processName = "system:ui"; 5767 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5768 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5769 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5770 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5771 mResolveActivity.exported = true; 5772 mResolveActivity.enabled = true; 5773 mResolveInfo.activityInfo = mResolveActivity; 5774 mResolveInfo.priority = 0; 5775 mResolveInfo.preferredOrder = 0; 5776 mResolveInfo.match = 0; 5777 mResolveComponentName = new ComponentName( 5778 mAndroidApplication.packageName, mResolveActivity.name); 5779 } 5780 } 5781 } 5782 5783 if (DEBUG_PACKAGE_SCANNING) { 5784 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5785 Log.d(TAG, "Scanning package " + pkg.packageName); 5786 } 5787 5788 if (mPackages.containsKey(pkg.packageName) 5789 || mSharedLibraries.containsKey(pkg.packageName)) { 5790 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5791 "Application package " + pkg.packageName 5792 + " already installed. Skipping duplicate."); 5793 } 5794 5795 // If we're only installing presumed-existing packages, require that the 5796 // scanned APK is both already known and at the path previously established 5797 // for it. Previously unknown packages we pick up normally, but if we have an 5798 // a priori expectation about this package's install presence, enforce it. 5799 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5800 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5801 if (known != null) { 5802 if (DEBUG_PACKAGE_SCANNING) { 5803 Log.d(TAG, "Examining " + pkg.codePath 5804 + " and requiring known paths " + known.codePathString 5805 + " & " + known.resourcePathString); 5806 } 5807 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5808 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5809 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5810 "Application package " + pkg.packageName 5811 + " found at " + pkg.applicationInfo.getCodePath() 5812 + " but expected at " + known.codePathString + "; ignoring."); 5813 } 5814 } 5815 } 5816 5817 // Initialize package source and resource directories 5818 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5819 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5820 5821 SharedUserSetting suid = null; 5822 PackageSetting pkgSetting = null; 5823 5824 if (!isSystemApp(pkg)) { 5825 // Only system apps can use these features. 5826 pkg.mOriginalPackages = null; 5827 pkg.mRealPackage = null; 5828 pkg.mAdoptPermissions = null; 5829 } 5830 5831 // writer 5832 synchronized (mPackages) { 5833 if (pkg.mSharedUserId != null) { 5834 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5835 if (suid == null) { 5836 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5837 "Creating application package " + pkg.packageName 5838 + " for shared user failed"); 5839 } 5840 if (DEBUG_PACKAGE_SCANNING) { 5841 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5842 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5843 + "): packages=" + suid.packages); 5844 } 5845 } 5846 5847 // Check if we are renaming from an original package name. 5848 PackageSetting origPackage = null; 5849 String realName = null; 5850 if (pkg.mOriginalPackages != null) { 5851 // This package may need to be renamed to a previously 5852 // installed name. Let's check on that... 5853 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5854 if (pkg.mOriginalPackages.contains(renamed)) { 5855 // This package had originally been installed as the 5856 // original name, and we have already taken care of 5857 // transitioning to the new one. Just update the new 5858 // one to continue using the old name. 5859 realName = pkg.mRealPackage; 5860 if (!pkg.packageName.equals(renamed)) { 5861 // Callers into this function may have already taken 5862 // care of renaming the package; only do it here if 5863 // it is not already done. 5864 pkg.setPackageName(renamed); 5865 } 5866 5867 } else { 5868 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5869 if ((origPackage = mSettings.peekPackageLPr( 5870 pkg.mOriginalPackages.get(i))) != null) { 5871 // We do have the package already installed under its 5872 // original name... should we use it? 5873 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5874 // New package is not compatible with original. 5875 origPackage = null; 5876 continue; 5877 } else if (origPackage.sharedUser != null) { 5878 // Make sure uid is compatible between packages. 5879 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5880 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5881 + " to " + pkg.packageName + ": old uid " 5882 + origPackage.sharedUser.name 5883 + " differs from " + pkg.mSharedUserId); 5884 origPackage = null; 5885 continue; 5886 } 5887 } else { 5888 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5889 + pkg.packageName + " to old name " + origPackage.name); 5890 } 5891 break; 5892 } 5893 } 5894 } 5895 } 5896 5897 if (mTransferedPackages.contains(pkg.packageName)) { 5898 Slog.w(TAG, "Package " + pkg.packageName 5899 + " was transferred to another, but its .apk remains"); 5900 } 5901 5902 // Just create the setting, don't add it yet. For already existing packages 5903 // the PkgSetting exists already and doesn't have to be created. 5904 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5905 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5906 pkg.applicationInfo.primaryCpuAbi, 5907 pkg.applicationInfo.secondaryCpuAbi, 5908 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5909 user, false); 5910 if (pkgSetting == null) { 5911 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5912 "Creating application package " + pkg.packageName + " failed"); 5913 } 5914 5915 if (pkgSetting.origPackage != null) { 5916 // If we are first transitioning from an original package, 5917 // fix up the new package's name now. We need to do this after 5918 // looking up the package under its new name, so getPackageLP 5919 // can take care of fiddling things correctly. 5920 pkg.setPackageName(origPackage.name); 5921 5922 // File a report about this. 5923 String msg = "New package " + pkgSetting.realName 5924 + " renamed to replace old package " + pkgSetting.name; 5925 reportSettingsProblem(Log.WARN, msg); 5926 5927 // Make a note of it. 5928 mTransferedPackages.add(origPackage.name); 5929 5930 // No longer need to retain this. 5931 pkgSetting.origPackage = null; 5932 } 5933 5934 if (realName != null) { 5935 // Make a note of it. 5936 mTransferedPackages.add(pkg.packageName); 5937 } 5938 5939 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5940 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5941 } 5942 5943 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5944 // Check all shared libraries and map to their actual file path. 5945 // We only do this here for apps not on a system dir, because those 5946 // are the only ones that can fail an install due to this. We 5947 // will take care of the system apps by updating all of their 5948 // library paths after the scan is done. 5949 updateSharedLibrariesLPw(pkg, null); 5950 } 5951 5952 if (mFoundPolicyFile) { 5953 SELinuxMMAC.assignSeinfoValue(pkg); 5954 } 5955 5956 pkg.applicationInfo.uid = pkgSetting.appId; 5957 pkg.mExtras = pkgSetting; 5958 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5959 try { 5960 verifySignaturesLP(pkgSetting, pkg); 5961 // We just determined the app is signed correctly, so bring 5962 // over the latest parsed certs. 5963 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5964 } catch (PackageManagerException e) { 5965 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5966 throw e; 5967 } 5968 // The signature has changed, but this package is in the system 5969 // image... let's recover! 5970 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5971 // However... if this package is part of a shared user, but it 5972 // doesn't match the signature of the shared user, let's fail. 5973 // What this means is that you can't change the signatures 5974 // associated with an overall shared user, which doesn't seem all 5975 // that unreasonable. 5976 if (pkgSetting.sharedUser != null) { 5977 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5978 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5979 throw new PackageManagerException( 5980 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5981 "Signature mismatch for shared user : " 5982 + pkgSetting.sharedUser); 5983 } 5984 } 5985 // File a report about this. 5986 String msg = "System package " + pkg.packageName 5987 + " signature changed; retaining data."; 5988 reportSettingsProblem(Log.WARN, msg); 5989 } 5990 } else { 5991 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5992 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5993 + pkg.packageName + " upgrade keys do not match the " 5994 + "previously installed version"); 5995 } else { 5996 // We just determined the app is signed correctly, so bring 5997 // over the latest parsed certs. 5998 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5999 } 6000 } 6001 // Verify that this new package doesn't have any content providers 6002 // that conflict with existing packages. Only do this if the 6003 // package isn't already installed, since we don't want to break 6004 // things that are installed. 6005 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6006 final int N = pkg.providers.size(); 6007 int i; 6008 for (i=0; i<N; i++) { 6009 PackageParser.Provider p = pkg.providers.get(i); 6010 if (p.info.authority != null) { 6011 String names[] = p.info.authority.split(";"); 6012 for (int j = 0; j < names.length; j++) { 6013 if (mProvidersByAuthority.containsKey(names[j])) { 6014 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6015 final String otherPackageName = 6016 ((other != null && other.getComponentName() != null) ? 6017 other.getComponentName().getPackageName() : "?"); 6018 throw new PackageManagerException( 6019 INSTALL_FAILED_CONFLICTING_PROVIDER, 6020 "Can't install because provider name " + names[j] 6021 + " (in package " + pkg.applicationInfo.packageName 6022 + ") is already used by " + otherPackageName); 6023 } 6024 } 6025 } 6026 } 6027 } 6028 6029 if (pkg.mAdoptPermissions != null) { 6030 // This package wants to adopt ownership of permissions from 6031 // another package. 6032 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6033 final String origName = pkg.mAdoptPermissions.get(i); 6034 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6035 if (orig != null) { 6036 if (verifyPackageUpdateLPr(orig, pkg)) { 6037 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6038 + pkg.packageName); 6039 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6040 } 6041 } 6042 } 6043 } 6044 } 6045 6046 final String pkgName = pkg.packageName; 6047 6048 final long scanFileTime = scanFile.lastModified(); 6049 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6050 pkg.applicationInfo.processName = fixProcessName( 6051 pkg.applicationInfo.packageName, 6052 pkg.applicationInfo.processName, 6053 pkg.applicationInfo.uid); 6054 6055 File dataPath; 6056 if (mPlatformPackage == pkg) { 6057 // The system package is special. 6058 dataPath = new File(Environment.getDataDirectory(), "system"); 6059 6060 pkg.applicationInfo.dataDir = dataPath.getPath(); 6061 6062 } else { 6063 // This is a normal package, need to make its data directory. 6064 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6065 UserHandle.USER_OWNER); 6066 6067 boolean uidError = false; 6068 if (dataPath.exists()) { 6069 int currentUid = 0; 6070 try { 6071 StructStat stat = Os.stat(dataPath.getPath()); 6072 currentUid = stat.st_uid; 6073 } catch (ErrnoException e) { 6074 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6075 } 6076 6077 // If we have mismatched owners for the data path, we have a problem. 6078 if (currentUid != pkg.applicationInfo.uid) { 6079 boolean recovered = false; 6080 if (currentUid == 0) { 6081 // The directory somehow became owned by root. Wow. 6082 // This is probably because the system was stopped while 6083 // installd was in the middle of messing with its libs 6084 // directory. Ask installd to fix that. 6085 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6086 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6087 if (ret >= 0) { 6088 recovered = true; 6089 String msg = "Package " + pkg.packageName 6090 + " unexpectedly changed to uid 0; recovered to " + 6091 + pkg.applicationInfo.uid; 6092 reportSettingsProblem(Log.WARN, msg); 6093 } 6094 } 6095 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6096 || (scanFlags&SCAN_BOOTING) != 0)) { 6097 // If this is a system app, we can at least delete its 6098 // current data so the application will still work. 6099 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6100 if (ret >= 0) { 6101 // TODO: Kill the processes first 6102 // Old data gone! 6103 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6104 ? "System package " : "Third party package "; 6105 String msg = prefix + pkg.packageName 6106 + " has changed from uid: " 6107 + currentUid + " to " 6108 + pkg.applicationInfo.uid + "; old data erased"; 6109 reportSettingsProblem(Log.WARN, msg); 6110 recovered = true; 6111 6112 // And now re-install the app. 6113 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6114 pkg.applicationInfo.seinfo); 6115 if (ret == -1) { 6116 // Ack should not happen! 6117 msg = prefix + pkg.packageName 6118 + " could not have data directory re-created after delete."; 6119 reportSettingsProblem(Log.WARN, msg); 6120 throw new PackageManagerException( 6121 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6122 } 6123 } 6124 if (!recovered) { 6125 mHasSystemUidErrors = true; 6126 } 6127 } else if (!recovered) { 6128 // If we allow this install to proceed, we will be broken. 6129 // Abort, abort! 6130 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6131 "scanPackageLI"); 6132 } 6133 if (!recovered) { 6134 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6135 + pkg.applicationInfo.uid + "/fs_" 6136 + currentUid; 6137 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6138 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6139 String msg = "Package " + pkg.packageName 6140 + " has mismatched uid: " 6141 + currentUid + " on disk, " 6142 + pkg.applicationInfo.uid + " in settings"; 6143 // writer 6144 synchronized (mPackages) { 6145 mSettings.mReadMessages.append(msg); 6146 mSettings.mReadMessages.append('\n'); 6147 uidError = true; 6148 if (!pkgSetting.uidError) { 6149 reportSettingsProblem(Log.ERROR, msg); 6150 } 6151 } 6152 } 6153 } 6154 pkg.applicationInfo.dataDir = dataPath.getPath(); 6155 if (mShouldRestoreconData) { 6156 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6157 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6158 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6159 } 6160 } else { 6161 if (DEBUG_PACKAGE_SCANNING) { 6162 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6163 Log.v(TAG, "Want this data dir: " + dataPath); 6164 } 6165 //invoke installer to do the actual installation 6166 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6167 pkg.applicationInfo.seinfo); 6168 if (ret < 0) { 6169 // Error from installer 6170 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6171 "Unable to create data dirs [errorCode=" + ret + "]"); 6172 } 6173 6174 if (dataPath.exists()) { 6175 pkg.applicationInfo.dataDir = dataPath.getPath(); 6176 } else { 6177 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6178 pkg.applicationInfo.dataDir = null; 6179 } 6180 } 6181 6182 pkgSetting.uidError = uidError; 6183 } 6184 6185 final String path = scanFile.getPath(); 6186 final String codePath = pkg.applicationInfo.getCodePath(); 6187 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6188 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6189 setBundledAppAbisAndRoots(pkg, pkgSetting); 6190 6191 // If we haven't found any native libraries for the app, check if it has 6192 // renderscript code. We'll need to force the app to 32 bit if it has 6193 // renderscript bitcode. 6194 if (pkg.applicationInfo.primaryCpuAbi == null 6195 && pkg.applicationInfo.secondaryCpuAbi == null 6196 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6197 NativeLibraryHelper.Handle handle = null; 6198 try { 6199 handle = NativeLibraryHelper.Handle.create(scanFile); 6200 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6201 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6202 } 6203 } catch (IOException ioe) { 6204 Slog.w(TAG, "Error scanning system app : " + ioe); 6205 } finally { 6206 IoUtils.closeQuietly(handle); 6207 } 6208 } 6209 6210 setNativeLibraryPaths(pkg); 6211 } else { 6212 // TODO: We can probably be smarter about this stuff. For installed apps, 6213 // we can calculate this information at install time once and for all. For 6214 // system apps, we can probably assume that this information doesn't change 6215 // after the first boot scan. As things stand, we do lots of unnecessary work. 6216 6217 // Give ourselves some initial paths; we'll come back for another 6218 // pass once we've determined ABI below. 6219 setNativeLibraryPaths(pkg); 6220 6221 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6222 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6223 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6224 6225 NativeLibraryHelper.Handle handle = null; 6226 try { 6227 handle = NativeLibraryHelper.Handle.create(scanFile); 6228 // TODO(multiArch): This can be null for apps that didn't go through the 6229 // usual installation process. We can calculate it again, like we 6230 // do during install time. 6231 // 6232 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6233 // unnecessary. 6234 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6235 6236 // Null out the abis so that they can be recalculated. 6237 pkg.applicationInfo.primaryCpuAbi = null; 6238 pkg.applicationInfo.secondaryCpuAbi = null; 6239 if (isMultiArch(pkg.applicationInfo)) { 6240 // Warn if we've set an abiOverride for multi-lib packages.. 6241 // By definition, we need to copy both 32 and 64 bit libraries for 6242 // such packages. 6243 if (pkg.cpuAbiOverride != null 6244 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6245 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6246 } 6247 6248 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6249 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6250 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6251 if (isAsec) { 6252 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6253 } else { 6254 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6255 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6256 useIsaSpecificSubdirs); 6257 } 6258 } 6259 6260 maybeThrowExceptionForMultiArchCopy( 6261 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6262 6263 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6264 if (isAsec) { 6265 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6266 } else { 6267 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6268 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6269 useIsaSpecificSubdirs); 6270 } 6271 } 6272 6273 maybeThrowExceptionForMultiArchCopy( 6274 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6275 6276 if (abi64 >= 0) { 6277 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6278 } 6279 6280 if (abi32 >= 0) { 6281 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6282 if (abi64 >= 0) { 6283 pkg.applicationInfo.secondaryCpuAbi = abi; 6284 } else { 6285 pkg.applicationInfo.primaryCpuAbi = abi; 6286 } 6287 } 6288 } else { 6289 String[] abiList = (cpuAbiOverride != null) ? 6290 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6291 6292 // Enable gross and lame hacks for apps that are built with old 6293 // SDK tools. We must scan their APKs for renderscript bitcode and 6294 // not launch them if it's present. Don't bother checking on devices 6295 // that don't have 64 bit support. 6296 boolean needsRenderScriptOverride = false; 6297 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6298 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6299 abiList = Build.SUPPORTED_32_BIT_ABIS; 6300 needsRenderScriptOverride = true; 6301 } 6302 6303 final int copyRet; 6304 if (isAsec) { 6305 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6306 } else { 6307 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6308 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6309 } 6310 6311 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6312 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6313 "Error unpackaging native libs for app, errorCode=" + copyRet); 6314 } 6315 6316 if (copyRet >= 0) { 6317 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6318 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6319 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6320 } else if (needsRenderScriptOverride) { 6321 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6322 } 6323 } 6324 } catch (IOException ioe) { 6325 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6326 } finally { 6327 IoUtils.closeQuietly(handle); 6328 } 6329 6330 // Now that we've calculated the ABIs and determined if it's an internal app, 6331 // we will go ahead and populate the nativeLibraryPath. 6332 setNativeLibraryPaths(pkg); 6333 6334 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6335 final int[] userIds = sUserManager.getUserIds(); 6336 synchronized (mInstallLock) { 6337 // Create a native library symlink only if we have native libraries 6338 // and if the native libraries are 32 bit libraries. We do not provide 6339 // this symlink for 64 bit libraries. 6340 if (pkg.applicationInfo.primaryCpuAbi != null && 6341 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6342 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6343 for (int userId : userIds) { 6344 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6345 nativeLibPath, userId) < 0) { 6346 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6347 "Failed linking native library dir (user=" + userId + ")"); 6348 } 6349 } 6350 } 6351 } 6352 } 6353 6354 // This is a special case for the "system" package, where the ABI is 6355 // dictated by the zygote configuration (and init.rc). We should keep track 6356 // of this ABI so that we can deal with "normal" applications that run under 6357 // the same UID correctly. 6358 if (mPlatformPackage == pkg) { 6359 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6360 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6361 } 6362 6363 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6364 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6365 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6366 // Copy the derived override back to the parsed package, so that we can 6367 // update the package settings accordingly. 6368 pkg.cpuAbiOverride = cpuAbiOverride; 6369 6370 if (DEBUG_ABI_SELECTION) { 6371 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6372 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6373 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6374 } 6375 6376 // Push the derived path down into PackageSettings so we know what to 6377 // clean up at uninstall time. 6378 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6379 6380 if (DEBUG_ABI_SELECTION) { 6381 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6382 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6383 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6384 } 6385 6386 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6387 // We don't do this here during boot because we can do it all 6388 // at once after scanning all existing packages. 6389 // 6390 // We also do this *before* we perform dexopt on this package, so that 6391 // we can avoid redundant dexopts, and also to make sure we've got the 6392 // code and package path correct. 6393 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6394 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6395 } 6396 6397 if ((scanFlags & SCAN_NO_DEX) == 0) { 6398 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6399 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6400 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6401 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6402 } 6403 } 6404 if (mFactoryTest && pkg.requestedPermissions.contains( 6405 android.Manifest.permission.FACTORY_TEST)) { 6406 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6407 } 6408 6409 ArrayList<PackageParser.Package> clientLibPkgs = null; 6410 6411 // writer 6412 synchronized (mPackages) { 6413 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6414 // Only system apps can add new shared libraries. 6415 if (pkg.libraryNames != null) { 6416 for (int i=0; i<pkg.libraryNames.size(); i++) { 6417 String name = pkg.libraryNames.get(i); 6418 boolean allowed = false; 6419 if (pkg.isUpdatedSystemApp()) { 6420 // New library entries can only be added through the 6421 // system image. This is important to get rid of a lot 6422 // of nasty edge cases: for example if we allowed a non- 6423 // system update of the app to add a library, then uninstalling 6424 // the update would make the library go away, and assumptions 6425 // we made such as through app install filtering would now 6426 // have allowed apps on the device which aren't compatible 6427 // with it. Better to just have the restriction here, be 6428 // conservative, and create many fewer cases that can negatively 6429 // impact the user experience. 6430 final PackageSetting sysPs = mSettings 6431 .getDisabledSystemPkgLPr(pkg.packageName); 6432 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6433 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6434 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6435 allowed = true; 6436 allowed = true; 6437 break; 6438 } 6439 } 6440 } 6441 } else { 6442 allowed = true; 6443 } 6444 if (allowed) { 6445 if (!mSharedLibraries.containsKey(name)) { 6446 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6447 } else if (!name.equals(pkg.packageName)) { 6448 Slog.w(TAG, "Package " + pkg.packageName + " library " 6449 + name + " already exists; skipping"); 6450 } 6451 } else { 6452 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6453 + name + " that is not declared on system image; skipping"); 6454 } 6455 } 6456 if ((scanFlags&SCAN_BOOTING) == 0) { 6457 // If we are not booting, we need to update any applications 6458 // that are clients of our shared library. If we are booting, 6459 // this will all be done once the scan is complete. 6460 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6461 } 6462 } 6463 } 6464 } 6465 6466 // We also need to dexopt any apps that are dependent on this library. Note that 6467 // if these fail, we should abort the install since installing the library will 6468 // result in some apps being broken. 6469 if (clientLibPkgs != null) { 6470 if ((scanFlags & SCAN_NO_DEX) == 0) { 6471 for (int i = 0; i < clientLibPkgs.size(); i++) { 6472 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6473 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6474 null /* instruction sets */, forceDex, 6475 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6476 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6477 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6478 "scanPackageLI failed to dexopt clientLibPkgs"); 6479 } 6480 } 6481 } 6482 } 6483 6484 // Request the ActivityManager to kill the process(only for existing packages) 6485 // so that we do not end up in a confused state while the user is still using the older 6486 // version of the application while the new one gets installed. 6487 if ((scanFlags & SCAN_REPLACING) != 0) { 6488 killApplication(pkg.applicationInfo.packageName, 6489 pkg.applicationInfo.uid, "update pkg"); 6490 } 6491 6492 // Also need to kill any apps that are dependent on the library. 6493 if (clientLibPkgs != null) { 6494 for (int i=0; i<clientLibPkgs.size(); i++) { 6495 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6496 killApplication(clientPkg.applicationInfo.packageName, 6497 clientPkg.applicationInfo.uid, "update lib"); 6498 } 6499 } 6500 6501 // writer 6502 synchronized (mPackages) { 6503 // We don't expect installation to fail beyond this point 6504 6505 // Add the new setting to mSettings 6506 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6507 // Add the new setting to mPackages 6508 mPackages.put(pkg.applicationInfo.packageName, pkg); 6509 // Make sure we don't accidentally delete its data. 6510 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6511 while (iter.hasNext()) { 6512 PackageCleanItem item = iter.next(); 6513 if (pkgName.equals(item.packageName)) { 6514 iter.remove(); 6515 } 6516 } 6517 6518 // Take care of first install / last update times. 6519 if (currentTime != 0) { 6520 if (pkgSetting.firstInstallTime == 0) { 6521 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6522 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6523 pkgSetting.lastUpdateTime = currentTime; 6524 } 6525 } else if (pkgSetting.firstInstallTime == 0) { 6526 // We need *something*. Take time time stamp of the file. 6527 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6528 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6529 if (scanFileTime != pkgSetting.timeStamp) { 6530 // A package on the system image has changed; consider this 6531 // to be an update. 6532 pkgSetting.lastUpdateTime = scanFileTime; 6533 } 6534 } 6535 6536 // Add the package's KeySets to the global KeySetManagerService 6537 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6538 try { 6539 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6540 if (pkg.mKeySetMapping != null) { 6541 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6542 if (pkg.mUpgradeKeySets != null) { 6543 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6544 } 6545 } 6546 } catch (NullPointerException e) { 6547 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6548 } catch (IllegalArgumentException e) { 6549 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6550 } 6551 6552 int N = pkg.providers.size(); 6553 StringBuilder r = null; 6554 int i; 6555 for (i=0; i<N; i++) { 6556 PackageParser.Provider p = pkg.providers.get(i); 6557 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6558 p.info.processName, pkg.applicationInfo.uid); 6559 mProviders.addProvider(p); 6560 p.syncable = p.info.isSyncable; 6561 if (p.info.authority != null) { 6562 String names[] = p.info.authority.split(";"); 6563 p.info.authority = null; 6564 for (int j = 0; j < names.length; j++) { 6565 if (j == 1 && p.syncable) { 6566 // We only want the first authority for a provider to possibly be 6567 // syncable, so if we already added this provider using a different 6568 // authority clear the syncable flag. We copy the provider before 6569 // changing it because the mProviders object contains a reference 6570 // to a provider that we don't want to change. 6571 // Only do this for the second authority since the resulting provider 6572 // object can be the same for all future authorities for this provider. 6573 p = new PackageParser.Provider(p); 6574 p.syncable = false; 6575 } 6576 if (!mProvidersByAuthority.containsKey(names[j])) { 6577 mProvidersByAuthority.put(names[j], p); 6578 if (p.info.authority == null) { 6579 p.info.authority = names[j]; 6580 } else { 6581 p.info.authority = p.info.authority + ";" + names[j]; 6582 } 6583 if (DEBUG_PACKAGE_SCANNING) { 6584 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6585 Log.d(TAG, "Registered content provider: " + names[j] 6586 + ", className = " + p.info.name + ", isSyncable = " 6587 + p.info.isSyncable); 6588 } 6589 } else { 6590 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6591 Slog.w(TAG, "Skipping provider name " + names[j] + 6592 " (in package " + pkg.applicationInfo.packageName + 6593 "): name already used by " 6594 + ((other != null && other.getComponentName() != null) 6595 ? other.getComponentName().getPackageName() : "?")); 6596 } 6597 } 6598 } 6599 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6600 if (r == null) { 6601 r = new StringBuilder(256); 6602 } else { 6603 r.append(' '); 6604 } 6605 r.append(p.info.name); 6606 } 6607 } 6608 if (r != null) { 6609 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6610 } 6611 6612 N = pkg.services.size(); 6613 r = null; 6614 for (i=0; i<N; i++) { 6615 PackageParser.Service s = pkg.services.get(i); 6616 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6617 s.info.processName, pkg.applicationInfo.uid); 6618 mServices.addService(s); 6619 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6620 if (r == null) { 6621 r = new StringBuilder(256); 6622 } else { 6623 r.append(' '); 6624 } 6625 r.append(s.info.name); 6626 } 6627 } 6628 if (r != null) { 6629 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6630 } 6631 6632 N = pkg.receivers.size(); 6633 r = null; 6634 for (i=0; i<N; i++) { 6635 PackageParser.Activity a = pkg.receivers.get(i); 6636 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6637 a.info.processName, pkg.applicationInfo.uid); 6638 mReceivers.addActivity(a, "receiver"); 6639 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6640 if (r == null) { 6641 r = new StringBuilder(256); 6642 } else { 6643 r.append(' '); 6644 } 6645 r.append(a.info.name); 6646 } 6647 } 6648 if (r != null) { 6649 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6650 } 6651 6652 N = pkg.activities.size(); 6653 r = null; 6654 for (i=0; i<N; i++) { 6655 PackageParser.Activity a = pkg.activities.get(i); 6656 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6657 a.info.processName, pkg.applicationInfo.uid); 6658 mActivities.addActivity(a, "activity"); 6659 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6660 if (r == null) { 6661 r = new StringBuilder(256); 6662 } else { 6663 r.append(' '); 6664 } 6665 r.append(a.info.name); 6666 } 6667 } 6668 if (r != null) { 6669 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6670 } 6671 6672 N = pkg.permissionGroups.size(); 6673 r = null; 6674 for (i=0; i<N; i++) { 6675 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6676 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6677 if (cur == null) { 6678 mPermissionGroups.put(pg.info.name, pg); 6679 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6680 if (r == null) { 6681 r = new StringBuilder(256); 6682 } else { 6683 r.append(' '); 6684 } 6685 r.append(pg.info.name); 6686 } 6687 } else { 6688 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6689 + pg.info.packageName + " ignored: original from " 6690 + cur.info.packageName); 6691 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6692 if (r == null) { 6693 r = new StringBuilder(256); 6694 } else { 6695 r.append(' '); 6696 } 6697 r.append("DUP:"); 6698 r.append(pg.info.name); 6699 } 6700 } 6701 } 6702 if (r != null) { 6703 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6704 } 6705 6706 N = pkg.permissions.size(); 6707 r = null; 6708 for (i=0; i<N; i++) { 6709 PackageParser.Permission p = pkg.permissions.get(i); 6710 6711 // Now that permission groups have a special meaning, we ignore permission 6712 // groups for legacy apps to prevent unexpected behavior. In particular, 6713 // permissions for one app being granted to someone just becuase they happen 6714 // to be in a group defined by another app (before this had no implications). 6715 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6716 p.group = mPermissionGroups.get(p.info.group); 6717 // Warn for a permission in an unknown group. 6718 if (p.info.group != null && p.group == null) { 6719 Slog.w(TAG, "Permission " + p.info.name + " from package " 6720 + p.info.packageName + " in an unknown group " + p.info.group); 6721 } 6722 } 6723 6724 ArrayMap<String, BasePermission> permissionMap = 6725 p.tree ? mSettings.mPermissionTrees 6726 : mSettings.mPermissions; 6727 BasePermission bp = permissionMap.get(p.info.name); 6728 6729 // Allow system apps to redefine non-system permissions 6730 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6731 final boolean currentOwnerIsSystem = (bp.perm != null 6732 && isSystemApp(bp.perm.owner)); 6733 if (isSystemApp(p.owner)) { 6734 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6735 // It's a built-in permission and no owner, take ownership now 6736 bp.packageSetting = pkgSetting; 6737 bp.perm = p; 6738 bp.uid = pkg.applicationInfo.uid; 6739 bp.sourcePackage = p.info.packageName; 6740 } else if (!currentOwnerIsSystem) { 6741 String msg = "New decl " + p.owner + " of permission " 6742 + p.info.name + " is system; overriding " + bp.sourcePackage; 6743 reportSettingsProblem(Log.WARN, msg); 6744 bp = null; 6745 } 6746 } 6747 } 6748 6749 if (bp == null) { 6750 bp = new BasePermission(p.info.name, p.info.packageName, 6751 BasePermission.TYPE_NORMAL); 6752 permissionMap.put(p.info.name, bp); 6753 } 6754 6755 if (bp.perm == null) { 6756 if (bp.sourcePackage == null 6757 || bp.sourcePackage.equals(p.info.packageName)) { 6758 BasePermission tree = findPermissionTreeLP(p.info.name); 6759 if (tree == null 6760 || tree.sourcePackage.equals(p.info.packageName)) { 6761 bp.packageSetting = pkgSetting; 6762 bp.perm = p; 6763 bp.uid = pkg.applicationInfo.uid; 6764 bp.sourcePackage = p.info.packageName; 6765 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6766 if (r == null) { 6767 r = new StringBuilder(256); 6768 } else { 6769 r.append(' '); 6770 } 6771 r.append(p.info.name); 6772 } 6773 } else { 6774 Slog.w(TAG, "Permission " + p.info.name + " from package " 6775 + p.info.packageName + " ignored: base tree " 6776 + tree.name + " is from package " 6777 + tree.sourcePackage); 6778 } 6779 } else { 6780 Slog.w(TAG, "Permission " + p.info.name + " from package " 6781 + p.info.packageName + " ignored: original from " 6782 + bp.sourcePackage); 6783 } 6784 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6785 if (r == null) { 6786 r = new StringBuilder(256); 6787 } else { 6788 r.append(' '); 6789 } 6790 r.append("DUP:"); 6791 r.append(p.info.name); 6792 } 6793 if (bp.perm == p) { 6794 bp.protectionLevel = p.info.protectionLevel; 6795 } 6796 } 6797 6798 if (r != null) { 6799 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6800 } 6801 6802 N = pkg.instrumentation.size(); 6803 r = null; 6804 for (i=0; i<N; i++) { 6805 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6806 a.info.packageName = pkg.applicationInfo.packageName; 6807 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6808 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6809 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6810 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6811 a.info.dataDir = pkg.applicationInfo.dataDir; 6812 6813 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6814 // need other information about the application, like the ABI and what not ? 6815 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6816 mInstrumentation.put(a.getComponentName(), a); 6817 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6818 if (r == null) { 6819 r = new StringBuilder(256); 6820 } else { 6821 r.append(' '); 6822 } 6823 r.append(a.info.name); 6824 } 6825 } 6826 if (r != null) { 6827 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6828 } 6829 6830 if (pkg.protectedBroadcasts != null) { 6831 N = pkg.protectedBroadcasts.size(); 6832 for (i=0; i<N; i++) { 6833 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6834 } 6835 } 6836 6837 pkgSetting.setTimeStamp(scanFileTime); 6838 6839 // Create idmap files for pairs of (packages, overlay packages). 6840 // Note: "android", ie framework-res.apk, is handled by native layers. 6841 if (pkg.mOverlayTarget != null) { 6842 // This is an overlay package. 6843 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6844 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6845 mOverlays.put(pkg.mOverlayTarget, 6846 new ArrayMap<String, PackageParser.Package>()); 6847 } 6848 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6849 map.put(pkg.packageName, pkg); 6850 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6851 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6852 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6853 "scanPackageLI failed to createIdmap"); 6854 } 6855 } 6856 } else if (mOverlays.containsKey(pkg.packageName) && 6857 !pkg.packageName.equals("android")) { 6858 // This is a regular package, with one or more known overlay packages. 6859 createIdmapsForPackageLI(pkg); 6860 } 6861 } 6862 6863 return pkg; 6864 } 6865 6866 /** 6867 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6868 * i.e, so that all packages can be run inside a single process if required. 6869 * 6870 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6871 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6872 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6873 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6874 * updating a package that belongs to a shared user. 6875 * 6876 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6877 * adds unnecessary complexity. 6878 */ 6879 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6880 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6881 String requiredInstructionSet = null; 6882 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6883 requiredInstructionSet = VMRuntime.getInstructionSet( 6884 scannedPackage.applicationInfo.primaryCpuAbi); 6885 } 6886 6887 PackageSetting requirer = null; 6888 for (PackageSetting ps : packagesForUser) { 6889 // If packagesForUser contains scannedPackage, we skip it. This will happen 6890 // when scannedPackage is an update of an existing package. Without this check, 6891 // we will never be able to change the ABI of any package belonging to a shared 6892 // user, even if it's compatible with other packages. 6893 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6894 if (ps.primaryCpuAbiString == null) { 6895 continue; 6896 } 6897 6898 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6899 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6900 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6901 // this but there's not much we can do. 6902 String errorMessage = "Instruction set mismatch, " 6903 + ((requirer == null) ? "[caller]" : requirer) 6904 + " requires " + requiredInstructionSet + " whereas " + ps 6905 + " requires " + instructionSet; 6906 Slog.w(TAG, errorMessage); 6907 } 6908 6909 if (requiredInstructionSet == null) { 6910 requiredInstructionSet = instructionSet; 6911 requirer = ps; 6912 } 6913 } 6914 } 6915 6916 if (requiredInstructionSet != null) { 6917 String adjustedAbi; 6918 if (requirer != null) { 6919 // requirer != null implies that either scannedPackage was null or that scannedPackage 6920 // did not require an ABI, in which case we have to adjust scannedPackage to match 6921 // the ABI of the set (which is the same as requirer's ABI) 6922 adjustedAbi = requirer.primaryCpuAbiString; 6923 if (scannedPackage != null) { 6924 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6925 } 6926 } else { 6927 // requirer == null implies that we're updating all ABIs in the set to 6928 // match scannedPackage. 6929 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6930 } 6931 6932 for (PackageSetting ps : packagesForUser) { 6933 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6934 if (ps.primaryCpuAbiString != null) { 6935 continue; 6936 } 6937 6938 ps.primaryCpuAbiString = adjustedAbi; 6939 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6940 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6941 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6942 6943 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6944 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6945 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6946 ps.primaryCpuAbiString = null; 6947 ps.pkg.applicationInfo.primaryCpuAbi = null; 6948 return; 6949 } else { 6950 mInstaller.rmdex(ps.codePathString, 6951 getDexCodeInstructionSet(getPreferredInstructionSet())); 6952 } 6953 } 6954 } 6955 } 6956 } 6957 } 6958 6959 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6960 synchronized (mPackages) { 6961 mResolverReplaced = true; 6962 // Set up information for custom user intent resolution activity. 6963 mResolveActivity.applicationInfo = pkg.applicationInfo; 6964 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6965 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6966 mResolveActivity.processName = pkg.applicationInfo.packageName; 6967 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6968 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6969 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6970 mResolveActivity.theme = 0; 6971 mResolveActivity.exported = true; 6972 mResolveActivity.enabled = true; 6973 mResolveInfo.activityInfo = mResolveActivity; 6974 mResolveInfo.priority = 0; 6975 mResolveInfo.preferredOrder = 0; 6976 mResolveInfo.match = 0; 6977 mResolveComponentName = mCustomResolverComponentName; 6978 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6979 mResolveComponentName); 6980 } 6981 } 6982 6983 private static String calculateBundledApkRoot(final String codePathString) { 6984 final File codePath = new File(codePathString); 6985 final File codeRoot; 6986 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6987 codeRoot = Environment.getRootDirectory(); 6988 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6989 codeRoot = Environment.getOemDirectory(); 6990 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6991 codeRoot = Environment.getVendorDirectory(); 6992 } else { 6993 // Unrecognized code path; take its top real segment as the apk root: 6994 // e.g. /something/app/blah.apk => /something 6995 try { 6996 File f = codePath.getCanonicalFile(); 6997 File parent = f.getParentFile(); // non-null because codePath is a file 6998 File tmp; 6999 while ((tmp = parent.getParentFile()) != null) { 7000 f = parent; 7001 parent = tmp; 7002 } 7003 codeRoot = f; 7004 Slog.w(TAG, "Unrecognized code path " 7005 + codePath + " - using " + codeRoot); 7006 } catch (IOException e) { 7007 // Can't canonicalize the code path -- shenanigans? 7008 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7009 return Environment.getRootDirectory().getPath(); 7010 } 7011 } 7012 return codeRoot.getPath(); 7013 } 7014 7015 /** 7016 * Derive and set the location of native libraries for the given package, 7017 * which varies depending on where and how the package was installed. 7018 */ 7019 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7020 final ApplicationInfo info = pkg.applicationInfo; 7021 final String codePath = pkg.codePath; 7022 final File codeFile = new File(codePath); 7023 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7024 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7025 7026 info.nativeLibraryRootDir = null; 7027 info.nativeLibraryRootRequiresIsa = false; 7028 info.nativeLibraryDir = null; 7029 info.secondaryNativeLibraryDir = null; 7030 7031 if (isApkFile(codeFile)) { 7032 // Monolithic install 7033 if (bundledApp) { 7034 // If "/system/lib64/apkname" exists, assume that is the per-package 7035 // native library directory to use; otherwise use "/system/lib/apkname". 7036 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7037 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7038 getPrimaryInstructionSet(info)); 7039 7040 // This is a bundled system app so choose the path based on the ABI. 7041 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7042 // is just the default path. 7043 final String apkName = deriveCodePathName(codePath); 7044 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7045 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7046 apkName).getAbsolutePath(); 7047 7048 if (info.secondaryCpuAbi != null) { 7049 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7050 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7051 secondaryLibDir, apkName).getAbsolutePath(); 7052 } 7053 } else if (asecApp) { 7054 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7055 .getAbsolutePath(); 7056 } else { 7057 final String apkName = deriveCodePathName(codePath); 7058 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7059 .getAbsolutePath(); 7060 } 7061 7062 info.nativeLibraryRootRequiresIsa = false; 7063 info.nativeLibraryDir = info.nativeLibraryRootDir; 7064 } else { 7065 // Cluster install 7066 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7067 info.nativeLibraryRootRequiresIsa = true; 7068 7069 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7070 getPrimaryInstructionSet(info)).getAbsolutePath(); 7071 7072 if (info.secondaryCpuAbi != null) { 7073 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7074 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7075 } 7076 } 7077 } 7078 7079 /** 7080 * Calculate the abis and roots for a bundled app. These can uniquely 7081 * be determined from the contents of the system partition, i.e whether 7082 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7083 * of this information, and instead assume that the system was built 7084 * sensibly. 7085 */ 7086 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7087 PackageSetting pkgSetting) { 7088 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7089 7090 // If "/system/lib64/apkname" exists, assume that is the per-package 7091 // native library directory to use; otherwise use "/system/lib/apkname". 7092 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7093 setBundledAppAbi(pkg, apkRoot, apkName); 7094 // pkgSetting might be null during rescan following uninstall of updates 7095 // to a bundled app, so accommodate that possibility. The settings in 7096 // that case will be established later from the parsed package. 7097 // 7098 // If the settings aren't null, sync them up with what we've just derived. 7099 // note that apkRoot isn't stored in the package settings. 7100 if (pkgSetting != null) { 7101 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7102 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7103 } 7104 } 7105 7106 /** 7107 * Deduces the ABI of a bundled app and sets the relevant fields on the 7108 * parsed pkg object. 7109 * 7110 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7111 * under which system libraries are installed. 7112 * @param apkName the name of the installed package. 7113 */ 7114 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7115 final File codeFile = new File(pkg.codePath); 7116 7117 final boolean has64BitLibs; 7118 final boolean has32BitLibs; 7119 if (isApkFile(codeFile)) { 7120 // Monolithic install 7121 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7122 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7123 } else { 7124 // Cluster install 7125 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7126 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7127 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7128 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7129 has64BitLibs = (new File(rootDir, isa)).exists(); 7130 } else { 7131 has64BitLibs = false; 7132 } 7133 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7134 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7135 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7136 has32BitLibs = (new File(rootDir, isa)).exists(); 7137 } else { 7138 has32BitLibs = false; 7139 } 7140 } 7141 7142 if (has64BitLibs && !has32BitLibs) { 7143 // The package has 64 bit libs, but not 32 bit libs. Its primary 7144 // ABI should be 64 bit. We can safely assume here that the bundled 7145 // native libraries correspond to the most preferred ABI in the list. 7146 7147 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7148 pkg.applicationInfo.secondaryCpuAbi = null; 7149 } else if (has32BitLibs && !has64BitLibs) { 7150 // The package has 32 bit libs but not 64 bit libs. Its primary 7151 // ABI should be 32 bit. 7152 7153 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7154 pkg.applicationInfo.secondaryCpuAbi = null; 7155 } else if (has32BitLibs && has64BitLibs) { 7156 // The application has both 64 and 32 bit bundled libraries. We check 7157 // here that the app declares multiArch support, and warn if it doesn't. 7158 // 7159 // We will be lenient here and record both ABIs. The primary will be the 7160 // ABI that's higher on the list, i.e, a device that's configured to prefer 7161 // 64 bit apps will see a 64 bit primary ABI, 7162 7163 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7164 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7165 } 7166 7167 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7168 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7169 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7170 } else { 7171 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7172 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7173 } 7174 } else { 7175 pkg.applicationInfo.primaryCpuAbi = null; 7176 pkg.applicationInfo.secondaryCpuAbi = null; 7177 } 7178 } 7179 7180 private void killApplication(String pkgName, int appId, String reason) { 7181 // Request the ActivityManager to kill the process(only for existing packages) 7182 // so that we do not end up in a confused state while the user is still using the older 7183 // version of the application while the new one gets installed. 7184 IActivityManager am = ActivityManagerNative.getDefault(); 7185 if (am != null) { 7186 try { 7187 am.killApplicationWithAppId(pkgName, appId, reason); 7188 } catch (RemoteException e) { 7189 } 7190 } 7191 } 7192 7193 void removePackageLI(PackageSetting ps, boolean chatty) { 7194 if (DEBUG_INSTALL) { 7195 if (chatty) 7196 Log.d(TAG, "Removing package " + ps.name); 7197 } 7198 7199 // writer 7200 synchronized (mPackages) { 7201 mPackages.remove(ps.name); 7202 final PackageParser.Package pkg = ps.pkg; 7203 if (pkg != null) { 7204 cleanPackageDataStructuresLILPw(pkg, chatty); 7205 } 7206 } 7207 } 7208 7209 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7210 if (DEBUG_INSTALL) { 7211 if (chatty) 7212 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7213 } 7214 7215 // writer 7216 synchronized (mPackages) { 7217 mPackages.remove(pkg.applicationInfo.packageName); 7218 cleanPackageDataStructuresLILPw(pkg, chatty); 7219 } 7220 } 7221 7222 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7223 int N = pkg.providers.size(); 7224 StringBuilder r = null; 7225 int i; 7226 for (i=0; i<N; i++) { 7227 PackageParser.Provider p = pkg.providers.get(i); 7228 mProviders.removeProvider(p); 7229 if (p.info.authority == null) { 7230 7231 /* There was another ContentProvider with this authority when 7232 * this app was installed so this authority is null, 7233 * Ignore it as we don't have to unregister the provider. 7234 */ 7235 continue; 7236 } 7237 String names[] = p.info.authority.split(";"); 7238 for (int j = 0; j < names.length; j++) { 7239 if (mProvidersByAuthority.get(names[j]) == p) { 7240 mProvidersByAuthority.remove(names[j]); 7241 if (DEBUG_REMOVE) { 7242 if (chatty) 7243 Log.d(TAG, "Unregistered content provider: " + names[j] 7244 + ", className = " + p.info.name + ", isSyncable = " 7245 + p.info.isSyncable); 7246 } 7247 } 7248 } 7249 if (DEBUG_REMOVE && chatty) { 7250 if (r == null) { 7251 r = new StringBuilder(256); 7252 } else { 7253 r.append(' '); 7254 } 7255 r.append(p.info.name); 7256 } 7257 } 7258 if (r != null) { 7259 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7260 } 7261 7262 N = pkg.services.size(); 7263 r = null; 7264 for (i=0; i<N; i++) { 7265 PackageParser.Service s = pkg.services.get(i); 7266 mServices.removeService(s); 7267 if (chatty) { 7268 if (r == null) { 7269 r = new StringBuilder(256); 7270 } else { 7271 r.append(' '); 7272 } 7273 r.append(s.info.name); 7274 } 7275 } 7276 if (r != null) { 7277 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7278 } 7279 7280 N = pkg.receivers.size(); 7281 r = null; 7282 for (i=0; i<N; i++) { 7283 PackageParser.Activity a = pkg.receivers.get(i); 7284 mReceivers.removeActivity(a, "receiver"); 7285 if (DEBUG_REMOVE && chatty) { 7286 if (r == null) { 7287 r = new StringBuilder(256); 7288 } else { 7289 r.append(' '); 7290 } 7291 r.append(a.info.name); 7292 } 7293 } 7294 if (r != null) { 7295 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7296 } 7297 7298 N = pkg.activities.size(); 7299 r = null; 7300 for (i=0; i<N; i++) { 7301 PackageParser.Activity a = pkg.activities.get(i); 7302 mActivities.removeActivity(a, "activity"); 7303 if (DEBUG_REMOVE && chatty) { 7304 if (r == null) { 7305 r = new StringBuilder(256); 7306 } else { 7307 r.append(' '); 7308 } 7309 r.append(a.info.name); 7310 } 7311 } 7312 if (r != null) { 7313 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7314 } 7315 7316 N = pkg.permissions.size(); 7317 r = null; 7318 for (i=0; i<N; i++) { 7319 PackageParser.Permission p = pkg.permissions.get(i); 7320 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7321 if (bp == null) { 7322 bp = mSettings.mPermissionTrees.get(p.info.name); 7323 } 7324 if (bp != null && bp.perm == p) { 7325 bp.perm = null; 7326 if (DEBUG_REMOVE && chatty) { 7327 if (r == null) { 7328 r = new StringBuilder(256); 7329 } else { 7330 r.append(' '); 7331 } 7332 r.append(p.info.name); 7333 } 7334 } 7335 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7336 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7337 if (appOpPerms != null) { 7338 appOpPerms.remove(pkg.packageName); 7339 } 7340 } 7341 } 7342 if (r != null) { 7343 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7344 } 7345 7346 N = pkg.requestedPermissions.size(); 7347 r = null; 7348 for (i=0; i<N; i++) { 7349 String perm = pkg.requestedPermissions.get(i); 7350 BasePermission bp = mSettings.mPermissions.get(perm); 7351 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7352 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7353 if (appOpPerms != null) { 7354 appOpPerms.remove(pkg.packageName); 7355 if (appOpPerms.isEmpty()) { 7356 mAppOpPermissionPackages.remove(perm); 7357 } 7358 } 7359 } 7360 } 7361 if (r != null) { 7362 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7363 } 7364 7365 N = pkg.instrumentation.size(); 7366 r = null; 7367 for (i=0; i<N; i++) { 7368 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7369 mInstrumentation.remove(a.getComponentName()); 7370 if (DEBUG_REMOVE && chatty) { 7371 if (r == null) { 7372 r = new StringBuilder(256); 7373 } else { 7374 r.append(' '); 7375 } 7376 r.append(a.info.name); 7377 } 7378 } 7379 if (r != null) { 7380 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7381 } 7382 7383 r = null; 7384 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7385 // Only system apps can hold shared libraries. 7386 if (pkg.libraryNames != null) { 7387 for (i=0; i<pkg.libraryNames.size(); i++) { 7388 String name = pkg.libraryNames.get(i); 7389 SharedLibraryEntry cur = mSharedLibraries.get(name); 7390 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7391 mSharedLibraries.remove(name); 7392 if (DEBUG_REMOVE && chatty) { 7393 if (r == null) { 7394 r = new StringBuilder(256); 7395 } else { 7396 r.append(' '); 7397 } 7398 r.append(name); 7399 } 7400 } 7401 } 7402 } 7403 } 7404 if (r != null) { 7405 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7406 } 7407 } 7408 7409 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7410 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7411 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7412 return true; 7413 } 7414 } 7415 return false; 7416 } 7417 7418 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7419 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7420 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7421 7422 private void updatePermissionsLPw(String changingPkg, 7423 PackageParser.Package pkgInfo, int flags) { 7424 // Make sure there are no dangling permission trees. 7425 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7426 while (it.hasNext()) { 7427 final BasePermission bp = it.next(); 7428 if (bp.packageSetting == null) { 7429 // We may not yet have parsed the package, so just see if 7430 // we still know about its settings. 7431 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7432 } 7433 if (bp.packageSetting == null) { 7434 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7435 + " from package " + bp.sourcePackage); 7436 it.remove(); 7437 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7438 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7439 Slog.i(TAG, "Removing old permission tree: " + bp.name 7440 + " from package " + bp.sourcePackage); 7441 flags |= UPDATE_PERMISSIONS_ALL; 7442 it.remove(); 7443 } 7444 } 7445 } 7446 7447 // Make sure all dynamic permissions have been assigned to a package, 7448 // and make sure there are no dangling permissions. 7449 it = mSettings.mPermissions.values().iterator(); 7450 while (it.hasNext()) { 7451 final BasePermission bp = it.next(); 7452 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7453 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7454 + bp.name + " pkg=" + bp.sourcePackage 7455 + " info=" + bp.pendingInfo); 7456 if (bp.packageSetting == null && bp.pendingInfo != null) { 7457 final BasePermission tree = findPermissionTreeLP(bp.name); 7458 if (tree != null && tree.perm != null) { 7459 bp.packageSetting = tree.packageSetting; 7460 bp.perm = new PackageParser.Permission(tree.perm.owner, 7461 new PermissionInfo(bp.pendingInfo)); 7462 bp.perm.info.packageName = tree.perm.info.packageName; 7463 bp.perm.info.name = bp.name; 7464 bp.uid = tree.uid; 7465 } 7466 } 7467 } 7468 if (bp.packageSetting == null) { 7469 // We may not yet have parsed the package, so just see if 7470 // we still know about its settings. 7471 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7472 } 7473 if (bp.packageSetting == null) { 7474 Slog.w(TAG, "Removing dangling permission: " + bp.name 7475 + " from package " + bp.sourcePackage); 7476 it.remove(); 7477 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7478 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7479 Slog.i(TAG, "Removing old permission: " + bp.name 7480 + " from package " + bp.sourcePackage); 7481 flags |= UPDATE_PERMISSIONS_ALL; 7482 it.remove(); 7483 } 7484 } 7485 } 7486 7487 // Now update the permissions for all packages, in particular 7488 // replace the granted permissions of the system packages. 7489 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7490 for (PackageParser.Package pkg : mPackages.values()) { 7491 if (pkg != pkgInfo) { 7492 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7493 changingPkg); 7494 } 7495 } 7496 } 7497 7498 if (pkgInfo != null) { 7499 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7500 } 7501 } 7502 7503 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7504 String packageOfInterest) { 7505 // IMPORTANT: There are two types of permissions: install and runtime. 7506 // Install time permissions are granted when the app is installed to 7507 // all device users and users added in the future. Runtime permissions 7508 // are granted at runtime explicitly to specific users. Normal and signature 7509 // protected permissions are install time permissions. Dangerous permissions 7510 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7511 // otherwise they are runtime permissions. This function does not manage 7512 // runtime permissions except for the case an app targeting Lollipop MR1 7513 // being upgraded to target a newer SDK, in which case dangerous permissions 7514 // are transformed from install time to runtime ones. 7515 7516 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7517 if (ps == null) { 7518 return; 7519 } 7520 7521 PermissionsState permissionsState = ps.getPermissionsState(); 7522 PermissionsState origPermissions = permissionsState; 7523 7524 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7525 7526 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7527 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7528 7529 boolean changedInstallPermission = false; 7530 7531 if (replace) { 7532 ps.installPermissionsFixed = false; 7533 if (!ps.isSharedUser()) { 7534 origPermissions = new PermissionsState(permissionsState); 7535 permissionsState.reset(); 7536 } 7537 } 7538 7539 permissionsState.setGlobalGids(mGlobalGids); 7540 7541 final int N = pkg.requestedPermissions.size(); 7542 for (int i=0; i<N; i++) { 7543 final String name = pkg.requestedPermissions.get(i); 7544 final BasePermission bp = mSettings.mPermissions.get(name); 7545 7546 if (DEBUG_INSTALL) { 7547 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7548 } 7549 7550 if (bp == null || bp.packageSetting == null) { 7551 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7552 Slog.w(TAG, "Unknown permission " + name 7553 + " in package " + pkg.packageName); 7554 } 7555 continue; 7556 } 7557 7558 final String perm = bp.name; 7559 boolean allowedSig = false; 7560 int grant = GRANT_DENIED; 7561 7562 // Keep track of app op permissions. 7563 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7564 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7565 if (pkgs == null) { 7566 pkgs = new ArraySet<>(); 7567 mAppOpPermissionPackages.put(bp.name, pkgs); 7568 } 7569 pkgs.add(pkg.packageName); 7570 } 7571 7572 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7573 switch (level) { 7574 case PermissionInfo.PROTECTION_NORMAL: { 7575 // For all apps normal permissions are install time ones. 7576 grant = GRANT_INSTALL; 7577 } break; 7578 7579 case PermissionInfo.PROTECTION_DANGEROUS: { 7580 if (!RUNTIME_PERMISSIONS_ENABLED 7581 || pkg.applicationInfo.targetSdkVersion 7582 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7583 // For legacy apps dangerous permissions are install time ones. 7584 grant = GRANT_INSTALL; 7585 } else if (ps.isSystem()) { 7586 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7587 if (origPermissions.hasInstallPermission(bp.name)) { 7588 // If a system app had an install permission, then the app was 7589 // upgraded and we grant the permissions as runtime to all users. 7590 grant = GRANT_UPGRADE; 7591 upgradeUserIds = currentUserIds; 7592 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7593 // If users changed since the last permissions update for a 7594 // system app, we grant the permission as runtime to the new users. 7595 grant = GRANT_UPGRADE; 7596 upgradeUserIds = currentUserIds; 7597 for (int userId : updatedUserIds) { 7598 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7599 } 7600 } else { 7601 // Otherwise, we grant the permission as runtime if the app 7602 // already had it, i.e. we preserve runtime permissions. 7603 grant = GRANT_RUNTIME; 7604 } 7605 } else if (origPermissions.hasInstallPermission(bp.name)) { 7606 // For legacy apps that became modern, install becomes runtime. 7607 grant = GRANT_UPGRADE; 7608 upgradeUserIds = currentUserIds; 7609 } else if (replace) { 7610 // For upgraded modern apps keep runtime permissions unchanged. 7611 grant = GRANT_RUNTIME; 7612 } 7613 } break; 7614 7615 case PermissionInfo.PROTECTION_SIGNATURE: { 7616 // For all apps signature permissions are install time ones. 7617 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7618 if (allowedSig) { 7619 grant = GRANT_INSTALL; 7620 } 7621 } break; 7622 } 7623 7624 if (DEBUG_INSTALL) { 7625 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7626 } 7627 7628 if (grant != GRANT_DENIED) { 7629 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7630 // If this is an existing, non-system package, then 7631 // we can't add any new permissions to it. 7632 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7633 // Except... if this is a permission that was added 7634 // to the platform (note: need to only do this when 7635 // updating the platform). 7636 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7637 grant = GRANT_DENIED; 7638 } 7639 } 7640 } 7641 7642 switch (grant) { 7643 case GRANT_INSTALL: { 7644 // Grant an install permission. 7645 if (permissionsState.grantInstallPermission(bp) != 7646 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7647 changedInstallPermission = true; 7648 } 7649 } break; 7650 7651 case GRANT_RUNTIME: { 7652 // Grant previously granted runtime permissions. 7653 for (int userId : UserManagerService.getInstance().getUserIds()) { 7654 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7655 if (permissionsState.grantRuntimePermission(bp, userId) == 7656 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7657 // If we cannot put the permission as it was, we have to write. 7658 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7659 changedRuntimePermissionUserIds, userId); 7660 } 7661 } 7662 } 7663 } break; 7664 7665 case GRANT_UPGRADE: { 7666 // Grant runtime permissions for a previously held install permission. 7667 permissionsState.revokeInstallPermission(bp); 7668 for (int userId : upgradeUserIds) { 7669 if (permissionsState.grantRuntimePermission(bp, userId) != 7670 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7671 // If we granted the permission, we have to write. 7672 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7673 changedRuntimePermissionUserIds, userId); 7674 } 7675 } 7676 } break; 7677 7678 default: { 7679 if (packageOfInterest == null 7680 || packageOfInterest.equals(pkg.packageName)) { 7681 Slog.w(TAG, "Not granting permission " + perm 7682 + " to package " + pkg.packageName 7683 + " because it was previously installed without"); 7684 } 7685 } break; 7686 } 7687 } else { 7688 if (permissionsState.revokeInstallPermission(bp) != 7689 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7690 changedInstallPermission = true; 7691 Slog.i(TAG, "Un-granting permission " + perm 7692 + " from package " + pkg.packageName 7693 + " (protectionLevel=" + bp.protectionLevel 7694 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7695 + ")"); 7696 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7697 // Don't print warning for app op permissions, since it is fine for them 7698 // not to be granted, there is a UI for the user to decide. 7699 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7700 Slog.w(TAG, "Not granting permission " + perm 7701 + " to package " + pkg.packageName 7702 + " (protectionLevel=" + bp.protectionLevel 7703 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7704 + ")"); 7705 } 7706 } 7707 } 7708 } 7709 7710 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7711 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7712 // This is the first that we have heard about this package, so the 7713 // permissions we have now selected are fixed until explicitly 7714 // changed. 7715 ps.installPermissionsFixed = true; 7716 } 7717 7718 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7719 7720 // Persist the runtime permissions state for users with changes. 7721 if (RUNTIME_PERMISSIONS_ENABLED) { 7722 for (int userId : changedRuntimePermissionUserIds) { 7723 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7724 } 7725 } 7726 } 7727 7728 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7729 boolean allowed = false; 7730 final int NP = PackageParser.NEW_PERMISSIONS.length; 7731 for (int ip=0; ip<NP; ip++) { 7732 final PackageParser.NewPermissionInfo npi 7733 = PackageParser.NEW_PERMISSIONS[ip]; 7734 if (npi.name.equals(perm) 7735 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7736 allowed = true; 7737 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7738 + pkg.packageName); 7739 break; 7740 } 7741 } 7742 return allowed; 7743 } 7744 7745 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7746 BasePermission bp, PermissionsState origPermissions) { 7747 boolean allowed; 7748 allowed = (compareSignatures( 7749 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7750 == PackageManager.SIGNATURE_MATCH) 7751 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7752 == PackageManager.SIGNATURE_MATCH); 7753 if (!allowed && (bp.protectionLevel 7754 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7755 if (isSystemApp(pkg)) { 7756 // For updated system applications, a system permission 7757 // is granted only if it had been defined by the original application. 7758 if (pkg.isUpdatedSystemApp()) { 7759 final PackageSetting sysPs = mSettings 7760 .getDisabledSystemPkgLPr(pkg.packageName); 7761 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7762 // If the original was granted this permission, we take 7763 // that grant decision as read and propagate it to the 7764 // update. 7765 if (sysPs.isPrivileged()) { 7766 allowed = true; 7767 } 7768 } else { 7769 // The system apk may have been updated with an older 7770 // version of the one on the data partition, but which 7771 // granted a new system permission that it didn't have 7772 // before. In this case we do want to allow the app to 7773 // now get the new permission if the ancestral apk is 7774 // privileged to get it. 7775 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7776 for (int j=0; 7777 j<sysPs.pkg.requestedPermissions.size(); j++) { 7778 if (perm.equals( 7779 sysPs.pkg.requestedPermissions.get(j))) { 7780 allowed = true; 7781 break; 7782 } 7783 } 7784 } 7785 } 7786 } else { 7787 allowed = isPrivilegedApp(pkg); 7788 } 7789 } 7790 } 7791 if (!allowed && (bp.protectionLevel 7792 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7793 // For development permissions, a development permission 7794 // is granted only if it was already granted. 7795 allowed = origPermissions.hasInstallPermission(perm); 7796 } 7797 return allowed; 7798 } 7799 7800 final class ActivityIntentResolver 7801 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7802 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7803 boolean defaultOnly, int userId) { 7804 if (!sUserManager.exists(userId)) return null; 7805 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7806 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7807 } 7808 7809 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7810 int userId) { 7811 if (!sUserManager.exists(userId)) return null; 7812 mFlags = flags; 7813 return super.queryIntent(intent, resolvedType, 7814 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7815 } 7816 7817 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7818 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7819 if (!sUserManager.exists(userId)) return null; 7820 if (packageActivities == null) { 7821 return null; 7822 } 7823 mFlags = flags; 7824 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7825 final int N = packageActivities.size(); 7826 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7827 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7828 7829 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7830 for (int i = 0; i < N; ++i) { 7831 intentFilters = packageActivities.get(i).intents; 7832 if (intentFilters != null && intentFilters.size() > 0) { 7833 PackageParser.ActivityIntentInfo[] array = 7834 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7835 intentFilters.toArray(array); 7836 listCut.add(array); 7837 } 7838 } 7839 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7840 } 7841 7842 public final void addActivity(PackageParser.Activity a, String type) { 7843 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7844 mActivities.put(a.getComponentName(), a); 7845 if (DEBUG_SHOW_INFO) 7846 Log.v( 7847 TAG, " " + type + " " + 7848 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7849 if (DEBUG_SHOW_INFO) 7850 Log.v(TAG, " Class=" + a.info.name); 7851 final int NI = a.intents.size(); 7852 for (int j=0; j<NI; j++) { 7853 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7854 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7855 intent.setPriority(0); 7856 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7857 + a.className + " with priority > 0, forcing to 0"); 7858 } 7859 if (DEBUG_SHOW_INFO) { 7860 Log.v(TAG, " IntentFilter:"); 7861 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7862 } 7863 if (!intent.debugCheck()) { 7864 Log.w(TAG, "==> For Activity " + a.info.name); 7865 } 7866 addFilter(intent); 7867 } 7868 } 7869 7870 public final void removeActivity(PackageParser.Activity a, String type) { 7871 mActivities.remove(a.getComponentName()); 7872 if (DEBUG_SHOW_INFO) { 7873 Log.v(TAG, " " + type + " " 7874 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7875 : a.info.name) + ":"); 7876 Log.v(TAG, " Class=" + a.info.name); 7877 } 7878 final int NI = a.intents.size(); 7879 for (int j=0; j<NI; j++) { 7880 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7881 if (DEBUG_SHOW_INFO) { 7882 Log.v(TAG, " IntentFilter:"); 7883 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7884 } 7885 removeFilter(intent); 7886 } 7887 } 7888 7889 @Override 7890 protected boolean allowFilterResult( 7891 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7892 ActivityInfo filterAi = filter.activity.info; 7893 for (int i=dest.size()-1; i>=0; i--) { 7894 ActivityInfo destAi = dest.get(i).activityInfo; 7895 if (destAi.name == filterAi.name 7896 && destAi.packageName == filterAi.packageName) { 7897 return false; 7898 } 7899 } 7900 return true; 7901 } 7902 7903 @Override 7904 protected ActivityIntentInfo[] newArray(int size) { 7905 return new ActivityIntentInfo[size]; 7906 } 7907 7908 @Override 7909 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7910 if (!sUserManager.exists(userId)) return true; 7911 PackageParser.Package p = filter.activity.owner; 7912 if (p != null) { 7913 PackageSetting ps = (PackageSetting)p.mExtras; 7914 if (ps != null) { 7915 // System apps are never considered stopped for purposes of 7916 // filtering, because there may be no way for the user to 7917 // actually re-launch them. 7918 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7919 && ps.getStopped(userId); 7920 } 7921 } 7922 return false; 7923 } 7924 7925 @Override 7926 protected boolean isPackageForFilter(String packageName, 7927 PackageParser.ActivityIntentInfo info) { 7928 return packageName.equals(info.activity.owner.packageName); 7929 } 7930 7931 @Override 7932 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7933 int match, int userId) { 7934 if (!sUserManager.exists(userId)) return null; 7935 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7936 return null; 7937 } 7938 final PackageParser.Activity activity = info.activity; 7939 if (mSafeMode && (activity.info.applicationInfo.flags 7940 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7941 return null; 7942 } 7943 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7944 if (ps == null) { 7945 return null; 7946 } 7947 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7948 ps.readUserState(userId), userId); 7949 if (ai == null) { 7950 return null; 7951 } 7952 final ResolveInfo res = new ResolveInfo(); 7953 res.activityInfo = ai; 7954 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7955 res.filter = info; 7956 } 7957 if (info != null) { 7958 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7959 } 7960 res.priority = info.getPriority(); 7961 res.preferredOrder = activity.owner.mPreferredOrder; 7962 //System.out.println("Result: " + res.activityInfo.className + 7963 // " = " + res.priority); 7964 res.match = match; 7965 res.isDefault = info.hasDefault; 7966 res.labelRes = info.labelRes; 7967 res.nonLocalizedLabel = info.nonLocalizedLabel; 7968 if (userNeedsBadging(userId)) { 7969 res.noResourceId = true; 7970 } else { 7971 res.icon = info.icon; 7972 } 7973 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7974 return res; 7975 } 7976 7977 @Override 7978 protected void sortResults(List<ResolveInfo> results) { 7979 Collections.sort(results, mResolvePrioritySorter); 7980 } 7981 7982 @Override 7983 protected void dumpFilter(PrintWriter out, String prefix, 7984 PackageParser.ActivityIntentInfo filter) { 7985 out.print(prefix); out.print( 7986 Integer.toHexString(System.identityHashCode(filter.activity))); 7987 out.print(' '); 7988 filter.activity.printComponentShortName(out); 7989 out.print(" filter "); 7990 out.println(Integer.toHexString(System.identityHashCode(filter))); 7991 } 7992 7993 @Override 7994 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7995 return filter.activity; 7996 } 7997 7998 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7999 PackageParser.Activity activity = (PackageParser.Activity)label; 8000 out.print(prefix); out.print( 8001 Integer.toHexString(System.identityHashCode(activity))); 8002 out.print(' '); 8003 activity.printComponentShortName(out); 8004 if (count > 1) { 8005 out.print(" ("); out.print(count); out.print(" filters)"); 8006 } 8007 out.println(); 8008 } 8009 8010// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8011// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8012// final List<ResolveInfo> retList = Lists.newArrayList(); 8013// while (i.hasNext()) { 8014// final ResolveInfo resolveInfo = i.next(); 8015// if (isEnabledLP(resolveInfo.activityInfo)) { 8016// retList.add(resolveInfo); 8017// } 8018// } 8019// return retList; 8020// } 8021 8022 // Keys are String (activity class name), values are Activity. 8023 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8024 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8025 private int mFlags; 8026 } 8027 8028 private final class ServiceIntentResolver 8029 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8030 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8031 boolean defaultOnly, int userId) { 8032 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8033 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8034 } 8035 8036 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8037 int userId) { 8038 if (!sUserManager.exists(userId)) return null; 8039 mFlags = flags; 8040 return super.queryIntent(intent, resolvedType, 8041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8042 } 8043 8044 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8045 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8046 if (!sUserManager.exists(userId)) return null; 8047 if (packageServices == null) { 8048 return null; 8049 } 8050 mFlags = flags; 8051 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8052 final int N = packageServices.size(); 8053 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8054 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8055 8056 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8057 for (int i = 0; i < N; ++i) { 8058 intentFilters = packageServices.get(i).intents; 8059 if (intentFilters != null && intentFilters.size() > 0) { 8060 PackageParser.ServiceIntentInfo[] array = 8061 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8062 intentFilters.toArray(array); 8063 listCut.add(array); 8064 } 8065 } 8066 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8067 } 8068 8069 public final void addService(PackageParser.Service s) { 8070 mServices.put(s.getComponentName(), s); 8071 if (DEBUG_SHOW_INFO) { 8072 Log.v(TAG, " " 8073 + (s.info.nonLocalizedLabel != null 8074 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8075 Log.v(TAG, " Class=" + s.info.name); 8076 } 8077 final int NI = s.intents.size(); 8078 int j; 8079 for (j=0; j<NI; j++) { 8080 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8081 if (DEBUG_SHOW_INFO) { 8082 Log.v(TAG, " IntentFilter:"); 8083 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8084 } 8085 if (!intent.debugCheck()) { 8086 Log.w(TAG, "==> For Service " + s.info.name); 8087 } 8088 addFilter(intent); 8089 } 8090 } 8091 8092 public final void removeService(PackageParser.Service s) { 8093 mServices.remove(s.getComponentName()); 8094 if (DEBUG_SHOW_INFO) { 8095 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8096 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8097 Log.v(TAG, " Class=" + s.info.name); 8098 } 8099 final int NI = s.intents.size(); 8100 int j; 8101 for (j=0; j<NI; j++) { 8102 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8103 if (DEBUG_SHOW_INFO) { 8104 Log.v(TAG, " IntentFilter:"); 8105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8106 } 8107 removeFilter(intent); 8108 } 8109 } 8110 8111 @Override 8112 protected boolean allowFilterResult( 8113 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8114 ServiceInfo filterSi = filter.service.info; 8115 for (int i=dest.size()-1; i>=0; i--) { 8116 ServiceInfo destAi = dest.get(i).serviceInfo; 8117 if (destAi.name == filterSi.name 8118 && destAi.packageName == filterSi.packageName) { 8119 return false; 8120 } 8121 } 8122 return true; 8123 } 8124 8125 @Override 8126 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8127 return new PackageParser.ServiceIntentInfo[size]; 8128 } 8129 8130 @Override 8131 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8132 if (!sUserManager.exists(userId)) return true; 8133 PackageParser.Package p = filter.service.owner; 8134 if (p != null) { 8135 PackageSetting ps = (PackageSetting)p.mExtras; 8136 if (ps != null) { 8137 // System apps are never considered stopped for purposes of 8138 // filtering, because there may be no way for the user to 8139 // actually re-launch them. 8140 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8141 && ps.getStopped(userId); 8142 } 8143 } 8144 return false; 8145 } 8146 8147 @Override 8148 protected boolean isPackageForFilter(String packageName, 8149 PackageParser.ServiceIntentInfo info) { 8150 return packageName.equals(info.service.owner.packageName); 8151 } 8152 8153 @Override 8154 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8155 int match, int userId) { 8156 if (!sUserManager.exists(userId)) return null; 8157 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8158 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8159 return null; 8160 } 8161 final PackageParser.Service service = info.service; 8162 if (mSafeMode && (service.info.applicationInfo.flags 8163 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8164 return null; 8165 } 8166 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8167 if (ps == null) { 8168 return null; 8169 } 8170 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8171 ps.readUserState(userId), userId); 8172 if (si == null) { 8173 return null; 8174 } 8175 final ResolveInfo res = new ResolveInfo(); 8176 res.serviceInfo = si; 8177 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8178 res.filter = filter; 8179 } 8180 res.priority = info.getPriority(); 8181 res.preferredOrder = service.owner.mPreferredOrder; 8182 res.match = match; 8183 res.isDefault = info.hasDefault; 8184 res.labelRes = info.labelRes; 8185 res.nonLocalizedLabel = info.nonLocalizedLabel; 8186 res.icon = info.icon; 8187 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8188 return res; 8189 } 8190 8191 @Override 8192 protected void sortResults(List<ResolveInfo> results) { 8193 Collections.sort(results, mResolvePrioritySorter); 8194 } 8195 8196 @Override 8197 protected void dumpFilter(PrintWriter out, String prefix, 8198 PackageParser.ServiceIntentInfo filter) { 8199 out.print(prefix); out.print( 8200 Integer.toHexString(System.identityHashCode(filter.service))); 8201 out.print(' '); 8202 filter.service.printComponentShortName(out); 8203 out.print(" filter "); 8204 out.println(Integer.toHexString(System.identityHashCode(filter))); 8205 } 8206 8207 @Override 8208 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8209 return filter.service; 8210 } 8211 8212 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8213 PackageParser.Service service = (PackageParser.Service)label; 8214 out.print(prefix); out.print( 8215 Integer.toHexString(System.identityHashCode(service))); 8216 out.print(' '); 8217 service.printComponentShortName(out); 8218 if (count > 1) { 8219 out.print(" ("); out.print(count); out.print(" filters)"); 8220 } 8221 out.println(); 8222 } 8223 8224// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8225// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8226// final List<ResolveInfo> retList = Lists.newArrayList(); 8227// while (i.hasNext()) { 8228// final ResolveInfo resolveInfo = (ResolveInfo) i; 8229// if (isEnabledLP(resolveInfo.serviceInfo)) { 8230// retList.add(resolveInfo); 8231// } 8232// } 8233// return retList; 8234// } 8235 8236 // Keys are String (activity class name), values are Activity. 8237 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8238 = new ArrayMap<ComponentName, PackageParser.Service>(); 8239 private int mFlags; 8240 }; 8241 8242 private final class ProviderIntentResolver 8243 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8244 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8245 boolean defaultOnly, int userId) { 8246 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8247 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8248 } 8249 8250 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8251 int userId) { 8252 if (!sUserManager.exists(userId)) 8253 return null; 8254 mFlags = flags; 8255 return super.queryIntent(intent, resolvedType, 8256 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8257 } 8258 8259 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8260 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8261 if (!sUserManager.exists(userId)) 8262 return null; 8263 if (packageProviders == null) { 8264 return null; 8265 } 8266 mFlags = flags; 8267 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8268 final int N = packageProviders.size(); 8269 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8270 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8271 8272 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8273 for (int i = 0; i < N; ++i) { 8274 intentFilters = packageProviders.get(i).intents; 8275 if (intentFilters != null && intentFilters.size() > 0) { 8276 PackageParser.ProviderIntentInfo[] array = 8277 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8278 intentFilters.toArray(array); 8279 listCut.add(array); 8280 } 8281 } 8282 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8283 } 8284 8285 public final void addProvider(PackageParser.Provider p) { 8286 if (mProviders.containsKey(p.getComponentName())) { 8287 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8288 return; 8289 } 8290 8291 mProviders.put(p.getComponentName(), p); 8292 if (DEBUG_SHOW_INFO) { 8293 Log.v(TAG, " " 8294 + (p.info.nonLocalizedLabel != null 8295 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8296 Log.v(TAG, " Class=" + p.info.name); 8297 } 8298 final int NI = p.intents.size(); 8299 int j; 8300 for (j = 0; j < NI; j++) { 8301 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8302 if (DEBUG_SHOW_INFO) { 8303 Log.v(TAG, " IntentFilter:"); 8304 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8305 } 8306 if (!intent.debugCheck()) { 8307 Log.w(TAG, "==> For Provider " + p.info.name); 8308 } 8309 addFilter(intent); 8310 } 8311 } 8312 8313 public final void removeProvider(PackageParser.Provider p) { 8314 mProviders.remove(p.getComponentName()); 8315 if (DEBUG_SHOW_INFO) { 8316 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8317 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8318 Log.v(TAG, " Class=" + p.info.name); 8319 } 8320 final int NI = p.intents.size(); 8321 int j; 8322 for (j = 0; j < NI; j++) { 8323 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8324 if (DEBUG_SHOW_INFO) { 8325 Log.v(TAG, " IntentFilter:"); 8326 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8327 } 8328 removeFilter(intent); 8329 } 8330 } 8331 8332 @Override 8333 protected boolean allowFilterResult( 8334 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8335 ProviderInfo filterPi = filter.provider.info; 8336 for (int i = dest.size() - 1; i >= 0; i--) { 8337 ProviderInfo destPi = dest.get(i).providerInfo; 8338 if (destPi.name == filterPi.name 8339 && destPi.packageName == filterPi.packageName) { 8340 return false; 8341 } 8342 } 8343 return true; 8344 } 8345 8346 @Override 8347 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8348 return new PackageParser.ProviderIntentInfo[size]; 8349 } 8350 8351 @Override 8352 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8353 if (!sUserManager.exists(userId)) 8354 return true; 8355 PackageParser.Package p = filter.provider.owner; 8356 if (p != null) { 8357 PackageSetting ps = (PackageSetting) p.mExtras; 8358 if (ps != null) { 8359 // System apps are never considered stopped for purposes of 8360 // filtering, because there may be no way for the user to 8361 // actually re-launch them. 8362 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8363 && ps.getStopped(userId); 8364 } 8365 } 8366 return false; 8367 } 8368 8369 @Override 8370 protected boolean isPackageForFilter(String packageName, 8371 PackageParser.ProviderIntentInfo info) { 8372 return packageName.equals(info.provider.owner.packageName); 8373 } 8374 8375 @Override 8376 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8377 int match, int userId) { 8378 if (!sUserManager.exists(userId)) 8379 return null; 8380 final PackageParser.ProviderIntentInfo info = filter; 8381 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8382 return null; 8383 } 8384 final PackageParser.Provider provider = info.provider; 8385 if (mSafeMode && (provider.info.applicationInfo.flags 8386 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8387 return null; 8388 } 8389 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8390 if (ps == null) { 8391 return null; 8392 } 8393 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8394 ps.readUserState(userId), userId); 8395 if (pi == null) { 8396 return null; 8397 } 8398 final ResolveInfo res = new ResolveInfo(); 8399 res.providerInfo = pi; 8400 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8401 res.filter = filter; 8402 } 8403 res.priority = info.getPriority(); 8404 res.preferredOrder = provider.owner.mPreferredOrder; 8405 res.match = match; 8406 res.isDefault = info.hasDefault; 8407 res.labelRes = info.labelRes; 8408 res.nonLocalizedLabel = info.nonLocalizedLabel; 8409 res.icon = info.icon; 8410 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8411 return res; 8412 } 8413 8414 @Override 8415 protected void sortResults(List<ResolveInfo> results) { 8416 Collections.sort(results, mResolvePrioritySorter); 8417 } 8418 8419 @Override 8420 protected void dumpFilter(PrintWriter out, String prefix, 8421 PackageParser.ProviderIntentInfo filter) { 8422 out.print(prefix); 8423 out.print( 8424 Integer.toHexString(System.identityHashCode(filter.provider))); 8425 out.print(' '); 8426 filter.provider.printComponentShortName(out); 8427 out.print(" filter "); 8428 out.println(Integer.toHexString(System.identityHashCode(filter))); 8429 } 8430 8431 @Override 8432 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8433 return filter.provider; 8434 } 8435 8436 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8437 PackageParser.Provider provider = (PackageParser.Provider)label; 8438 out.print(prefix); out.print( 8439 Integer.toHexString(System.identityHashCode(provider))); 8440 out.print(' '); 8441 provider.printComponentShortName(out); 8442 if (count > 1) { 8443 out.print(" ("); out.print(count); out.print(" filters)"); 8444 } 8445 out.println(); 8446 } 8447 8448 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8449 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8450 private int mFlags; 8451 }; 8452 8453 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8454 new Comparator<ResolveInfo>() { 8455 public int compare(ResolveInfo r1, ResolveInfo r2) { 8456 int v1 = r1.priority; 8457 int v2 = r2.priority; 8458 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8459 if (v1 != v2) { 8460 return (v1 > v2) ? -1 : 1; 8461 } 8462 v1 = r1.preferredOrder; 8463 v2 = r2.preferredOrder; 8464 if (v1 != v2) { 8465 return (v1 > v2) ? -1 : 1; 8466 } 8467 if (r1.isDefault != r2.isDefault) { 8468 return r1.isDefault ? -1 : 1; 8469 } 8470 v1 = r1.match; 8471 v2 = r2.match; 8472 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8473 if (v1 != v2) { 8474 return (v1 > v2) ? -1 : 1; 8475 } 8476 if (r1.system != r2.system) { 8477 return r1.system ? -1 : 1; 8478 } 8479 return 0; 8480 } 8481 }; 8482 8483 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8484 new Comparator<ProviderInfo>() { 8485 public int compare(ProviderInfo p1, ProviderInfo p2) { 8486 final int v1 = p1.initOrder; 8487 final int v2 = p2.initOrder; 8488 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8489 } 8490 }; 8491 8492 static final void sendPackageBroadcast(String action, String pkg, 8493 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 8494 int[] userIds) { 8495 IActivityManager am = ActivityManagerNative.getDefault(); 8496 if (am != null) { 8497 try { 8498 if (userIds == null) { 8499 userIds = am.getRunningUserIds(); 8500 } 8501 for (int id : userIds) { 8502 final Intent intent = new Intent(action, 8503 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8504 if (extras != null) { 8505 intent.putExtras(extras); 8506 } 8507 if (targetPkg != null) { 8508 intent.setPackage(targetPkg); 8509 } 8510 // Modify the UID when posting to other users 8511 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8512 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8513 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8514 intent.putExtra(Intent.EXTRA_UID, uid); 8515 } 8516 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8517 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8518 if (DEBUG_BROADCASTS) { 8519 RuntimeException here = new RuntimeException("here"); 8520 here.fillInStackTrace(); 8521 Slog.d(TAG, "Sending to user " + id + ": " 8522 + intent.toShortString(false, true, false, false) 8523 + " " + intent.getExtras(), here); 8524 } 8525 am.broadcastIntent(null, intent, null, finishedReceiver, 8526 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8527 finishedReceiver != null, false, id); 8528 } 8529 } catch (RemoteException ex) { 8530 } 8531 } 8532 } 8533 8534 /** 8535 * Check if the external storage media is available. This is true if there 8536 * is a mounted external storage medium or if the external storage is 8537 * emulated. 8538 */ 8539 private boolean isExternalMediaAvailable() { 8540 return mMediaMounted || Environment.isExternalStorageEmulated(); 8541 } 8542 8543 @Override 8544 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8545 // writer 8546 synchronized (mPackages) { 8547 if (!isExternalMediaAvailable()) { 8548 // If the external storage is no longer mounted at this point, 8549 // the caller may not have been able to delete all of this 8550 // packages files and can not delete any more. Bail. 8551 return null; 8552 } 8553 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8554 if (lastPackage != null) { 8555 pkgs.remove(lastPackage); 8556 } 8557 if (pkgs.size() > 0) { 8558 return pkgs.get(0); 8559 } 8560 } 8561 return null; 8562 } 8563 8564 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8565 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8566 userId, andCode ? 1 : 0, packageName); 8567 if (mSystemReady) { 8568 msg.sendToTarget(); 8569 } else { 8570 if (mPostSystemReadyMessages == null) { 8571 mPostSystemReadyMessages = new ArrayList<>(); 8572 } 8573 mPostSystemReadyMessages.add(msg); 8574 } 8575 } 8576 8577 void startCleaningPackages() { 8578 // reader 8579 synchronized (mPackages) { 8580 if (!isExternalMediaAvailable()) { 8581 return; 8582 } 8583 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8584 return; 8585 } 8586 } 8587 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8588 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8589 IActivityManager am = ActivityManagerNative.getDefault(); 8590 if (am != null) { 8591 try { 8592 am.startService(null, intent, null, UserHandle.USER_OWNER); 8593 } catch (RemoteException e) { 8594 } 8595 } 8596 } 8597 8598 @Override 8599 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8600 int installFlags, String installerPackageName, VerificationParams verificationParams, 8601 String packageAbiOverride) { 8602 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8603 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8604 } 8605 8606 @Override 8607 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8608 int installFlags, String installerPackageName, VerificationParams verificationParams, 8609 String packageAbiOverride, int userId) { 8610 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8611 8612 final int callingUid = Binder.getCallingUid(); 8613 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8614 8615 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8616 try { 8617 if (observer != null) { 8618 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8619 } 8620 } catch (RemoteException re) { 8621 } 8622 return; 8623 } 8624 8625 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8626 installFlags |= PackageManager.INSTALL_FROM_ADB; 8627 8628 } else { 8629 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8630 // about installerPackageName. 8631 8632 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8633 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8634 } 8635 8636 UserHandle user; 8637 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8638 user = UserHandle.ALL; 8639 } else { 8640 user = new UserHandle(userId); 8641 } 8642 8643 // Only system components can circumvent runtime permissions when installing. 8644 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8645 && mContext.checkCallingOrSelfPermission(Manifest.permission 8646 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8647 throw new SecurityException("You need the " 8648 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8649 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8650 } 8651 8652 verificationParams.setInstallerUid(callingUid); 8653 8654 final File originFile = new File(originPath); 8655 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8656 8657 final Message msg = mHandler.obtainMessage(INIT_COPY); 8658 msg.obj = new InstallParams(origin, observer, installFlags, 8659 installerPackageName, null, verificationParams, user, packageAbiOverride); 8660 mHandler.sendMessage(msg); 8661 } 8662 8663 void installStage(String packageName, File stagedDir, String stagedCid, 8664 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8665 String installerPackageName, int installerUid, UserHandle user) { 8666 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8667 params.referrerUri, installerUid, null); 8668 8669 final OriginInfo origin; 8670 if (stagedDir != null) { 8671 origin = OriginInfo.fromStagedFile(stagedDir); 8672 } else { 8673 origin = OriginInfo.fromStagedContainer(stagedCid); 8674 } 8675 8676 final Message msg = mHandler.obtainMessage(INIT_COPY); 8677 msg.obj = new InstallParams(origin, observer, params.installFlags, 8678 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8679 mHandler.sendMessage(msg); 8680 } 8681 8682 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8683 Bundle extras = new Bundle(1); 8684 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8685 8686 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8687 packageName, extras, null, null, new int[] {userId}); 8688 try { 8689 IActivityManager am = ActivityManagerNative.getDefault(); 8690 final boolean isSystem = 8691 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8692 if (isSystem && am.isUserRunning(userId, false)) { 8693 // The just-installed/enabled app is bundled on the system, so presumed 8694 // to be able to run automatically without needing an explicit launch. 8695 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8696 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8697 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8698 .setPackage(packageName); 8699 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8700 android.app.AppOpsManager.OP_NONE, false, false, userId); 8701 } 8702 } catch (RemoteException e) { 8703 // shouldn't happen 8704 Slog.w(TAG, "Unable to bootstrap installed package", e); 8705 } 8706 } 8707 8708 @Override 8709 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8710 int userId) { 8711 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8712 PackageSetting pkgSetting; 8713 final int uid = Binder.getCallingUid(); 8714 enforceCrossUserPermission(uid, userId, true, true, 8715 "setApplicationHiddenSetting for user " + userId); 8716 8717 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8718 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8719 return false; 8720 } 8721 8722 long callingId = Binder.clearCallingIdentity(); 8723 try { 8724 boolean sendAdded = false; 8725 boolean sendRemoved = false; 8726 // writer 8727 synchronized (mPackages) { 8728 pkgSetting = mSettings.mPackages.get(packageName); 8729 if (pkgSetting == null) { 8730 return false; 8731 } 8732 if (pkgSetting.getHidden(userId) != hidden) { 8733 pkgSetting.setHidden(hidden, userId); 8734 mSettings.writePackageRestrictionsLPr(userId); 8735 if (hidden) { 8736 sendRemoved = true; 8737 } else { 8738 sendAdded = true; 8739 } 8740 } 8741 } 8742 if (sendAdded) { 8743 sendPackageAddedForUser(packageName, pkgSetting, userId); 8744 return true; 8745 } 8746 if (sendRemoved) { 8747 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8748 "hiding pkg"); 8749 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8750 } 8751 } finally { 8752 Binder.restoreCallingIdentity(callingId); 8753 } 8754 return false; 8755 } 8756 8757 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8758 int userId) { 8759 final PackageRemovedInfo info = new PackageRemovedInfo(); 8760 info.removedPackage = packageName; 8761 info.removedUsers = new int[] {userId}; 8762 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8763 info.sendBroadcast(false, false, false); 8764 } 8765 8766 /** 8767 * Returns true if application is not found or there was an error. Otherwise it returns 8768 * the hidden state of the package for the given user. 8769 */ 8770 @Override 8771 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8772 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8773 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8774 false, "getApplicationHidden for user " + userId); 8775 PackageSetting pkgSetting; 8776 long callingId = Binder.clearCallingIdentity(); 8777 try { 8778 // writer 8779 synchronized (mPackages) { 8780 pkgSetting = mSettings.mPackages.get(packageName); 8781 if (pkgSetting == null) { 8782 return true; 8783 } 8784 return pkgSetting.getHidden(userId); 8785 } 8786 } finally { 8787 Binder.restoreCallingIdentity(callingId); 8788 } 8789 } 8790 8791 /** 8792 * @hide 8793 */ 8794 @Override 8795 public int installExistingPackageAsUser(String packageName, int userId) { 8796 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8797 null); 8798 PackageSetting pkgSetting; 8799 final int uid = Binder.getCallingUid(); 8800 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8801 + userId); 8802 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8803 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8804 } 8805 8806 long callingId = Binder.clearCallingIdentity(); 8807 try { 8808 boolean sendAdded = false; 8809 8810 // writer 8811 synchronized (mPackages) { 8812 pkgSetting = mSettings.mPackages.get(packageName); 8813 if (pkgSetting == null) { 8814 return PackageManager.INSTALL_FAILED_INVALID_URI; 8815 } 8816 if (!pkgSetting.getInstalled(userId)) { 8817 pkgSetting.setInstalled(true, userId); 8818 pkgSetting.setHidden(false, userId); 8819 mSettings.writePackageRestrictionsLPr(userId); 8820 sendAdded = true; 8821 } 8822 } 8823 8824 if (sendAdded) { 8825 sendPackageAddedForUser(packageName, pkgSetting, userId); 8826 } 8827 } finally { 8828 Binder.restoreCallingIdentity(callingId); 8829 } 8830 8831 return PackageManager.INSTALL_SUCCEEDED; 8832 } 8833 8834 boolean isUserRestricted(int userId, String restrictionKey) { 8835 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8836 if (restrictions.getBoolean(restrictionKey, false)) { 8837 Log.w(TAG, "User is restricted: " + restrictionKey); 8838 return true; 8839 } 8840 return false; 8841 } 8842 8843 @Override 8844 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8845 mContext.enforceCallingOrSelfPermission( 8846 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8847 "Only package verification agents can verify applications"); 8848 8849 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8850 final PackageVerificationResponse response = new PackageVerificationResponse( 8851 verificationCode, Binder.getCallingUid()); 8852 msg.arg1 = id; 8853 msg.obj = response; 8854 mHandler.sendMessage(msg); 8855 } 8856 8857 @Override 8858 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8859 long millisecondsToDelay) { 8860 mContext.enforceCallingOrSelfPermission( 8861 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8862 "Only package verification agents can extend verification timeouts"); 8863 8864 final PackageVerificationState state = mPendingVerification.get(id); 8865 final PackageVerificationResponse response = new PackageVerificationResponse( 8866 verificationCodeAtTimeout, Binder.getCallingUid()); 8867 8868 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8869 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8870 } 8871 if (millisecondsToDelay < 0) { 8872 millisecondsToDelay = 0; 8873 } 8874 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8875 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8876 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8877 } 8878 8879 if ((state != null) && !state.timeoutExtended()) { 8880 state.extendTimeout(); 8881 8882 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8883 msg.arg1 = id; 8884 msg.obj = response; 8885 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8886 } 8887 } 8888 8889 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8890 int verificationCode, UserHandle user) { 8891 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8892 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8893 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8894 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8895 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8896 8897 mContext.sendBroadcastAsUser(intent, user, 8898 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8899 } 8900 8901 private ComponentName matchComponentForVerifier(String packageName, 8902 List<ResolveInfo> receivers) { 8903 ActivityInfo targetReceiver = null; 8904 8905 final int NR = receivers.size(); 8906 for (int i = 0; i < NR; i++) { 8907 final ResolveInfo info = receivers.get(i); 8908 if (info.activityInfo == null) { 8909 continue; 8910 } 8911 8912 if (packageName.equals(info.activityInfo.packageName)) { 8913 targetReceiver = info.activityInfo; 8914 break; 8915 } 8916 } 8917 8918 if (targetReceiver == null) { 8919 return null; 8920 } 8921 8922 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8923 } 8924 8925 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8926 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8927 if (pkgInfo.verifiers.length == 0) { 8928 return null; 8929 } 8930 8931 final int N = pkgInfo.verifiers.length; 8932 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8933 for (int i = 0; i < N; i++) { 8934 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8935 8936 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8937 receivers); 8938 if (comp == null) { 8939 continue; 8940 } 8941 8942 final int verifierUid = getUidForVerifier(verifierInfo); 8943 if (verifierUid == -1) { 8944 continue; 8945 } 8946 8947 if (DEBUG_VERIFY) { 8948 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8949 + " with the correct signature"); 8950 } 8951 sufficientVerifiers.add(comp); 8952 verificationState.addSufficientVerifier(verifierUid); 8953 } 8954 8955 return sufficientVerifiers; 8956 } 8957 8958 private int getUidForVerifier(VerifierInfo verifierInfo) { 8959 synchronized (mPackages) { 8960 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8961 if (pkg == null) { 8962 return -1; 8963 } else if (pkg.mSignatures.length != 1) { 8964 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8965 + " has more than one signature; ignoring"); 8966 return -1; 8967 } 8968 8969 /* 8970 * If the public key of the package's signature does not match 8971 * our expected public key, then this is a different package and 8972 * we should skip. 8973 */ 8974 8975 final byte[] expectedPublicKey; 8976 try { 8977 final Signature verifierSig = pkg.mSignatures[0]; 8978 final PublicKey publicKey = verifierSig.getPublicKey(); 8979 expectedPublicKey = publicKey.getEncoded(); 8980 } catch (CertificateException e) { 8981 return -1; 8982 } 8983 8984 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8985 8986 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8987 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8988 + " does not have the expected public key; ignoring"); 8989 return -1; 8990 } 8991 8992 return pkg.applicationInfo.uid; 8993 } 8994 } 8995 8996 @Override 8997 public void finishPackageInstall(int token) { 8998 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8999 9000 if (DEBUG_INSTALL) { 9001 Slog.v(TAG, "BM finishing package install for " + token); 9002 } 9003 9004 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9005 mHandler.sendMessage(msg); 9006 } 9007 9008 /** 9009 * Get the verification agent timeout. 9010 * 9011 * @return verification timeout in milliseconds 9012 */ 9013 private long getVerificationTimeout() { 9014 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9015 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9016 DEFAULT_VERIFICATION_TIMEOUT); 9017 } 9018 9019 /** 9020 * Get the default verification agent response code. 9021 * 9022 * @return default verification response code 9023 */ 9024 private int getDefaultVerificationResponse() { 9025 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9026 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9027 DEFAULT_VERIFICATION_RESPONSE); 9028 } 9029 9030 /** 9031 * Check whether or not package verification has been enabled. 9032 * 9033 * @return true if verification should be performed 9034 */ 9035 private boolean isVerificationEnabled(int userId, int installFlags) { 9036 if (!DEFAULT_VERIFY_ENABLE) { 9037 return false; 9038 } 9039 9040 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9041 9042 // Check if installing from ADB 9043 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9044 // Do not run verification in a test harness environment 9045 if (ActivityManager.isRunningInTestHarness()) { 9046 return false; 9047 } 9048 if (ensureVerifyAppsEnabled) { 9049 return true; 9050 } 9051 // Check if the developer does not want package verification for ADB installs 9052 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9053 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9054 return false; 9055 } 9056 } 9057 9058 if (ensureVerifyAppsEnabled) { 9059 return true; 9060 } 9061 9062 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9063 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9064 } 9065 9066 @Override 9067 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9068 throws RemoteException { 9069 mContext.enforceCallingOrSelfPermission( 9070 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9071 "Only intentfilter verification agents can verify applications"); 9072 9073 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9074 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9075 Binder.getCallingUid(), verificationCode, failedDomains); 9076 msg.arg1 = id; 9077 msg.obj = response; 9078 mHandler.sendMessage(msg); 9079 } 9080 9081 @Override 9082 public int getIntentVerificationStatus(String packageName, int userId) { 9083 synchronized (mPackages) { 9084 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9085 } 9086 } 9087 9088 @Override 9089 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9090 boolean result = false; 9091 synchronized (mPackages) { 9092 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9093 } 9094 scheduleWritePackageRestrictionsLocked(userId); 9095 return result; 9096 } 9097 9098 @Override 9099 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9100 synchronized (mPackages) { 9101 return mSettings.getIntentFilterVerificationsLPr(packageName); 9102 } 9103 } 9104 9105 @Override 9106 public List<IntentFilter> getAllIntentFilters(String packageName) { 9107 if (TextUtils.isEmpty(packageName)) { 9108 return Collections.<IntentFilter>emptyList(); 9109 } 9110 synchronized (mPackages) { 9111 PackageParser.Package pkg = mPackages.get(packageName); 9112 if (pkg == null || pkg.activities == null) { 9113 return Collections.<IntentFilter>emptyList(); 9114 } 9115 final int count = pkg.activities.size(); 9116 ArrayList<IntentFilter> result = new ArrayList<>(); 9117 for (int n=0; n<count; n++) { 9118 PackageParser.Activity activity = pkg.activities.get(n); 9119 if (activity.intents != null || activity.intents.size() > 0) { 9120 result.addAll(activity.intents); 9121 } 9122 } 9123 return result; 9124 } 9125 } 9126 9127 @Override 9128 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9129 synchronized (mPackages) { 9130 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9131 result |= updateIntentVerificationStatus(packageName, 9132 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9133 UserHandle.myUserId()); 9134 return result; 9135 } 9136 } 9137 9138 @Override 9139 public String getDefaultBrowserPackageName(int userId) { 9140 synchronized (mPackages) { 9141 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9142 } 9143 } 9144 9145 /** 9146 * Get the "allow unknown sources" setting. 9147 * 9148 * @return the current "allow unknown sources" setting 9149 */ 9150 private int getUnknownSourcesSettings() { 9151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9152 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9153 -1); 9154 } 9155 9156 @Override 9157 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9158 final int uid = Binder.getCallingUid(); 9159 // writer 9160 synchronized (mPackages) { 9161 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9162 if (targetPackageSetting == null) { 9163 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9164 } 9165 9166 PackageSetting installerPackageSetting; 9167 if (installerPackageName != null) { 9168 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9169 if (installerPackageSetting == null) { 9170 throw new IllegalArgumentException("Unknown installer package: " 9171 + installerPackageName); 9172 } 9173 } else { 9174 installerPackageSetting = null; 9175 } 9176 9177 Signature[] callerSignature; 9178 Object obj = mSettings.getUserIdLPr(uid); 9179 if (obj != null) { 9180 if (obj instanceof SharedUserSetting) { 9181 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9182 } else if (obj instanceof PackageSetting) { 9183 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9184 } else { 9185 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9186 } 9187 } else { 9188 throw new SecurityException("Unknown calling uid " + uid); 9189 } 9190 9191 // Verify: can't set installerPackageName to a package that is 9192 // not signed with the same cert as the caller. 9193 if (installerPackageSetting != null) { 9194 if (compareSignatures(callerSignature, 9195 installerPackageSetting.signatures.mSignatures) 9196 != PackageManager.SIGNATURE_MATCH) { 9197 throw new SecurityException( 9198 "Caller does not have same cert as new installer package " 9199 + installerPackageName); 9200 } 9201 } 9202 9203 // Verify: if target already has an installer package, it must 9204 // be signed with the same cert as the caller. 9205 if (targetPackageSetting.installerPackageName != null) { 9206 PackageSetting setting = mSettings.mPackages.get( 9207 targetPackageSetting.installerPackageName); 9208 // If the currently set package isn't valid, then it's always 9209 // okay to change it. 9210 if (setting != null) { 9211 if (compareSignatures(callerSignature, 9212 setting.signatures.mSignatures) 9213 != PackageManager.SIGNATURE_MATCH) { 9214 throw new SecurityException( 9215 "Caller does not have same cert as old installer package " 9216 + targetPackageSetting.installerPackageName); 9217 } 9218 } 9219 } 9220 9221 // Okay! 9222 targetPackageSetting.installerPackageName = installerPackageName; 9223 scheduleWriteSettingsLocked(); 9224 } 9225 } 9226 9227 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9228 // Queue up an async operation since the package installation may take a little while. 9229 mHandler.post(new Runnable() { 9230 public void run() { 9231 mHandler.removeCallbacks(this); 9232 // Result object to be returned 9233 PackageInstalledInfo res = new PackageInstalledInfo(); 9234 res.returnCode = currentStatus; 9235 res.uid = -1; 9236 res.pkg = null; 9237 res.removedInfo = new PackageRemovedInfo(); 9238 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9239 args.doPreInstall(res.returnCode); 9240 synchronized (mInstallLock) { 9241 installPackageLI(args, res); 9242 } 9243 args.doPostInstall(res.returnCode, res.uid); 9244 } 9245 9246 // A restore should be performed at this point if (a) the install 9247 // succeeded, (b) the operation is not an update, and (c) the new 9248 // package has not opted out of backup participation. 9249 final boolean update = res.removedInfo.removedPackage != null; 9250 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9251 boolean doRestore = !update 9252 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9253 9254 // Set up the post-install work request bookkeeping. This will be used 9255 // and cleaned up by the post-install event handling regardless of whether 9256 // there's a restore pass performed. Token values are >= 1. 9257 int token; 9258 if (mNextInstallToken < 0) mNextInstallToken = 1; 9259 token = mNextInstallToken++; 9260 9261 PostInstallData data = new PostInstallData(args, res); 9262 mRunningInstalls.put(token, data); 9263 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9264 9265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9266 // Pass responsibility to the Backup Manager. It will perform a 9267 // restore if appropriate, then pass responsibility back to the 9268 // Package Manager to run the post-install observer callbacks 9269 // and broadcasts. 9270 IBackupManager bm = IBackupManager.Stub.asInterface( 9271 ServiceManager.getService(Context.BACKUP_SERVICE)); 9272 if (bm != null) { 9273 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9274 + " to BM for possible restore"); 9275 try { 9276 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9277 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9278 } else { 9279 doRestore = false; 9280 } 9281 } catch (RemoteException e) { 9282 // can't happen; the backup manager is local 9283 } catch (Exception e) { 9284 Slog.e(TAG, "Exception trying to enqueue restore", e); 9285 doRestore = false; 9286 } 9287 } else { 9288 Slog.e(TAG, "Backup Manager not found!"); 9289 doRestore = false; 9290 } 9291 } 9292 9293 if (!doRestore) { 9294 // No restore possible, or the Backup Manager was mysteriously not 9295 // available -- just fire the post-install work request directly. 9296 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9297 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9298 mHandler.sendMessage(msg); 9299 } 9300 } 9301 }); 9302 } 9303 9304 private abstract class HandlerParams { 9305 private static final int MAX_RETRIES = 4; 9306 9307 /** 9308 * Number of times startCopy() has been attempted and had a non-fatal 9309 * error. 9310 */ 9311 private int mRetries = 0; 9312 9313 /** User handle for the user requesting the information or installation. */ 9314 private final UserHandle mUser; 9315 9316 HandlerParams(UserHandle user) { 9317 mUser = user; 9318 } 9319 9320 UserHandle getUser() { 9321 return mUser; 9322 } 9323 9324 final boolean startCopy() { 9325 boolean res; 9326 try { 9327 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9328 9329 if (++mRetries > MAX_RETRIES) { 9330 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9331 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9332 handleServiceError(); 9333 return false; 9334 } else { 9335 handleStartCopy(); 9336 res = true; 9337 } 9338 } catch (RemoteException e) { 9339 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9340 mHandler.sendEmptyMessage(MCS_RECONNECT); 9341 res = false; 9342 } 9343 handleReturnCode(); 9344 return res; 9345 } 9346 9347 final void serviceError() { 9348 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9349 handleServiceError(); 9350 handleReturnCode(); 9351 } 9352 9353 abstract void handleStartCopy() throws RemoteException; 9354 abstract void handleServiceError(); 9355 abstract void handleReturnCode(); 9356 } 9357 9358 class MeasureParams extends HandlerParams { 9359 private final PackageStats mStats; 9360 private boolean mSuccess; 9361 9362 private final IPackageStatsObserver mObserver; 9363 9364 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9365 super(new UserHandle(stats.userHandle)); 9366 mObserver = observer; 9367 mStats = stats; 9368 } 9369 9370 @Override 9371 public String toString() { 9372 return "MeasureParams{" 9373 + Integer.toHexString(System.identityHashCode(this)) 9374 + " " + mStats.packageName + "}"; 9375 } 9376 9377 @Override 9378 void handleStartCopy() throws RemoteException { 9379 synchronized (mInstallLock) { 9380 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9381 } 9382 9383 if (mSuccess) { 9384 final boolean mounted; 9385 if (Environment.isExternalStorageEmulated()) { 9386 mounted = true; 9387 } else { 9388 final String status = Environment.getExternalStorageState(); 9389 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9390 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9391 } 9392 9393 if (mounted) { 9394 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9395 9396 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9397 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9398 9399 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9400 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9401 9402 // Always subtract cache size, since it's a subdirectory 9403 mStats.externalDataSize -= mStats.externalCacheSize; 9404 9405 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9406 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9407 9408 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9409 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9410 } 9411 } 9412 } 9413 9414 @Override 9415 void handleReturnCode() { 9416 if (mObserver != null) { 9417 try { 9418 mObserver.onGetStatsCompleted(mStats, mSuccess); 9419 } catch (RemoteException e) { 9420 Slog.i(TAG, "Observer no longer exists."); 9421 } 9422 } 9423 } 9424 9425 @Override 9426 void handleServiceError() { 9427 Slog.e(TAG, "Could not measure application " + mStats.packageName 9428 + " external storage"); 9429 } 9430 } 9431 9432 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9433 throws RemoteException { 9434 long result = 0; 9435 for (File path : paths) { 9436 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9437 } 9438 return result; 9439 } 9440 9441 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9442 for (File path : paths) { 9443 try { 9444 mcs.clearDirectory(path.getAbsolutePath()); 9445 } catch (RemoteException e) { 9446 } 9447 } 9448 } 9449 9450 static class OriginInfo { 9451 /** 9452 * Location where install is coming from, before it has been 9453 * copied/renamed into place. This could be a single monolithic APK 9454 * file, or a cluster directory. This location may be untrusted. 9455 */ 9456 final File file; 9457 final String cid; 9458 9459 /** 9460 * Flag indicating that {@link #file} or {@link #cid} has already been 9461 * staged, meaning downstream users don't need to defensively copy the 9462 * contents. 9463 */ 9464 final boolean staged; 9465 9466 /** 9467 * Flag indicating that {@link #file} or {@link #cid} is an already 9468 * installed app that is being moved. 9469 */ 9470 final boolean existing; 9471 9472 final String resolvedPath; 9473 final File resolvedFile; 9474 9475 static OriginInfo fromNothing() { 9476 return new OriginInfo(null, null, false, false); 9477 } 9478 9479 static OriginInfo fromUntrustedFile(File file) { 9480 return new OriginInfo(file, null, false, false); 9481 } 9482 9483 static OriginInfo fromExistingFile(File file) { 9484 return new OriginInfo(file, null, false, true); 9485 } 9486 9487 static OriginInfo fromStagedFile(File file) { 9488 return new OriginInfo(file, null, true, false); 9489 } 9490 9491 static OriginInfo fromStagedContainer(String cid) { 9492 return new OriginInfo(null, cid, true, false); 9493 } 9494 9495 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9496 this.file = file; 9497 this.cid = cid; 9498 this.staged = staged; 9499 this.existing = existing; 9500 9501 if (cid != null) { 9502 resolvedPath = PackageHelper.getSdDir(cid); 9503 resolvedFile = new File(resolvedPath); 9504 } else if (file != null) { 9505 resolvedPath = file.getAbsolutePath(); 9506 resolvedFile = file; 9507 } else { 9508 resolvedPath = null; 9509 resolvedFile = null; 9510 } 9511 } 9512 } 9513 9514 class InstallParams extends HandlerParams { 9515 final OriginInfo origin; 9516 final IPackageInstallObserver2 observer; 9517 int installFlags; 9518 final String installerPackageName; 9519 final String volumeUuid; 9520 final VerificationParams verificationParams; 9521 private InstallArgs mArgs; 9522 private int mRet; 9523 final String packageAbiOverride; 9524 9525 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9526 String installerPackageName, String volumeUuid, 9527 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9528 super(user); 9529 this.origin = origin; 9530 this.observer = observer; 9531 this.installFlags = installFlags; 9532 this.installerPackageName = installerPackageName; 9533 this.volumeUuid = volumeUuid; 9534 this.verificationParams = verificationParams; 9535 this.packageAbiOverride = packageAbiOverride; 9536 } 9537 9538 @Override 9539 public String toString() { 9540 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9541 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9542 } 9543 9544 public ManifestDigest getManifestDigest() { 9545 if (verificationParams == null) { 9546 return null; 9547 } 9548 return verificationParams.getManifestDigest(); 9549 } 9550 9551 private int installLocationPolicy(PackageInfoLite pkgLite) { 9552 String packageName = pkgLite.packageName; 9553 int installLocation = pkgLite.installLocation; 9554 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9555 // reader 9556 synchronized (mPackages) { 9557 PackageParser.Package pkg = mPackages.get(packageName); 9558 if (pkg != null) { 9559 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9560 // Check for downgrading. 9561 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9562 try { 9563 checkDowngrade(pkg, pkgLite); 9564 } catch (PackageManagerException e) { 9565 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9566 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9567 } 9568 } 9569 // Check for updated system application. 9570 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9571 if (onSd) { 9572 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9573 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9574 } 9575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9576 } else { 9577 if (onSd) { 9578 // Install flag overrides everything. 9579 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9580 } 9581 // If current upgrade specifies particular preference 9582 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9583 // Application explicitly specified internal. 9584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9585 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9586 // App explictly prefers external. Let policy decide 9587 } else { 9588 // Prefer previous location 9589 if (isExternal(pkg)) { 9590 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9591 } 9592 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9593 } 9594 } 9595 } else { 9596 // Invalid install. Return error code 9597 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9598 } 9599 } 9600 } 9601 // All the special cases have been taken care of. 9602 // Return result based on recommended install location. 9603 if (onSd) { 9604 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9605 } 9606 return pkgLite.recommendedInstallLocation; 9607 } 9608 9609 /* 9610 * Invoke remote method to get package information and install 9611 * location values. Override install location based on default 9612 * policy if needed and then create install arguments based 9613 * on the install location. 9614 */ 9615 public void handleStartCopy() throws RemoteException { 9616 int ret = PackageManager.INSTALL_SUCCEEDED; 9617 9618 // If we're already staged, we've firmly committed to an install location 9619 if (origin.staged) { 9620 if (origin.file != null) { 9621 installFlags |= PackageManager.INSTALL_INTERNAL; 9622 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9623 } else if (origin.cid != null) { 9624 installFlags |= PackageManager.INSTALL_EXTERNAL; 9625 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9626 } else { 9627 throw new IllegalStateException("Invalid stage location"); 9628 } 9629 } 9630 9631 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9632 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9633 9634 PackageInfoLite pkgLite = null; 9635 9636 if (onInt && onSd) { 9637 // Check if both bits are set. 9638 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9640 } else { 9641 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9642 packageAbiOverride); 9643 9644 /* 9645 * If we have too little free space, try to free cache 9646 * before giving up. 9647 */ 9648 if (!origin.staged && pkgLite.recommendedInstallLocation 9649 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9650 // TODO: focus freeing disk space on the target device 9651 final StorageManager storage = StorageManager.from(mContext); 9652 final long lowThreshold = storage.getStorageLowBytes( 9653 Environment.getDataDirectory()); 9654 9655 final long sizeBytes = mContainerService.calculateInstalledSize( 9656 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9657 9658 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9659 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9660 installFlags, packageAbiOverride); 9661 } 9662 9663 /* 9664 * The cache free must have deleted the file we 9665 * downloaded to install. 9666 * 9667 * TODO: fix the "freeCache" call to not delete 9668 * the file we care about. 9669 */ 9670 if (pkgLite.recommendedInstallLocation 9671 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9672 pkgLite.recommendedInstallLocation 9673 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9674 } 9675 } 9676 } 9677 9678 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9679 int loc = pkgLite.recommendedInstallLocation; 9680 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9681 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9682 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9683 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9684 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9685 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9686 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9687 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9688 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9689 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9690 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9691 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9692 } else { 9693 // Override with defaults if needed. 9694 loc = installLocationPolicy(pkgLite); 9695 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9696 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9697 } else if (!onSd && !onInt) { 9698 // Override install location with flags 9699 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9700 // Set the flag to install on external media. 9701 installFlags |= PackageManager.INSTALL_EXTERNAL; 9702 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9703 } else { 9704 // Make sure the flag for installing on external 9705 // media is unset 9706 installFlags |= PackageManager.INSTALL_INTERNAL; 9707 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9708 } 9709 } 9710 } 9711 } 9712 9713 final InstallArgs args = createInstallArgs(this); 9714 mArgs = args; 9715 9716 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9717 /* 9718 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9719 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9720 */ 9721 int userIdentifier = getUser().getIdentifier(); 9722 if (userIdentifier == UserHandle.USER_ALL 9723 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9724 userIdentifier = UserHandle.USER_OWNER; 9725 } 9726 9727 /* 9728 * Determine if we have any installed package verifiers. If we 9729 * do, then we'll defer to them to verify the packages. 9730 */ 9731 final int requiredUid = mRequiredVerifierPackage == null ? -1 9732 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9733 if (!origin.existing && requiredUid != -1 9734 && isVerificationEnabled(userIdentifier, installFlags)) { 9735 final Intent verification = new Intent( 9736 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9737 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9738 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9739 PACKAGE_MIME_TYPE); 9740 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9741 9742 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9743 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9744 0 /* TODO: Which userId? */); 9745 9746 if (DEBUG_VERIFY) { 9747 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9748 + verification.toString() + " with " + pkgLite.verifiers.length 9749 + " optional verifiers"); 9750 } 9751 9752 final int verificationId = mPendingVerificationToken++; 9753 9754 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9755 9756 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9757 installerPackageName); 9758 9759 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9760 installFlags); 9761 9762 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9763 pkgLite.packageName); 9764 9765 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9766 pkgLite.versionCode); 9767 9768 if (verificationParams != null) { 9769 if (verificationParams.getVerificationURI() != null) { 9770 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9771 verificationParams.getVerificationURI()); 9772 } 9773 if (verificationParams.getOriginatingURI() != null) { 9774 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9775 verificationParams.getOriginatingURI()); 9776 } 9777 if (verificationParams.getReferrer() != null) { 9778 verification.putExtra(Intent.EXTRA_REFERRER, 9779 verificationParams.getReferrer()); 9780 } 9781 if (verificationParams.getOriginatingUid() >= 0) { 9782 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9783 verificationParams.getOriginatingUid()); 9784 } 9785 if (verificationParams.getInstallerUid() >= 0) { 9786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9787 verificationParams.getInstallerUid()); 9788 } 9789 } 9790 9791 final PackageVerificationState verificationState = new PackageVerificationState( 9792 requiredUid, args); 9793 9794 mPendingVerification.append(verificationId, verificationState); 9795 9796 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9797 receivers, verificationState); 9798 9799 /* 9800 * If any sufficient verifiers were listed in the package 9801 * manifest, attempt to ask them. 9802 */ 9803 if (sufficientVerifiers != null) { 9804 final int N = sufficientVerifiers.size(); 9805 if (N == 0) { 9806 Slog.i(TAG, "Additional verifiers required, but none installed."); 9807 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9808 } else { 9809 for (int i = 0; i < N; i++) { 9810 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9811 9812 final Intent sufficientIntent = new Intent(verification); 9813 sufficientIntent.setComponent(verifierComponent); 9814 9815 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9816 } 9817 } 9818 } 9819 9820 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9821 mRequiredVerifierPackage, receivers); 9822 if (ret == PackageManager.INSTALL_SUCCEEDED 9823 && mRequiredVerifierPackage != null) { 9824 /* 9825 * Send the intent to the required verification agent, 9826 * but only start the verification timeout after the 9827 * target BroadcastReceivers have run. 9828 */ 9829 verification.setComponent(requiredVerifierComponent); 9830 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9831 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9832 new BroadcastReceiver() { 9833 @Override 9834 public void onReceive(Context context, Intent intent) { 9835 final Message msg = mHandler 9836 .obtainMessage(CHECK_PENDING_VERIFICATION); 9837 msg.arg1 = verificationId; 9838 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9839 } 9840 }, null, 0, null, null); 9841 9842 /* 9843 * We don't want the copy to proceed until verification 9844 * succeeds, so null out this field. 9845 */ 9846 mArgs = null; 9847 } 9848 } else { 9849 /* 9850 * No package verification is enabled, so immediately start 9851 * the remote call to initiate copy using temporary file. 9852 */ 9853 ret = args.copyApk(mContainerService, true); 9854 } 9855 } 9856 9857 mRet = ret; 9858 } 9859 9860 @Override 9861 void handleReturnCode() { 9862 // If mArgs is null, then MCS couldn't be reached. When it 9863 // reconnects, it will try again to install. At that point, this 9864 // will succeed. 9865 if (mArgs != null) { 9866 processPendingInstall(mArgs, mRet); 9867 } 9868 } 9869 9870 @Override 9871 void handleServiceError() { 9872 mArgs = createInstallArgs(this); 9873 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9874 } 9875 9876 public boolean isForwardLocked() { 9877 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9878 } 9879 } 9880 9881 /** 9882 * Used during creation of InstallArgs 9883 * 9884 * @param installFlags package installation flags 9885 * @return true if should be installed on external storage 9886 */ 9887 private static boolean installOnExternalAsec(int installFlags) { 9888 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9889 return false; 9890 } 9891 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9892 return true; 9893 } 9894 return false; 9895 } 9896 9897 /** 9898 * Used during creation of InstallArgs 9899 * 9900 * @param installFlags package installation flags 9901 * @return true if should be installed as forward locked 9902 */ 9903 private static boolean installForwardLocked(int installFlags) { 9904 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9905 } 9906 9907 private InstallArgs createInstallArgs(InstallParams params) { 9908 if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9909 return new AsecInstallArgs(params); 9910 } else { 9911 return new FileInstallArgs(params); 9912 } 9913 } 9914 9915 /** 9916 * Create args that describe an existing installed package. Typically used 9917 * when cleaning up old installs, or used as a move source. 9918 */ 9919 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9920 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9921 final boolean isInAsec; 9922 if (installOnExternalAsec(installFlags)) { 9923 /* Apps on SD card are always in ASEC containers. */ 9924 isInAsec = true; 9925 } else if (installForwardLocked(installFlags) 9926 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9927 /* 9928 * Forward-locked apps are only in ASEC containers if they're the 9929 * new style 9930 */ 9931 isInAsec = true; 9932 } else { 9933 isInAsec = false; 9934 } 9935 9936 if (isInAsec) { 9937 return new AsecInstallArgs(codePath, instructionSets, 9938 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9939 } else { 9940 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9941 instructionSets); 9942 } 9943 } 9944 9945 static abstract class InstallArgs { 9946 /** @see InstallParams#origin */ 9947 final OriginInfo origin; 9948 9949 final IPackageInstallObserver2 observer; 9950 // Always refers to PackageManager flags only 9951 final int installFlags; 9952 final String installerPackageName; 9953 final String volumeUuid; 9954 final ManifestDigest manifestDigest; 9955 final UserHandle user; 9956 final String abiOverride; 9957 9958 // The list of instruction sets supported by this app. This is currently 9959 // only used during the rmdex() phase to clean up resources. We can get rid of this 9960 // if we move dex files under the common app path. 9961 /* nullable */ String[] instructionSets; 9962 9963 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9964 String installerPackageName, String volumeUuid, ManifestDigest manifestDigest, 9965 UserHandle user, String[] instructionSets, String abiOverride) { 9966 this.origin = origin; 9967 this.installFlags = installFlags; 9968 this.observer = observer; 9969 this.installerPackageName = installerPackageName; 9970 this.volumeUuid = volumeUuid; 9971 this.manifestDigest = manifestDigest; 9972 this.user = user; 9973 this.instructionSets = instructionSets; 9974 this.abiOverride = abiOverride; 9975 } 9976 9977 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9978 abstract int doPreInstall(int status); 9979 9980 /** 9981 * Rename package into final resting place. All paths on the given 9982 * scanned package should be updated to reflect the rename. 9983 */ 9984 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9985 abstract int doPostInstall(int status, int uid); 9986 9987 /** @see PackageSettingBase#codePathString */ 9988 abstract String getCodePath(); 9989 /** @see PackageSettingBase#resourcePathString */ 9990 abstract String getResourcePath(); 9991 abstract String getLegacyNativeLibraryPath(); 9992 9993 // Need installer lock especially for dex file removal. 9994 abstract void cleanUpResourcesLI(); 9995 abstract boolean doPostDeleteLI(boolean delete); 9996 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9997 9998 /** 9999 * Called before the source arguments are copied. This is used mostly 10000 * for MoveParams when it needs to read the source file to put it in the 10001 * destination. 10002 */ 10003 int doPreCopy() { 10004 return PackageManager.INSTALL_SUCCEEDED; 10005 } 10006 10007 /** 10008 * Called after the source arguments are copied. This is used mostly for 10009 * MoveParams when it needs to read the source file to put it in the 10010 * destination. 10011 * 10012 * @return 10013 */ 10014 int doPostCopy(int uid) { 10015 return PackageManager.INSTALL_SUCCEEDED; 10016 } 10017 10018 protected boolean isFwdLocked() { 10019 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10020 } 10021 10022 protected boolean isExternalAsec() { 10023 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10024 } 10025 10026 UserHandle getUser() { 10027 return user; 10028 } 10029 } 10030 10031 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10032 if (!allCodePaths.isEmpty()) { 10033 if (instructionSets == null) { 10034 throw new IllegalStateException("instructionSet == null"); 10035 } 10036 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10037 for (String codePath : allCodePaths) { 10038 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10039 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10040 if (retCode < 0) { 10041 Slog.w(TAG, "Couldn't remove dex file for package: " 10042 + " at location " + codePath + ", retcode=" + retCode); 10043 // we don't consider this to be a failure of the core package deletion 10044 } 10045 } 10046 } 10047 } 10048 } 10049 10050 /** 10051 * Logic to handle installation of non-ASEC applications, including copying 10052 * and renaming logic. 10053 */ 10054 class FileInstallArgs extends InstallArgs { 10055 private File codeFile; 10056 private File resourceFile; 10057 private File legacyNativeLibraryPath; 10058 10059 // Example topology: 10060 // /data/app/com.example/base.apk 10061 // /data/app/com.example/split_foo.apk 10062 // /data/app/com.example/lib/arm/libfoo.so 10063 // /data/app/com.example/lib/arm64/libfoo.so 10064 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10065 10066 /** New install */ 10067 FileInstallArgs(InstallParams params) { 10068 super(params.origin, params.observer, params.installFlags, 10069 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10070 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10071 if (isFwdLocked()) { 10072 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10073 } 10074 } 10075 10076 /** Existing install */ 10077 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 10078 String[] instructionSets) { 10079 super(OriginInfo.fromNothing(), null, 0, null, null, null, null, instructionSets, null); 10080 this.codeFile = (codePath != null) ? new File(codePath) : null; 10081 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10082 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 10083 new File(legacyNativeLibraryPath) : null; 10084 } 10085 10086 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10087 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 10088 isFwdLocked(), abiOverride); 10089 10090 final StorageManager storage = StorageManager.from(mContext); 10091 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 10092 } 10093 10094 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10095 if (origin.staged) { 10096 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10097 codeFile = origin.file; 10098 resourceFile = origin.file; 10099 return PackageManager.INSTALL_SUCCEEDED; 10100 } 10101 10102 try { 10103 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10104 codeFile = tempDir; 10105 resourceFile = tempDir; 10106 } catch (IOException e) { 10107 Slog.w(TAG, "Failed to create copy file: " + e); 10108 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10109 } 10110 10111 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10112 @Override 10113 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10114 if (!FileUtils.isValidExtFilename(name)) { 10115 throw new IllegalArgumentException("Invalid filename: " + name); 10116 } 10117 try { 10118 final File file = new File(codeFile, name); 10119 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10120 O_RDWR | O_CREAT, 0644); 10121 Os.chmod(file.getAbsolutePath(), 0644); 10122 return new ParcelFileDescriptor(fd); 10123 } catch (ErrnoException e) { 10124 throw new RemoteException("Failed to open: " + e.getMessage()); 10125 } 10126 } 10127 }; 10128 10129 int ret = PackageManager.INSTALL_SUCCEEDED; 10130 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10131 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10132 Slog.e(TAG, "Failed to copy package"); 10133 return ret; 10134 } 10135 10136 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10137 NativeLibraryHelper.Handle handle = null; 10138 try { 10139 handle = NativeLibraryHelper.Handle.create(codeFile); 10140 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10141 abiOverride); 10142 } catch (IOException e) { 10143 Slog.e(TAG, "Copying native libraries failed", e); 10144 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10145 } finally { 10146 IoUtils.closeQuietly(handle); 10147 } 10148 10149 return ret; 10150 } 10151 10152 int doPreInstall(int status) { 10153 if (status != PackageManager.INSTALL_SUCCEEDED) { 10154 cleanUp(); 10155 } 10156 return status; 10157 } 10158 10159 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10160 if (status != PackageManager.INSTALL_SUCCEEDED) { 10161 cleanUp(); 10162 return false; 10163 } else { 10164 final File targetDir = codeFile.getParentFile(); 10165 final File beforeCodeFile = codeFile; 10166 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10167 10168 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10169 try { 10170 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10171 } catch (ErrnoException e) { 10172 Slog.d(TAG, "Failed to rename", e); 10173 return false; 10174 } 10175 10176 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10177 Slog.d(TAG, "Failed to restorecon"); 10178 return false; 10179 } 10180 10181 // Reflect the rename internally 10182 codeFile = afterCodeFile; 10183 resourceFile = afterCodeFile; 10184 10185 // Reflect the rename in scanned details 10186 pkg.codePath = afterCodeFile.getAbsolutePath(); 10187 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10188 pkg.baseCodePath); 10189 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10190 pkg.splitCodePaths); 10191 10192 // Reflect the rename in app info 10193 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10194 pkg.applicationInfo.setCodePath(pkg.codePath); 10195 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10196 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10197 pkg.applicationInfo.setResourcePath(pkg.codePath); 10198 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10199 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10200 10201 return true; 10202 } 10203 } 10204 10205 int doPostInstall(int status, int uid) { 10206 if (status != PackageManager.INSTALL_SUCCEEDED) { 10207 cleanUp(); 10208 } 10209 return status; 10210 } 10211 10212 @Override 10213 String getCodePath() { 10214 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10215 } 10216 10217 @Override 10218 String getResourcePath() { 10219 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10220 } 10221 10222 @Override 10223 String getLegacyNativeLibraryPath() { 10224 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 10225 } 10226 10227 private boolean cleanUp() { 10228 if (codeFile == null || !codeFile.exists()) { 10229 return false; 10230 } 10231 10232 if (codeFile.isDirectory()) { 10233 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10234 } else { 10235 codeFile.delete(); 10236 } 10237 10238 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10239 resourceFile.delete(); 10240 } 10241 10242 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 10243 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 10244 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 10245 } 10246 legacyNativeLibraryPath.delete(); 10247 } 10248 10249 return true; 10250 } 10251 10252 void cleanUpResourcesLI() { 10253 // Try enumerating all code paths before deleting 10254 List<String> allCodePaths = Collections.EMPTY_LIST; 10255 if (codeFile != null && codeFile.exists()) { 10256 try { 10257 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10258 allCodePaths = pkg.getAllCodePaths(); 10259 } catch (PackageParserException e) { 10260 // Ignored; we tried our best 10261 } 10262 } 10263 10264 cleanUp(); 10265 removeDexFiles(allCodePaths, instructionSets); 10266 } 10267 10268 boolean doPostDeleteLI(boolean delete) { 10269 // XXX err, shouldn't we respect the delete flag? 10270 cleanUpResourcesLI(); 10271 return true; 10272 } 10273 } 10274 10275 private boolean isAsecExternal(String cid) { 10276 final String asecPath = PackageHelper.getSdFilesystem(cid); 10277 return !asecPath.startsWith(mAsecInternalPath); 10278 } 10279 10280 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10281 PackageManagerException { 10282 if (copyRet < 0) { 10283 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10284 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10285 throw new PackageManagerException(copyRet, message); 10286 } 10287 } 10288 } 10289 10290 /** 10291 * Extract the MountService "container ID" from the full code path of an 10292 * .apk. 10293 */ 10294 static String cidFromCodePath(String fullCodePath) { 10295 int eidx = fullCodePath.lastIndexOf("/"); 10296 String subStr1 = fullCodePath.substring(0, eidx); 10297 int sidx = subStr1.lastIndexOf("/"); 10298 return subStr1.substring(sidx+1, eidx); 10299 } 10300 10301 /** 10302 * Logic to handle installation of ASEC applications, including copying and 10303 * renaming logic. 10304 */ 10305 class AsecInstallArgs extends InstallArgs { 10306 static final String RES_FILE_NAME = "pkg.apk"; 10307 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10308 10309 String cid; 10310 String packagePath; 10311 String resourcePath; 10312 String legacyNativeLibraryDir; 10313 10314 /** New install */ 10315 AsecInstallArgs(InstallParams params) { 10316 super(params.origin, params.observer, params.installFlags, 10317 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10318 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10319 } 10320 10321 /** Existing install */ 10322 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10323 boolean isExternal, boolean isForwardLocked) { 10324 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 10325 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10326 instructionSets, null); 10327 // Hackily pretend we're still looking at a full code path 10328 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10329 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10330 } 10331 10332 // Extract cid from fullCodePath 10333 int eidx = fullCodePath.lastIndexOf("/"); 10334 String subStr1 = fullCodePath.substring(0, eidx); 10335 int sidx = subStr1.lastIndexOf("/"); 10336 cid = subStr1.substring(sidx+1, eidx); 10337 setMountPath(subStr1); 10338 } 10339 10340 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10341 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10342 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10343 instructionSets, null); 10344 this.cid = cid; 10345 setMountPath(PackageHelper.getSdDir(cid)); 10346 } 10347 10348 void createCopyFile() { 10349 cid = mInstallerService.allocateExternalStageCidLegacy(); 10350 } 10351 10352 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 10353 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 10354 abiOverride); 10355 10356 final File target; 10357 if (isExternalAsec()) { 10358 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 10359 } else { 10360 target = Environment.getDataDirectory(); 10361 } 10362 10363 final StorageManager storage = StorageManager.from(mContext); 10364 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 10365 } 10366 10367 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10368 if (origin.staged) { 10369 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10370 cid = origin.cid; 10371 setMountPath(PackageHelper.getSdDir(cid)); 10372 return PackageManager.INSTALL_SUCCEEDED; 10373 } 10374 10375 if (temp) { 10376 createCopyFile(); 10377 } else { 10378 /* 10379 * Pre-emptively destroy the container since it's destroyed if 10380 * copying fails due to it existing anyway. 10381 */ 10382 PackageHelper.destroySdDir(cid); 10383 } 10384 10385 final String newMountPath = imcs.copyPackageToContainer( 10386 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10387 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10388 10389 if (newMountPath != null) { 10390 setMountPath(newMountPath); 10391 return PackageManager.INSTALL_SUCCEEDED; 10392 } else { 10393 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10394 } 10395 } 10396 10397 @Override 10398 String getCodePath() { 10399 return packagePath; 10400 } 10401 10402 @Override 10403 String getResourcePath() { 10404 return resourcePath; 10405 } 10406 10407 @Override 10408 String getLegacyNativeLibraryPath() { 10409 return legacyNativeLibraryDir; 10410 } 10411 10412 int doPreInstall(int status) { 10413 if (status != PackageManager.INSTALL_SUCCEEDED) { 10414 // Destroy container 10415 PackageHelper.destroySdDir(cid); 10416 } else { 10417 boolean mounted = PackageHelper.isContainerMounted(cid); 10418 if (!mounted) { 10419 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10420 Process.SYSTEM_UID); 10421 if (newMountPath != null) { 10422 setMountPath(newMountPath); 10423 } else { 10424 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10425 } 10426 } 10427 } 10428 return status; 10429 } 10430 10431 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10432 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10433 String newMountPath = null; 10434 if (PackageHelper.isContainerMounted(cid)) { 10435 // Unmount the container 10436 if (!PackageHelper.unMountSdDir(cid)) { 10437 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10438 return false; 10439 } 10440 } 10441 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10442 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10443 " which might be stale. Will try to clean up."); 10444 // Clean up the stale container and proceed to recreate. 10445 if (!PackageHelper.destroySdDir(newCacheId)) { 10446 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10447 return false; 10448 } 10449 // Successfully cleaned up stale container. Try to rename again. 10450 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10451 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10452 + " inspite of cleaning it up."); 10453 return false; 10454 } 10455 } 10456 if (!PackageHelper.isContainerMounted(newCacheId)) { 10457 Slog.w(TAG, "Mounting container " + newCacheId); 10458 newMountPath = PackageHelper.mountSdDir(newCacheId, 10459 getEncryptKey(), Process.SYSTEM_UID); 10460 } else { 10461 newMountPath = PackageHelper.getSdDir(newCacheId); 10462 } 10463 if (newMountPath == null) { 10464 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10465 return false; 10466 } 10467 Log.i(TAG, "Succesfully renamed " + cid + 10468 " to " + newCacheId + 10469 " at new path: " + newMountPath); 10470 cid = newCacheId; 10471 10472 final File beforeCodeFile = new File(packagePath); 10473 setMountPath(newMountPath); 10474 final File afterCodeFile = new File(packagePath); 10475 10476 // Reflect the rename in scanned details 10477 pkg.codePath = afterCodeFile.getAbsolutePath(); 10478 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10479 pkg.baseCodePath); 10480 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10481 pkg.splitCodePaths); 10482 10483 // Reflect the rename in app info 10484 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10485 pkg.applicationInfo.setCodePath(pkg.codePath); 10486 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10487 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10488 pkg.applicationInfo.setResourcePath(pkg.codePath); 10489 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10490 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10491 10492 return true; 10493 } 10494 10495 private void setMountPath(String mountPath) { 10496 final File mountFile = new File(mountPath); 10497 10498 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10499 if (monolithicFile.exists()) { 10500 packagePath = monolithicFile.getAbsolutePath(); 10501 if (isFwdLocked()) { 10502 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10503 } else { 10504 resourcePath = packagePath; 10505 } 10506 } else { 10507 packagePath = mountFile.getAbsolutePath(); 10508 resourcePath = packagePath; 10509 } 10510 10511 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 10512 } 10513 10514 int doPostInstall(int status, int uid) { 10515 if (status != PackageManager.INSTALL_SUCCEEDED) { 10516 cleanUp(); 10517 } else { 10518 final int groupOwner; 10519 final String protectedFile; 10520 if (isFwdLocked()) { 10521 groupOwner = UserHandle.getSharedAppGid(uid); 10522 protectedFile = RES_FILE_NAME; 10523 } else { 10524 groupOwner = -1; 10525 protectedFile = null; 10526 } 10527 10528 if (uid < Process.FIRST_APPLICATION_UID 10529 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10530 Slog.e(TAG, "Failed to finalize " + cid); 10531 PackageHelper.destroySdDir(cid); 10532 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10533 } 10534 10535 boolean mounted = PackageHelper.isContainerMounted(cid); 10536 if (!mounted) { 10537 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10538 } 10539 } 10540 return status; 10541 } 10542 10543 private void cleanUp() { 10544 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10545 10546 // Destroy secure container 10547 PackageHelper.destroySdDir(cid); 10548 } 10549 10550 private List<String> getAllCodePaths() { 10551 final File codeFile = new File(getCodePath()); 10552 if (codeFile != null && codeFile.exists()) { 10553 try { 10554 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10555 return pkg.getAllCodePaths(); 10556 } catch (PackageParserException e) { 10557 // Ignored; we tried our best 10558 } 10559 } 10560 return Collections.EMPTY_LIST; 10561 } 10562 10563 void cleanUpResourcesLI() { 10564 // Enumerate all code paths before deleting 10565 cleanUpResourcesLI(getAllCodePaths()); 10566 } 10567 10568 private void cleanUpResourcesLI(List<String> allCodePaths) { 10569 cleanUp(); 10570 removeDexFiles(allCodePaths, instructionSets); 10571 } 10572 10573 10574 10575 String getPackageName() { 10576 return getAsecPackageName(cid); 10577 } 10578 10579 boolean doPostDeleteLI(boolean delete) { 10580 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10581 final List<String> allCodePaths = getAllCodePaths(); 10582 boolean mounted = PackageHelper.isContainerMounted(cid); 10583 if (mounted) { 10584 // Unmount first 10585 if (PackageHelper.unMountSdDir(cid)) { 10586 mounted = false; 10587 } 10588 } 10589 if (!mounted && delete) { 10590 cleanUpResourcesLI(allCodePaths); 10591 } 10592 return !mounted; 10593 } 10594 10595 @Override 10596 int doPreCopy() { 10597 if (isFwdLocked()) { 10598 if (!PackageHelper.fixSdPermissions(cid, 10599 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10600 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10601 } 10602 } 10603 10604 return PackageManager.INSTALL_SUCCEEDED; 10605 } 10606 10607 @Override 10608 int doPostCopy(int uid) { 10609 if (isFwdLocked()) { 10610 if (uid < Process.FIRST_APPLICATION_UID 10611 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10612 RES_FILE_NAME)) { 10613 Slog.e(TAG, "Failed to finalize " + cid); 10614 PackageHelper.destroySdDir(cid); 10615 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10616 } 10617 } 10618 10619 return PackageManager.INSTALL_SUCCEEDED; 10620 } 10621 } 10622 10623 static String getAsecPackageName(String packageCid) { 10624 int idx = packageCid.lastIndexOf("-"); 10625 if (idx == -1) { 10626 return packageCid; 10627 } 10628 return packageCid.substring(0, idx); 10629 } 10630 10631 // Utility method used to create code paths based on package name and available index. 10632 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10633 String idxStr = ""; 10634 int idx = 1; 10635 // Fall back to default value of idx=1 if prefix is not 10636 // part of oldCodePath 10637 if (oldCodePath != null) { 10638 String subStr = oldCodePath; 10639 // Drop the suffix right away 10640 if (suffix != null && subStr.endsWith(suffix)) { 10641 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10642 } 10643 // If oldCodePath already contains prefix find out the 10644 // ending index to either increment or decrement. 10645 int sidx = subStr.lastIndexOf(prefix); 10646 if (sidx != -1) { 10647 subStr = subStr.substring(sidx + prefix.length()); 10648 if (subStr != null) { 10649 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10650 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10651 } 10652 try { 10653 idx = Integer.parseInt(subStr); 10654 if (idx <= 1) { 10655 idx++; 10656 } else { 10657 idx--; 10658 } 10659 } catch(NumberFormatException e) { 10660 } 10661 } 10662 } 10663 } 10664 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10665 return prefix + idxStr; 10666 } 10667 10668 private File getNextCodePath(File targetDir, String packageName) { 10669 int suffix = 1; 10670 File result; 10671 do { 10672 result = new File(targetDir, packageName + "-" + suffix); 10673 suffix++; 10674 } while (result.exists()); 10675 return result; 10676 } 10677 10678 // Utility method that returns the relative package path with respect 10679 // to the installation directory. Like say for /data/data/com.test-1.apk 10680 // string com.test-1 is returned. 10681 static String deriveCodePathName(String codePath) { 10682 if (codePath == null) { 10683 return null; 10684 } 10685 final File codeFile = new File(codePath); 10686 final String name = codeFile.getName(); 10687 if (codeFile.isDirectory()) { 10688 return name; 10689 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10690 final int lastDot = name.lastIndexOf('.'); 10691 return name.substring(0, lastDot); 10692 } else { 10693 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10694 return null; 10695 } 10696 } 10697 10698 class PackageInstalledInfo { 10699 String name; 10700 int uid; 10701 // The set of users that originally had this package installed. 10702 int[] origUsers; 10703 // The set of users that now have this package installed. 10704 int[] newUsers; 10705 PackageParser.Package pkg; 10706 int returnCode; 10707 String returnMsg; 10708 PackageRemovedInfo removedInfo; 10709 10710 public void setError(int code, String msg) { 10711 returnCode = code; 10712 returnMsg = msg; 10713 Slog.w(TAG, msg); 10714 } 10715 10716 public void setError(String msg, PackageParserException e) { 10717 returnCode = e.error; 10718 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10719 Slog.w(TAG, msg, e); 10720 } 10721 10722 public void setError(String msg, PackageManagerException e) { 10723 returnCode = e.error; 10724 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10725 Slog.w(TAG, msg, e); 10726 } 10727 10728 // In some error cases we want to convey more info back to the observer 10729 String origPackage; 10730 String origPermission; 10731 } 10732 10733 /* 10734 * Install a non-existing package. 10735 */ 10736 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10737 UserHandle user, String installerPackageName, String volumeUuid, 10738 PackageInstalledInfo res) { 10739 // Remember this for later, in case we need to rollback this install 10740 String pkgName = pkg.packageName; 10741 10742 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10743 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10744 UserHandle.USER_OWNER).exists(); 10745 synchronized(mPackages) { 10746 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10747 // A package with the same name is already installed, though 10748 // it has been renamed to an older name. The package we 10749 // are trying to install should be installed as an update to 10750 // the existing one, but that has not been requested, so bail. 10751 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10752 + " without first uninstalling package running as " 10753 + mSettings.mRenamedPackages.get(pkgName)); 10754 return; 10755 } 10756 if (mPackages.containsKey(pkgName)) { 10757 // Don't allow installation over an existing package with the same name. 10758 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10759 + " without first uninstalling."); 10760 return; 10761 } 10762 } 10763 10764 try { 10765 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10766 System.currentTimeMillis(), user); 10767 10768 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10769 // delete the partially installed application. the data directory will have to be 10770 // restored if it was already existing 10771 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10772 // remove package from internal structures. Note that we want deletePackageX to 10773 // delete the package data and cache directories that it created in 10774 // scanPackageLocked, unless those directories existed before we even tried to 10775 // install. 10776 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10777 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10778 res.removedInfo, true); 10779 } 10780 10781 } catch (PackageManagerException e) { 10782 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10783 } 10784 } 10785 10786 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10787 // Upgrade keysets are being used. Determine if new package has a superset of the 10788 // required keys. 10789 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10791 for (int i = 0; i < upgradeKeySets.length; i++) { 10792 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10793 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10794 return true; 10795 } 10796 } 10797 return false; 10798 } 10799 10800 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10801 UserHandle user, String installerPackageName, String volumeUuid, 10802 PackageInstalledInfo res) { 10803 PackageParser.Package oldPackage; 10804 String pkgName = pkg.packageName; 10805 int[] allUsers; 10806 boolean[] perUserInstalled; 10807 10808 // First find the old package info and check signatures 10809 synchronized(mPackages) { 10810 oldPackage = mPackages.get(pkgName); 10811 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10812 PackageSetting ps = mSettings.mPackages.get(pkgName); 10813 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10814 // default to original signature matching 10815 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10816 != PackageManager.SIGNATURE_MATCH) { 10817 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10818 "New package has a different signature: " + pkgName); 10819 return; 10820 } 10821 } else { 10822 if(!checkUpgradeKeySetLP(ps, pkg)) { 10823 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10824 "New package not signed by keys specified by upgrade-keysets: " 10825 + pkgName); 10826 return; 10827 } 10828 } 10829 10830 // In case of rollback, remember per-user/profile install state 10831 allUsers = sUserManager.getUserIds(); 10832 perUserInstalled = new boolean[allUsers.length]; 10833 for (int i = 0; i < allUsers.length; i++) { 10834 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10835 } 10836 } 10837 10838 boolean sysPkg = (isSystemApp(oldPackage)); 10839 if (sysPkg) { 10840 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10841 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10842 } else { 10843 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10844 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10845 } 10846 } 10847 10848 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10849 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10850 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10851 String volumeUuid, PackageInstalledInfo res) { 10852 String pkgName = deletedPackage.packageName; 10853 boolean deletedPkg = true; 10854 boolean updatedSettings = false; 10855 10856 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10857 + deletedPackage); 10858 long origUpdateTime; 10859 if (pkg.mExtras != null) { 10860 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10861 } else { 10862 origUpdateTime = 0; 10863 } 10864 10865 // First delete the existing package while retaining the data directory 10866 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10867 res.removedInfo, true)) { 10868 // If the existing package wasn't successfully deleted 10869 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10870 deletedPkg = false; 10871 } else { 10872 // Successfully deleted the old package; proceed with replace. 10873 10874 // If deleted package lived in a container, give users a chance to 10875 // relinquish resources before killing. 10876 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10877 if (DEBUG_INSTALL) { 10878 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10879 } 10880 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10881 final ArrayList<String> pkgList = new ArrayList<String>(1); 10882 pkgList.add(deletedPackage.applicationInfo.packageName); 10883 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10884 } 10885 10886 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 10887 try { 10888 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10889 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10890 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 10891 perUserInstalled, res, user); 10892 updatedSettings = true; 10893 } catch (PackageManagerException e) { 10894 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10895 } 10896 } 10897 10898 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10899 // remove package from internal structures. Note that we want deletePackageX to 10900 // delete the package data and cache directories that it created in 10901 // scanPackageLocked, unless those directories existed before we even tried to 10902 // install. 10903 if(updatedSettings) { 10904 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10905 deletePackageLI( 10906 pkgName, null, true, allUsers, perUserInstalled, 10907 PackageManager.DELETE_KEEP_DATA, 10908 res.removedInfo, true); 10909 } 10910 // Since we failed to install the new package we need to restore the old 10911 // package that we deleted. 10912 if (deletedPkg) { 10913 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10914 File restoreFile = new File(deletedPackage.codePath); 10915 // Parse old package 10916 boolean oldExternal = isExternal(deletedPackage); 10917 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10918 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10919 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 10920 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10921 try { 10922 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10923 } catch (PackageManagerException e) { 10924 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10925 + e.getMessage()); 10926 return; 10927 } 10928 // Restore of old package succeeded. Update permissions. 10929 // writer 10930 synchronized (mPackages) { 10931 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10932 UPDATE_PERMISSIONS_ALL); 10933 // can downgrade to reader 10934 mSettings.writeLPr(); 10935 } 10936 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10937 } 10938 } 10939 } 10940 10941 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10942 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10943 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10944 String volumeUuid, PackageInstalledInfo res) { 10945 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10946 + ", old=" + deletedPackage); 10947 boolean disabledSystem = false; 10948 boolean updatedSettings = false; 10949 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10950 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10951 != 0) { 10952 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10953 } 10954 String packageName = deletedPackage.packageName; 10955 if (packageName == null) { 10956 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10957 "Attempt to delete null packageName."); 10958 return; 10959 } 10960 PackageParser.Package oldPkg; 10961 PackageSetting oldPkgSetting; 10962 // reader 10963 synchronized (mPackages) { 10964 oldPkg = mPackages.get(packageName); 10965 oldPkgSetting = mSettings.mPackages.get(packageName); 10966 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10967 (oldPkgSetting == null)) { 10968 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10969 "Couldn't find package:" + packageName + " information"); 10970 return; 10971 } 10972 } 10973 10974 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10975 10976 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10977 res.removedInfo.removedPackage = packageName; 10978 // Remove existing system package 10979 removePackageLI(oldPkgSetting, true); 10980 // writer 10981 synchronized (mPackages) { 10982 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10983 if (!disabledSystem && deletedPackage != null) { 10984 // We didn't need to disable the .apk as a current system package, 10985 // which means we are replacing another update that is already 10986 // installed. We need to make sure to delete the older one's .apk. 10987 res.removedInfo.args = createInstallArgsForExisting(0, 10988 deletedPackage.applicationInfo.getCodePath(), 10989 deletedPackage.applicationInfo.getResourcePath(), 10990 deletedPackage.applicationInfo.nativeLibraryRootDir, 10991 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10992 } else { 10993 res.removedInfo.args = null; 10994 } 10995 } 10996 10997 // Successfully disabled the old package. Now proceed with re-installation 10998 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 10999 11000 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11001 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11002 11003 PackageParser.Package newPackage = null; 11004 try { 11005 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11006 if (newPackage.mExtras != null) { 11007 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11008 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11009 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11010 11011 // is the update attempting to change shared user? that isn't going to work... 11012 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11013 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11014 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11015 + " to " + newPkgSetting.sharedUser); 11016 updatedSettings = true; 11017 } 11018 } 11019 11020 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11021 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11022 perUserInstalled, res, user); 11023 updatedSettings = true; 11024 } 11025 11026 } catch (PackageManagerException e) { 11027 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11028 } 11029 11030 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11031 // Re installation failed. Restore old information 11032 // Remove new pkg information 11033 if (newPackage != null) { 11034 removeInstalledPackageLI(newPackage, true); 11035 } 11036 // Add back the old system package 11037 try { 11038 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11039 } catch (PackageManagerException e) { 11040 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11041 } 11042 // Restore the old system information in Settings 11043 synchronized (mPackages) { 11044 if (disabledSystem) { 11045 mSettings.enableSystemPackageLPw(packageName); 11046 } 11047 if (updatedSettings) { 11048 mSettings.setInstallerPackageName(packageName, 11049 oldPkgSetting.installerPackageName); 11050 } 11051 mSettings.writeLPr(); 11052 } 11053 } 11054 } 11055 11056 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11057 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11058 UserHandle user) { 11059 String pkgName = newPackage.packageName; 11060 synchronized (mPackages) { 11061 //write settings. the installStatus will be incomplete at this stage. 11062 //note that the new package setting would have already been 11063 //added to mPackages. It hasn't been persisted yet. 11064 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11065 mSettings.writeLPr(); 11066 } 11067 11068 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11069 11070 synchronized (mPackages) { 11071 updatePermissionsLPw(newPackage.packageName, newPackage, 11072 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11073 ? UPDATE_PERMISSIONS_ALL : 0)); 11074 // For system-bundled packages, we assume that installing an upgraded version 11075 // of the package implies that the user actually wants to run that new code, 11076 // so we enable the package. 11077 PackageSetting ps = mSettings.mPackages.get(pkgName); 11078 if (ps != null) { 11079 if (isSystemApp(newPackage)) { 11080 // NB: implicit assumption that system package upgrades apply to all users 11081 if (DEBUG_INSTALL) { 11082 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11083 } 11084 if (res.origUsers != null) { 11085 for (int userHandle : res.origUsers) { 11086 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11087 userHandle, installerPackageName); 11088 } 11089 } 11090 // Also convey the prior install/uninstall state 11091 if (allUsers != null && perUserInstalled != null) { 11092 for (int i = 0; i < allUsers.length; i++) { 11093 if (DEBUG_INSTALL) { 11094 Slog.d(TAG, " user " + allUsers[i] 11095 + " => " + perUserInstalled[i]); 11096 } 11097 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11098 } 11099 // these install state changes will be persisted in the 11100 // upcoming call to mSettings.writeLPr(). 11101 } 11102 } 11103 // It's implied that when a user requests installation, they want the app to be 11104 // installed and enabled. 11105 int userId = user.getIdentifier(); 11106 if (userId != UserHandle.USER_ALL) { 11107 ps.setInstalled(true, userId); 11108 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11109 } 11110 } 11111 res.name = pkgName; 11112 res.uid = newPackage.applicationInfo.uid; 11113 res.pkg = newPackage; 11114 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11115 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11116 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11117 //to update install status 11118 mSettings.writeLPr(); 11119 } 11120 } 11121 11122 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11123 final int installFlags = args.installFlags; 11124 final String installerPackageName = args.installerPackageName; 11125 final String volumeUuid = args.volumeUuid; 11126 final File tmpPackageFile = new File(args.getCodePath()); 11127 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11128 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11129 || (args.volumeUuid != null)); 11130 boolean replace = false; 11131 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11132 // Result object to be returned 11133 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11134 11135 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11136 // Retrieve PackageSettings and parse package 11137 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11138 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11139 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11140 PackageParser pp = new PackageParser(); 11141 pp.setSeparateProcesses(mSeparateProcesses); 11142 pp.setDisplayMetrics(mMetrics); 11143 11144 final PackageParser.Package pkg; 11145 try { 11146 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11147 } catch (PackageParserException e) { 11148 res.setError("Failed parse during installPackageLI", e); 11149 return; 11150 } 11151 11152 // Mark that we have an install time CPU ABI override. 11153 pkg.cpuAbiOverride = args.abiOverride; 11154 11155 String pkgName = res.name = pkg.packageName; 11156 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11157 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11158 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11159 return; 11160 } 11161 } 11162 11163 try { 11164 pp.collectCertificates(pkg, parseFlags); 11165 pp.collectManifestDigest(pkg); 11166 } catch (PackageParserException e) { 11167 res.setError("Failed collect during installPackageLI", e); 11168 return; 11169 } 11170 11171 /* If the installer passed in a manifest digest, compare it now. */ 11172 if (args.manifestDigest != null) { 11173 if (DEBUG_INSTALL) { 11174 final String parsedManifest = pkg.manifestDigest == null ? "null" 11175 : pkg.manifestDigest.toString(); 11176 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11177 + parsedManifest); 11178 } 11179 11180 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11181 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11182 return; 11183 } 11184 } else if (DEBUG_INSTALL) { 11185 final String parsedManifest = pkg.manifestDigest == null 11186 ? "null" : pkg.manifestDigest.toString(); 11187 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11188 } 11189 11190 // Get rid of all references to package scan path via parser. 11191 pp = null; 11192 String oldCodePath = null; 11193 boolean systemApp = false; 11194 synchronized (mPackages) { 11195 // Check if installing already existing package 11196 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11197 String oldName = mSettings.mRenamedPackages.get(pkgName); 11198 if (pkg.mOriginalPackages != null 11199 && pkg.mOriginalPackages.contains(oldName) 11200 && mPackages.containsKey(oldName)) { 11201 // This package is derived from an original package, 11202 // and this device has been updating from that original 11203 // name. We must continue using the original name, so 11204 // rename the new package here. 11205 pkg.setPackageName(oldName); 11206 pkgName = pkg.packageName; 11207 replace = true; 11208 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11209 + oldName + " pkgName=" + pkgName); 11210 } else if (mPackages.containsKey(pkgName)) { 11211 // This package, under its official name, already exists 11212 // on the device; we should replace it. 11213 replace = true; 11214 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11215 } 11216 } 11217 11218 PackageSetting ps = mSettings.mPackages.get(pkgName); 11219 if (ps != null) { 11220 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11221 11222 // Quick sanity check that we're signed correctly if updating; 11223 // we'll check this again later when scanning, but we want to 11224 // bail early here before tripping over redefined permissions. 11225 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11226 try { 11227 verifySignaturesLP(ps, pkg); 11228 } catch (PackageManagerException e) { 11229 res.setError(e.error, e.getMessage()); 11230 return; 11231 } 11232 } else { 11233 if (!checkUpgradeKeySetLP(ps, pkg)) { 11234 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11235 + pkg.packageName + " upgrade keys do not match the " 11236 + "previously installed version"); 11237 return; 11238 } 11239 } 11240 11241 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11242 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11243 systemApp = (ps.pkg.applicationInfo.flags & 11244 ApplicationInfo.FLAG_SYSTEM) != 0; 11245 } 11246 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11247 } 11248 11249 // Check whether the newly-scanned package wants to define an already-defined perm 11250 int N = pkg.permissions.size(); 11251 for (int i = N-1; i >= 0; i--) { 11252 PackageParser.Permission perm = pkg.permissions.get(i); 11253 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11254 if (bp != null) { 11255 // If the defining package is signed with our cert, it's okay. This 11256 // also includes the "updating the same package" case, of course. 11257 // "updating same package" could also involve key-rotation. 11258 final boolean sigsOk; 11259 if (!bp.sourcePackage.equals(pkg.packageName) 11260 || !(bp.packageSetting instanceof PackageSetting) 11261 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11262 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11263 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11264 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11265 } else { 11266 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11267 } 11268 if (!sigsOk) { 11269 // If the owning package is the system itself, we log but allow 11270 // install to proceed; we fail the install on all other permission 11271 // redefinitions. 11272 if (!bp.sourcePackage.equals("android")) { 11273 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11274 + pkg.packageName + " attempting to redeclare permission " 11275 + perm.info.name + " already owned by " + bp.sourcePackage); 11276 res.origPermission = perm.info.name; 11277 res.origPackage = bp.sourcePackage; 11278 return; 11279 } else { 11280 Slog.w(TAG, "Package " + pkg.packageName 11281 + " attempting to redeclare system permission " 11282 + perm.info.name + "; ignoring new declaration"); 11283 pkg.permissions.remove(i); 11284 } 11285 } 11286 } 11287 } 11288 11289 } 11290 11291 if (systemApp && onExternal) { 11292 // Disable updates to system apps on sdcard 11293 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11294 "Cannot install updates to system apps on sdcard"); 11295 return; 11296 } 11297 11298 // If app directory is not writable, dexopt will be called after the rename 11299 if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11300 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11301 scanFlags |= SCAN_NO_DEX; 11302 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11303 int result = mPackageDexOptimizer 11304 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11305 false /* defer */, false /* inclDependencies */); 11306 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11307 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11308 return; 11309 } 11310 } 11311 11312 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11313 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11314 return; 11315 } 11316 11317 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11318 11319 if (replace) { 11320 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 11321 installerPackageName, volumeUuid, res); 11322 } else { 11323 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11324 args.user, installerPackageName, volumeUuid, res); 11325 } 11326 synchronized (mPackages) { 11327 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11328 if (ps != null) { 11329 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11330 } 11331 } 11332 } 11333 11334 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11335 if (mIntentFilterVerifierComponent == null) { 11336 Slog.d(TAG, "No IntentFilter verification will not be done as " 11337 + "there is no IntentFilterVerifier available!"); 11338 return; 11339 } 11340 11341 final int verifierUid = getPackageUid( 11342 mIntentFilterVerifierComponent.getPackageName(), 11343 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11344 11345 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11346 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11347 msg.obj = pkg; 11348 msg.arg1 = userId; 11349 msg.arg2 = verifierUid; 11350 11351 mHandler.sendMessage(msg); 11352 } 11353 11354 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11355 PackageParser.Package pkg) { 11356 int size = pkg.activities.size(); 11357 if (size == 0) { 11358 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11359 return; 11360 } 11361 11362 final boolean hasDomainURLs = hasDomainURLs(pkg); 11363 if (!hasDomainURLs) { 11364 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11365 return; 11366 } 11367 11368 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11369 + " Activities needs verification ..."); 11370 11371 final int verificationId = mIntentFilterVerificationToken++; 11372 int count = 0; 11373 final String packageName = pkg.packageName; 11374 ArrayList<String> allHosts = new ArrayList<>(); 11375 11376 synchronized (mPackages) { 11377 for (PackageParser.Activity a : pkg.activities) { 11378 for (ActivityIntentInfo filter : a.intents) { 11379 boolean needsFilterVerification = filter.needsVerification(); 11380 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11381 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11382 mIntentFilterVerifier.addOneIntentFilterVerification( 11383 verifierUid, userId, verificationId, filter, packageName); 11384 count++; 11385 } else if (!needsFilterVerification) { 11386 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11387 if (hasValidDomains(filter)) { 11388 ArrayList<String> hosts = filter.getHostsList(); 11389 if (hosts.size() > 0) { 11390 allHosts.addAll(hosts); 11391 } else { 11392 if (allHosts.isEmpty()) { 11393 allHosts.add("*"); 11394 } 11395 } 11396 } 11397 } else { 11398 Slog.d(TAG, "Verification already done for IntentFilter:" 11399 + filter.toString()); 11400 } 11401 } 11402 } 11403 } 11404 11405 if (count > 0) { 11406 mIntentFilterVerifier.startVerifications(userId); 11407 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11408 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11409 } else { 11410 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11411 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11412 packageName, allHosts) != null) { 11413 scheduleWriteSettingsLocked(); 11414 } 11415 } 11416 } 11417 11418 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11419 final ComponentName cn = filter.activity.getComponentName(); 11420 final String packageName = cn.getPackageName(); 11421 11422 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11423 packageName); 11424 if (ivi == null) { 11425 return true; 11426 } 11427 int status = ivi.getStatus(); 11428 switch (status) { 11429 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11430 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11431 return true; 11432 11433 default: 11434 // Nothing to do 11435 return false; 11436 } 11437 } 11438 11439 private static boolean isMultiArch(PackageSetting ps) { 11440 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11441 } 11442 11443 private static boolean isMultiArch(ApplicationInfo info) { 11444 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11445 } 11446 11447 private static boolean isExternal(PackageParser.Package pkg) { 11448 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11449 } 11450 11451 private static boolean isExternal(PackageSetting ps) { 11452 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11453 } 11454 11455 private static boolean isExternal(ApplicationInfo info) { 11456 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11457 } 11458 11459 private static boolean isSystemApp(PackageParser.Package pkg) { 11460 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11461 } 11462 11463 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11464 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11465 } 11466 11467 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11468 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11469 } 11470 11471 private static boolean isSystemApp(PackageSetting ps) { 11472 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11473 } 11474 11475 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11476 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11477 } 11478 11479 private int packageFlagsToInstallFlags(PackageSetting ps) { 11480 int installFlags = 0; 11481 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11482 // This existing package was an external ASEC install when we have 11483 // the external flag without a UUID 11484 installFlags |= PackageManager.INSTALL_EXTERNAL; 11485 } 11486 if (ps.isForwardLocked()) { 11487 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11488 } 11489 return installFlags; 11490 } 11491 11492 private void deleteTempPackageFiles() { 11493 final FilenameFilter filter = new FilenameFilter() { 11494 public boolean accept(File dir, String name) { 11495 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11496 } 11497 }; 11498 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11499 file.delete(); 11500 } 11501 } 11502 11503 @Override 11504 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11505 int flags) { 11506 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11507 flags); 11508 } 11509 11510 @Override 11511 public void deletePackage(final String packageName, 11512 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11513 mContext.enforceCallingOrSelfPermission( 11514 android.Manifest.permission.DELETE_PACKAGES, null); 11515 final int uid = Binder.getCallingUid(); 11516 if (UserHandle.getUserId(uid) != userId) { 11517 mContext.enforceCallingPermission( 11518 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11519 "deletePackage for user " + userId); 11520 } 11521 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11522 try { 11523 observer.onPackageDeleted(packageName, 11524 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11525 } catch (RemoteException re) { 11526 } 11527 return; 11528 } 11529 11530 boolean uninstallBlocked = false; 11531 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11532 int[] users = sUserManager.getUserIds(); 11533 for (int i = 0; i < users.length; ++i) { 11534 if (getBlockUninstallForUser(packageName, users[i])) { 11535 uninstallBlocked = true; 11536 break; 11537 } 11538 } 11539 } else { 11540 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11541 } 11542 if (uninstallBlocked) { 11543 try { 11544 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11545 null); 11546 } catch (RemoteException re) { 11547 } 11548 return; 11549 } 11550 11551 if (DEBUG_REMOVE) { 11552 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11553 } 11554 // Queue up an async operation since the package deletion may take a little while. 11555 mHandler.post(new Runnable() { 11556 public void run() { 11557 mHandler.removeCallbacks(this); 11558 final int returnCode = deletePackageX(packageName, userId, flags); 11559 if (observer != null) { 11560 try { 11561 observer.onPackageDeleted(packageName, returnCode, null); 11562 } catch (RemoteException e) { 11563 Log.i(TAG, "Observer no longer exists."); 11564 } //end catch 11565 } //end if 11566 } //end run 11567 }); 11568 } 11569 11570 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11571 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11572 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11573 try { 11574 if (dpm != null) { 11575 if (dpm.isDeviceOwner(packageName)) { 11576 return true; 11577 } 11578 int[] users; 11579 if (userId == UserHandle.USER_ALL) { 11580 users = sUserManager.getUserIds(); 11581 } else { 11582 users = new int[]{userId}; 11583 } 11584 for (int i = 0; i < users.length; ++i) { 11585 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11586 return true; 11587 } 11588 } 11589 } 11590 } catch (RemoteException e) { 11591 } 11592 return false; 11593 } 11594 11595 /** 11596 * This method is an internal method that could be get invoked either 11597 * to delete an installed package or to clean up a failed installation. 11598 * After deleting an installed package, a broadcast is sent to notify any 11599 * listeners that the package has been installed. For cleaning up a failed 11600 * installation, the broadcast is not necessary since the package's 11601 * installation wouldn't have sent the initial broadcast either 11602 * The key steps in deleting a package are 11603 * deleting the package information in internal structures like mPackages, 11604 * deleting the packages base directories through installd 11605 * updating mSettings to reflect current status 11606 * persisting settings for later use 11607 * sending a broadcast if necessary 11608 */ 11609 private int deletePackageX(String packageName, int userId, int flags) { 11610 final PackageRemovedInfo info = new PackageRemovedInfo(); 11611 final boolean res; 11612 11613 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11614 ? UserHandle.ALL : new UserHandle(userId); 11615 11616 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11617 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11618 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11619 } 11620 11621 boolean removedForAllUsers = false; 11622 boolean systemUpdate = false; 11623 11624 // for the uninstall-updates case and restricted profiles, remember the per- 11625 // userhandle installed state 11626 int[] allUsers; 11627 boolean[] perUserInstalled; 11628 synchronized (mPackages) { 11629 PackageSetting ps = mSettings.mPackages.get(packageName); 11630 allUsers = sUserManager.getUserIds(); 11631 perUserInstalled = new boolean[allUsers.length]; 11632 for (int i = 0; i < allUsers.length; i++) { 11633 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11634 } 11635 } 11636 11637 synchronized (mInstallLock) { 11638 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11639 res = deletePackageLI(packageName, removeForUser, 11640 true, allUsers, perUserInstalled, 11641 flags | REMOVE_CHATTY, info, true); 11642 systemUpdate = info.isRemovedPackageSystemUpdate; 11643 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11644 removedForAllUsers = true; 11645 } 11646 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11647 + " removedForAllUsers=" + removedForAllUsers); 11648 } 11649 11650 if (res) { 11651 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11652 11653 // If the removed package was a system update, the old system package 11654 // was re-enabled; we need to broadcast this information 11655 if (systemUpdate) { 11656 Bundle extras = new Bundle(1); 11657 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11658 ? info.removedAppId : info.uid); 11659 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11660 11661 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11662 extras, null, null, null); 11663 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11664 extras, null, null, null); 11665 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11666 null, packageName, null, null); 11667 } 11668 } 11669 // Force a gc here. 11670 Runtime.getRuntime().gc(); 11671 // Delete the resources here after sending the broadcast to let 11672 // other processes clean up before deleting resources. 11673 if (info.args != null) { 11674 synchronized (mInstallLock) { 11675 info.args.doPostDeleteLI(true); 11676 } 11677 } 11678 11679 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11680 } 11681 11682 static class PackageRemovedInfo { 11683 String removedPackage; 11684 int uid = -1; 11685 int removedAppId = -1; 11686 int[] removedUsers = null; 11687 boolean isRemovedPackageSystemUpdate = false; 11688 // Clean up resources deleted packages. 11689 InstallArgs args = null; 11690 11691 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11692 Bundle extras = new Bundle(1); 11693 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11694 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11695 if (replacing) { 11696 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11697 } 11698 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11699 if (removedPackage != null) { 11700 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11701 extras, null, null, removedUsers); 11702 if (fullRemove && !replacing) { 11703 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11704 extras, null, null, removedUsers); 11705 } 11706 } 11707 if (removedAppId >= 0) { 11708 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11709 removedUsers); 11710 } 11711 } 11712 } 11713 11714 /* 11715 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11716 * flag is not set, the data directory is removed as well. 11717 * make sure this flag is set for partially installed apps. If not its meaningless to 11718 * delete a partially installed application. 11719 */ 11720 private void removePackageDataLI(PackageSetting ps, 11721 int[] allUserHandles, boolean[] perUserInstalled, 11722 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11723 String packageName = ps.name; 11724 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11725 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11726 // Retrieve object to delete permissions for shared user later on 11727 final PackageSetting deletedPs; 11728 // reader 11729 synchronized (mPackages) { 11730 deletedPs = mSettings.mPackages.get(packageName); 11731 if (outInfo != null) { 11732 outInfo.removedPackage = packageName; 11733 outInfo.removedUsers = deletedPs != null 11734 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11735 : null; 11736 } 11737 } 11738 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11739 removeDataDirsLI(ps.volumeUuid, packageName); 11740 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11741 } 11742 // writer 11743 synchronized (mPackages) { 11744 if (deletedPs != null) { 11745 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11746 if (outInfo != null) { 11747 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11748 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11749 } 11750 updatePermissionsLPw(deletedPs.name, null, 0); 11751 if (deletedPs.sharedUser != null) { 11752 // Remove permissions associated with package. Since runtime 11753 // permissions are per user we have to kill the removed package 11754 // or packages running under the shared user of the removed 11755 // package if revoking the permissions requested only by the removed 11756 // package is successful and this causes a change in gids. 11757 for (int userId : UserManagerService.getInstance().getUserIds()) { 11758 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11759 userId); 11760 if (userIdToKill == UserHandle.USER_ALL 11761 || userIdToKill >= UserHandle.USER_OWNER) { 11762 // If gids changed for this user, kill all affected packages. 11763 mHandler.post(new Runnable() { 11764 @Override 11765 public void run() { 11766 // This has to happen with no lock held. 11767 killSettingPackagesForUser(deletedPs, userIdToKill, 11768 KILL_APP_REASON_GIDS_CHANGED); 11769 } 11770 }); 11771 break; 11772 } 11773 } 11774 } 11775 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11776 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11777 } 11778 // make sure to preserve per-user disabled state if this removal was just 11779 // a downgrade of a system app to the factory package 11780 if (allUserHandles != null && perUserInstalled != null) { 11781 if (DEBUG_REMOVE) { 11782 Slog.d(TAG, "Propagating install state across downgrade"); 11783 } 11784 for (int i = 0; i < allUserHandles.length; i++) { 11785 if (DEBUG_REMOVE) { 11786 Slog.d(TAG, " user " + allUserHandles[i] 11787 + " => " + perUserInstalled[i]); 11788 } 11789 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11790 } 11791 } 11792 } 11793 // can downgrade to reader 11794 if (writeSettings) { 11795 // Save settings now 11796 mSettings.writeLPr(); 11797 } 11798 } 11799 if (outInfo != null) { 11800 // A user ID was deleted here. Go through all users and remove it 11801 // from KeyStore. 11802 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11803 } 11804 } 11805 11806 static boolean locationIsPrivileged(File path) { 11807 try { 11808 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11809 .getCanonicalPath(); 11810 return path.getCanonicalPath().startsWith(privilegedAppDir); 11811 } catch (IOException e) { 11812 Slog.e(TAG, "Unable to access code path " + path); 11813 } 11814 return false; 11815 } 11816 11817 /* 11818 * Tries to delete system package. 11819 */ 11820 private boolean deleteSystemPackageLI(PackageSetting newPs, 11821 int[] allUserHandles, boolean[] perUserInstalled, 11822 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11823 final boolean applyUserRestrictions 11824 = (allUserHandles != null) && (perUserInstalled != null); 11825 PackageSetting disabledPs = null; 11826 // Confirm if the system package has been updated 11827 // An updated system app can be deleted. This will also have to restore 11828 // the system pkg from system partition 11829 // reader 11830 synchronized (mPackages) { 11831 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11832 } 11833 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11834 + " disabledPs=" + disabledPs); 11835 if (disabledPs == null) { 11836 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11837 return false; 11838 } else if (DEBUG_REMOVE) { 11839 Slog.d(TAG, "Deleting system pkg from data partition"); 11840 } 11841 if (DEBUG_REMOVE) { 11842 if (applyUserRestrictions) { 11843 Slog.d(TAG, "Remembering install states:"); 11844 for (int i = 0; i < allUserHandles.length; i++) { 11845 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11846 } 11847 } 11848 } 11849 // Delete the updated package 11850 outInfo.isRemovedPackageSystemUpdate = true; 11851 if (disabledPs.versionCode < newPs.versionCode) { 11852 // Delete data for downgrades 11853 flags &= ~PackageManager.DELETE_KEEP_DATA; 11854 } else { 11855 // Preserve data by setting flag 11856 flags |= PackageManager.DELETE_KEEP_DATA; 11857 } 11858 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11859 allUserHandles, perUserInstalled, outInfo, writeSettings); 11860 if (!ret) { 11861 return false; 11862 } 11863 // writer 11864 synchronized (mPackages) { 11865 // Reinstate the old system package 11866 mSettings.enableSystemPackageLPw(newPs.name); 11867 // Remove any native libraries from the upgraded package. 11868 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11869 } 11870 // Install the system package 11871 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11872 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11873 if (locationIsPrivileged(disabledPs.codePath)) { 11874 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11875 } 11876 11877 final PackageParser.Package newPkg; 11878 try { 11879 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11880 } catch (PackageManagerException e) { 11881 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11882 return false; 11883 } 11884 11885 // writer 11886 synchronized (mPackages) { 11887 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11888 updatePermissionsLPw(newPkg.packageName, newPkg, 11889 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11890 if (applyUserRestrictions) { 11891 if (DEBUG_REMOVE) { 11892 Slog.d(TAG, "Propagating install state across reinstall"); 11893 } 11894 for (int i = 0; i < allUserHandles.length; i++) { 11895 if (DEBUG_REMOVE) { 11896 Slog.d(TAG, " user " + allUserHandles[i] 11897 + " => " + perUserInstalled[i]); 11898 } 11899 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11900 } 11901 // Regardless of writeSettings we need to ensure that this restriction 11902 // state propagation is persisted 11903 mSettings.writeAllUsersPackageRestrictionsLPr(); 11904 } 11905 // can downgrade to reader here 11906 if (writeSettings) { 11907 mSettings.writeLPr(); 11908 } 11909 } 11910 return true; 11911 } 11912 11913 private boolean deleteInstalledPackageLI(PackageSetting ps, 11914 boolean deleteCodeAndResources, int flags, 11915 int[] allUserHandles, boolean[] perUserInstalled, 11916 PackageRemovedInfo outInfo, boolean writeSettings) { 11917 if (outInfo != null) { 11918 outInfo.uid = ps.appId; 11919 } 11920 11921 // Delete package data from internal structures and also remove data if flag is set 11922 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11923 11924 // Delete application code and resources 11925 if (deleteCodeAndResources && (outInfo != null)) { 11926 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11927 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11928 getAppDexInstructionSets(ps)); 11929 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11930 } 11931 return true; 11932 } 11933 11934 @Override 11935 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11936 int userId) { 11937 mContext.enforceCallingOrSelfPermission( 11938 android.Manifest.permission.DELETE_PACKAGES, null); 11939 synchronized (mPackages) { 11940 PackageSetting ps = mSettings.mPackages.get(packageName); 11941 if (ps == null) { 11942 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11943 return false; 11944 } 11945 if (!ps.getInstalled(userId)) { 11946 // Can't block uninstall for an app that is not installed or enabled. 11947 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11948 return false; 11949 } 11950 ps.setBlockUninstall(blockUninstall, userId); 11951 mSettings.writePackageRestrictionsLPr(userId); 11952 } 11953 return true; 11954 } 11955 11956 @Override 11957 public boolean getBlockUninstallForUser(String packageName, int userId) { 11958 synchronized (mPackages) { 11959 PackageSetting ps = mSettings.mPackages.get(packageName); 11960 if (ps == null) { 11961 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11962 return false; 11963 } 11964 return ps.getBlockUninstall(userId); 11965 } 11966 } 11967 11968 /* 11969 * This method handles package deletion in general 11970 */ 11971 private boolean deletePackageLI(String packageName, UserHandle user, 11972 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11973 int flags, PackageRemovedInfo outInfo, 11974 boolean writeSettings) { 11975 if (packageName == null) { 11976 Slog.w(TAG, "Attempt to delete null packageName."); 11977 return false; 11978 } 11979 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11980 PackageSetting ps; 11981 boolean dataOnly = false; 11982 int removeUser = -1; 11983 int appId = -1; 11984 synchronized (mPackages) { 11985 ps = mSettings.mPackages.get(packageName); 11986 if (ps == null) { 11987 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11988 return false; 11989 } 11990 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11991 && user.getIdentifier() != UserHandle.USER_ALL) { 11992 // The caller is asking that the package only be deleted for a single 11993 // user. To do this, we just mark its uninstalled state and delete 11994 // its data. If this is a system app, we only allow this to happen if 11995 // they have set the special DELETE_SYSTEM_APP which requests different 11996 // semantics than normal for uninstalling system apps. 11997 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11998 ps.setUserState(user.getIdentifier(), 11999 COMPONENT_ENABLED_STATE_DEFAULT, 12000 false, //installed 12001 true, //stopped 12002 true, //notLaunched 12003 false, //hidden 12004 null, null, null, 12005 false, // blockUninstall 12006 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12007 if (!isSystemApp(ps)) { 12008 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12009 // Other user still have this package installed, so all 12010 // we need to do is clear this user's data and save that 12011 // it is uninstalled. 12012 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12013 removeUser = user.getIdentifier(); 12014 appId = ps.appId; 12015 scheduleWritePackageRestrictionsLocked(removeUser); 12016 } else { 12017 // We need to set it back to 'installed' so the uninstall 12018 // broadcasts will be sent correctly. 12019 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12020 ps.setInstalled(true, user.getIdentifier()); 12021 } 12022 } else { 12023 // This is a system app, so we assume that the 12024 // other users still have this package installed, so all 12025 // we need to do is clear this user's data and save that 12026 // it is uninstalled. 12027 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12028 removeUser = user.getIdentifier(); 12029 appId = ps.appId; 12030 scheduleWritePackageRestrictionsLocked(removeUser); 12031 } 12032 } 12033 } 12034 12035 if (removeUser >= 0) { 12036 // From above, we determined that we are deleting this only 12037 // for a single user. Continue the work here. 12038 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12039 if (outInfo != null) { 12040 outInfo.removedPackage = packageName; 12041 outInfo.removedAppId = appId; 12042 outInfo.removedUsers = new int[] {removeUser}; 12043 } 12044 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12045 removeKeystoreDataIfNeeded(removeUser, appId); 12046 schedulePackageCleaning(packageName, removeUser, false); 12047 synchronized (mPackages) { 12048 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12049 scheduleWritePackageRestrictionsLocked(removeUser); 12050 } 12051 } 12052 return true; 12053 } 12054 12055 if (dataOnly) { 12056 // Delete application data first 12057 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12058 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12059 return true; 12060 } 12061 12062 boolean ret = false; 12063 if (isSystemApp(ps)) { 12064 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12065 // When an updated system application is deleted we delete the existing resources as well and 12066 // fall back to existing code in system partition 12067 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12068 flags, outInfo, writeSettings); 12069 } else { 12070 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12071 // Kill application pre-emptively especially for apps on sd. 12072 killApplication(packageName, ps.appId, "uninstall pkg"); 12073 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12074 allUserHandles, perUserInstalled, 12075 outInfo, writeSettings); 12076 } 12077 12078 return ret; 12079 } 12080 12081 private final class ClearStorageConnection implements ServiceConnection { 12082 IMediaContainerService mContainerService; 12083 12084 @Override 12085 public void onServiceConnected(ComponentName name, IBinder service) { 12086 synchronized (this) { 12087 mContainerService = IMediaContainerService.Stub.asInterface(service); 12088 notifyAll(); 12089 } 12090 } 12091 12092 @Override 12093 public void onServiceDisconnected(ComponentName name) { 12094 } 12095 } 12096 12097 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12098 final boolean mounted; 12099 if (Environment.isExternalStorageEmulated()) { 12100 mounted = true; 12101 } else { 12102 final String status = Environment.getExternalStorageState(); 12103 12104 mounted = status.equals(Environment.MEDIA_MOUNTED) 12105 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12106 } 12107 12108 if (!mounted) { 12109 return; 12110 } 12111 12112 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12113 int[] users; 12114 if (userId == UserHandle.USER_ALL) { 12115 users = sUserManager.getUserIds(); 12116 } else { 12117 users = new int[] { userId }; 12118 } 12119 final ClearStorageConnection conn = new ClearStorageConnection(); 12120 if (mContext.bindServiceAsUser( 12121 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12122 try { 12123 for (int curUser : users) { 12124 long timeout = SystemClock.uptimeMillis() + 5000; 12125 synchronized (conn) { 12126 long now = SystemClock.uptimeMillis(); 12127 while (conn.mContainerService == null && now < timeout) { 12128 try { 12129 conn.wait(timeout - now); 12130 } catch (InterruptedException e) { 12131 } 12132 } 12133 } 12134 if (conn.mContainerService == null) { 12135 return; 12136 } 12137 12138 final UserEnvironment userEnv = new UserEnvironment(curUser); 12139 clearDirectory(conn.mContainerService, 12140 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12141 if (allData) { 12142 clearDirectory(conn.mContainerService, 12143 userEnv.buildExternalStorageAppDataDirs(packageName)); 12144 clearDirectory(conn.mContainerService, 12145 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12146 } 12147 } 12148 } finally { 12149 mContext.unbindService(conn); 12150 } 12151 } 12152 } 12153 12154 @Override 12155 public void clearApplicationUserData(final String packageName, 12156 final IPackageDataObserver observer, final int userId) { 12157 mContext.enforceCallingOrSelfPermission( 12158 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12159 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12160 // Queue up an async operation since the package deletion may take a little while. 12161 mHandler.post(new Runnable() { 12162 public void run() { 12163 mHandler.removeCallbacks(this); 12164 final boolean succeeded; 12165 synchronized (mInstallLock) { 12166 succeeded = clearApplicationUserDataLI(packageName, userId); 12167 } 12168 clearExternalStorageDataSync(packageName, userId, true); 12169 if (succeeded) { 12170 // invoke DeviceStorageMonitor's update method to clear any notifications 12171 DeviceStorageMonitorInternal 12172 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12173 if (dsm != null) { 12174 dsm.checkMemory(); 12175 } 12176 } 12177 if(observer != null) { 12178 try { 12179 observer.onRemoveCompleted(packageName, succeeded); 12180 } catch (RemoteException e) { 12181 Log.i(TAG, "Observer no longer exists."); 12182 } 12183 } //end if observer 12184 } //end run 12185 }); 12186 } 12187 12188 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12189 if (packageName == null) { 12190 Slog.w(TAG, "Attempt to delete null packageName."); 12191 return false; 12192 } 12193 12194 // Try finding details about the requested package 12195 PackageParser.Package pkg; 12196 synchronized (mPackages) { 12197 pkg = mPackages.get(packageName); 12198 if (pkg == null) { 12199 final PackageSetting ps = mSettings.mPackages.get(packageName); 12200 if (ps != null) { 12201 pkg = ps.pkg; 12202 } 12203 } 12204 } 12205 12206 if (pkg == null) { 12207 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12208 } 12209 12210 // Always delete data directories for package, even if we found no other 12211 // record of app. This helps users recover from UID mismatches without 12212 // resorting to a full data wipe. 12213 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12214 if (retCode < 0) { 12215 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12216 return false; 12217 } 12218 12219 if (pkg == null) { 12220 return false; 12221 } 12222 12223 if (pkg != null && pkg.applicationInfo != null) { 12224 final int appId = pkg.applicationInfo.uid; 12225 removeKeystoreDataIfNeeded(userId, appId); 12226 } 12227 12228 // Create a native library symlink only if we have native libraries 12229 // and if the native libraries are 32 bit libraries. We do not provide 12230 // this symlink for 64 bit libraries. 12231 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12232 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12233 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12234 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12235 nativeLibPath, userId) < 0) { 12236 Slog.w(TAG, "Failed linking native library dir"); 12237 return false; 12238 } 12239 } 12240 12241 return true; 12242 } 12243 12244 /** 12245 * Remove entries from the keystore daemon. Will only remove it if the 12246 * {@code appId} is valid. 12247 */ 12248 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12249 if (appId < 0) { 12250 return; 12251 } 12252 12253 final KeyStore keyStore = KeyStore.getInstance(); 12254 if (keyStore != null) { 12255 if (userId == UserHandle.USER_ALL) { 12256 for (final int individual : sUserManager.getUserIds()) { 12257 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12258 } 12259 } else { 12260 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12261 } 12262 } else { 12263 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12264 } 12265 } 12266 12267 @Override 12268 public void deleteApplicationCacheFiles(final String packageName, 12269 final IPackageDataObserver observer) { 12270 mContext.enforceCallingOrSelfPermission( 12271 android.Manifest.permission.DELETE_CACHE_FILES, null); 12272 // Queue up an async operation since the package deletion may take a little while. 12273 final int userId = UserHandle.getCallingUserId(); 12274 mHandler.post(new Runnable() { 12275 public void run() { 12276 mHandler.removeCallbacks(this); 12277 final boolean succeded; 12278 synchronized (mInstallLock) { 12279 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12280 } 12281 clearExternalStorageDataSync(packageName, userId, false); 12282 if(observer != null) { 12283 try { 12284 observer.onRemoveCompleted(packageName, succeded); 12285 } catch (RemoteException e) { 12286 Log.i(TAG, "Observer no longer exists."); 12287 } 12288 } //end if observer 12289 } //end run 12290 }); 12291 } 12292 12293 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12294 if (packageName == null) { 12295 Slog.w(TAG, "Attempt to delete null packageName."); 12296 return false; 12297 } 12298 PackageParser.Package p; 12299 synchronized (mPackages) { 12300 p = mPackages.get(packageName); 12301 } 12302 if (p == null) { 12303 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12304 return false; 12305 } 12306 final ApplicationInfo applicationInfo = p.applicationInfo; 12307 if (applicationInfo == null) { 12308 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12309 return false; 12310 } 12311 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12312 if (retCode < 0) { 12313 Slog.w(TAG, "Couldn't remove cache files for package: " 12314 + packageName + " u" + userId); 12315 return false; 12316 } 12317 return true; 12318 } 12319 12320 @Override 12321 public void getPackageSizeInfo(final String packageName, int userHandle, 12322 final IPackageStatsObserver observer) { 12323 mContext.enforceCallingOrSelfPermission( 12324 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12325 if (packageName == null) { 12326 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12327 } 12328 12329 PackageStats stats = new PackageStats(packageName, userHandle); 12330 12331 /* 12332 * Queue up an async operation since the package measurement may take a 12333 * little while. 12334 */ 12335 Message msg = mHandler.obtainMessage(INIT_COPY); 12336 msg.obj = new MeasureParams(stats, observer); 12337 mHandler.sendMessage(msg); 12338 } 12339 12340 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12341 PackageStats pStats) { 12342 if (packageName == null) { 12343 Slog.w(TAG, "Attempt to get size of null packageName."); 12344 return false; 12345 } 12346 PackageParser.Package p; 12347 boolean dataOnly = false; 12348 String libDirRoot = null; 12349 String asecPath = null; 12350 PackageSetting ps = null; 12351 synchronized (mPackages) { 12352 p = mPackages.get(packageName); 12353 ps = mSettings.mPackages.get(packageName); 12354 if(p == null) { 12355 dataOnly = true; 12356 if((ps == null) || (ps.pkg == null)) { 12357 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12358 return false; 12359 } 12360 p = ps.pkg; 12361 } 12362 if (ps != null) { 12363 libDirRoot = ps.legacyNativeLibraryPathString; 12364 } 12365 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12366 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12367 if (secureContainerId != null) { 12368 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12369 } 12370 } 12371 } 12372 String publicSrcDir = null; 12373 if(!dataOnly) { 12374 final ApplicationInfo applicationInfo = p.applicationInfo; 12375 if (applicationInfo == null) { 12376 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12377 return false; 12378 } 12379 if (p.isForwardLocked()) { 12380 publicSrcDir = applicationInfo.getBaseResourcePath(); 12381 } 12382 } 12383 // TODO: extend to measure size of split APKs 12384 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12385 // not just the first level. 12386 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12387 // just the primary. 12388 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12389 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12390 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12391 if (res < 0) { 12392 return false; 12393 } 12394 12395 // Fix-up for forward-locked applications in ASEC containers. 12396 if (!isExternal(p)) { 12397 pStats.codeSize += pStats.externalCodeSize; 12398 pStats.externalCodeSize = 0L; 12399 } 12400 12401 return true; 12402 } 12403 12404 12405 @Override 12406 public void addPackageToPreferred(String packageName) { 12407 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12408 } 12409 12410 @Override 12411 public void removePackageFromPreferred(String packageName) { 12412 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12413 } 12414 12415 @Override 12416 public List<PackageInfo> getPreferredPackages(int flags) { 12417 return new ArrayList<PackageInfo>(); 12418 } 12419 12420 private int getUidTargetSdkVersionLockedLPr(int uid) { 12421 Object obj = mSettings.getUserIdLPr(uid); 12422 if (obj instanceof SharedUserSetting) { 12423 final SharedUserSetting sus = (SharedUserSetting) obj; 12424 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12425 final Iterator<PackageSetting> it = sus.packages.iterator(); 12426 while (it.hasNext()) { 12427 final PackageSetting ps = it.next(); 12428 if (ps.pkg != null) { 12429 int v = ps.pkg.applicationInfo.targetSdkVersion; 12430 if (v < vers) vers = v; 12431 } 12432 } 12433 return vers; 12434 } else if (obj instanceof PackageSetting) { 12435 final PackageSetting ps = (PackageSetting) obj; 12436 if (ps.pkg != null) { 12437 return ps.pkg.applicationInfo.targetSdkVersion; 12438 } 12439 } 12440 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12441 } 12442 12443 @Override 12444 public void addPreferredActivity(IntentFilter filter, int match, 12445 ComponentName[] set, ComponentName activity, int userId) { 12446 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12447 "Adding preferred"); 12448 } 12449 12450 private void addPreferredActivityInternal(IntentFilter filter, int match, 12451 ComponentName[] set, ComponentName activity, boolean always, int userId, 12452 String opname) { 12453 // writer 12454 int callingUid = Binder.getCallingUid(); 12455 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12456 if (filter.countActions() == 0) { 12457 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12458 return; 12459 } 12460 synchronized (mPackages) { 12461 if (mContext.checkCallingOrSelfPermission( 12462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12463 != PackageManager.PERMISSION_GRANTED) { 12464 if (getUidTargetSdkVersionLockedLPr(callingUid) 12465 < Build.VERSION_CODES.FROYO) { 12466 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12467 + callingUid); 12468 return; 12469 } 12470 mContext.enforceCallingOrSelfPermission( 12471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12472 } 12473 12474 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12475 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12476 + userId + ":"); 12477 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12478 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12479 scheduleWritePackageRestrictionsLocked(userId); 12480 } 12481 } 12482 12483 @Override 12484 public void replacePreferredActivity(IntentFilter filter, int match, 12485 ComponentName[] set, ComponentName activity, int userId) { 12486 if (filter.countActions() != 1) { 12487 throw new IllegalArgumentException( 12488 "replacePreferredActivity expects filter to have only 1 action."); 12489 } 12490 if (filter.countDataAuthorities() != 0 12491 || filter.countDataPaths() != 0 12492 || filter.countDataSchemes() > 1 12493 || filter.countDataTypes() != 0) { 12494 throw new IllegalArgumentException( 12495 "replacePreferredActivity expects filter to have no data authorities, " + 12496 "paths, or types; and at most one scheme."); 12497 } 12498 12499 final int callingUid = Binder.getCallingUid(); 12500 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12501 synchronized (mPackages) { 12502 if (mContext.checkCallingOrSelfPermission( 12503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12504 != PackageManager.PERMISSION_GRANTED) { 12505 if (getUidTargetSdkVersionLockedLPr(callingUid) 12506 < Build.VERSION_CODES.FROYO) { 12507 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12508 + Binder.getCallingUid()); 12509 return; 12510 } 12511 mContext.enforceCallingOrSelfPermission( 12512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12513 } 12514 12515 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12516 if (pir != null) { 12517 // Get all of the existing entries that exactly match this filter. 12518 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12519 if (existing != null && existing.size() == 1) { 12520 PreferredActivity cur = existing.get(0); 12521 if (DEBUG_PREFERRED) { 12522 Slog.i(TAG, "Checking replace of preferred:"); 12523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12524 if (!cur.mPref.mAlways) { 12525 Slog.i(TAG, " -- CUR; not mAlways!"); 12526 } else { 12527 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12528 Slog.i(TAG, " -- CUR: mSet=" 12529 + Arrays.toString(cur.mPref.mSetComponents)); 12530 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12531 Slog.i(TAG, " -- NEW: mMatch=" 12532 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12533 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12534 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12535 } 12536 } 12537 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12538 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12539 && cur.mPref.sameSet(set)) { 12540 // Setting the preferred activity to what it happens to be already 12541 if (DEBUG_PREFERRED) { 12542 Slog.i(TAG, "Replacing with same preferred activity " 12543 + cur.mPref.mShortComponent + " for user " 12544 + userId + ":"); 12545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12546 } 12547 return; 12548 } 12549 } 12550 12551 if (existing != null) { 12552 if (DEBUG_PREFERRED) { 12553 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12554 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12555 } 12556 for (int i = 0; i < existing.size(); i++) { 12557 PreferredActivity pa = existing.get(i); 12558 if (DEBUG_PREFERRED) { 12559 Slog.i(TAG, "Removing existing preferred activity " 12560 + pa.mPref.mComponent + ":"); 12561 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12562 } 12563 pir.removeFilter(pa); 12564 } 12565 } 12566 } 12567 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12568 "Replacing preferred"); 12569 } 12570 } 12571 12572 @Override 12573 public void clearPackagePreferredActivities(String packageName) { 12574 final int uid = Binder.getCallingUid(); 12575 // writer 12576 synchronized (mPackages) { 12577 PackageParser.Package pkg = mPackages.get(packageName); 12578 if (pkg == null || pkg.applicationInfo.uid != uid) { 12579 if (mContext.checkCallingOrSelfPermission( 12580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12581 != PackageManager.PERMISSION_GRANTED) { 12582 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12583 < Build.VERSION_CODES.FROYO) { 12584 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12585 + Binder.getCallingUid()); 12586 return; 12587 } 12588 mContext.enforceCallingOrSelfPermission( 12589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12590 } 12591 } 12592 12593 int user = UserHandle.getCallingUserId(); 12594 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12595 scheduleWritePackageRestrictionsLocked(user); 12596 } 12597 } 12598 } 12599 12600 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12601 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12602 ArrayList<PreferredActivity> removed = null; 12603 boolean changed = false; 12604 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12605 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12606 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12607 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12608 continue; 12609 } 12610 Iterator<PreferredActivity> it = pir.filterIterator(); 12611 while (it.hasNext()) { 12612 PreferredActivity pa = it.next(); 12613 // Mark entry for removal only if it matches the package name 12614 // and the entry is of type "always". 12615 if (packageName == null || 12616 (pa.mPref.mComponent.getPackageName().equals(packageName) 12617 && pa.mPref.mAlways)) { 12618 if (removed == null) { 12619 removed = new ArrayList<PreferredActivity>(); 12620 } 12621 removed.add(pa); 12622 } 12623 } 12624 if (removed != null) { 12625 for (int j=0; j<removed.size(); j++) { 12626 PreferredActivity pa = removed.get(j); 12627 pir.removeFilter(pa); 12628 } 12629 changed = true; 12630 } 12631 } 12632 return changed; 12633 } 12634 12635 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12636 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12637 if (userId == UserHandle.USER_ALL) { 12638 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12639 for (int oneUserId : sUserManager.getUserIds()) { 12640 scheduleWritePackageRestrictionsLocked(oneUserId); 12641 } 12642 } else { 12643 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12644 scheduleWritePackageRestrictionsLocked(userId); 12645 } 12646 } 12647 12648 @Override 12649 public void resetPreferredActivities(int userId) { 12650 /* TODO: Actually use userId. Why is it being passed in? */ 12651 mContext.enforceCallingOrSelfPermission( 12652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12653 // writer 12654 synchronized (mPackages) { 12655 int user = UserHandle.getCallingUserId(); 12656 clearPackagePreferredActivitiesLPw(null, user); 12657 mSettings.readDefaultPreferredAppsLPw(this, user); 12658 scheduleWritePackageRestrictionsLocked(user); 12659 } 12660 } 12661 12662 @Override 12663 public int getPreferredActivities(List<IntentFilter> outFilters, 12664 List<ComponentName> outActivities, String packageName) { 12665 12666 int num = 0; 12667 final int userId = UserHandle.getCallingUserId(); 12668 // reader 12669 synchronized (mPackages) { 12670 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12671 if (pir != null) { 12672 final Iterator<PreferredActivity> it = pir.filterIterator(); 12673 while (it.hasNext()) { 12674 final PreferredActivity pa = it.next(); 12675 if (packageName == null 12676 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12677 && pa.mPref.mAlways)) { 12678 if (outFilters != null) { 12679 outFilters.add(new IntentFilter(pa)); 12680 } 12681 if (outActivities != null) { 12682 outActivities.add(pa.mPref.mComponent); 12683 } 12684 } 12685 } 12686 } 12687 } 12688 12689 return num; 12690 } 12691 12692 @Override 12693 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12694 int userId) { 12695 int callingUid = Binder.getCallingUid(); 12696 if (callingUid != Process.SYSTEM_UID) { 12697 throw new SecurityException( 12698 "addPersistentPreferredActivity can only be run by the system"); 12699 } 12700 if (filter.countActions() == 0) { 12701 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12702 return; 12703 } 12704 synchronized (mPackages) { 12705 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12706 " :"); 12707 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12708 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12709 new PersistentPreferredActivity(filter, activity)); 12710 scheduleWritePackageRestrictionsLocked(userId); 12711 } 12712 } 12713 12714 @Override 12715 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12716 int callingUid = Binder.getCallingUid(); 12717 if (callingUid != Process.SYSTEM_UID) { 12718 throw new SecurityException( 12719 "clearPackagePersistentPreferredActivities can only be run by the system"); 12720 } 12721 ArrayList<PersistentPreferredActivity> removed = null; 12722 boolean changed = false; 12723 synchronized (mPackages) { 12724 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12725 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12726 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12727 .valueAt(i); 12728 if (userId != thisUserId) { 12729 continue; 12730 } 12731 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12732 while (it.hasNext()) { 12733 PersistentPreferredActivity ppa = it.next(); 12734 // Mark entry for removal only if it matches the package name. 12735 if (ppa.mComponent.getPackageName().equals(packageName)) { 12736 if (removed == null) { 12737 removed = new ArrayList<PersistentPreferredActivity>(); 12738 } 12739 removed.add(ppa); 12740 } 12741 } 12742 if (removed != null) { 12743 for (int j=0; j<removed.size(); j++) { 12744 PersistentPreferredActivity ppa = removed.get(j); 12745 ppir.removeFilter(ppa); 12746 } 12747 changed = true; 12748 } 12749 } 12750 12751 if (changed) { 12752 scheduleWritePackageRestrictionsLocked(userId); 12753 } 12754 } 12755 } 12756 12757 /** 12758 * Non-Binder method, support for the backup/restore mechanism: write the 12759 * full set of preferred activities in its canonical XML format. Returns true 12760 * on success; false otherwise. 12761 */ 12762 @Override 12763 public byte[] getPreferredActivityBackup(int userId) { 12764 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12765 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12766 } 12767 12768 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12769 try { 12770 final XmlSerializer serializer = new FastXmlSerializer(); 12771 serializer.setOutput(dataStream, "utf-8"); 12772 serializer.startDocument(null, true); 12773 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12774 12775 synchronized (mPackages) { 12776 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12777 } 12778 12779 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12780 serializer.endDocument(); 12781 serializer.flush(); 12782 } catch (Exception e) { 12783 if (DEBUG_BACKUP) { 12784 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12785 } 12786 return null; 12787 } 12788 12789 return dataStream.toByteArray(); 12790 } 12791 12792 @Override 12793 public void restorePreferredActivities(byte[] backup, int userId) { 12794 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12795 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12796 } 12797 12798 try { 12799 final XmlPullParser parser = Xml.newPullParser(); 12800 parser.setInput(new ByteArrayInputStream(backup), null); 12801 12802 int type; 12803 while ((type = parser.next()) != XmlPullParser.START_TAG 12804 && type != XmlPullParser.END_DOCUMENT) { 12805 } 12806 if (type != XmlPullParser.START_TAG) { 12807 // oops didn't find a start tag?! 12808 if (DEBUG_BACKUP) { 12809 Slog.e(TAG, "Didn't find start tag during restore"); 12810 } 12811 return; 12812 } 12813 12814 // this is supposed to be TAG_PREFERRED_BACKUP 12815 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12816 if (DEBUG_BACKUP) { 12817 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12818 } 12819 return; 12820 } 12821 12822 // skip interfering stuff, then we're aligned with the backing implementation 12823 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12824 synchronized (mPackages) { 12825 mSettings.readPreferredActivitiesLPw(parser, userId); 12826 } 12827 } catch (Exception e) { 12828 if (DEBUG_BACKUP) { 12829 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12830 } 12831 } 12832 } 12833 12834 @Override 12835 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12836 int sourceUserId, int targetUserId, int flags) { 12837 mContext.enforceCallingOrSelfPermission( 12838 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12839 int callingUid = Binder.getCallingUid(); 12840 enforceOwnerRights(ownerPackage, callingUid); 12841 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12842 if (intentFilter.countActions() == 0) { 12843 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12844 return; 12845 } 12846 synchronized (mPackages) { 12847 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12848 ownerPackage, targetUserId, flags); 12849 CrossProfileIntentResolver resolver = 12850 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12851 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12852 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12853 if (existing != null) { 12854 int size = existing.size(); 12855 for (int i = 0; i < size; i++) { 12856 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12857 return; 12858 } 12859 } 12860 } 12861 resolver.addFilter(newFilter); 12862 scheduleWritePackageRestrictionsLocked(sourceUserId); 12863 } 12864 } 12865 12866 @Override 12867 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12868 mContext.enforceCallingOrSelfPermission( 12869 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12870 int callingUid = Binder.getCallingUid(); 12871 enforceOwnerRights(ownerPackage, callingUid); 12872 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12873 synchronized (mPackages) { 12874 CrossProfileIntentResolver resolver = 12875 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12876 ArraySet<CrossProfileIntentFilter> set = 12877 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12878 for (CrossProfileIntentFilter filter : set) { 12879 if (filter.getOwnerPackage().equals(ownerPackage)) { 12880 resolver.removeFilter(filter); 12881 } 12882 } 12883 scheduleWritePackageRestrictionsLocked(sourceUserId); 12884 } 12885 } 12886 12887 // Enforcing that callingUid is owning pkg on userId 12888 private void enforceOwnerRights(String pkg, int callingUid) { 12889 // The system owns everything. 12890 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12891 return; 12892 } 12893 int callingUserId = UserHandle.getUserId(callingUid); 12894 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12895 if (pi == null) { 12896 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12897 + callingUserId); 12898 } 12899 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12900 throw new SecurityException("Calling uid " + callingUid 12901 + " does not own package " + pkg); 12902 } 12903 } 12904 12905 @Override 12906 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12907 Intent intent = new Intent(Intent.ACTION_MAIN); 12908 intent.addCategory(Intent.CATEGORY_HOME); 12909 12910 final int callingUserId = UserHandle.getCallingUserId(); 12911 List<ResolveInfo> list = queryIntentActivities(intent, null, 12912 PackageManager.GET_META_DATA, callingUserId); 12913 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12914 true, false, false, callingUserId); 12915 12916 allHomeCandidates.clear(); 12917 if (list != null) { 12918 for (ResolveInfo ri : list) { 12919 allHomeCandidates.add(ri); 12920 } 12921 } 12922 return (preferred == null || preferred.activityInfo == null) 12923 ? null 12924 : new ComponentName(preferred.activityInfo.packageName, 12925 preferred.activityInfo.name); 12926 } 12927 12928 @Override 12929 public void setApplicationEnabledSetting(String appPackageName, 12930 int newState, int flags, int userId, String callingPackage) { 12931 if (!sUserManager.exists(userId)) return; 12932 if (callingPackage == null) { 12933 callingPackage = Integer.toString(Binder.getCallingUid()); 12934 } 12935 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12936 } 12937 12938 @Override 12939 public void setComponentEnabledSetting(ComponentName componentName, 12940 int newState, int flags, int userId) { 12941 if (!sUserManager.exists(userId)) return; 12942 setEnabledSetting(componentName.getPackageName(), 12943 componentName.getClassName(), newState, flags, userId, null); 12944 } 12945 12946 private void setEnabledSetting(final String packageName, String className, int newState, 12947 final int flags, int userId, String callingPackage) { 12948 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12949 || newState == COMPONENT_ENABLED_STATE_ENABLED 12950 || newState == COMPONENT_ENABLED_STATE_DISABLED 12951 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12952 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12953 throw new IllegalArgumentException("Invalid new component state: " 12954 + newState); 12955 } 12956 PackageSetting pkgSetting; 12957 final int uid = Binder.getCallingUid(); 12958 final int permission = mContext.checkCallingOrSelfPermission( 12959 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12960 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12961 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12962 boolean sendNow = false; 12963 boolean isApp = (className == null); 12964 String componentName = isApp ? packageName : className; 12965 int packageUid = -1; 12966 ArrayList<String> components; 12967 12968 // writer 12969 synchronized (mPackages) { 12970 pkgSetting = mSettings.mPackages.get(packageName); 12971 if (pkgSetting == null) { 12972 if (className == null) { 12973 throw new IllegalArgumentException( 12974 "Unknown package: " + packageName); 12975 } 12976 throw new IllegalArgumentException( 12977 "Unknown component: " + packageName 12978 + "/" + className); 12979 } 12980 // Allow root and verify that userId is not being specified by a different user 12981 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12982 throw new SecurityException( 12983 "Permission Denial: attempt to change component state from pid=" 12984 + Binder.getCallingPid() 12985 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12986 } 12987 if (className == null) { 12988 // We're dealing with an application/package level state change 12989 if (pkgSetting.getEnabled(userId) == newState) { 12990 // Nothing to do 12991 return; 12992 } 12993 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12994 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12995 // Don't care about who enables an app. 12996 callingPackage = null; 12997 } 12998 pkgSetting.setEnabled(newState, userId, callingPackage); 12999 // pkgSetting.pkg.mSetEnabled = newState; 13000 } else { 13001 // We're dealing with a component level state change 13002 // First, verify that this is a valid class name. 13003 PackageParser.Package pkg = pkgSetting.pkg; 13004 if (pkg == null || !pkg.hasComponentClassName(className)) { 13005 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13006 throw new IllegalArgumentException("Component class " + className 13007 + " does not exist in " + packageName); 13008 } else { 13009 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13010 + className + " does not exist in " + packageName); 13011 } 13012 } 13013 switch (newState) { 13014 case COMPONENT_ENABLED_STATE_ENABLED: 13015 if (!pkgSetting.enableComponentLPw(className, userId)) { 13016 return; 13017 } 13018 break; 13019 case COMPONENT_ENABLED_STATE_DISABLED: 13020 if (!pkgSetting.disableComponentLPw(className, userId)) { 13021 return; 13022 } 13023 break; 13024 case COMPONENT_ENABLED_STATE_DEFAULT: 13025 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13026 return; 13027 } 13028 break; 13029 default: 13030 Slog.e(TAG, "Invalid new component state: " + newState); 13031 return; 13032 } 13033 } 13034 scheduleWritePackageRestrictionsLocked(userId); 13035 components = mPendingBroadcasts.get(userId, packageName); 13036 final boolean newPackage = components == null; 13037 if (newPackage) { 13038 components = new ArrayList<String>(); 13039 } 13040 if (!components.contains(componentName)) { 13041 components.add(componentName); 13042 } 13043 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13044 sendNow = true; 13045 // Purge entry from pending broadcast list if another one exists already 13046 // since we are sending one right away. 13047 mPendingBroadcasts.remove(userId, packageName); 13048 } else { 13049 if (newPackage) { 13050 mPendingBroadcasts.put(userId, packageName, components); 13051 } 13052 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13053 // Schedule a message 13054 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13055 } 13056 } 13057 } 13058 13059 long callingId = Binder.clearCallingIdentity(); 13060 try { 13061 if (sendNow) { 13062 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13063 sendPackageChangedBroadcast(packageName, 13064 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13065 } 13066 } finally { 13067 Binder.restoreCallingIdentity(callingId); 13068 } 13069 } 13070 13071 private void sendPackageChangedBroadcast(String packageName, 13072 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13073 if (DEBUG_INSTALL) 13074 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13075 + componentNames); 13076 Bundle extras = new Bundle(4); 13077 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13078 String nameList[] = new String[componentNames.size()]; 13079 componentNames.toArray(nameList); 13080 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13081 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13082 extras.putInt(Intent.EXTRA_UID, packageUid); 13083 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13084 new int[] {UserHandle.getUserId(packageUid)}); 13085 } 13086 13087 @Override 13088 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13089 if (!sUserManager.exists(userId)) return; 13090 final int uid = Binder.getCallingUid(); 13091 final int permission = mContext.checkCallingOrSelfPermission( 13092 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13093 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13094 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13095 // writer 13096 synchronized (mPackages) { 13097 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 13098 uid, userId)) { 13099 scheduleWritePackageRestrictionsLocked(userId); 13100 } 13101 } 13102 } 13103 13104 @Override 13105 public String getInstallerPackageName(String packageName) { 13106 // reader 13107 synchronized (mPackages) { 13108 return mSettings.getInstallerPackageNameLPr(packageName); 13109 } 13110 } 13111 13112 @Override 13113 public int getApplicationEnabledSetting(String packageName, int userId) { 13114 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13115 int uid = Binder.getCallingUid(); 13116 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13117 // reader 13118 synchronized (mPackages) { 13119 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13120 } 13121 } 13122 13123 @Override 13124 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13125 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13126 int uid = Binder.getCallingUid(); 13127 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13128 // reader 13129 synchronized (mPackages) { 13130 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13131 } 13132 } 13133 13134 @Override 13135 public void enterSafeMode() { 13136 enforceSystemOrRoot("Only the system can request entering safe mode"); 13137 13138 if (!mSystemReady) { 13139 mSafeMode = true; 13140 } 13141 } 13142 13143 @Override 13144 public void systemReady() { 13145 mSystemReady = true; 13146 13147 // Read the compatibilty setting when the system is ready. 13148 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13149 mContext.getContentResolver(), 13150 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13151 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13152 if (DEBUG_SETTINGS) { 13153 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13154 } 13155 13156 synchronized (mPackages) { 13157 // Verify that all of the preferred activity components actually 13158 // exist. It is possible for applications to be updated and at 13159 // that point remove a previously declared activity component that 13160 // had been set as a preferred activity. We try to clean this up 13161 // the next time we encounter that preferred activity, but it is 13162 // possible for the user flow to never be able to return to that 13163 // situation so here we do a sanity check to make sure we haven't 13164 // left any junk around. 13165 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13166 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13167 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13168 removed.clear(); 13169 for (PreferredActivity pa : pir.filterSet()) { 13170 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13171 removed.add(pa); 13172 } 13173 } 13174 if (removed.size() > 0) { 13175 for (int r=0; r<removed.size(); r++) { 13176 PreferredActivity pa = removed.get(r); 13177 Slog.w(TAG, "Removing dangling preferred activity: " 13178 + pa.mPref.mComponent); 13179 pir.removeFilter(pa); 13180 } 13181 mSettings.writePackageRestrictionsLPr( 13182 mSettings.mPreferredActivities.keyAt(i)); 13183 } 13184 } 13185 } 13186 sUserManager.systemReady(); 13187 13188 // Kick off any messages waiting for system ready 13189 if (mPostSystemReadyMessages != null) { 13190 for (Message msg : mPostSystemReadyMessages) { 13191 msg.sendToTarget(); 13192 } 13193 mPostSystemReadyMessages = null; 13194 } 13195 13196 // Watch for external volumes that come and go over time 13197 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13198 storage.registerListener(mStorageListener); 13199 13200 mInstallerService.systemReady(); 13201 } 13202 13203 @Override 13204 public boolean isSafeMode() { 13205 return mSafeMode; 13206 } 13207 13208 @Override 13209 public boolean hasSystemUidErrors() { 13210 return mHasSystemUidErrors; 13211 } 13212 13213 static String arrayToString(int[] array) { 13214 StringBuffer buf = new StringBuffer(128); 13215 buf.append('['); 13216 if (array != null) { 13217 for (int i=0; i<array.length; i++) { 13218 if (i > 0) buf.append(", "); 13219 buf.append(array[i]); 13220 } 13221 } 13222 buf.append(']'); 13223 return buf.toString(); 13224 } 13225 13226 static class DumpState { 13227 public static final int DUMP_LIBS = 1 << 0; 13228 public static final int DUMP_FEATURES = 1 << 1; 13229 public static final int DUMP_RESOLVERS = 1 << 2; 13230 public static final int DUMP_PERMISSIONS = 1 << 3; 13231 public static final int DUMP_PACKAGES = 1 << 4; 13232 public static final int DUMP_SHARED_USERS = 1 << 5; 13233 public static final int DUMP_MESSAGES = 1 << 6; 13234 public static final int DUMP_PROVIDERS = 1 << 7; 13235 public static final int DUMP_VERIFIERS = 1 << 8; 13236 public static final int DUMP_PREFERRED = 1 << 9; 13237 public static final int DUMP_PREFERRED_XML = 1 << 10; 13238 public static final int DUMP_KEYSETS = 1 << 11; 13239 public static final int DUMP_VERSION = 1 << 12; 13240 public static final int DUMP_INSTALLS = 1 << 13; 13241 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13242 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13243 13244 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13245 13246 private int mTypes; 13247 13248 private int mOptions; 13249 13250 private boolean mTitlePrinted; 13251 13252 private SharedUserSetting mSharedUser; 13253 13254 public boolean isDumping(int type) { 13255 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13256 return true; 13257 } 13258 13259 return (mTypes & type) != 0; 13260 } 13261 13262 public void setDump(int type) { 13263 mTypes |= type; 13264 } 13265 13266 public boolean isOptionEnabled(int option) { 13267 return (mOptions & option) != 0; 13268 } 13269 13270 public void setOptionEnabled(int option) { 13271 mOptions |= option; 13272 } 13273 13274 public boolean onTitlePrinted() { 13275 final boolean printed = mTitlePrinted; 13276 mTitlePrinted = true; 13277 return printed; 13278 } 13279 13280 public boolean getTitlePrinted() { 13281 return mTitlePrinted; 13282 } 13283 13284 public void setTitlePrinted(boolean enabled) { 13285 mTitlePrinted = enabled; 13286 } 13287 13288 public SharedUserSetting getSharedUser() { 13289 return mSharedUser; 13290 } 13291 13292 public void setSharedUser(SharedUserSetting user) { 13293 mSharedUser = user; 13294 } 13295 } 13296 13297 @Override 13298 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13299 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13300 != PackageManager.PERMISSION_GRANTED) { 13301 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13302 + Binder.getCallingPid() 13303 + ", uid=" + Binder.getCallingUid() 13304 + " without permission " 13305 + android.Manifest.permission.DUMP); 13306 return; 13307 } 13308 13309 DumpState dumpState = new DumpState(); 13310 boolean fullPreferred = false; 13311 boolean checkin = false; 13312 13313 String packageName = null; 13314 13315 int opti = 0; 13316 while (opti < args.length) { 13317 String opt = args[opti]; 13318 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13319 break; 13320 } 13321 opti++; 13322 13323 if ("-a".equals(opt)) { 13324 // Right now we only know how to print all. 13325 } else if ("-h".equals(opt)) { 13326 pw.println("Package manager dump options:"); 13327 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13328 pw.println(" --checkin: dump for a checkin"); 13329 pw.println(" -f: print details of intent filters"); 13330 pw.println(" -h: print this help"); 13331 pw.println(" cmd may be one of:"); 13332 pw.println(" l[ibraries]: list known shared libraries"); 13333 pw.println(" f[ibraries]: list device features"); 13334 pw.println(" k[eysets]: print known keysets"); 13335 pw.println(" r[esolvers]: dump intent resolvers"); 13336 pw.println(" perm[issions]: dump permissions"); 13337 pw.println(" pref[erred]: print preferred package settings"); 13338 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13339 pw.println(" prov[iders]: dump content providers"); 13340 pw.println(" p[ackages]: dump installed packages"); 13341 pw.println(" s[hared-users]: dump shared user IDs"); 13342 pw.println(" m[essages]: print collected runtime messages"); 13343 pw.println(" v[erifiers]: print package verifier info"); 13344 pw.println(" version: print database version info"); 13345 pw.println(" write: write current settings now"); 13346 pw.println(" <package.name>: info about given package"); 13347 pw.println(" installs: details about install sessions"); 13348 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13349 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13350 return; 13351 } else if ("--checkin".equals(opt)) { 13352 checkin = true; 13353 } else if ("-f".equals(opt)) { 13354 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13355 } else { 13356 pw.println("Unknown argument: " + opt + "; use -h for help"); 13357 } 13358 } 13359 13360 // Is the caller requesting to dump a particular piece of data? 13361 if (opti < args.length) { 13362 String cmd = args[opti]; 13363 opti++; 13364 // Is this a package name? 13365 if ("android".equals(cmd) || cmd.contains(".")) { 13366 packageName = cmd; 13367 // When dumping a single package, we always dump all of its 13368 // filter information since the amount of data will be reasonable. 13369 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13370 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13371 dumpState.setDump(DumpState.DUMP_LIBS); 13372 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13373 dumpState.setDump(DumpState.DUMP_FEATURES); 13374 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13375 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13376 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13377 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13378 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13379 dumpState.setDump(DumpState.DUMP_PREFERRED); 13380 } else if ("preferred-xml".equals(cmd)) { 13381 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13382 if (opti < args.length && "--full".equals(args[opti])) { 13383 fullPreferred = true; 13384 opti++; 13385 } 13386 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13387 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13388 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13389 dumpState.setDump(DumpState.DUMP_PACKAGES); 13390 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13391 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13392 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13393 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13394 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13395 dumpState.setDump(DumpState.DUMP_MESSAGES); 13396 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13397 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13398 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13399 || "intent-filter-verifiers".equals(cmd)) { 13400 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13401 } else if ("version".equals(cmd)) { 13402 dumpState.setDump(DumpState.DUMP_VERSION); 13403 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13404 dumpState.setDump(DumpState.DUMP_KEYSETS); 13405 } else if ("installs".equals(cmd)) { 13406 dumpState.setDump(DumpState.DUMP_INSTALLS); 13407 } else if ("write".equals(cmd)) { 13408 synchronized (mPackages) { 13409 mSettings.writeLPr(); 13410 pw.println("Settings written."); 13411 return; 13412 } 13413 } 13414 } 13415 13416 if (checkin) { 13417 pw.println("vers,1"); 13418 } 13419 13420 // reader 13421 synchronized (mPackages) { 13422 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13423 if (!checkin) { 13424 if (dumpState.onTitlePrinted()) 13425 pw.println(); 13426 pw.println("Database versions:"); 13427 pw.print(" SDK Version:"); 13428 pw.print(" internal="); 13429 pw.print(mSettings.mInternalSdkPlatform); 13430 pw.print(" external="); 13431 pw.println(mSettings.mExternalSdkPlatform); 13432 pw.print(" DB Version:"); 13433 pw.print(" internal="); 13434 pw.print(mSettings.mInternalDatabaseVersion); 13435 pw.print(" external="); 13436 pw.println(mSettings.mExternalDatabaseVersion); 13437 } 13438 } 13439 13440 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13441 if (!checkin) { 13442 if (dumpState.onTitlePrinted()) 13443 pw.println(); 13444 pw.println("Verifiers:"); 13445 pw.print(" Required: "); 13446 pw.print(mRequiredVerifierPackage); 13447 pw.print(" (uid="); 13448 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13449 pw.println(")"); 13450 } else if (mRequiredVerifierPackage != null) { 13451 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13452 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13453 } 13454 } 13455 13456 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13457 packageName == null) { 13458 if (mIntentFilterVerifierComponent != null) { 13459 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13460 if (!checkin) { 13461 if (dumpState.onTitlePrinted()) 13462 pw.println(); 13463 pw.println("Intent Filter Verifier:"); 13464 pw.print(" Using: "); 13465 pw.print(verifierPackageName); 13466 pw.print(" (uid="); 13467 pw.print(getPackageUid(verifierPackageName, 0)); 13468 pw.println(")"); 13469 } else if (verifierPackageName != null) { 13470 pw.print("ifv,"); pw.print(verifierPackageName); 13471 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13472 } 13473 } else { 13474 pw.println(); 13475 pw.println("No Intent Filter Verifier available!"); 13476 } 13477 } 13478 13479 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13480 boolean printedHeader = false; 13481 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13482 while (it.hasNext()) { 13483 String name = it.next(); 13484 SharedLibraryEntry ent = mSharedLibraries.get(name); 13485 if (!checkin) { 13486 if (!printedHeader) { 13487 if (dumpState.onTitlePrinted()) 13488 pw.println(); 13489 pw.println("Libraries:"); 13490 printedHeader = true; 13491 } 13492 pw.print(" "); 13493 } else { 13494 pw.print("lib,"); 13495 } 13496 pw.print(name); 13497 if (!checkin) { 13498 pw.print(" -> "); 13499 } 13500 if (ent.path != null) { 13501 if (!checkin) { 13502 pw.print("(jar) "); 13503 pw.print(ent.path); 13504 } else { 13505 pw.print(",jar,"); 13506 pw.print(ent.path); 13507 } 13508 } else { 13509 if (!checkin) { 13510 pw.print("(apk) "); 13511 pw.print(ent.apk); 13512 } else { 13513 pw.print(",apk,"); 13514 pw.print(ent.apk); 13515 } 13516 } 13517 pw.println(); 13518 } 13519 } 13520 13521 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13522 if (dumpState.onTitlePrinted()) 13523 pw.println(); 13524 if (!checkin) { 13525 pw.println("Features:"); 13526 } 13527 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13528 while (it.hasNext()) { 13529 String name = it.next(); 13530 if (!checkin) { 13531 pw.print(" "); 13532 } else { 13533 pw.print("feat,"); 13534 } 13535 pw.println(name); 13536 } 13537 } 13538 13539 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13540 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13541 : "Activity Resolver Table:", " ", packageName, 13542 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13543 dumpState.setTitlePrinted(true); 13544 } 13545 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13546 : "Receiver Resolver Table:", " ", packageName, 13547 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13548 dumpState.setTitlePrinted(true); 13549 } 13550 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13551 : "Service Resolver Table:", " ", packageName, 13552 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13553 dumpState.setTitlePrinted(true); 13554 } 13555 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13556 : "Provider Resolver Table:", " ", packageName, 13557 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13558 dumpState.setTitlePrinted(true); 13559 } 13560 } 13561 13562 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13563 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13564 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13565 int user = mSettings.mPreferredActivities.keyAt(i); 13566 if (pir.dump(pw, 13567 dumpState.getTitlePrinted() 13568 ? "\nPreferred Activities User " + user + ":" 13569 : "Preferred Activities User " + user + ":", " ", 13570 packageName, true, false)) { 13571 dumpState.setTitlePrinted(true); 13572 } 13573 } 13574 } 13575 13576 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13577 pw.flush(); 13578 FileOutputStream fout = new FileOutputStream(fd); 13579 BufferedOutputStream str = new BufferedOutputStream(fout); 13580 XmlSerializer serializer = new FastXmlSerializer(); 13581 try { 13582 serializer.setOutput(str, "utf-8"); 13583 serializer.startDocument(null, true); 13584 serializer.setFeature( 13585 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13586 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13587 serializer.endDocument(); 13588 serializer.flush(); 13589 } catch (IllegalArgumentException e) { 13590 pw.println("Failed writing: " + e); 13591 } catch (IllegalStateException e) { 13592 pw.println("Failed writing: " + e); 13593 } catch (IOException e) { 13594 pw.println("Failed writing: " + e); 13595 } 13596 } 13597 13598 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13599 pw.println(); 13600 int count = mSettings.mPackages.size(); 13601 if (count == 0) { 13602 pw.println("No domain preferred apps!"); 13603 pw.println(); 13604 } else { 13605 final String prefix = " "; 13606 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13607 if (allPackageSettings.size() == 0) { 13608 pw.println("No domain preferred apps!"); 13609 pw.println(); 13610 } else { 13611 pw.println("Domain preferred apps status:"); 13612 pw.println(); 13613 count = 0; 13614 for (PackageSetting ps : allPackageSettings) { 13615 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13616 if (ivi == null || ivi.getPackageName() == null) continue; 13617 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13618 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13619 pw.println(prefix + "Status: " + ivi.getStatusString()); 13620 pw.println(); 13621 count++; 13622 } 13623 if (count == 0) { 13624 pw.println(prefix + "No domain preferred app status!"); 13625 pw.println(); 13626 } 13627 for (int userId : sUserManager.getUserIds()) { 13628 pw.println("Domain preferred apps for User " + userId + ":"); 13629 pw.println(); 13630 count = 0; 13631 for (PackageSetting ps : allPackageSettings) { 13632 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13633 if (ivi == null || ivi.getPackageName() == null) { 13634 continue; 13635 } 13636 final int status = ps.getDomainVerificationStatusForUser(userId); 13637 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13638 continue; 13639 } 13640 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13641 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13642 String statusStr = IntentFilterVerificationInfo. 13643 getStatusStringFromValue(status); 13644 pw.println(prefix + "Status: " + statusStr); 13645 pw.println(); 13646 count++; 13647 } 13648 if (count == 0) { 13649 pw.println(prefix + "No domain preferred apps!"); 13650 pw.println(); 13651 } 13652 } 13653 } 13654 } 13655 } 13656 13657 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13658 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13659 if (packageName == null) { 13660 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13661 if (iperm == 0) { 13662 if (dumpState.onTitlePrinted()) 13663 pw.println(); 13664 pw.println("AppOp Permissions:"); 13665 } 13666 pw.print(" AppOp Permission "); 13667 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13668 pw.println(":"); 13669 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13670 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13671 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13672 } 13673 } 13674 } 13675 } 13676 13677 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13678 boolean printedSomething = false; 13679 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13680 if (packageName != null && !packageName.equals(p.info.packageName)) { 13681 continue; 13682 } 13683 if (!printedSomething) { 13684 if (dumpState.onTitlePrinted()) 13685 pw.println(); 13686 pw.println("Registered ContentProviders:"); 13687 printedSomething = true; 13688 } 13689 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13690 pw.print(" "); pw.println(p.toString()); 13691 } 13692 printedSomething = false; 13693 for (Map.Entry<String, PackageParser.Provider> entry : 13694 mProvidersByAuthority.entrySet()) { 13695 PackageParser.Provider p = entry.getValue(); 13696 if (packageName != null && !packageName.equals(p.info.packageName)) { 13697 continue; 13698 } 13699 if (!printedSomething) { 13700 if (dumpState.onTitlePrinted()) 13701 pw.println(); 13702 pw.println("ContentProvider Authorities:"); 13703 printedSomething = true; 13704 } 13705 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13706 pw.print(" "); pw.println(p.toString()); 13707 if (p.info != null && p.info.applicationInfo != null) { 13708 final String appInfo = p.info.applicationInfo.toString(); 13709 pw.print(" applicationInfo="); pw.println(appInfo); 13710 } 13711 } 13712 } 13713 13714 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13715 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13716 } 13717 13718 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13719 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13720 } 13721 13722 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13723 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13724 } 13725 13726 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13727 // XXX should handle packageName != null by dumping only install data that 13728 // the given package is involved with. 13729 if (dumpState.onTitlePrinted()) pw.println(); 13730 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13731 } 13732 13733 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13734 if (dumpState.onTitlePrinted()) pw.println(); 13735 mSettings.dumpReadMessagesLPr(pw, dumpState); 13736 13737 pw.println(); 13738 pw.println("Package warning messages:"); 13739 BufferedReader in = null; 13740 String line = null; 13741 try { 13742 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13743 while ((line = in.readLine()) != null) { 13744 if (line.contains("ignored: updated version")) continue; 13745 pw.println(line); 13746 } 13747 } catch (IOException ignored) { 13748 } finally { 13749 IoUtils.closeQuietly(in); 13750 } 13751 } 13752 13753 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13754 BufferedReader in = null; 13755 String line = null; 13756 try { 13757 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13758 while ((line = in.readLine()) != null) { 13759 if (line.contains("ignored: updated version")) continue; 13760 pw.print("msg,"); 13761 pw.println(line); 13762 } 13763 } catch (IOException ignored) { 13764 } finally { 13765 IoUtils.closeQuietly(in); 13766 } 13767 } 13768 } 13769 } 13770 13771 // ------- apps on sdcard specific code ------- 13772 static final boolean DEBUG_SD_INSTALL = false; 13773 13774 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13775 13776 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13777 13778 private boolean mMediaMounted = false; 13779 13780 static String getEncryptKey() { 13781 try { 13782 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13783 SD_ENCRYPTION_KEYSTORE_NAME); 13784 if (sdEncKey == null) { 13785 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13786 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13787 if (sdEncKey == null) { 13788 Slog.e(TAG, "Failed to create encryption keys"); 13789 return null; 13790 } 13791 } 13792 return sdEncKey; 13793 } catch (NoSuchAlgorithmException nsae) { 13794 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13795 return null; 13796 } catch (IOException ioe) { 13797 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13798 return null; 13799 } 13800 } 13801 13802 /* 13803 * Update media status on PackageManager. 13804 */ 13805 @Override 13806 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13807 int callingUid = Binder.getCallingUid(); 13808 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13809 throw new SecurityException("Media status can only be updated by the system"); 13810 } 13811 // reader; this apparently protects mMediaMounted, but should probably 13812 // be a different lock in that case. 13813 synchronized (mPackages) { 13814 Log.i(TAG, "Updating external media status from " 13815 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13816 + (mediaStatus ? "mounted" : "unmounted")); 13817 if (DEBUG_SD_INSTALL) 13818 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13819 + ", mMediaMounted=" + mMediaMounted); 13820 if (mediaStatus == mMediaMounted) { 13821 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13822 : 0, -1); 13823 mHandler.sendMessage(msg); 13824 return; 13825 } 13826 mMediaMounted = mediaStatus; 13827 } 13828 // Queue up an async operation since the package installation may take a 13829 // little while. 13830 mHandler.post(new Runnable() { 13831 public void run() { 13832 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13833 } 13834 }); 13835 } 13836 13837 /** 13838 * Called by MountService when the initial ASECs to scan are available. 13839 * Should block until all the ASEC containers are finished being scanned. 13840 */ 13841 public void scanAvailableAsecs() { 13842 updateExternalMediaStatusInner(true, false, false); 13843 if (mShouldRestoreconData) { 13844 SELinuxMMAC.setRestoreconDone(); 13845 mShouldRestoreconData = false; 13846 } 13847 } 13848 13849 /* 13850 * Collect information of applications on external media, map them against 13851 * existing containers and update information based on current mount status. 13852 * Please note that we always have to report status if reportStatus has been 13853 * set to true especially when unloading packages. 13854 */ 13855 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13856 boolean externalStorage) { 13857 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13858 int[] uidArr = EmptyArray.INT; 13859 13860 final String[] list = PackageHelper.getSecureContainerList(); 13861 if (ArrayUtils.isEmpty(list)) { 13862 Log.i(TAG, "No secure containers found"); 13863 } else { 13864 // Process list of secure containers and categorize them 13865 // as active or stale based on their package internal state. 13866 13867 // reader 13868 synchronized (mPackages) { 13869 for (String cid : list) { 13870 // Leave stages untouched for now; installer service owns them 13871 if (PackageInstallerService.isStageName(cid)) continue; 13872 13873 if (DEBUG_SD_INSTALL) 13874 Log.i(TAG, "Processing container " + cid); 13875 String pkgName = getAsecPackageName(cid); 13876 if (pkgName == null) { 13877 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13878 continue; 13879 } 13880 if (DEBUG_SD_INSTALL) 13881 Log.i(TAG, "Looking for pkg : " + pkgName); 13882 13883 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13884 if (ps == null) { 13885 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13886 continue; 13887 } 13888 13889 /* 13890 * Skip packages that are not external if we're unmounting 13891 * external storage. 13892 */ 13893 if (externalStorage && !isMounted && !isExternal(ps)) { 13894 continue; 13895 } 13896 13897 final AsecInstallArgs args = new AsecInstallArgs(cid, 13898 getAppDexInstructionSets(ps), ps.isForwardLocked()); 13899 // The package status is changed only if the code path 13900 // matches between settings and the container id. 13901 if (ps.codePathString != null 13902 && ps.codePathString.startsWith(args.getCodePath())) { 13903 if (DEBUG_SD_INSTALL) { 13904 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13905 + " at code path: " + ps.codePathString); 13906 } 13907 13908 // We do have a valid package installed on sdcard 13909 processCids.put(args, ps.codePathString); 13910 final int uid = ps.appId; 13911 if (uid != -1) { 13912 uidArr = ArrayUtils.appendInt(uidArr, uid); 13913 } 13914 } else { 13915 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13916 + ps.codePathString); 13917 } 13918 } 13919 } 13920 13921 Arrays.sort(uidArr); 13922 } 13923 13924 // Process packages with valid entries. 13925 if (isMounted) { 13926 if (DEBUG_SD_INSTALL) 13927 Log.i(TAG, "Loading packages"); 13928 loadMediaPackages(processCids, uidArr); 13929 startCleaningPackages(); 13930 mInstallerService.onSecureContainersAvailable(); 13931 } else { 13932 if (DEBUG_SD_INSTALL) 13933 Log.i(TAG, "Unloading packages"); 13934 unloadMediaPackages(processCids, uidArr, reportStatus); 13935 } 13936 } 13937 13938 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13939 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 13940 final int size = infos.size(); 13941 final String[] packageNames = new String[size]; 13942 final int[] packageUids = new int[size]; 13943 for (int i = 0; i < size; i++) { 13944 final ApplicationInfo info = infos.get(i); 13945 packageNames[i] = info.packageName; 13946 packageUids[i] = info.uid; 13947 } 13948 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 13949 finishedReceiver); 13950 } 13951 13952 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13953 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13954 sendResourcesChangedBroadcast(mediaStatus, replacing, 13955 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 13956 } 13957 13958 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13959 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13960 int size = pkgList.length; 13961 if (size > 0) { 13962 // Send broadcasts here 13963 Bundle extras = new Bundle(); 13964 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13965 if (uidArr != null) { 13966 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13967 } 13968 if (replacing) { 13969 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13970 } 13971 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13972 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13973 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13974 } 13975 } 13976 13977 /* 13978 * Look at potentially valid container ids from processCids If package 13979 * information doesn't match the one on record or package scanning fails, 13980 * the cid is added to list of removeCids. We currently don't delete stale 13981 * containers. 13982 */ 13983 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13984 ArrayList<String> pkgList = new ArrayList<String>(); 13985 Set<AsecInstallArgs> keys = processCids.keySet(); 13986 13987 for (AsecInstallArgs args : keys) { 13988 String codePath = processCids.get(args); 13989 if (DEBUG_SD_INSTALL) 13990 Log.i(TAG, "Loading container : " + args.cid); 13991 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13992 try { 13993 // Make sure there are no container errors first. 13994 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13995 Slog.e(TAG, "Failed to mount cid : " + args.cid 13996 + " when installing from sdcard"); 13997 continue; 13998 } 13999 // Check code path here. 14000 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14001 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14002 + " does not match one in settings " + codePath); 14003 continue; 14004 } 14005 // Parse package 14006 int parseFlags = mDefParseFlags; 14007 if (args.isExternalAsec()) { 14008 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14009 } 14010 if (args.isFwdLocked()) { 14011 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14012 } 14013 14014 synchronized (mInstallLock) { 14015 PackageParser.Package pkg = null; 14016 try { 14017 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14018 } catch (PackageManagerException e) { 14019 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14020 } 14021 // Scan the package 14022 if (pkg != null) { 14023 /* 14024 * TODO why is the lock being held? doPostInstall is 14025 * called in other places without the lock. This needs 14026 * to be straightened out. 14027 */ 14028 // writer 14029 synchronized (mPackages) { 14030 retCode = PackageManager.INSTALL_SUCCEEDED; 14031 pkgList.add(pkg.packageName); 14032 // Post process args 14033 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14034 pkg.applicationInfo.uid); 14035 } 14036 } else { 14037 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14038 } 14039 } 14040 14041 } finally { 14042 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14043 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14044 } 14045 } 14046 } 14047 // writer 14048 synchronized (mPackages) { 14049 // If the platform SDK has changed since the last time we booted, 14050 // we need to re-grant app permission to catch any new ones that 14051 // appear. This is really a hack, and means that apps can in some 14052 // cases get permissions that the user didn't initially explicitly 14053 // allow... it would be nice to have some better way to handle 14054 // this situation. 14055 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14056 if (regrantPermissions) 14057 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14058 + mSdkVersion + "; regranting permissions for external storage"); 14059 mSettings.mExternalSdkPlatform = mSdkVersion; 14060 14061 // Make sure group IDs have been assigned, and any permission 14062 // changes in other apps are accounted for 14063 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14064 | (regrantPermissions 14065 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14066 : 0)); 14067 14068 mSettings.updateExternalDatabaseVersion(); 14069 14070 // can downgrade to reader 14071 // Persist settings 14072 mSettings.writeLPr(); 14073 } 14074 // Send a broadcast to let everyone know we are done processing 14075 if (pkgList.size() > 0) { 14076 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14077 } 14078 } 14079 14080 /* 14081 * Utility method to unload a list of specified containers 14082 */ 14083 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14084 // Just unmount all valid containers. 14085 for (AsecInstallArgs arg : cidArgs) { 14086 synchronized (mInstallLock) { 14087 arg.doPostDeleteLI(false); 14088 } 14089 } 14090 } 14091 14092 /* 14093 * Unload packages mounted on external media. This involves deleting package 14094 * data from internal structures, sending broadcasts about diabled packages, 14095 * gc'ing to free up references, unmounting all secure containers 14096 * corresponding to packages on external media, and posting a 14097 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14098 * that we always have to post this message if status has been requested no 14099 * matter what. 14100 */ 14101 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14102 final boolean reportStatus) { 14103 if (DEBUG_SD_INSTALL) 14104 Log.i(TAG, "unloading media packages"); 14105 ArrayList<String> pkgList = new ArrayList<String>(); 14106 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14107 final Set<AsecInstallArgs> keys = processCids.keySet(); 14108 for (AsecInstallArgs args : keys) { 14109 String pkgName = args.getPackageName(); 14110 if (DEBUG_SD_INSTALL) 14111 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14112 // Delete package internally 14113 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14114 synchronized (mInstallLock) { 14115 boolean res = deletePackageLI(pkgName, null, false, null, null, 14116 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14117 if (res) { 14118 pkgList.add(pkgName); 14119 } else { 14120 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14121 failedList.add(args); 14122 } 14123 } 14124 } 14125 14126 // reader 14127 synchronized (mPackages) { 14128 // We didn't update the settings after removing each package; 14129 // write them now for all packages. 14130 mSettings.writeLPr(); 14131 } 14132 14133 // We have to absolutely send UPDATED_MEDIA_STATUS only 14134 // after confirming that all the receivers processed the ordered 14135 // broadcast when packages get disabled, force a gc to clean things up. 14136 // and unload all the containers. 14137 if (pkgList.size() > 0) { 14138 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14139 new IIntentReceiver.Stub() { 14140 public void performReceive(Intent intent, int resultCode, String data, 14141 Bundle extras, boolean ordered, boolean sticky, 14142 int sendingUser) throws RemoteException { 14143 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14144 reportStatus ? 1 : 0, 1, keys); 14145 mHandler.sendMessage(msg); 14146 } 14147 }); 14148 } else { 14149 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14150 keys); 14151 mHandler.sendMessage(msg); 14152 } 14153 } 14154 14155 private void loadPrivatePackages(VolumeInfo vol) { 14156 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14157 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14158 synchronized (mPackages) { 14159 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14160 for (PackageSetting ps : packages) { 14161 synchronized (mInstallLock) { 14162 final PackageParser.Package pkg; 14163 try { 14164 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14165 loaded.add(pkg.applicationInfo); 14166 } catch (PackageManagerException e) { 14167 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14168 } 14169 } 14170 } 14171 14172 // TODO: regrant any permissions that changed based since original install 14173 14174 mSettings.writeLPr(); 14175 } 14176 14177 Slog.d(TAG, "Loaded packages " + loaded); 14178 sendResourcesChangedBroadcast(true, false, loaded, null); 14179 } 14180 14181 private void unloadPrivatePackages(VolumeInfo vol) { 14182 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14183 synchronized (mPackages) { 14184 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14185 for (PackageSetting ps : packages) { 14186 if (ps.pkg == null) continue; 14187 synchronized (mInstallLock) { 14188 final ApplicationInfo info = ps.pkg.applicationInfo; 14189 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14190 if (deletePackageLI(ps.name, null, false, null, null, 14191 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14192 unloaded.add(info); 14193 } else { 14194 Slog.w(TAG, "Failed to unload " + ps.codePath); 14195 } 14196 } 14197 } 14198 14199 mSettings.writeLPr(); 14200 } 14201 14202 Slog.d(TAG, "Unloaded packages " + unloaded); 14203 sendResourcesChangedBroadcast(false, false, unloaded, null); 14204 } 14205 14206 @Override 14207 public int movePackage(final String packageName, final String volumeUuid) { 14208 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14209 14210 final int moveId = mNextMoveId.getAndIncrement(); 14211 try { 14212 movePackageInternal(packageName, volumeUuid, moveId); 14213 } catch (PackageManagerException e) { 14214 Slog.d(TAG, "Failed to move " + packageName, e); 14215 mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14216 } 14217 return moveId; 14218 } 14219 14220 private void movePackageInternal(final String packageName, final String volumeUuid, 14221 final int moveId) throws PackageManagerException { 14222 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14223 final PackageManager pm = mContext.getPackageManager(); 14224 14225 final boolean currentAsec; 14226 final String currentVolumeUuid; 14227 final File codeFile; 14228 final String installerPackageName; 14229 final String packageAbiOverride; 14230 final int appId; 14231 final String seinfo; 14232 14233 // reader 14234 synchronized (mPackages) { 14235 final PackageParser.Package pkg = mPackages.get(packageName); 14236 final PackageSetting ps = mSettings.mPackages.get(packageName); 14237 if (pkg == null || ps == null) { 14238 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14239 } 14240 14241 if (pkg.applicationInfo.isSystemApp()) { 14242 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14243 "Cannot move system application"); 14244 } else if (pkg.mOperationPending) { 14245 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14246 "Attempt to move package which has pending operations"); 14247 } 14248 14249 // TODO: yell if already in desired location 14250 14251 mMoveCallbacks.notifyStarted(moveId, 14252 String.valueOf(pm.getApplicationLabel(pkg.applicationInfo))); 14253 14254 pkg.mOperationPending = true; 14255 14256 currentAsec = pkg.applicationInfo.isForwardLocked() 14257 || pkg.applicationInfo.isExternalAsec(); 14258 currentVolumeUuid = ps.volumeUuid; 14259 codeFile = new File(pkg.codePath); 14260 installerPackageName = ps.installerPackageName; 14261 packageAbiOverride = ps.cpuAbiOverrideString; 14262 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14263 seinfo = pkg.applicationInfo.seinfo; 14264 } 14265 14266 int installFlags; 14267 final boolean moveData; 14268 14269 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14270 installFlags = INSTALL_INTERNAL; 14271 moveData = !currentAsec; 14272 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14273 installFlags = INSTALL_EXTERNAL; 14274 moveData = false; 14275 } else { 14276 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14277 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14278 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14279 || !volume.isMountedWritable()) { 14280 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14281 "Move location not mounted private volume"); 14282 } 14283 14284 Preconditions.checkState(!currentAsec); 14285 14286 installFlags = INSTALL_INTERNAL; 14287 moveData = true; 14288 } 14289 14290 Slog.d(TAG, "Moving " + packageName + " from " + currentVolumeUuid + " to " + volumeUuid); 14291 mMoveCallbacks.notifyStatusChanged(moveId, 10, -1); 14292 14293 if (moveData) { 14294 synchronized (mInstallLock) { 14295 // TODO: split this into separate copy and delete operations 14296 if (mInstaller.moveUserDataDirs(currentVolumeUuid, volumeUuid, packageName, appId, 14297 seinfo) != 0) { 14298 synchronized (mPackages) { 14299 final PackageParser.Package pkg = mPackages.get(packageName); 14300 if (pkg != null) { 14301 pkg.mOperationPending = false; 14302 } 14303 } 14304 14305 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14306 "Failed to move private data"); 14307 } 14308 } 14309 } 14310 14311 mMoveCallbacks.notifyStatusChanged(moveId, 50); 14312 14313 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14314 @Override 14315 public void onUserActionRequired(Intent intent) throws RemoteException { 14316 throw new IllegalStateException(); 14317 } 14318 14319 @Override 14320 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14321 Bundle extras) throws RemoteException { 14322 Slog.d(TAG, "Install result for move: " 14323 + PackageManager.installStatusToString(returnCode, msg)); 14324 14325 // We usually have a new package now after the install, but if 14326 // we failed we need to clear the pending flag on the original 14327 // package object. 14328 synchronized (mPackages) { 14329 final PackageParser.Package pkg = mPackages.get(packageName); 14330 if (pkg != null) { 14331 pkg.mOperationPending = false; 14332 } 14333 } 14334 14335 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14336 switch (status) { 14337 case PackageInstaller.STATUS_SUCCESS: 14338 mMoveCallbacks.notifyStatusChanged(moveId, 14339 PackageManager.MOVE_SUCCEEDED); 14340 break; 14341 case PackageInstaller.STATUS_FAILURE_STORAGE: 14342 mMoveCallbacks.notifyStatusChanged(moveId, 14343 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14344 break; 14345 default: 14346 mMoveCallbacks.notifyStatusChanged(moveId, 14347 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14348 break; 14349 } 14350 } 14351 }; 14352 14353 // Treat a move like reinstalling an existing app, which ensures that we 14354 // process everythign uniformly, like unpacking native libraries. 14355 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14356 14357 final Message msg = mHandler.obtainMessage(INIT_COPY); 14358 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14359 msg.obj = new InstallParams(origin, installObserver, installFlags, 14360 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14361 mHandler.sendMessage(msg); 14362 } 14363 14364 @Override 14365 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14367 14368 final int realMoveId = mNextMoveId.getAndIncrement(); 14369 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14370 @Override 14371 public void onStarted(int moveId, String title) { 14372 // Ignored 14373 } 14374 14375 @Override 14376 public void onStatusChanged(int moveId, int status, long estMillis) { 14377 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14378 } 14379 }; 14380 14381 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14382 storage.setPrimaryStorageUuid(volumeUuid, callback); 14383 return realMoveId; 14384 } 14385 14386 @Override 14387 public int getMoveStatus(int moveId) { 14388 mContext.enforceCallingOrSelfPermission( 14389 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14390 return mMoveCallbacks.mLastStatus.get(moveId); 14391 } 14392 14393 @Override 14394 public void registerMoveCallback(IPackageMoveObserver callback) { 14395 mContext.enforceCallingOrSelfPermission( 14396 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14397 mMoveCallbacks.register(callback); 14398 } 14399 14400 @Override 14401 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14402 mContext.enforceCallingOrSelfPermission( 14403 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14404 mMoveCallbacks.unregister(callback); 14405 } 14406 14407 @Override 14408 public boolean setInstallLocation(int loc) { 14409 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14410 null); 14411 if (getInstallLocation() == loc) { 14412 return true; 14413 } 14414 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14415 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14416 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14417 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14418 return true; 14419 } 14420 return false; 14421 } 14422 14423 @Override 14424 public int getInstallLocation() { 14425 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14426 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14427 PackageHelper.APP_INSTALL_AUTO); 14428 } 14429 14430 /** Called by UserManagerService */ 14431 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14432 mDirtyUsers.remove(userHandle); 14433 mSettings.removeUserLPw(userHandle); 14434 mPendingBroadcasts.remove(userHandle); 14435 if (mInstaller != null) { 14436 // Technically, we shouldn't be doing this with the package lock 14437 // held. However, this is very rare, and there is already so much 14438 // other disk I/O going on, that we'll let it slide for now. 14439 final StorageManager storage = StorageManager.from(mContext); 14440 final List<VolumeInfo> vols = storage.getVolumes(); 14441 for (VolumeInfo vol : vols) { 14442 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14443 final String volumeUuid = vol.getFsUuid(); 14444 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14445 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14446 } 14447 } 14448 } 14449 mUserNeedsBadging.delete(userHandle); 14450 removeUnusedPackagesLILPw(userManager, userHandle); 14451 } 14452 14453 /** 14454 * We're removing userHandle and would like to remove any downloaded packages 14455 * that are no longer in use by any other user. 14456 * @param userHandle the user being removed 14457 */ 14458 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14459 final boolean DEBUG_CLEAN_APKS = false; 14460 int [] users = userManager.getUserIdsLPr(); 14461 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14462 while (psit.hasNext()) { 14463 PackageSetting ps = psit.next(); 14464 if (ps.pkg == null) { 14465 continue; 14466 } 14467 final String packageName = ps.pkg.packageName; 14468 // Skip over if system app 14469 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14470 continue; 14471 } 14472 if (DEBUG_CLEAN_APKS) { 14473 Slog.i(TAG, "Checking package " + packageName); 14474 } 14475 boolean keep = false; 14476 for (int i = 0; i < users.length; i++) { 14477 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14478 keep = true; 14479 if (DEBUG_CLEAN_APKS) { 14480 Slog.i(TAG, " Keeping package " + packageName + " for user " 14481 + users[i]); 14482 } 14483 break; 14484 } 14485 } 14486 if (!keep) { 14487 if (DEBUG_CLEAN_APKS) { 14488 Slog.i(TAG, " Removing package " + packageName); 14489 } 14490 mHandler.post(new Runnable() { 14491 public void run() { 14492 deletePackageX(packageName, userHandle, 0); 14493 } //end run 14494 }); 14495 } 14496 } 14497 } 14498 14499 /** Called by UserManagerService */ 14500 void createNewUserLILPw(int userHandle, File path) { 14501 if (mInstaller != null) { 14502 mInstaller.createUserConfig(userHandle); 14503 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14504 } 14505 } 14506 14507 void newUserCreatedLILPw(int userHandle) { 14508 // Adding a user requires updating runtime permissions for system apps. 14509 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14510 } 14511 14512 @Override 14513 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14514 mContext.enforceCallingOrSelfPermission( 14515 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14516 "Only package verification agents can read the verifier device identity"); 14517 14518 synchronized (mPackages) { 14519 return mSettings.getVerifierDeviceIdentityLPw(); 14520 } 14521 } 14522 14523 @Override 14524 public void setPermissionEnforced(String permission, boolean enforced) { 14525 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14526 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14527 synchronized (mPackages) { 14528 if (mSettings.mReadExternalStorageEnforced == null 14529 || mSettings.mReadExternalStorageEnforced != enforced) { 14530 mSettings.mReadExternalStorageEnforced = enforced; 14531 mSettings.writeLPr(); 14532 } 14533 } 14534 // kill any non-foreground processes so we restart them and 14535 // grant/revoke the GID. 14536 final IActivityManager am = ActivityManagerNative.getDefault(); 14537 if (am != null) { 14538 final long token = Binder.clearCallingIdentity(); 14539 try { 14540 am.killProcessesBelowForeground("setPermissionEnforcement"); 14541 } catch (RemoteException e) { 14542 } finally { 14543 Binder.restoreCallingIdentity(token); 14544 } 14545 } 14546 } else { 14547 throw new IllegalArgumentException("No selective enforcement for " + permission); 14548 } 14549 } 14550 14551 @Override 14552 @Deprecated 14553 public boolean isPermissionEnforced(String permission) { 14554 return true; 14555 } 14556 14557 @Override 14558 public boolean isStorageLow() { 14559 final long token = Binder.clearCallingIdentity(); 14560 try { 14561 final DeviceStorageMonitorInternal 14562 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14563 if (dsm != null) { 14564 return dsm.isMemoryLow(); 14565 } else { 14566 return false; 14567 } 14568 } finally { 14569 Binder.restoreCallingIdentity(token); 14570 } 14571 } 14572 14573 @Override 14574 public IPackageInstaller getPackageInstaller() { 14575 return mInstallerService; 14576 } 14577 14578 private boolean userNeedsBadging(int userId) { 14579 int index = mUserNeedsBadging.indexOfKey(userId); 14580 if (index < 0) { 14581 final UserInfo userInfo; 14582 final long token = Binder.clearCallingIdentity(); 14583 try { 14584 userInfo = sUserManager.getUserInfo(userId); 14585 } finally { 14586 Binder.restoreCallingIdentity(token); 14587 } 14588 final boolean b; 14589 if (userInfo != null && userInfo.isManagedProfile()) { 14590 b = true; 14591 } else { 14592 b = false; 14593 } 14594 mUserNeedsBadging.put(userId, b); 14595 return b; 14596 } 14597 return mUserNeedsBadging.valueAt(index); 14598 } 14599 14600 @Override 14601 public KeySet getKeySetByAlias(String packageName, String alias) { 14602 if (packageName == null || alias == null) { 14603 return null; 14604 } 14605 synchronized(mPackages) { 14606 final PackageParser.Package pkg = mPackages.get(packageName); 14607 if (pkg == null) { 14608 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14609 throw new IllegalArgumentException("Unknown package: " + packageName); 14610 } 14611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14612 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14613 } 14614 } 14615 14616 @Override 14617 public KeySet getSigningKeySet(String packageName) { 14618 if (packageName == null) { 14619 return null; 14620 } 14621 synchronized(mPackages) { 14622 final PackageParser.Package pkg = mPackages.get(packageName); 14623 if (pkg == null) { 14624 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14625 throw new IllegalArgumentException("Unknown package: " + packageName); 14626 } 14627 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14628 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14629 throw new SecurityException("May not access signing KeySet of other apps."); 14630 } 14631 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14632 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14633 } 14634 } 14635 14636 @Override 14637 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14638 if (packageName == null || ks == null) { 14639 return false; 14640 } 14641 synchronized(mPackages) { 14642 final PackageParser.Package pkg = mPackages.get(packageName); 14643 if (pkg == null) { 14644 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14645 throw new IllegalArgumentException("Unknown package: " + packageName); 14646 } 14647 IBinder ksh = ks.getToken(); 14648 if (ksh instanceof KeySetHandle) { 14649 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14650 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14651 } 14652 return false; 14653 } 14654 } 14655 14656 @Override 14657 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14658 if (packageName == null || ks == null) { 14659 return false; 14660 } 14661 synchronized(mPackages) { 14662 final PackageParser.Package pkg = mPackages.get(packageName); 14663 if (pkg == null) { 14664 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14665 throw new IllegalArgumentException("Unknown package: " + packageName); 14666 } 14667 IBinder ksh = ks.getToken(); 14668 if (ksh instanceof KeySetHandle) { 14669 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14670 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14671 } 14672 return false; 14673 } 14674 } 14675 14676 public void getUsageStatsIfNoPackageUsageInfo() { 14677 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14678 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14679 if (usm == null) { 14680 throw new IllegalStateException("UsageStatsManager must be initialized"); 14681 } 14682 long now = System.currentTimeMillis(); 14683 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14684 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14685 String packageName = entry.getKey(); 14686 PackageParser.Package pkg = mPackages.get(packageName); 14687 if (pkg == null) { 14688 continue; 14689 } 14690 UsageStats usage = entry.getValue(); 14691 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14692 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14693 } 14694 } 14695 } 14696 14697 /** 14698 * Check and throw if the given before/after packages would be considered a 14699 * downgrade. 14700 */ 14701 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14702 throws PackageManagerException { 14703 if (after.versionCode < before.mVersionCode) { 14704 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14705 "Update version code " + after.versionCode + " is older than current " 14706 + before.mVersionCode); 14707 } else if (after.versionCode == before.mVersionCode) { 14708 if (after.baseRevisionCode < before.baseRevisionCode) { 14709 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14710 "Update base revision code " + after.baseRevisionCode 14711 + " is older than current " + before.baseRevisionCode); 14712 } 14713 14714 if (!ArrayUtils.isEmpty(after.splitNames)) { 14715 for (int i = 0; i < after.splitNames.length; i++) { 14716 final String splitName = after.splitNames[i]; 14717 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14718 if (j != -1) { 14719 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14720 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14721 "Update split " + splitName + " revision code " 14722 + after.splitRevisionCodes[i] + " is older than current " 14723 + before.splitRevisionCodes[j]); 14724 } 14725 } 14726 } 14727 } 14728 } 14729 } 14730 14731 private static class MoveCallbacks extends Handler { 14732 private static final int MSG_STARTED = 1; 14733 private static final int MSG_STATUS_CHANGED = 2; 14734 14735 private final RemoteCallbackList<IPackageMoveObserver> 14736 mCallbacks = new RemoteCallbackList<>(); 14737 14738 private final SparseIntArray mLastStatus = new SparseIntArray(); 14739 14740 public MoveCallbacks(Looper looper) { 14741 super(looper); 14742 } 14743 14744 public void register(IPackageMoveObserver callback) { 14745 mCallbacks.register(callback); 14746 } 14747 14748 public void unregister(IPackageMoveObserver callback) { 14749 mCallbacks.unregister(callback); 14750 } 14751 14752 @Override 14753 public void handleMessage(Message msg) { 14754 final SomeArgs args = (SomeArgs) msg.obj; 14755 final int n = mCallbacks.beginBroadcast(); 14756 for (int i = 0; i < n; i++) { 14757 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14758 try { 14759 invokeCallback(callback, msg.what, args); 14760 } catch (RemoteException ignored) { 14761 } 14762 } 14763 mCallbacks.finishBroadcast(); 14764 args.recycle(); 14765 } 14766 14767 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14768 throws RemoteException { 14769 switch (what) { 14770 case MSG_STARTED: { 14771 callback.onStarted(args.argi1, (String) args.arg2); 14772 break; 14773 } 14774 case MSG_STATUS_CHANGED: { 14775 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14776 break; 14777 } 14778 } 14779 } 14780 14781 private void notifyStarted(int moveId, String title) { 14782 Slog.v(TAG, "Move " + moveId + " started with title " + title); 14783 14784 final SomeArgs args = SomeArgs.obtain(); 14785 args.argi1 = moveId; 14786 args.arg2 = title; 14787 obtainMessage(MSG_STARTED, args).sendToTarget(); 14788 } 14789 14790 private void notifyStatusChanged(int moveId, int status) { 14791 notifyStatusChanged(moveId, status, -1); 14792 } 14793 14794 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14795 Slog.v(TAG, "Move " + moveId + " status " + status); 14796 14797 final SomeArgs args = SomeArgs.obtain(); 14798 args.argi1 = moveId; 14799 args.argi2 = status; 14800 args.arg3 = estMillis; 14801 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14802 14803 synchronized (mLastStatus) { 14804 mLastStatus.put(moveId, status); 14805 } 14806 } 14807 } 14808} 14809