PackageManagerService.java revision a320505f3a39e21f29065f0f2a01089363825318
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.os.storage.VolumeRecord; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArrayMap; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.MathUtils; 175import android.util.PrintStreamPrinter; 176import android.util.Slog; 177import android.util.SparseArray; 178import android.util.SparseBooleanArray; 179import android.util.SparseIntArray; 180import android.util.Xml; 181import android.view.Display; 182 183import dalvik.system.DexFile; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187import libcore.util.EmptyArray; 188 189import com.android.internal.R; 190import com.android.internal.app.IMediaContainerService; 191import com.android.internal.app.ResolverActivity; 192import com.android.internal.content.NativeLibraryHelper; 193import com.android.internal.content.PackageHelper; 194import com.android.internal.os.IParcelFileDescriptorFactory; 195import com.android.internal.os.SomeArgs; 196import com.android.internal.util.ArrayUtils; 197import com.android.internal.util.FastPrintWriter; 198import com.android.internal.util.FastXmlSerializer; 199import com.android.internal.util.IndentingPrintWriter; 200import com.android.internal.util.Preconditions; 201import com.android.server.EventLogTags; 202import com.android.server.FgThread; 203import com.android.server.IntentResolver; 204import com.android.server.LocalServices; 205import com.android.server.ServiceThread; 206import com.android.server.SystemConfig; 207import com.android.server.Watchdog; 208import com.android.server.pm.Settings.DatabaseVersion; 209import com.android.server.storage.DeviceStorageMonitorInternal; 210 211import org.xmlpull.v1.XmlPullParser; 212import org.xmlpull.v1.XmlSerializer; 213 214import java.io.BufferedInputStream; 215import java.io.BufferedOutputStream; 216import java.io.BufferedReader; 217import java.io.ByteArrayInputStream; 218import java.io.ByteArrayOutputStream; 219import java.io.File; 220import java.io.FileDescriptor; 221import java.io.FileNotFoundException; 222import java.io.FileOutputStream; 223import java.io.FileReader; 224import java.io.FilenameFilter; 225import java.io.IOException; 226import java.io.InputStream; 227import java.io.PrintWriter; 228import java.nio.charset.StandardCharsets; 229import java.security.NoSuchAlgorithmException; 230import java.security.PublicKey; 231import java.security.cert.CertificateEncodingException; 232import java.security.cert.CertificateException; 233import java.text.SimpleDateFormat; 234import java.util.ArrayList; 235import java.util.Arrays; 236import java.util.Collection; 237import java.util.Collections; 238import java.util.Comparator; 239import java.util.Date; 240import java.util.Iterator; 241import java.util.List; 242import java.util.Map; 243import java.util.Objects; 244import java.util.Set; 245import java.util.concurrent.CountDownLatch; 246import java.util.concurrent.TimeUnit; 247import java.util.concurrent.atomic.AtomicBoolean; 248import java.util.concurrent.atomic.AtomicInteger; 249import java.util.concurrent.atomic.AtomicLong; 250 251/** 252 * Keep track of all those .apks everywhere. 253 * 254 * This is very central to the platform's security; please run the unit 255 * tests whenever making modifications here: 256 * 257mmm frameworks/base/tests/AndroidTests 258adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 259adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 260 * 261 * {@hide} 262 */ 263public class PackageManagerService extends IPackageManager.Stub { 264 static final String TAG = "PackageManager"; 265 static final boolean DEBUG_SETTINGS = false; 266 static final boolean DEBUG_PREFERRED = false; 267 static final boolean DEBUG_UPGRADE = false; 268 private static final boolean DEBUG_BACKUP = true; 269 private static final boolean DEBUG_INSTALL = false; 270 private static final boolean DEBUG_REMOVE = false; 271 private static final boolean DEBUG_BROADCASTS = false; 272 private static final boolean DEBUG_SHOW_INFO = false; 273 private static final boolean DEBUG_PACKAGE_INFO = false; 274 private static final boolean DEBUG_INTENT_MATCHING = false; 275 private static final boolean DEBUG_PACKAGE_SCANNING = false; 276 private static final boolean DEBUG_VERIFY = false; 277 private static final boolean DEBUG_DEXOPT = false; 278 private static final boolean DEBUG_ABI_SELECTION = false; 279 280 static final boolean RUNTIME_PERMISSIONS_ENABLED = true; 281 282 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 307 static final int REMOVE_CHATTY = 1<<16; 308 309 /** 310 * Timeout (in milliseconds) after which the watchdog should declare that 311 * our handler thread is wedged. The usual default for such things is one 312 * minute but we sometimes do very lengthy I/O operations on this thread, 313 * such as installing multi-gigabyte applications, so ours needs to be longer. 314 */ 315 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 316 317 /** 318 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 319 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 320 * settings entry if available, otherwise we use the hardcoded default. If it's been 321 * more than this long since the last fstrim, we force one during the boot sequence. 322 * 323 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 324 * one gets run at the next available charging+idle time. This final mandatory 325 * no-fstrim check kicks in only of the other scheduling criteria is never met. 326 */ 327 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 328 329 /** 330 * Whether verification is enabled by default. 331 */ 332 private static final boolean DEFAULT_VERIFY_ENABLE = true; 333 334 /** 335 * The default maximum time to wait for the verification agent to return in 336 * milliseconds. 337 */ 338 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 339 340 /** 341 * The default response for package verification timeout. 342 * 343 * This can be either PackageManager.VERIFICATION_ALLOW or 344 * PackageManager.VERIFICATION_REJECT. 345 */ 346 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 347 348 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 349 350 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 351 DEFAULT_CONTAINER_PACKAGE, 352 "com.android.defcontainer.DefaultContainerService"); 353 354 private static final String KILL_APP_REASON_GIDS_CHANGED = 355 "permission grant or revoke changed gids"; 356 357 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 358 "permissions revoked"; 359 360 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 361 362 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 363 364 /** Permission grant: not grant the permission. */ 365 private static final int GRANT_DENIED = 1; 366 367 /** Permission grant: grant the permission as an install permission. */ 368 private static final int GRANT_INSTALL = 2; 369 370 /** Permission grant: grant the permission as a runtime one. */ 371 private static final int GRANT_RUNTIME = 3; 372 373 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 374 private static final int GRANT_UPGRADE = 4; 375 376 final ServiceThread mHandlerThread; 377 378 final PackageHandler mHandler; 379 380 /** 381 * Messages for {@link #mHandler} that need to wait for system ready before 382 * being dispatched. 383 */ 384 private ArrayList<Message> mPostSystemReadyMessages; 385 386 final int mSdkVersion = Build.VERSION.SDK_INT; 387 388 final Context mContext; 389 final boolean mFactoryTest; 390 final boolean mOnlyCore; 391 final boolean mLazyDexOpt; 392 final long mDexOptLRUThresholdInMills; 393 final DisplayMetrics mMetrics; 394 final int mDefParseFlags; 395 final String[] mSeparateProcesses; 396 final boolean mIsUpgrade; 397 398 // This is where all application persistent data goes. 399 final File mAppDataDir; 400 401 // This is where all application persistent data goes for secondary users. 402 final File mUserAppDataDir; 403 404 /** The location for ASEC container files on internal storage. */ 405 final String mAsecInternalPath; 406 407 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 408 // LOCK HELD. Can be called with mInstallLock held. 409 final Installer mInstaller; 410 411 /** Directory where installed third-party apps stored */ 412 final File mAppInstallDir; 413 414 /** 415 * Directory to which applications installed internally have their 416 * 32 bit native libraries copied. 417 */ 418 private File mAppLib32InstallDir; 419 420 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 421 // apps. 422 final File mDrmAppPrivateInstallDir; 423 424 // ---------------------------------------------------------------- 425 426 // Lock for state used when installing and doing other long running 427 // operations. Methods that must be called with this lock held have 428 // the suffix "LI". 429 final Object mInstallLock = new Object(); 430 431 // ---------------------------------------------------------------- 432 433 // Keys are String (package name), values are Package. This also serves 434 // as the lock for the global state. Methods that must be called with 435 // this lock held have the prefix "LP". 436 final ArrayMap<String, PackageParser.Package> mPackages = 437 new ArrayMap<String, PackageParser.Package>(); 438 439 // Tracks available target package names -> overlay package paths. 440 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 441 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 442 443 final Settings mSettings; 444 boolean mRestoredSettings; 445 446 // System configuration read by SystemConfig. 447 final int[] mGlobalGids; 448 final SparseArray<ArraySet<String>> mSystemPermissions; 449 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 450 451 // If mac_permissions.xml was found for seinfo labeling. 452 boolean mFoundPolicyFile; 453 454 // If a recursive restorecon of /data/data/<pkg> is needed. 455 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 456 457 public static final class SharedLibraryEntry { 458 public final String path; 459 public final String apk; 460 461 SharedLibraryEntry(String _path, String _apk) { 462 path = _path; 463 apk = _apk; 464 } 465 } 466 467 // Currently known shared libraries. 468 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 469 new ArrayMap<String, SharedLibraryEntry>(); 470 471 // All available activities, for your resolving pleasure. 472 final ActivityIntentResolver mActivities = 473 new ActivityIntentResolver(); 474 475 // All available receivers, for your resolving pleasure. 476 final ActivityIntentResolver mReceivers = 477 new ActivityIntentResolver(); 478 479 // All available services, for your resolving pleasure. 480 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 481 482 // All available providers, for your resolving pleasure. 483 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 484 485 // Mapping from provider base names (first directory in content URI codePath) 486 // to the provider information. 487 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 488 new ArrayMap<String, PackageParser.Provider>(); 489 490 // Mapping from instrumentation class names to info about them. 491 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 492 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 493 494 // Mapping from permission names to info about them. 495 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 496 new ArrayMap<String, PackageParser.PermissionGroup>(); 497 498 // Packages whose data we have transfered into another package, thus 499 // should no longer exist. 500 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 501 502 // Broadcast actions that are only available to the system. 503 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 504 505 /** List of packages waiting for verification. */ 506 final SparseArray<PackageVerificationState> mPendingVerification 507 = new SparseArray<PackageVerificationState>(); 508 509 /** Set of packages associated with each app op permission. */ 510 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 511 512 final PackageInstallerService mInstallerService; 513 514 private final PackageDexOptimizer mPackageDexOptimizer; 515 516 private AtomicInteger mNextMoveId = new AtomicInteger(); 517 private final MoveCallbacks mMoveCallbacks; 518 519 // Cache of users who need badging. 520 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 521 522 /** Token for keys in mPendingVerification. */ 523 private int mPendingVerificationToken = 0; 524 525 volatile boolean mSystemReady; 526 volatile boolean mSafeMode; 527 volatile boolean mHasSystemUidErrors; 528 529 ApplicationInfo mAndroidApplication; 530 final ActivityInfo mResolveActivity = new ActivityInfo(); 531 final ResolveInfo mResolveInfo = new ResolveInfo(); 532 ComponentName mResolveComponentName; 533 PackageParser.Package mPlatformPackage; 534 ComponentName mCustomResolverComponentName; 535 536 boolean mResolverReplaced = false; 537 538 private final ComponentName mIntentFilterVerifierComponent; 539 private int mIntentFilterVerificationToken = 0; 540 541 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 542 = new SparseArray<IntentFilterVerificationState>(); 543 544 private interface IntentFilterVerifier<T extends IntentFilter> { 545 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 546 T filter, String packageName); 547 void startVerifications(int userId); 548 void receiveVerificationResponse(int verificationId); 549 } 550 551 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 552 private Context mContext; 553 private ComponentName mIntentFilterVerifierComponent; 554 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 555 556 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 557 mContext = context; 558 mIntentFilterVerifierComponent = verifierComponent; 559 } 560 561 private String getDefaultScheme() { 562 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 563 return IntentFilter.SCHEME_HTTP; 564 } 565 566 @Override 567 public void startVerifications(int userId) { 568 // Launch verifications requests 569 int count = mCurrentIntentFilterVerifications.size(); 570 for (int n=0; n<count; n++) { 571 int verificationId = mCurrentIntentFilterVerifications.get(n); 572 final IntentFilterVerificationState ivs = 573 mIntentFilterVerificationStates.get(verificationId); 574 575 String packageName = ivs.getPackageName(); 576 577 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 578 final int filterCount = filters.size(); 579 ArraySet<String> domainsSet = new ArraySet<>(); 580 for (int m=0; m<filterCount; m++) { 581 PackageParser.ActivityIntentInfo filter = filters.get(m); 582 domainsSet.addAll(filter.getHostsList()); 583 } 584 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 585 synchronized (mPackages) { 586 if (mSettings.createIntentFilterVerificationIfNeededLPw( 587 packageName, domainsList) != null) { 588 scheduleWriteSettingsLocked(); 589 } 590 } 591 sendVerificationRequest(userId, verificationId, ivs); 592 } 593 mCurrentIntentFilterVerifications.clear(); 594 } 595 596 private void sendVerificationRequest(int userId, int verificationId, 597 IntentFilterVerificationState ivs) { 598 599 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 600 verificationIntent.putExtra( 601 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 602 verificationId); 603 verificationIntent.putExtra( 604 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 605 getDefaultScheme()); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 608 ivs.getHostsString()); 609 verificationIntent.putExtra( 610 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 611 ivs.getPackageName()); 612 verificationIntent.setComponent(mIntentFilterVerifierComponent); 613 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 614 615 UserHandle user = new UserHandle(userId); 616 mContext.sendBroadcastAsUser(verificationIntent, user); 617 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 618 } 619 620 public void receiveVerificationResponse(int verificationId) { 621 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 622 623 final boolean verified = ivs.isVerified(); 624 625 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 626 final int count = filters.size(); 627 for (int n=0; n<count; n++) { 628 PackageParser.ActivityIntentInfo filter = filters.get(n); 629 filter.setVerified(verified); 630 631 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 632 + verified + " and hosts:" + ivs.getHostsString()); 633 } 634 635 mIntentFilterVerificationStates.remove(verificationId); 636 637 final String packageName = ivs.getPackageName(); 638 IntentFilterVerificationInfo ivi = null; 639 640 synchronized (mPackages) { 641 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 642 } 643 if (ivi == null) { 644 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 645 + verificationId + " packageName:" + packageName); 646 return; 647 } 648 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 649 + verificationId); 650 651 synchronized (mPackages) { 652 if (verified) { 653 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 654 } else { 655 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 656 } 657 scheduleWriteSettingsLocked(); 658 659 final int userId = ivs.getUserId(); 660 if (userId != UserHandle.USER_ALL) { 661 final int userStatus = 662 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 663 664 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 665 boolean needUpdate = false; 666 667 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 668 // already been set by the User thru the Disambiguation dialog 669 switch (userStatus) { 670 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 671 if (verified) { 672 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 673 } else { 674 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 675 } 676 needUpdate = true; 677 break; 678 679 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 680 if (verified) { 681 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 682 needUpdate = true; 683 } 684 break; 685 686 default: 687 // Nothing to do 688 } 689 690 if (needUpdate) { 691 mSettings.updateIntentFilterVerificationStatusLPw( 692 packageName, updatedStatus, userId); 693 scheduleWritePackageRestrictionsLocked(userId); 694 } 695 } 696 } 697 } 698 699 @Override 700 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 701 ActivityIntentInfo filter, String packageName) { 702 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 703 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 704 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 705 return false; 706 } 707 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 708 if (ivs == null) { 709 ivs = createDomainVerificationState(verifierId, userId, verificationId, 710 packageName); 711 } 712 if (!hasValidDomains(filter)) { 713 return false; 714 } 715 ivs.addFilter(filter); 716 return true; 717 } 718 719 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 720 int userId, int verificationId, String packageName) { 721 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 722 verifierId, userId, packageName); 723 ivs.setPendingState(); 724 synchronized (mPackages) { 725 mIntentFilterVerificationStates.append(verificationId, ivs); 726 mCurrentIntentFilterVerifications.add(verificationId); 727 } 728 return ivs; 729 } 730 } 731 732 private static boolean hasValidDomains(ActivityIntentInfo filter) { 733 return hasValidDomains(filter, true); 734 } 735 736 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 737 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 738 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 739 if (!hasHTTPorHTTPS) { 740 if (logging) { 741 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 742 } 743 return false; 744 } 745 return true; 746 } 747 748 private IntentFilterVerifier mIntentFilterVerifier; 749 750 // Set of pending broadcasts for aggregating enable/disable of components. 751 static class PendingPackageBroadcasts { 752 // for each user id, a map of <package name -> components within that package> 753 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 754 755 public PendingPackageBroadcasts() { 756 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 757 } 758 759 public ArrayList<String> get(int userId, String packageName) { 760 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 761 return packages.get(packageName); 762 } 763 764 public void put(int userId, String packageName, ArrayList<String> components) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 packages.put(packageName, components); 767 } 768 769 public void remove(int userId, String packageName) { 770 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 771 if (packages != null) { 772 packages.remove(packageName); 773 } 774 } 775 776 public void remove(int userId) { 777 mUidMap.remove(userId); 778 } 779 780 public int userIdCount() { 781 return mUidMap.size(); 782 } 783 784 public int userIdAt(int n) { 785 return mUidMap.keyAt(n); 786 } 787 788 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 789 return mUidMap.get(userId); 790 } 791 792 public int size() { 793 // total number of pending broadcast entries across all userIds 794 int num = 0; 795 for (int i = 0; i< mUidMap.size(); i++) { 796 num += mUidMap.valueAt(i).size(); 797 } 798 return num; 799 } 800 801 public void clear() { 802 mUidMap.clear(); 803 } 804 805 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 806 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 807 if (map == null) { 808 map = new ArrayMap<String, ArrayList<String>>(); 809 mUidMap.put(userId, map); 810 } 811 return map; 812 } 813 } 814 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 815 816 // Service Connection to remote media container service to copy 817 // package uri's from external media onto secure containers 818 // or internal storage. 819 private IMediaContainerService mContainerService = null; 820 821 static final int SEND_PENDING_BROADCAST = 1; 822 static final int MCS_BOUND = 3; 823 static final int END_COPY = 4; 824 static final int INIT_COPY = 5; 825 static final int MCS_UNBIND = 6; 826 static final int START_CLEANING_PACKAGE = 7; 827 static final int FIND_INSTALL_LOC = 8; 828 static final int POST_INSTALL = 9; 829 static final int MCS_RECONNECT = 10; 830 static final int MCS_GIVE_UP = 11; 831 static final int UPDATED_MEDIA_STATUS = 12; 832 static final int WRITE_SETTINGS = 13; 833 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 834 static final int PACKAGE_VERIFIED = 15; 835 static final int CHECK_PENDING_VERIFICATION = 16; 836 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 837 static final int INTENT_FILTER_VERIFIED = 18; 838 839 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 840 841 // Delay time in millisecs 842 static final int BROADCAST_DELAY = 10 * 1000; 843 844 static UserManagerService sUserManager; 845 846 // Stores a list of users whose package restrictions file needs to be updated 847 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 848 849 final private DefaultContainerConnection mDefContainerConn = 850 new DefaultContainerConnection(); 851 class DefaultContainerConnection implements ServiceConnection { 852 public void onServiceConnected(ComponentName name, IBinder service) { 853 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 854 IMediaContainerService imcs = 855 IMediaContainerService.Stub.asInterface(service); 856 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 857 } 858 859 public void onServiceDisconnected(ComponentName name) { 860 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 861 } 862 }; 863 864 // Recordkeeping of restore-after-install operations that are currently in flight 865 // between the Package Manager and the Backup Manager 866 class PostInstallData { 867 public InstallArgs args; 868 public PackageInstalledInfo res; 869 870 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 871 args = _a; 872 res = _r; 873 } 874 }; 875 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 876 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 877 878 // backup/restore of preferred activity state 879 private static final String TAG_PREFERRED_BACKUP = "pa"; 880 881 private final String mRequiredVerifierPackage; 882 883 private final PackageUsage mPackageUsage = new PackageUsage(); 884 885 private class PackageUsage { 886 private static final int WRITE_INTERVAL 887 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 888 889 private final Object mFileLock = new Object(); 890 private final AtomicLong mLastWritten = new AtomicLong(0); 891 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 892 893 private boolean mIsHistoricalPackageUsageAvailable = true; 894 895 boolean isHistoricalPackageUsageAvailable() { 896 return mIsHistoricalPackageUsageAvailable; 897 } 898 899 void write(boolean force) { 900 if (force) { 901 writeInternal(); 902 return; 903 } 904 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 905 && !DEBUG_DEXOPT) { 906 return; 907 } 908 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 909 new Thread("PackageUsage_DiskWriter") { 910 @Override 911 public void run() { 912 try { 913 writeInternal(); 914 } finally { 915 mBackgroundWriteRunning.set(false); 916 } 917 } 918 }.start(); 919 } 920 } 921 922 private void writeInternal() { 923 synchronized (mPackages) { 924 synchronized (mFileLock) { 925 AtomicFile file = getFile(); 926 FileOutputStream f = null; 927 try { 928 f = file.startWrite(); 929 BufferedOutputStream out = new BufferedOutputStream(f); 930 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 931 StringBuilder sb = new StringBuilder(); 932 for (PackageParser.Package pkg : mPackages.values()) { 933 if (pkg.mLastPackageUsageTimeInMills == 0) { 934 continue; 935 } 936 sb.setLength(0); 937 sb.append(pkg.packageName); 938 sb.append(' '); 939 sb.append((long)pkg.mLastPackageUsageTimeInMills); 940 sb.append('\n'); 941 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 942 } 943 out.flush(); 944 file.finishWrite(f); 945 } catch (IOException e) { 946 if (f != null) { 947 file.failWrite(f); 948 } 949 Log.e(TAG, "Failed to write package usage times", e); 950 } 951 } 952 } 953 mLastWritten.set(SystemClock.elapsedRealtime()); 954 } 955 956 void readLP() { 957 synchronized (mFileLock) { 958 AtomicFile file = getFile(); 959 BufferedInputStream in = null; 960 try { 961 in = new BufferedInputStream(file.openRead()); 962 StringBuffer sb = new StringBuffer(); 963 while (true) { 964 String packageName = readToken(in, sb, ' '); 965 if (packageName == null) { 966 break; 967 } 968 String timeInMillisString = readToken(in, sb, '\n'); 969 if (timeInMillisString == null) { 970 throw new IOException("Failed to find last usage time for package " 971 + packageName); 972 } 973 PackageParser.Package pkg = mPackages.get(packageName); 974 if (pkg == null) { 975 continue; 976 } 977 long timeInMillis; 978 try { 979 timeInMillis = Long.parseLong(timeInMillisString.toString()); 980 } catch (NumberFormatException e) { 981 throw new IOException("Failed to parse " + timeInMillisString 982 + " as a long.", e); 983 } 984 pkg.mLastPackageUsageTimeInMills = timeInMillis; 985 } 986 } catch (FileNotFoundException expected) { 987 mIsHistoricalPackageUsageAvailable = false; 988 } catch (IOException e) { 989 Log.w(TAG, "Failed to read package usage times", e); 990 } finally { 991 IoUtils.closeQuietly(in); 992 } 993 } 994 mLastWritten.set(SystemClock.elapsedRealtime()); 995 } 996 997 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 998 throws IOException { 999 sb.setLength(0); 1000 while (true) { 1001 int ch = in.read(); 1002 if (ch == -1) { 1003 if (sb.length() == 0) { 1004 return null; 1005 } 1006 throw new IOException("Unexpected EOF"); 1007 } 1008 if (ch == endOfToken) { 1009 return sb.toString(); 1010 } 1011 sb.append((char)ch); 1012 } 1013 } 1014 1015 private AtomicFile getFile() { 1016 File dataDir = Environment.getDataDirectory(); 1017 File systemDir = new File(dataDir, "system"); 1018 File fname = new File(systemDir, "package-usage.list"); 1019 return new AtomicFile(fname); 1020 } 1021 } 1022 1023 class PackageHandler extends Handler { 1024 private boolean mBound = false; 1025 final ArrayList<HandlerParams> mPendingInstalls = 1026 new ArrayList<HandlerParams>(); 1027 1028 private boolean connectToService() { 1029 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1030 " DefaultContainerService"); 1031 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1032 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1033 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1034 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1035 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1036 mBound = true; 1037 return true; 1038 } 1039 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1040 return false; 1041 } 1042 1043 private void disconnectService() { 1044 mContainerService = null; 1045 mBound = false; 1046 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1047 mContext.unbindService(mDefContainerConn); 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 } 1050 1051 PackageHandler(Looper looper) { 1052 super(looper); 1053 } 1054 1055 public void handleMessage(Message msg) { 1056 try { 1057 doHandleMessage(msg); 1058 } finally { 1059 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1060 } 1061 } 1062 1063 void doHandleMessage(Message msg) { 1064 switch (msg.what) { 1065 case INIT_COPY: { 1066 HandlerParams params = (HandlerParams) msg.obj; 1067 int idx = mPendingInstalls.size(); 1068 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1069 // If a bind was already initiated we dont really 1070 // need to do anything. The pending install 1071 // will be processed later on. 1072 if (!mBound) { 1073 // If this is the only one pending we might 1074 // have to bind to the service again. 1075 if (!connectToService()) { 1076 Slog.e(TAG, "Failed to bind to media container service"); 1077 params.serviceError(); 1078 return; 1079 } else { 1080 // Once we bind to the service, the first 1081 // pending request will be processed. 1082 mPendingInstalls.add(idx, params); 1083 } 1084 } else { 1085 mPendingInstalls.add(idx, params); 1086 // Already bound to the service. Just make 1087 // sure we trigger off processing the first request. 1088 if (idx == 0) { 1089 mHandler.sendEmptyMessage(MCS_BOUND); 1090 } 1091 } 1092 break; 1093 } 1094 case MCS_BOUND: { 1095 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1096 if (msg.obj != null) { 1097 mContainerService = (IMediaContainerService) msg.obj; 1098 } 1099 if (mContainerService == null) { 1100 // Something seriously wrong. Bail out 1101 Slog.e(TAG, "Cannot bind to media container service"); 1102 for (HandlerParams params : mPendingInstalls) { 1103 // Indicate service bind error 1104 params.serviceError(); 1105 } 1106 mPendingInstalls.clear(); 1107 } else if (mPendingInstalls.size() > 0) { 1108 HandlerParams params = mPendingInstalls.get(0); 1109 if (params != null) { 1110 if (params.startCopy()) { 1111 // We are done... look for more work or to 1112 // go idle. 1113 if (DEBUG_SD_INSTALL) Log.i(TAG, 1114 "Checking for more work or unbind..."); 1115 // Delete pending install 1116 if (mPendingInstalls.size() > 0) { 1117 mPendingInstalls.remove(0); 1118 } 1119 if (mPendingInstalls.size() == 0) { 1120 if (mBound) { 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Posting delayed MCS_UNBIND"); 1123 removeMessages(MCS_UNBIND); 1124 Message ubmsg = obtainMessage(MCS_UNBIND); 1125 // Unbind after a little delay, to avoid 1126 // continual thrashing. 1127 sendMessageDelayed(ubmsg, 10000); 1128 } 1129 } else { 1130 // There are more pending requests in queue. 1131 // Just post MCS_BOUND message to trigger processing 1132 // of next pending install. 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, 1134 "Posting MCS_BOUND for next work"); 1135 mHandler.sendEmptyMessage(MCS_BOUND); 1136 } 1137 } 1138 } 1139 } else { 1140 // Should never happen ideally. 1141 Slog.w(TAG, "Empty queue"); 1142 } 1143 break; 1144 } 1145 case MCS_RECONNECT: { 1146 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1147 if (mPendingInstalls.size() > 0) { 1148 if (mBound) { 1149 disconnectService(); 1150 } 1151 if (!connectToService()) { 1152 Slog.e(TAG, "Failed to bind to media container service"); 1153 for (HandlerParams params : mPendingInstalls) { 1154 // Indicate service bind error 1155 params.serviceError(); 1156 } 1157 mPendingInstalls.clear(); 1158 } 1159 } 1160 break; 1161 } 1162 case MCS_UNBIND: { 1163 // If there is no actual work left, then time to unbind. 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1165 1166 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1167 if (mBound) { 1168 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1169 1170 disconnectService(); 1171 } 1172 } else if (mPendingInstalls.size() > 0) { 1173 // There are more pending requests in queue. 1174 // Just post MCS_BOUND message to trigger processing 1175 // of next pending install. 1176 mHandler.sendEmptyMessage(MCS_BOUND); 1177 } 1178 1179 break; 1180 } 1181 case MCS_GIVE_UP: { 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1183 mPendingInstalls.remove(0); 1184 break; 1185 } 1186 case SEND_PENDING_BROADCAST: { 1187 String packages[]; 1188 ArrayList<String> components[]; 1189 int size = 0; 1190 int uids[]; 1191 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1192 synchronized (mPackages) { 1193 if (mPendingBroadcasts == null) { 1194 return; 1195 } 1196 size = mPendingBroadcasts.size(); 1197 if (size <= 0) { 1198 // Nothing to be done. Just return 1199 return; 1200 } 1201 packages = new String[size]; 1202 components = new ArrayList[size]; 1203 uids = new int[size]; 1204 int i = 0; // filling out the above arrays 1205 1206 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1207 int packageUserId = mPendingBroadcasts.userIdAt(n); 1208 Iterator<Map.Entry<String, ArrayList<String>>> it 1209 = mPendingBroadcasts.packagesForUserId(packageUserId) 1210 .entrySet().iterator(); 1211 while (it.hasNext() && i < size) { 1212 Map.Entry<String, ArrayList<String>> ent = it.next(); 1213 packages[i] = ent.getKey(); 1214 components[i] = ent.getValue(); 1215 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1216 uids[i] = (ps != null) 1217 ? UserHandle.getUid(packageUserId, ps.appId) 1218 : -1; 1219 i++; 1220 } 1221 } 1222 size = i; 1223 mPendingBroadcasts.clear(); 1224 } 1225 // Send broadcasts 1226 for (int i = 0; i < size; i++) { 1227 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1228 } 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1230 break; 1231 } 1232 case START_CLEANING_PACKAGE: { 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 final String packageName = (String)msg.obj; 1235 final int userId = msg.arg1; 1236 final boolean andCode = msg.arg2 != 0; 1237 synchronized (mPackages) { 1238 if (userId == UserHandle.USER_ALL) { 1239 int[] users = sUserManager.getUserIds(); 1240 for (int user : users) { 1241 mSettings.addPackageToCleanLPw( 1242 new PackageCleanItem(user, packageName, andCode)); 1243 } 1244 } else { 1245 mSettings.addPackageToCleanLPw( 1246 new PackageCleanItem(userId, packageName, andCode)); 1247 } 1248 } 1249 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1250 startCleaningPackages(); 1251 } break; 1252 case POST_INSTALL: { 1253 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1254 PostInstallData data = mRunningInstalls.get(msg.arg1); 1255 mRunningInstalls.delete(msg.arg1); 1256 boolean deleteOld = false; 1257 1258 if (data != null) { 1259 InstallArgs args = data.args; 1260 PackageInstalledInfo res = data.res; 1261 1262 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1263 res.removedInfo.sendBroadcast(false, true, false); 1264 Bundle extras = new Bundle(1); 1265 extras.putInt(Intent.EXTRA_UID, res.uid); 1266 1267 // Now that we successfully installed the package, grant runtime 1268 // permissions if requested before broadcasting the install. 1269 if ((args.installFlags 1270 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1271 grantRequestedRuntimePermissions(res.pkg, 1272 args.user.getIdentifier()); 1273 } 1274 1275 // Determine the set of users who are adding this 1276 // package for the first time vs. those who are seeing 1277 // an update. 1278 int[] firstUsers; 1279 int[] updateUsers = new int[0]; 1280 if (res.origUsers == null || res.origUsers.length == 0) { 1281 firstUsers = res.newUsers; 1282 } else { 1283 firstUsers = new int[0]; 1284 for (int i=0; i<res.newUsers.length; i++) { 1285 int user = res.newUsers[i]; 1286 boolean isNew = true; 1287 for (int j=0; j<res.origUsers.length; j++) { 1288 if (res.origUsers[j] == user) { 1289 isNew = false; 1290 break; 1291 } 1292 } 1293 if (isNew) { 1294 int[] newFirst = new int[firstUsers.length+1]; 1295 System.arraycopy(firstUsers, 0, newFirst, 0, 1296 firstUsers.length); 1297 newFirst[firstUsers.length] = user; 1298 firstUsers = newFirst; 1299 } else { 1300 int[] newUpdate = new int[updateUsers.length+1]; 1301 System.arraycopy(updateUsers, 0, newUpdate, 0, 1302 updateUsers.length); 1303 newUpdate[updateUsers.length] = user; 1304 updateUsers = newUpdate; 1305 } 1306 } 1307 } 1308 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1309 res.pkg.applicationInfo.packageName, 1310 extras, null, null, firstUsers); 1311 final boolean update = res.removedInfo.removedPackage != null; 1312 if (update) { 1313 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1314 } 1315 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1316 res.pkg.applicationInfo.packageName, 1317 extras, null, null, updateUsers); 1318 if (update) { 1319 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1320 res.pkg.applicationInfo.packageName, 1321 extras, null, null, updateUsers); 1322 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1323 null, null, 1324 res.pkg.applicationInfo.packageName, null, updateUsers); 1325 1326 // treat asec-hosted packages like removable media on upgrade 1327 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1328 if (DEBUG_INSTALL) { 1329 Slog.i(TAG, "upgrading pkg " + res.pkg 1330 + " is ASEC-hosted -> AVAILABLE"); 1331 } 1332 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1333 ArrayList<String> pkgList = new ArrayList<String>(1); 1334 pkgList.add(res.pkg.applicationInfo.packageName); 1335 sendResourcesChangedBroadcast(true, true, 1336 pkgList,uidArray, null); 1337 } 1338 } 1339 if (res.removedInfo.args != null) { 1340 // Remove the replaced package's older resources safely now 1341 deleteOld = true; 1342 } 1343 1344 // Log current value of "unknown sources" setting 1345 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1346 getUnknownSourcesSettings()); 1347 } 1348 // Force a gc to clear up things 1349 Runtime.getRuntime().gc(); 1350 // We delete after a gc for applications on sdcard. 1351 if (deleteOld) { 1352 synchronized (mInstallLock) { 1353 res.removedInfo.args.doPostDeleteLI(true); 1354 } 1355 } 1356 if (args.observer != null) { 1357 try { 1358 Bundle extras = extrasForInstallResult(res); 1359 args.observer.onPackageInstalled(res.name, res.returnCode, 1360 res.returnMsg, extras); 1361 } catch (RemoteException e) { 1362 Slog.i(TAG, "Observer no longer exists."); 1363 } 1364 } 1365 } else { 1366 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1367 } 1368 } break; 1369 case UPDATED_MEDIA_STATUS: { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1371 boolean reportStatus = msg.arg1 == 1; 1372 boolean doGc = msg.arg2 == 1; 1373 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1374 if (doGc) { 1375 // Force a gc to clear up stale containers. 1376 Runtime.getRuntime().gc(); 1377 } 1378 if (msg.obj != null) { 1379 @SuppressWarnings("unchecked") 1380 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1382 // Unload containers 1383 unloadAllContainers(args); 1384 } 1385 if (reportStatus) { 1386 try { 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1388 PackageHelper.getMountService().finishMediaUpdate(); 1389 } catch (RemoteException e) { 1390 Log.e(TAG, "MountService not running?"); 1391 } 1392 } 1393 } break; 1394 case WRITE_SETTINGS: { 1395 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1396 synchronized (mPackages) { 1397 removeMessages(WRITE_SETTINGS); 1398 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1399 mSettings.writeLPr(); 1400 mDirtyUsers.clear(); 1401 } 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 } break; 1404 case WRITE_PACKAGE_RESTRICTIONS: { 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 synchronized (mPackages) { 1407 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1408 for (int userId : mDirtyUsers) { 1409 mSettings.writePackageRestrictionsLPr(userId); 1410 } 1411 mDirtyUsers.clear(); 1412 } 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1414 } break; 1415 case CHECK_PENDING_VERIFICATION: { 1416 final int verificationId = msg.arg1; 1417 final PackageVerificationState state = mPendingVerification.get(verificationId); 1418 1419 if ((state != null) && !state.timeoutExtended()) { 1420 final InstallArgs args = state.getInstallArgs(); 1421 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1422 1423 Slog.i(TAG, "Verification timed out for " + originUri); 1424 mPendingVerification.remove(verificationId); 1425 1426 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1427 1428 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1429 Slog.i(TAG, "Continuing with installation of " + originUri); 1430 state.setVerifierResponse(Binder.getCallingUid(), 1431 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1432 broadcastPackageVerified(verificationId, originUri, 1433 PackageManager.VERIFICATION_ALLOW, 1434 state.getInstallArgs().getUser()); 1435 try { 1436 ret = args.copyApk(mContainerService, true); 1437 } catch (RemoteException e) { 1438 Slog.e(TAG, "Could not contact the ContainerService"); 1439 } 1440 } else { 1441 broadcastPackageVerified(verificationId, originUri, 1442 PackageManager.VERIFICATION_REJECT, 1443 state.getInstallArgs().getUser()); 1444 } 1445 1446 processPendingInstall(args, ret); 1447 mHandler.sendEmptyMessage(MCS_UNBIND); 1448 } 1449 break; 1450 } 1451 case PACKAGE_VERIFIED: { 1452 final int verificationId = msg.arg1; 1453 1454 final PackageVerificationState state = mPendingVerification.get(verificationId); 1455 if (state == null) { 1456 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1457 break; 1458 } 1459 1460 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1461 1462 state.setVerifierResponse(response.callerUid, response.code); 1463 1464 if (state.isVerificationComplete()) { 1465 mPendingVerification.remove(verificationId); 1466 1467 final InstallArgs args = state.getInstallArgs(); 1468 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1469 1470 int ret; 1471 if (state.isInstallAllowed()) { 1472 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1473 broadcastPackageVerified(verificationId, originUri, 1474 response.code, state.getInstallArgs().getUser()); 1475 try { 1476 ret = args.copyApk(mContainerService, true); 1477 } catch (RemoteException e) { 1478 Slog.e(TAG, "Could not contact the ContainerService"); 1479 } 1480 } else { 1481 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1482 } 1483 1484 processPendingInstall(args, ret); 1485 1486 mHandler.sendEmptyMessage(MCS_UNBIND); 1487 } 1488 1489 break; 1490 } 1491 case START_INTENT_FILTER_VERIFICATIONS: { 1492 int userId = msg.arg1; 1493 int verifierUid = msg.arg2; 1494 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1495 1496 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1497 break; 1498 } 1499 case INTENT_FILTER_VERIFIED: { 1500 final int verificationId = msg.arg1; 1501 1502 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1503 verificationId); 1504 if (state == null) { 1505 Slog.w(TAG, "Invalid IntentFilter verification token " 1506 + verificationId + " received"); 1507 break; 1508 } 1509 1510 final int userId = state.getUserId(); 1511 1512 Slog.d(TAG, "Processing IntentFilter verification with token:" 1513 + verificationId + " and userId:" + userId); 1514 1515 final IntentFilterVerificationResponse response = 1516 (IntentFilterVerificationResponse) msg.obj; 1517 1518 state.setVerifierResponse(response.callerUid, response.code); 1519 1520 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1521 + " and userId:" + userId 1522 + " is settings verifier response with response code:" 1523 + response.code); 1524 1525 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1526 Slog.d(TAG, "Domains failing verification: " 1527 + response.getFailedDomainsString()); 1528 } 1529 1530 if (state.isVerificationComplete()) { 1531 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1532 } else { 1533 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1534 + " was not said to be complete"); 1535 } 1536 1537 break; 1538 } 1539 } 1540 } 1541 } 1542 1543 private StorageEventListener mStorageListener = new StorageEventListener() { 1544 @Override 1545 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1546 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1547 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1548 // TODO: ensure that private directories exist for all active users 1549 // TODO: remove user data whose serial number doesn't match 1550 loadPrivatePackages(vol); 1551 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1552 unloadPrivatePackages(vol); 1553 } 1554 } 1555 1556 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1557 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1558 updateExternalMediaStatus(true, false); 1559 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1560 updateExternalMediaStatus(false, false); 1561 } 1562 } 1563 } 1564 1565 @Override 1566 public void onVolumeForgotten(String fsUuid) { 1567 // TODO: remove all packages hosted on this uuid 1568 } 1569 }; 1570 1571 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1572 if (userId >= UserHandle.USER_OWNER) { 1573 grantRequestedRuntimePermissionsForUser(pkg, userId); 1574 } else if (userId == UserHandle.USER_ALL) { 1575 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1576 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1577 } 1578 } 1579 } 1580 1581 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1582 SettingBase sb = (SettingBase) pkg.mExtras; 1583 if (sb == null) { 1584 return; 1585 } 1586 1587 PermissionsState permissionsState = sb.getPermissionsState(); 1588 1589 for (String permission : pkg.requestedPermissions) { 1590 BasePermission bp = mSettings.mPermissions.get(permission); 1591 if (bp != null && bp.isRuntime()) { 1592 permissionsState.grantRuntimePermission(bp, userId); 1593 } 1594 } 1595 } 1596 1597 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1598 Bundle extras = null; 1599 switch (res.returnCode) { 1600 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1601 extras = new Bundle(); 1602 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1603 res.origPermission); 1604 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1605 res.origPackage); 1606 break; 1607 } 1608 case PackageManager.INSTALL_SUCCEEDED: { 1609 extras = new Bundle(); 1610 extras.putBoolean(Intent.EXTRA_REPLACING, 1611 res.removedInfo != null && res.removedInfo.removedPackage != null); 1612 break; 1613 } 1614 } 1615 return extras; 1616 } 1617 1618 void scheduleWriteSettingsLocked() { 1619 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1620 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1621 } 1622 } 1623 1624 void scheduleWritePackageRestrictionsLocked(int userId) { 1625 if (!sUserManager.exists(userId)) return; 1626 mDirtyUsers.add(userId); 1627 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1628 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1629 } 1630 } 1631 1632 public static PackageManagerService main(Context context, Installer installer, 1633 boolean factoryTest, boolean onlyCore) { 1634 PackageManagerService m = new PackageManagerService(context, installer, 1635 factoryTest, onlyCore); 1636 ServiceManager.addService("package", m); 1637 return m; 1638 } 1639 1640 static String[] splitString(String str, char sep) { 1641 int count = 1; 1642 int i = 0; 1643 while ((i=str.indexOf(sep, i)) >= 0) { 1644 count++; 1645 i++; 1646 } 1647 1648 String[] res = new String[count]; 1649 i=0; 1650 count = 0; 1651 int lastI=0; 1652 while ((i=str.indexOf(sep, i)) >= 0) { 1653 res[count] = str.substring(lastI, i); 1654 count++; 1655 i++; 1656 lastI = i; 1657 } 1658 res[count] = str.substring(lastI, str.length()); 1659 return res; 1660 } 1661 1662 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1663 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1664 Context.DISPLAY_SERVICE); 1665 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1666 } 1667 1668 public PackageManagerService(Context context, Installer installer, 1669 boolean factoryTest, boolean onlyCore) { 1670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1671 SystemClock.uptimeMillis()); 1672 1673 if (mSdkVersion <= 0) { 1674 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1675 } 1676 1677 mContext = context; 1678 mFactoryTest = factoryTest; 1679 mOnlyCore = onlyCore; 1680 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1681 mMetrics = new DisplayMetrics(); 1682 mSettings = new Settings(mPackages); 1683 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1684 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1685 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1686 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1687 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1688 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1689 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 1696 // TODO: add a property to control this? 1697 long dexOptLRUThresholdInMinutes; 1698 if (mLazyDexOpt) { 1699 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1700 } else { 1701 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1702 } 1703 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1704 1705 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1706 if (separateProcesses != null && separateProcesses.length() > 0) { 1707 if ("*".equals(separateProcesses)) { 1708 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1709 mSeparateProcesses = null; 1710 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1711 } else { 1712 mDefParseFlags = 0; 1713 mSeparateProcesses = separateProcesses.split(","); 1714 Slog.w(TAG, "Running with debug.separate_processes: " 1715 + separateProcesses); 1716 } 1717 } else { 1718 mDefParseFlags = 0; 1719 mSeparateProcesses = null; 1720 } 1721 1722 mInstaller = installer; 1723 mPackageDexOptimizer = new PackageDexOptimizer(this); 1724 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1725 1726 getDefaultDisplayMetrics(context, mMetrics); 1727 1728 SystemConfig systemConfig = SystemConfig.getInstance(); 1729 mGlobalGids = systemConfig.getGlobalGids(); 1730 mSystemPermissions = systemConfig.getSystemPermissions(); 1731 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1732 1733 synchronized (mInstallLock) { 1734 // writer 1735 synchronized (mPackages) { 1736 mHandlerThread = new ServiceThread(TAG, 1737 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1738 mHandlerThread.start(); 1739 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1740 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1741 1742 File dataDir = Environment.getDataDirectory(); 1743 mAppDataDir = new File(dataDir, "data"); 1744 mAppInstallDir = new File(dataDir, "app"); 1745 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1746 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1747 mUserAppDataDir = new File(dataDir, "user"); 1748 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1749 1750 sUserManager = new UserManagerService(context, this, 1751 mInstallLock, mPackages); 1752 1753 // Propagate permission configuration in to package manager. 1754 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1755 = systemConfig.getPermissions(); 1756 for (int i=0; i<permConfig.size(); i++) { 1757 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1758 BasePermission bp = mSettings.mPermissions.get(perm.name); 1759 if (bp == null) { 1760 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1761 mSettings.mPermissions.put(perm.name, bp); 1762 } 1763 if (perm.gids != null) { 1764 bp.setGids(perm.gids, perm.perUser); 1765 } 1766 } 1767 1768 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1769 for (int i=0; i<libConfig.size(); i++) { 1770 mSharedLibraries.put(libConfig.keyAt(i), 1771 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1772 } 1773 1774 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1775 1776 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1777 mSdkVersion, mOnlyCore); 1778 1779 String customResolverActivity = Resources.getSystem().getString( 1780 R.string.config_customResolverActivity); 1781 if (TextUtils.isEmpty(customResolverActivity)) { 1782 customResolverActivity = null; 1783 } else { 1784 mCustomResolverComponentName = ComponentName.unflattenFromString( 1785 customResolverActivity); 1786 } 1787 1788 long startTime = SystemClock.uptimeMillis(); 1789 1790 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1791 startTime); 1792 1793 // Set flag to monitor and not change apk file paths when 1794 // scanning install directories. 1795 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1796 1797 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1798 1799 /** 1800 * Add everything in the in the boot class path to the 1801 * list of process files because dexopt will have been run 1802 * if necessary during zygote startup. 1803 */ 1804 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1805 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1806 1807 if (bootClassPath != null) { 1808 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1809 for (String element : bootClassPathElements) { 1810 alreadyDexOpted.add(element); 1811 } 1812 } else { 1813 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1814 } 1815 1816 if (systemServerClassPath != null) { 1817 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1818 for (String element : systemServerClassPathElements) { 1819 alreadyDexOpted.add(element); 1820 } 1821 } else { 1822 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1823 } 1824 1825 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1826 final String[] dexCodeInstructionSets = 1827 getDexCodeInstructionSets( 1828 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1829 1830 /** 1831 * Ensure all external libraries have had dexopt run on them. 1832 */ 1833 if (mSharedLibraries.size() > 0) { 1834 // NOTE: For now, we're compiling these system "shared libraries" 1835 // (and framework jars) into all available architectures. It's possible 1836 // to compile them only when we come across an app that uses them (there's 1837 // already logic for that in scanPackageLI) but that adds some complexity. 1838 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1839 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1840 final String lib = libEntry.path; 1841 if (lib == null) { 1842 continue; 1843 } 1844 1845 try { 1846 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1847 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1848 alreadyDexOpted.add(lib); 1849 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1850 } 1851 } catch (FileNotFoundException e) { 1852 Slog.w(TAG, "Library not found: " + lib); 1853 } catch (IOException e) { 1854 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1855 + e.getMessage()); 1856 } 1857 } 1858 } 1859 } 1860 1861 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1862 1863 // Gross hack for now: we know this file doesn't contain any 1864 // code, so don't dexopt it to avoid the resulting log spew. 1865 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1866 1867 // Gross hack for now: we know this file is only part of 1868 // the boot class path for art, so don't dexopt it to 1869 // avoid the resulting log spew. 1870 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1871 1872 /** 1873 * And there are a number of commands implemented in Java, which 1874 * we currently need to do the dexopt on so that they can be 1875 * run from a non-root shell. 1876 */ 1877 String[] frameworkFiles = frameworkDir.list(); 1878 if (frameworkFiles != null) { 1879 // TODO: We could compile these only for the most preferred ABI. We should 1880 // first double check that the dex files for these commands are not referenced 1881 // by other system apps. 1882 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1883 for (int i=0; i<frameworkFiles.length; i++) { 1884 File libPath = new File(frameworkDir, frameworkFiles[i]); 1885 String path = libPath.getPath(); 1886 // Skip the file if we already did it. 1887 if (alreadyDexOpted.contains(path)) { 1888 continue; 1889 } 1890 // Skip the file if it is not a type we want to dexopt. 1891 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1892 continue; 1893 } 1894 try { 1895 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1896 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1897 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1898 } 1899 } catch (FileNotFoundException e) { 1900 Slog.w(TAG, "Jar not found: " + path); 1901 } catch (IOException e) { 1902 Slog.w(TAG, "Exception reading jar: " + path, e); 1903 } 1904 } 1905 } 1906 } 1907 1908 // Collect vendor overlay packages. 1909 // (Do this before scanning any apps.) 1910 // For security and version matching reason, only consider 1911 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1912 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1913 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1914 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1915 1916 // Find base frameworks (resource packages without code). 1917 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1918 | PackageParser.PARSE_IS_SYSTEM_DIR 1919 | PackageParser.PARSE_IS_PRIVILEGED, 1920 scanFlags | SCAN_NO_DEX, 0); 1921 1922 // Collected privileged system packages. 1923 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1924 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1925 | PackageParser.PARSE_IS_SYSTEM_DIR 1926 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1927 1928 // Collect ordinary system packages. 1929 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1930 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1931 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1932 1933 // Collect all vendor packages. 1934 File vendorAppDir = new File("/vendor/app"); 1935 try { 1936 vendorAppDir = vendorAppDir.getCanonicalFile(); 1937 } catch (IOException e) { 1938 // failed to look up canonical path, continue with original one 1939 } 1940 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1942 1943 // Collect all OEM packages. 1944 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1945 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1946 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1947 1948 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1949 mInstaller.moveFiles(); 1950 1951 // Prune any system packages that no longer exist. 1952 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1953 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1954 if (!mOnlyCore) { 1955 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1956 while (psit.hasNext()) { 1957 PackageSetting ps = psit.next(); 1958 1959 /* 1960 * If this is not a system app, it can't be a 1961 * disable system app. 1962 */ 1963 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1964 continue; 1965 } 1966 1967 /* 1968 * If the package is scanned, it's not erased. 1969 */ 1970 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1971 if (scannedPkg != null) { 1972 /* 1973 * If the system app is both scanned and in the 1974 * disabled packages list, then it must have been 1975 * added via OTA. Remove it from the currently 1976 * scanned package so the previously user-installed 1977 * application can be scanned. 1978 */ 1979 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1980 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1981 + ps.name + "; removing system app. Last known codePath=" 1982 + ps.codePathString + ", installStatus=" + ps.installStatus 1983 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1984 + scannedPkg.mVersionCode); 1985 removePackageLI(ps, true); 1986 expectingBetter.put(ps.name, ps.codePath); 1987 } 1988 1989 continue; 1990 } 1991 1992 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1993 psit.remove(); 1994 logCriticalInfo(Log.WARN, "System package " + ps.name 1995 + " no longer exists; wiping its data"); 1996 removeDataDirsLI(null, ps.name); 1997 } else { 1998 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1999 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2000 possiblyDeletedUpdatedSystemApps.add(ps.name); 2001 } 2002 } 2003 } 2004 } 2005 2006 //look for any incomplete package installations 2007 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2008 //clean up list 2009 for(int i = 0; i < deletePkgsList.size(); i++) { 2010 //clean up here 2011 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2012 } 2013 //delete tmp files 2014 deleteTempPackageFiles(); 2015 2016 // Remove any shared userIDs that have no associated packages 2017 mSettings.pruneSharedUsersLPw(); 2018 2019 if (!mOnlyCore) { 2020 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2021 SystemClock.uptimeMillis()); 2022 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2023 2024 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2025 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2026 2027 /** 2028 * Remove disable package settings for any updated system 2029 * apps that were removed via an OTA. If they're not a 2030 * previously-updated app, remove them completely. 2031 * Otherwise, just revoke their system-level permissions. 2032 */ 2033 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2034 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2035 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2036 2037 String msg; 2038 if (deletedPkg == null) { 2039 msg = "Updated system package " + deletedAppName 2040 + " no longer exists; wiping its data"; 2041 removeDataDirsLI(null, deletedAppName); 2042 } else { 2043 msg = "Updated system app + " + deletedAppName 2044 + " no longer present; removing system privileges for " 2045 + deletedAppName; 2046 2047 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2048 2049 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2050 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2051 } 2052 logCriticalInfo(Log.WARN, msg); 2053 } 2054 2055 /** 2056 * Make sure all system apps that we expected to appear on 2057 * the userdata partition actually showed up. If they never 2058 * appeared, crawl back and revive the system version. 2059 */ 2060 for (int i = 0; i < expectingBetter.size(); i++) { 2061 final String packageName = expectingBetter.keyAt(i); 2062 if (!mPackages.containsKey(packageName)) { 2063 final File scanFile = expectingBetter.valueAt(i); 2064 2065 logCriticalInfo(Log.WARN, "Expected better " + packageName 2066 + " but never showed up; reverting to system"); 2067 2068 final int reparseFlags; 2069 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2070 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2071 | PackageParser.PARSE_IS_SYSTEM_DIR 2072 | PackageParser.PARSE_IS_PRIVILEGED; 2073 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2074 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2075 | PackageParser.PARSE_IS_SYSTEM_DIR; 2076 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2077 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2078 | PackageParser.PARSE_IS_SYSTEM_DIR; 2079 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2080 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2081 | PackageParser.PARSE_IS_SYSTEM_DIR; 2082 } else { 2083 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2084 continue; 2085 } 2086 2087 mSettings.enableSystemPackageLPw(packageName); 2088 2089 try { 2090 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2091 } catch (PackageManagerException e) { 2092 Slog.e(TAG, "Failed to parse original system package: " 2093 + e.getMessage()); 2094 } 2095 } 2096 } 2097 } 2098 2099 // Now that we know all of the shared libraries, update all clients to have 2100 // the correct library paths. 2101 updateAllSharedLibrariesLPw(); 2102 2103 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2104 // NOTE: We ignore potential failures here during a system scan (like 2105 // the rest of the commands above) because there's precious little we 2106 // can do about it. A settings error is reported, though. 2107 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2108 false /* force dexopt */, false /* defer dexopt */); 2109 } 2110 2111 // Now that we know all the packages we are keeping, 2112 // read and update their last usage times. 2113 mPackageUsage.readLP(); 2114 2115 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2116 SystemClock.uptimeMillis()); 2117 Slog.i(TAG, "Time to scan packages: " 2118 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2119 + " seconds"); 2120 2121 // If the platform SDK has changed since the last time we booted, 2122 // we need to re-grant app permission to catch any new ones that 2123 // appear. This is really a hack, and means that apps can in some 2124 // cases get permissions that the user didn't initially explicitly 2125 // allow... it would be nice to have some better way to handle 2126 // this situation. 2127 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2128 != mSdkVersion; 2129 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2130 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2131 + "; regranting permissions for internal storage"); 2132 mSettings.mInternalSdkPlatform = mSdkVersion; 2133 2134 // For now runtime permissions are toggled via a system property. 2135 if (!RUNTIME_PERMISSIONS_ENABLED) { 2136 // Remove the runtime permissions state if the feature 2137 // was disabled by flipping the system property. 2138 mSettings.deleteRuntimePermissionsFiles(); 2139 } 2140 2141 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2142 | (regrantPermissions 2143 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2144 : 0)); 2145 2146 // If this is the first boot, and it is a normal boot, then 2147 // we need to initialize the default preferred apps. 2148 if (!mRestoredSettings && !onlyCore) { 2149 mSettings.readDefaultPreferredAppsLPw(this, 0); 2150 } 2151 2152 // If this is first boot after an OTA, and a normal boot, then 2153 // we need to clear code cache directories. 2154 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2155 if (mIsUpgrade && !onlyCore) { 2156 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2157 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2158 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2159 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2160 } 2161 mSettings.mFingerprint = Build.FINGERPRINT; 2162 } 2163 2164 // All the changes are done during package scanning. 2165 mSettings.updateInternalDatabaseVersion(); 2166 2167 // can downgrade to reader 2168 mSettings.writeLPr(); 2169 2170 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2171 SystemClock.uptimeMillis()); 2172 2173 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2174 2175 mInstallerService = new PackageInstallerService(context, this); 2176 2177 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2178 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2179 mIntentFilterVerifierComponent); 2180 2181 primeDomainVerificationsLPw(false); 2182 2183 } // synchronized (mPackages) 2184 } // synchronized (mInstallLock) 2185 2186 // Now after opening every single application zip, make sure they 2187 // are all flushed. Not really needed, but keeps things nice and 2188 // tidy. 2189 Runtime.getRuntime().gc(); 2190 } 2191 2192 @Override 2193 public boolean isFirstBoot() { 2194 return !mRestoredSettings; 2195 } 2196 2197 @Override 2198 public boolean isOnlyCoreApps() { 2199 return mOnlyCore; 2200 } 2201 2202 @Override 2203 public boolean isUpgrade() { 2204 return mIsUpgrade; 2205 } 2206 2207 private String getRequiredVerifierLPr() { 2208 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2209 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2210 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2211 2212 String requiredVerifier = null; 2213 2214 final int N = receivers.size(); 2215 for (int i = 0; i < N; i++) { 2216 final ResolveInfo info = receivers.get(i); 2217 2218 if (info.activityInfo == null) { 2219 continue; 2220 } 2221 2222 final String packageName = info.activityInfo.packageName; 2223 2224 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2225 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2226 continue; 2227 } 2228 2229 if (requiredVerifier != null) { 2230 throw new RuntimeException("There can be only one required verifier"); 2231 } 2232 2233 requiredVerifier = packageName; 2234 } 2235 2236 return requiredVerifier; 2237 } 2238 2239 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2240 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2241 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2242 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2243 2244 ComponentName verifierComponentName = null; 2245 2246 int priority = -1000; 2247 final int N = receivers.size(); 2248 for (int i = 0; i < N; i++) { 2249 final ResolveInfo info = receivers.get(i); 2250 2251 if (info.activityInfo == null) { 2252 continue; 2253 } 2254 2255 final String packageName = info.activityInfo.packageName; 2256 2257 final PackageSetting ps = mSettings.mPackages.get(packageName); 2258 if (ps == null) { 2259 continue; 2260 } 2261 2262 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2263 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2264 continue; 2265 } 2266 2267 // Select the IntentFilterVerifier with the highest priority 2268 if (priority < info.priority) { 2269 priority = info.priority; 2270 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2271 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2272 " with priority: " + info.priority); 2273 } 2274 } 2275 2276 return verifierComponentName; 2277 } 2278 2279 private void primeDomainVerificationsLPw(boolean logging) { 2280 Slog.d(TAG, "Start priming domain verification"); 2281 boolean updated = false; 2282 ArrayList<String> allHosts = new ArrayList<>(); 2283 for (PackageParser.Package pkg : mPackages.values()) { 2284 final String packageName = pkg.packageName; 2285 if (!hasDomainURLs(pkg)) { 2286 if (logging) { 2287 Slog.d(TAG, "No priming domain verifications for " + 2288 "package with no domain URLs: " + packageName); 2289 } 2290 continue; 2291 } 2292 if (!pkg.isSystemApp()) { 2293 if (logging) { 2294 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2295 packageName); 2296 } 2297 continue; 2298 } 2299 for (PackageParser.Activity a : pkg.activities) { 2300 for (ActivityIntentInfo filter : a.intents) { 2301 if (hasValidDomains(filter, false)) { 2302 allHosts.addAll(filter.getHostsList()); 2303 } 2304 } 2305 } 2306 if (allHosts.size() == 0) { 2307 allHosts.add("*"); 2308 } 2309 IntentFilterVerificationInfo ivi = 2310 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHosts); 2311 if (ivi != null) { 2312 // We will always log this 2313 Slog.d(TAG, "Priming domain verifications for package: " + packageName); 2314 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2315 updated = true; 2316 } 2317 else { 2318 if (logging) { 2319 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2320 } 2321 } 2322 allHosts.clear(); 2323 } 2324 if (updated) { 2325 scheduleWriteSettingsLocked(); 2326 } 2327 Slog.d(TAG, "End priming domain verification"); 2328 } 2329 2330 @Override 2331 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2332 throws RemoteException { 2333 try { 2334 return super.onTransact(code, data, reply, flags); 2335 } catch (RuntimeException e) { 2336 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2337 Slog.wtf(TAG, "Package Manager Crash", e); 2338 } 2339 throw e; 2340 } 2341 } 2342 2343 void cleanupInstallFailedPackage(PackageSetting ps) { 2344 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2345 2346 removeDataDirsLI(ps.volumeUuid, ps.name); 2347 if (ps.codePath != null) { 2348 if (ps.codePath.isDirectory()) { 2349 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2350 } else { 2351 ps.codePath.delete(); 2352 } 2353 } 2354 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2355 if (ps.resourcePath.isDirectory()) { 2356 FileUtils.deleteContents(ps.resourcePath); 2357 } 2358 ps.resourcePath.delete(); 2359 } 2360 mSettings.removePackageLPw(ps.name); 2361 } 2362 2363 static int[] appendInts(int[] cur, int[] add) { 2364 if (add == null) return cur; 2365 if (cur == null) return add; 2366 final int N = add.length; 2367 for (int i=0; i<N; i++) { 2368 cur = appendInt(cur, add[i]); 2369 } 2370 return cur; 2371 } 2372 2373 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2374 if (!sUserManager.exists(userId)) return null; 2375 final PackageSetting ps = (PackageSetting) p.mExtras; 2376 if (ps == null) { 2377 return null; 2378 } 2379 2380 final PermissionsState permissionsState = ps.getPermissionsState(); 2381 2382 final int[] gids = permissionsState.computeGids(userId); 2383 final Set<String> permissions = permissionsState.getPermissions(userId); 2384 final PackageUserState state = ps.readUserState(userId); 2385 2386 return PackageParser.generatePackageInfo(p, gids, flags, 2387 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2388 } 2389 2390 @Override 2391 public boolean isPackageFrozen(String packageName) { 2392 synchronized (mPackages) { 2393 final PackageSetting ps = mSettings.mPackages.get(packageName); 2394 if (ps != null) { 2395 return ps.frozen; 2396 } 2397 } 2398 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2399 return true; 2400 } 2401 2402 @Override 2403 public boolean isPackageAvailable(String packageName, int userId) { 2404 if (!sUserManager.exists(userId)) return false; 2405 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2406 synchronized (mPackages) { 2407 PackageParser.Package p = mPackages.get(packageName); 2408 if (p != null) { 2409 final PackageSetting ps = (PackageSetting) p.mExtras; 2410 if (ps != null) { 2411 final PackageUserState state = ps.readUserState(userId); 2412 if (state != null) { 2413 return PackageParser.isAvailable(state); 2414 } 2415 } 2416 } 2417 } 2418 return false; 2419 } 2420 2421 @Override 2422 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2423 if (!sUserManager.exists(userId)) return null; 2424 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2425 // reader 2426 synchronized (mPackages) { 2427 PackageParser.Package p = mPackages.get(packageName); 2428 if (DEBUG_PACKAGE_INFO) 2429 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2430 if (p != null) { 2431 return generatePackageInfo(p, flags, userId); 2432 } 2433 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2434 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2435 } 2436 } 2437 return null; 2438 } 2439 2440 @Override 2441 public String[] currentToCanonicalPackageNames(String[] names) { 2442 String[] out = new String[names.length]; 2443 // reader 2444 synchronized (mPackages) { 2445 for (int i=names.length-1; i>=0; i--) { 2446 PackageSetting ps = mSettings.mPackages.get(names[i]); 2447 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2448 } 2449 } 2450 return out; 2451 } 2452 2453 @Override 2454 public String[] canonicalToCurrentPackageNames(String[] names) { 2455 String[] out = new String[names.length]; 2456 // reader 2457 synchronized (mPackages) { 2458 for (int i=names.length-1; i>=0; i--) { 2459 String cur = mSettings.mRenamedPackages.get(names[i]); 2460 out[i] = cur != null ? cur : names[i]; 2461 } 2462 } 2463 return out; 2464 } 2465 2466 @Override 2467 public int getPackageUid(String packageName, int userId) { 2468 if (!sUserManager.exists(userId)) return -1; 2469 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2470 2471 // reader 2472 synchronized (mPackages) { 2473 PackageParser.Package p = mPackages.get(packageName); 2474 if(p != null) { 2475 return UserHandle.getUid(userId, p.applicationInfo.uid); 2476 } 2477 PackageSetting ps = mSettings.mPackages.get(packageName); 2478 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2479 return -1; 2480 } 2481 p = ps.pkg; 2482 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2483 } 2484 } 2485 2486 @Override 2487 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2488 if (!sUserManager.exists(userId)) { 2489 return null; 2490 } 2491 2492 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2493 "getPackageGids"); 2494 2495 // reader 2496 synchronized (mPackages) { 2497 PackageParser.Package p = mPackages.get(packageName); 2498 if (DEBUG_PACKAGE_INFO) { 2499 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2500 } 2501 if (p != null) { 2502 PackageSetting ps = (PackageSetting) p.mExtras; 2503 return ps.getPermissionsState().computeGids(userId); 2504 } 2505 } 2506 2507 return null; 2508 } 2509 2510 static PermissionInfo generatePermissionInfo( 2511 BasePermission bp, int flags) { 2512 if (bp.perm != null) { 2513 return PackageParser.generatePermissionInfo(bp.perm, flags); 2514 } 2515 PermissionInfo pi = new PermissionInfo(); 2516 pi.name = bp.name; 2517 pi.packageName = bp.sourcePackage; 2518 pi.nonLocalizedLabel = bp.name; 2519 pi.protectionLevel = bp.protectionLevel; 2520 return pi; 2521 } 2522 2523 @Override 2524 public PermissionInfo getPermissionInfo(String name, int flags) { 2525 // reader 2526 synchronized (mPackages) { 2527 final BasePermission p = mSettings.mPermissions.get(name); 2528 if (p != null) { 2529 return generatePermissionInfo(p, flags); 2530 } 2531 return null; 2532 } 2533 } 2534 2535 @Override 2536 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2537 // reader 2538 synchronized (mPackages) { 2539 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2540 for (BasePermission p : mSettings.mPermissions.values()) { 2541 if (group == null) { 2542 if (p.perm == null || p.perm.info.group == null) { 2543 out.add(generatePermissionInfo(p, flags)); 2544 } 2545 } else { 2546 if (p.perm != null && group.equals(p.perm.info.group)) { 2547 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2548 } 2549 } 2550 } 2551 2552 if (out.size() > 0) { 2553 return out; 2554 } 2555 return mPermissionGroups.containsKey(group) ? out : null; 2556 } 2557 } 2558 2559 @Override 2560 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2561 // reader 2562 synchronized (mPackages) { 2563 return PackageParser.generatePermissionGroupInfo( 2564 mPermissionGroups.get(name), flags); 2565 } 2566 } 2567 2568 @Override 2569 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2570 // reader 2571 synchronized (mPackages) { 2572 final int N = mPermissionGroups.size(); 2573 ArrayList<PermissionGroupInfo> out 2574 = new ArrayList<PermissionGroupInfo>(N); 2575 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2576 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2577 } 2578 return out; 2579 } 2580 } 2581 2582 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2583 int userId) { 2584 if (!sUserManager.exists(userId)) return null; 2585 PackageSetting ps = mSettings.mPackages.get(packageName); 2586 if (ps != null) { 2587 if (ps.pkg == null) { 2588 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2589 flags, userId); 2590 if (pInfo != null) { 2591 return pInfo.applicationInfo; 2592 } 2593 return null; 2594 } 2595 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2596 ps.readUserState(userId), userId); 2597 } 2598 return null; 2599 } 2600 2601 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2602 int userId) { 2603 if (!sUserManager.exists(userId)) return null; 2604 PackageSetting ps = mSettings.mPackages.get(packageName); 2605 if (ps != null) { 2606 PackageParser.Package pkg = ps.pkg; 2607 if (pkg == null) { 2608 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2609 return null; 2610 } 2611 // Only data remains, so we aren't worried about code paths 2612 pkg = new PackageParser.Package(packageName); 2613 pkg.applicationInfo.packageName = packageName; 2614 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2615 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2616 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2617 packageName, userId).getAbsolutePath(); 2618 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2619 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2620 } 2621 return generatePackageInfo(pkg, flags, userId); 2622 } 2623 return null; 2624 } 2625 2626 @Override 2627 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2628 if (!sUserManager.exists(userId)) return null; 2629 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2630 // writer 2631 synchronized (mPackages) { 2632 PackageParser.Package p = mPackages.get(packageName); 2633 if (DEBUG_PACKAGE_INFO) Log.v( 2634 TAG, "getApplicationInfo " + packageName 2635 + ": " + p); 2636 if (p != null) { 2637 PackageSetting ps = mSettings.mPackages.get(packageName); 2638 if (ps == null) return null; 2639 // Note: isEnabledLP() does not apply here - always return info 2640 return PackageParser.generateApplicationInfo( 2641 p, flags, ps.readUserState(userId), userId); 2642 } 2643 if ("android".equals(packageName)||"system".equals(packageName)) { 2644 return mAndroidApplication; 2645 } 2646 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2647 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2648 } 2649 } 2650 return null; 2651 } 2652 2653 @Override 2654 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2655 final IPackageDataObserver observer) { 2656 mContext.enforceCallingOrSelfPermission( 2657 android.Manifest.permission.CLEAR_APP_CACHE, null); 2658 // Queue up an async operation since clearing cache may take a little while. 2659 mHandler.post(new Runnable() { 2660 public void run() { 2661 mHandler.removeCallbacks(this); 2662 int retCode = -1; 2663 synchronized (mInstallLock) { 2664 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2665 if (retCode < 0) { 2666 Slog.w(TAG, "Couldn't clear application caches"); 2667 } 2668 } 2669 if (observer != null) { 2670 try { 2671 observer.onRemoveCompleted(null, (retCode >= 0)); 2672 } catch (RemoteException e) { 2673 Slog.w(TAG, "RemoveException when invoking call back"); 2674 } 2675 } 2676 } 2677 }); 2678 } 2679 2680 @Override 2681 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2682 final IntentSender pi) { 2683 mContext.enforceCallingOrSelfPermission( 2684 android.Manifest.permission.CLEAR_APP_CACHE, null); 2685 // Queue up an async operation since clearing cache may take a little while. 2686 mHandler.post(new Runnable() { 2687 public void run() { 2688 mHandler.removeCallbacks(this); 2689 int retCode = -1; 2690 synchronized (mInstallLock) { 2691 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2692 if (retCode < 0) { 2693 Slog.w(TAG, "Couldn't clear application caches"); 2694 } 2695 } 2696 if(pi != null) { 2697 try { 2698 // Callback via pending intent 2699 int code = (retCode >= 0) ? 1 : 0; 2700 pi.sendIntent(null, code, null, 2701 null, null); 2702 } catch (SendIntentException e1) { 2703 Slog.i(TAG, "Failed to send pending intent"); 2704 } 2705 } 2706 } 2707 }); 2708 } 2709 2710 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2711 synchronized (mInstallLock) { 2712 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2713 throw new IOException("Failed to free enough space"); 2714 } 2715 } 2716 } 2717 2718 @Override 2719 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2720 if (!sUserManager.exists(userId)) return null; 2721 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2722 synchronized (mPackages) { 2723 PackageParser.Activity a = mActivities.mActivities.get(component); 2724 2725 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2726 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2727 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2728 if (ps == null) return null; 2729 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2730 userId); 2731 } 2732 if (mResolveComponentName.equals(component)) { 2733 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2734 new PackageUserState(), userId); 2735 } 2736 } 2737 return null; 2738 } 2739 2740 @Override 2741 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2742 String resolvedType) { 2743 synchronized (mPackages) { 2744 PackageParser.Activity a = mActivities.mActivities.get(component); 2745 if (a == null) { 2746 return false; 2747 } 2748 for (int i=0; i<a.intents.size(); i++) { 2749 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2750 intent.getData(), intent.getCategories(), TAG) >= 0) { 2751 return true; 2752 } 2753 } 2754 return false; 2755 } 2756 } 2757 2758 @Override 2759 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2760 if (!sUserManager.exists(userId)) return null; 2761 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2762 synchronized (mPackages) { 2763 PackageParser.Activity a = mReceivers.mActivities.get(component); 2764 if (DEBUG_PACKAGE_INFO) Log.v( 2765 TAG, "getReceiverInfo " + component + ": " + a); 2766 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2767 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2768 if (ps == null) return null; 2769 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2770 userId); 2771 } 2772 } 2773 return null; 2774 } 2775 2776 @Override 2777 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2778 if (!sUserManager.exists(userId)) return null; 2779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2780 synchronized (mPackages) { 2781 PackageParser.Service s = mServices.mServices.get(component); 2782 if (DEBUG_PACKAGE_INFO) Log.v( 2783 TAG, "getServiceInfo " + component + ": " + s); 2784 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2785 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2786 if (ps == null) return null; 2787 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2788 userId); 2789 } 2790 } 2791 return null; 2792 } 2793 2794 @Override 2795 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return null; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2798 synchronized (mPackages) { 2799 PackageParser.Provider p = mProviders.mProviders.get(component); 2800 if (DEBUG_PACKAGE_INFO) Log.v( 2801 TAG, "getProviderInfo " + component + ": " + p); 2802 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2803 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2804 if (ps == null) return null; 2805 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2806 userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public String[] getSystemSharedLibraryNames() { 2814 Set<String> libSet; 2815 synchronized (mPackages) { 2816 libSet = mSharedLibraries.keySet(); 2817 int size = libSet.size(); 2818 if (size > 0) { 2819 String[] libs = new String[size]; 2820 libSet.toArray(libs); 2821 return libs; 2822 } 2823 } 2824 return null; 2825 } 2826 2827 /** 2828 * @hide 2829 */ 2830 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2831 synchronized (mPackages) { 2832 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2833 if (lib != null && lib.apk != null) { 2834 return mPackages.get(lib.apk); 2835 } 2836 } 2837 return null; 2838 } 2839 2840 @Override 2841 public FeatureInfo[] getSystemAvailableFeatures() { 2842 Collection<FeatureInfo> featSet; 2843 synchronized (mPackages) { 2844 featSet = mAvailableFeatures.values(); 2845 int size = featSet.size(); 2846 if (size > 0) { 2847 FeatureInfo[] features = new FeatureInfo[size+1]; 2848 featSet.toArray(features); 2849 FeatureInfo fi = new FeatureInfo(); 2850 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2851 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2852 features[size] = fi; 2853 return features; 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public boolean hasSystemFeature(String name) { 2861 synchronized (mPackages) { 2862 return mAvailableFeatures.containsKey(name); 2863 } 2864 } 2865 2866 private void checkValidCaller(int uid, int userId) { 2867 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2868 return; 2869 2870 throw new SecurityException("Caller uid=" + uid 2871 + " is not privileged to communicate with user=" + userId); 2872 } 2873 2874 @Override 2875 public int checkPermission(String permName, String pkgName, int userId) { 2876 if (!sUserManager.exists(userId)) { 2877 return PackageManager.PERMISSION_DENIED; 2878 } 2879 2880 synchronized (mPackages) { 2881 final PackageParser.Package p = mPackages.get(pkgName); 2882 if (p != null && p.mExtras != null) { 2883 final PackageSetting ps = (PackageSetting) p.mExtras; 2884 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2885 return PackageManager.PERMISSION_GRANTED; 2886 } 2887 } 2888 } 2889 2890 return PackageManager.PERMISSION_DENIED; 2891 } 2892 2893 @Override 2894 public int checkUidPermission(String permName, int uid) { 2895 final int userId = UserHandle.getUserId(uid); 2896 2897 if (!sUserManager.exists(userId)) { 2898 return PackageManager.PERMISSION_DENIED; 2899 } 2900 2901 synchronized (mPackages) { 2902 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2903 if (obj != null) { 2904 final SettingBase ps = (SettingBase) obj; 2905 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2906 return PackageManager.PERMISSION_GRANTED; 2907 } 2908 } else { 2909 ArraySet<String> perms = mSystemPermissions.get(uid); 2910 if (perms != null && perms.contains(permName)) { 2911 return PackageManager.PERMISSION_GRANTED; 2912 } 2913 } 2914 } 2915 2916 return PackageManager.PERMISSION_DENIED; 2917 } 2918 2919 /** 2920 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2921 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2922 * @param checkShell TODO(yamasani): 2923 * @param message the message to log on security exception 2924 */ 2925 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2926 boolean checkShell, String message) { 2927 if (userId < 0) { 2928 throw new IllegalArgumentException("Invalid userId " + userId); 2929 } 2930 if (checkShell) { 2931 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2932 } 2933 if (userId == UserHandle.getUserId(callingUid)) return; 2934 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2935 if (requireFullPermission) { 2936 mContext.enforceCallingOrSelfPermission( 2937 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2938 } else { 2939 try { 2940 mContext.enforceCallingOrSelfPermission( 2941 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2942 } catch (SecurityException se) { 2943 mContext.enforceCallingOrSelfPermission( 2944 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2945 } 2946 } 2947 } 2948 } 2949 2950 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2951 if (callingUid == Process.SHELL_UID) { 2952 if (userHandle >= 0 2953 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2954 throw new SecurityException("Shell does not have permission to access user " 2955 + userHandle); 2956 } else if (userHandle < 0) { 2957 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2958 + Debug.getCallers(3)); 2959 } 2960 } 2961 } 2962 2963 private BasePermission findPermissionTreeLP(String permName) { 2964 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2965 if (permName.startsWith(bp.name) && 2966 permName.length() > bp.name.length() && 2967 permName.charAt(bp.name.length()) == '.') { 2968 return bp; 2969 } 2970 } 2971 return null; 2972 } 2973 2974 private BasePermission checkPermissionTreeLP(String permName) { 2975 if (permName != null) { 2976 BasePermission bp = findPermissionTreeLP(permName); 2977 if (bp != null) { 2978 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2979 return bp; 2980 } 2981 throw new SecurityException("Calling uid " 2982 + Binder.getCallingUid() 2983 + " is not allowed to add to permission tree " 2984 + bp.name + " owned by uid " + bp.uid); 2985 } 2986 } 2987 throw new SecurityException("No permission tree found for " + permName); 2988 } 2989 2990 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2991 if (s1 == null) { 2992 return s2 == null; 2993 } 2994 if (s2 == null) { 2995 return false; 2996 } 2997 if (s1.getClass() != s2.getClass()) { 2998 return false; 2999 } 3000 return s1.equals(s2); 3001 } 3002 3003 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3004 if (pi1.icon != pi2.icon) return false; 3005 if (pi1.logo != pi2.logo) return false; 3006 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3007 if (!compareStrings(pi1.name, pi2.name)) return false; 3008 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3009 // We'll take care of setting this one. 3010 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3011 // These are not currently stored in settings. 3012 //if (!compareStrings(pi1.group, pi2.group)) return false; 3013 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3014 //if (pi1.labelRes != pi2.labelRes) return false; 3015 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3016 return true; 3017 } 3018 3019 int permissionInfoFootprint(PermissionInfo info) { 3020 int size = info.name.length(); 3021 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3022 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3023 return size; 3024 } 3025 3026 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3027 int size = 0; 3028 for (BasePermission perm : mSettings.mPermissions.values()) { 3029 if (perm.uid == tree.uid) { 3030 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3031 } 3032 } 3033 return size; 3034 } 3035 3036 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3037 // We calculate the max size of permissions defined by this uid and throw 3038 // if that plus the size of 'info' would exceed our stated maximum. 3039 if (tree.uid != Process.SYSTEM_UID) { 3040 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3041 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3042 throw new SecurityException("Permission tree size cap exceeded"); 3043 } 3044 } 3045 } 3046 3047 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3048 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3049 throw new SecurityException("Label must be specified in permission"); 3050 } 3051 BasePermission tree = checkPermissionTreeLP(info.name); 3052 BasePermission bp = mSettings.mPermissions.get(info.name); 3053 boolean added = bp == null; 3054 boolean changed = true; 3055 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3056 if (added) { 3057 enforcePermissionCapLocked(info, tree); 3058 bp = new BasePermission(info.name, tree.sourcePackage, 3059 BasePermission.TYPE_DYNAMIC); 3060 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3061 throw new SecurityException( 3062 "Not allowed to modify non-dynamic permission " 3063 + info.name); 3064 } else { 3065 if (bp.protectionLevel == fixedLevel 3066 && bp.perm.owner.equals(tree.perm.owner) 3067 && bp.uid == tree.uid 3068 && comparePermissionInfos(bp.perm.info, info)) { 3069 changed = false; 3070 } 3071 } 3072 bp.protectionLevel = fixedLevel; 3073 info = new PermissionInfo(info); 3074 info.protectionLevel = fixedLevel; 3075 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3076 bp.perm.info.packageName = tree.perm.info.packageName; 3077 bp.uid = tree.uid; 3078 if (added) { 3079 mSettings.mPermissions.put(info.name, bp); 3080 } 3081 if (changed) { 3082 if (!async) { 3083 mSettings.writeLPr(); 3084 } else { 3085 scheduleWriteSettingsLocked(); 3086 } 3087 } 3088 return added; 3089 } 3090 3091 @Override 3092 public boolean addPermission(PermissionInfo info) { 3093 synchronized (mPackages) { 3094 return addPermissionLocked(info, false); 3095 } 3096 } 3097 3098 @Override 3099 public boolean addPermissionAsync(PermissionInfo info) { 3100 synchronized (mPackages) { 3101 return addPermissionLocked(info, true); 3102 } 3103 } 3104 3105 @Override 3106 public void removePermission(String name) { 3107 synchronized (mPackages) { 3108 checkPermissionTreeLP(name); 3109 BasePermission bp = mSettings.mPermissions.get(name); 3110 if (bp != null) { 3111 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3112 throw new SecurityException( 3113 "Not allowed to modify non-dynamic permission " 3114 + name); 3115 } 3116 mSettings.mPermissions.remove(name); 3117 mSettings.writeLPr(); 3118 } 3119 } 3120 } 3121 3122 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3123 BasePermission bp) { 3124 int index = pkg.requestedPermissions.indexOf(bp.name); 3125 if (index == -1) { 3126 throw new SecurityException("Package " + pkg.packageName 3127 + " has not requested permission " + bp.name); 3128 } 3129 if (!bp.isRuntime()) { 3130 throw new SecurityException("Permission " + bp.name 3131 + " is not a changeable permission type"); 3132 } 3133 } 3134 3135 @Override 3136 public boolean grantPermission(String packageName, String name, int userId) { 3137 if (!RUNTIME_PERMISSIONS_ENABLED) { 3138 return false; 3139 } 3140 3141 if (!sUserManager.exists(userId)) { 3142 return false; 3143 } 3144 3145 mContext.enforceCallingOrSelfPermission( 3146 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3147 "grantPermission"); 3148 3149 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3150 "grantPermission"); 3151 3152 boolean gidsChanged = false; 3153 final SettingBase sb; 3154 3155 synchronized (mPackages) { 3156 final PackageParser.Package pkg = mPackages.get(packageName); 3157 if (pkg == null) { 3158 throw new IllegalArgumentException("Unknown package: " + packageName); 3159 } 3160 3161 final BasePermission bp = mSettings.mPermissions.get(name); 3162 if (bp == null) { 3163 throw new IllegalArgumentException("Unknown permission: " + name); 3164 } 3165 3166 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3167 3168 sb = (SettingBase) pkg.mExtras; 3169 if (sb == null) { 3170 throw new IllegalArgumentException("Unknown package: " + packageName); 3171 } 3172 3173 final PermissionsState permissionsState = sb.getPermissionsState(); 3174 3175 final int result = permissionsState.grantRuntimePermission(bp, userId); 3176 switch (result) { 3177 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3178 return false; 3179 } 3180 3181 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3182 gidsChanged = true; 3183 } break; 3184 } 3185 3186 // Not critical if that is lost - app has to request again. 3187 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3188 } 3189 3190 if (gidsChanged) { 3191 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3192 } 3193 3194 return true; 3195 } 3196 3197 @Override 3198 public boolean revokePermission(String packageName, String name, int userId) { 3199 if (!RUNTIME_PERMISSIONS_ENABLED) { 3200 return false; 3201 } 3202 3203 if (!sUserManager.exists(userId)) { 3204 return false; 3205 } 3206 3207 mContext.enforceCallingOrSelfPermission( 3208 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3209 "revokePermission"); 3210 3211 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3212 "revokePermission"); 3213 3214 final SettingBase sb; 3215 3216 synchronized (mPackages) { 3217 final PackageParser.Package pkg = mPackages.get(packageName); 3218 if (pkg == null) { 3219 throw new IllegalArgumentException("Unknown package: " + packageName); 3220 } 3221 3222 final BasePermission bp = mSettings.mPermissions.get(name); 3223 if (bp == null) { 3224 throw new IllegalArgumentException("Unknown permission: " + name); 3225 } 3226 3227 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3228 3229 sb = (SettingBase) pkg.mExtras; 3230 if (sb == null) { 3231 throw new IllegalArgumentException("Unknown package: " + packageName); 3232 } 3233 3234 final PermissionsState permissionsState = sb.getPermissionsState(); 3235 3236 if (permissionsState.revokeRuntimePermission(bp, userId) == 3237 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3238 return false; 3239 } 3240 3241 // Critical, after this call all should never have the permission. 3242 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3243 } 3244 3245 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3246 3247 return true; 3248 } 3249 3250 @Override 3251 public boolean isProtectedBroadcast(String actionName) { 3252 synchronized (mPackages) { 3253 return mProtectedBroadcasts.contains(actionName); 3254 } 3255 } 3256 3257 @Override 3258 public int checkSignatures(String pkg1, String pkg2) { 3259 synchronized (mPackages) { 3260 final PackageParser.Package p1 = mPackages.get(pkg1); 3261 final PackageParser.Package p2 = mPackages.get(pkg2); 3262 if (p1 == null || p1.mExtras == null 3263 || p2 == null || p2.mExtras == null) { 3264 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3265 } 3266 return compareSignatures(p1.mSignatures, p2.mSignatures); 3267 } 3268 } 3269 3270 @Override 3271 public int checkUidSignatures(int uid1, int uid2) { 3272 // Map to base uids. 3273 uid1 = UserHandle.getAppId(uid1); 3274 uid2 = UserHandle.getAppId(uid2); 3275 // reader 3276 synchronized (mPackages) { 3277 Signature[] s1; 3278 Signature[] s2; 3279 Object obj = mSettings.getUserIdLPr(uid1); 3280 if (obj != null) { 3281 if (obj instanceof SharedUserSetting) { 3282 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3283 } else if (obj instanceof PackageSetting) { 3284 s1 = ((PackageSetting)obj).signatures.mSignatures; 3285 } else { 3286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3287 } 3288 } else { 3289 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3290 } 3291 obj = mSettings.getUserIdLPr(uid2); 3292 if (obj != null) { 3293 if (obj instanceof SharedUserSetting) { 3294 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3295 } else if (obj instanceof PackageSetting) { 3296 s2 = ((PackageSetting)obj).signatures.mSignatures; 3297 } else { 3298 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3299 } 3300 } else { 3301 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3302 } 3303 return compareSignatures(s1, s2); 3304 } 3305 } 3306 3307 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3308 final long identity = Binder.clearCallingIdentity(); 3309 try { 3310 if (sb instanceof SharedUserSetting) { 3311 SharedUserSetting sus = (SharedUserSetting) sb; 3312 final int packageCount = sus.packages.size(); 3313 for (int i = 0; i < packageCount; i++) { 3314 PackageSetting susPs = sus.packages.valueAt(i); 3315 if (userId == UserHandle.USER_ALL) { 3316 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3317 } else { 3318 final int uid = UserHandle.getUid(userId, susPs.appId); 3319 killUid(uid, reason); 3320 } 3321 } 3322 } else if (sb instanceof PackageSetting) { 3323 PackageSetting ps = (PackageSetting) sb; 3324 if (userId == UserHandle.USER_ALL) { 3325 killApplication(ps.pkg.packageName, ps.appId, reason); 3326 } else { 3327 final int uid = UserHandle.getUid(userId, ps.appId); 3328 killUid(uid, reason); 3329 } 3330 } 3331 } finally { 3332 Binder.restoreCallingIdentity(identity); 3333 } 3334 } 3335 3336 private static void killUid(int uid, String reason) { 3337 IActivityManager am = ActivityManagerNative.getDefault(); 3338 if (am != null) { 3339 try { 3340 am.killUid(uid, reason); 3341 } catch (RemoteException e) { 3342 /* ignore - same process */ 3343 } 3344 } 3345 } 3346 3347 /** 3348 * Compares two sets of signatures. Returns: 3349 * <br /> 3350 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3351 * <br /> 3352 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3353 * <br /> 3354 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3355 * <br /> 3356 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3357 * <br /> 3358 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3359 */ 3360 static int compareSignatures(Signature[] s1, Signature[] s2) { 3361 if (s1 == null) { 3362 return s2 == null 3363 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3364 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3365 } 3366 3367 if (s2 == null) { 3368 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3369 } 3370 3371 if (s1.length != s2.length) { 3372 return PackageManager.SIGNATURE_NO_MATCH; 3373 } 3374 3375 // Since both signature sets are of size 1, we can compare without HashSets. 3376 if (s1.length == 1) { 3377 return s1[0].equals(s2[0]) ? 3378 PackageManager.SIGNATURE_MATCH : 3379 PackageManager.SIGNATURE_NO_MATCH; 3380 } 3381 3382 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3383 for (Signature sig : s1) { 3384 set1.add(sig); 3385 } 3386 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3387 for (Signature sig : s2) { 3388 set2.add(sig); 3389 } 3390 // Make sure s2 contains all signatures in s1. 3391 if (set1.equals(set2)) { 3392 return PackageManager.SIGNATURE_MATCH; 3393 } 3394 return PackageManager.SIGNATURE_NO_MATCH; 3395 } 3396 3397 /** 3398 * If the database version for this type of package (internal storage or 3399 * external storage) is less than the version where package signatures 3400 * were updated, return true. 3401 */ 3402 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3403 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3404 DatabaseVersion.SIGNATURE_END_ENTITY)) 3405 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3406 DatabaseVersion.SIGNATURE_END_ENTITY)); 3407 } 3408 3409 /** 3410 * Used for backward compatibility to make sure any packages with 3411 * certificate chains get upgraded to the new style. {@code existingSigs} 3412 * will be in the old format (since they were stored on disk from before the 3413 * system upgrade) and {@code scannedSigs} will be in the newer format. 3414 */ 3415 private int compareSignaturesCompat(PackageSignatures existingSigs, 3416 PackageParser.Package scannedPkg) { 3417 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3418 return PackageManager.SIGNATURE_NO_MATCH; 3419 } 3420 3421 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3422 for (Signature sig : existingSigs.mSignatures) { 3423 existingSet.add(sig); 3424 } 3425 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3426 for (Signature sig : scannedPkg.mSignatures) { 3427 try { 3428 Signature[] chainSignatures = sig.getChainSignatures(); 3429 for (Signature chainSig : chainSignatures) { 3430 scannedCompatSet.add(chainSig); 3431 } 3432 } catch (CertificateEncodingException e) { 3433 scannedCompatSet.add(sig); 3434 } 3435 } 3436 /* 3437 * Make sure the expanded scanned set contains all signatures in the 3438 * existing one. 3439 */ 3440 if (scannedCompatSet.equals(existingSet)) { 3441 // Migrate the old signatures to the new scheme. 3442 existingSigs.assignSignatures(scannedPkg.mSignatures); 3443 // The new KeySets will be re-added later in the scanning process. 3444 synchronized (mPackages) { 3445 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3446 } 3447 return PackageManager.SIGNATURE_MATCH; 3448 } 3449 return PackageManager.SIGNATURE_NO_MATCH; 3450 } 3451 3452 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3453 if (isExternal(scannedPkg)) { 3454 return mSettings.isExternalDatabaseVersionOlderThan( 3455 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3456 } else { 3457 return mSettings.isInternalDatabaseVersionOlderThan( 3458 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3459 } 3460 } 3461 3462 private int compareSignaturesRecover(PackageSignatures existingSigs, 3463 PackageParser.Package scannedPkg) { 3464 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3465 return PackageManager.SIGNATURE_NO_MATCH; 3466 } 3467 3468 String msg = null; 3469 try { 3470 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3471 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3472 + scannedPkg.packageName); 3473 return PackageManager.SIGNATURE_MATCH; 3474 } 3475 } catch (CertificateException e) { 3476 msg = e.getMessage(); 3477 } 3478 3479 logCriticalInfo(Log.INFO, 3480 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3481 return PackageManager.SIGNATURE_NO_MATCH; 3482 } 3483 3484 @Override 3485 public String[] getPackagesForUid(int uid) { 3486 uid = UserHandle.getAppId(uid); 3487 // reader 3488 synchronized (mPackages) { 3489 Object obj = mSettings.getUserIdLPr(uid); 3490 if (obj instanceof SharedUserSetting) { 3491 final SharedUserSetting sus = (SharedUserSetting) obj; 3492 final int N = sus.packages.size(); 3493 final String[] res = new String[N]; 3494 final Iterator<PackageSetting> it = sus.packages.iterator(); 3495 int i = 0; 3496 while (it.hasNext()) { 3497 res[i++] = it.next().name; 3498 } 3499 return res; 3500 } else if (obj instanceof PackageSetting) { 3501 final PackageSetting ps = (PackageSetting) obj; 3502 return new String[] { ps.name }; 3503 } 3504 } 3505 return null; 3506 } 3507 3508 @Override 3509 public String getNameForUid(int uid) { 3510 // reader 3511 synchronized (mPackages) { 3512 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3513 if (obj instanceof SharedUserSetting) { 3514 final SharedUserSetting sus = (SharedUserSetting) obj; 3515 return sus.name + ":" + sus.userId; 3516 } else if (obj instanceof PackageSetting) { 3517 final PackageSetting ps = (PackageSetting) obj; 3518 return ps.name; 3519 } 3520 } 3521 return null; 3522 } 3523 3524 @Override 3525 public int getUidForSharedUser(String sharedUserName) { 3526 if(sharedUserName == null) { 3527 return -1; 3528 } 3529 // reader 3530 synchronized (mPackages) { 3531 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3532 if (suid == null) { 3533 return -1; 3534 } 3535 return suid.userId; 3536 } 3537 } 3538 3539 @Override 3540 public int getFlagsForUid(int uid) { 3541 synchronized (mPackages) { 3542 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3543 if (obj instanceof SharedUserSetting) { 3544 final SharedUserSetting sus = (SharedUserSetting) obj; 3545 return sus.pkgFlags; 3546 } else if (obj instanceof PackageSetting) { 3547 final PackageSetting ps = (PackageSetting) obj; 3548 return ps.pkgFlags; 3549 } 3550 } 3551 return 0; 3552 } 3553 3554 @Override 3555 public int getPrivateFlagsForUid(int uid) { 3556 synchronized (mPackages) { 3557 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3558 if (obj instanceof SharedUserSetting) { 3559 final SharedUserSetting sus = (SharedUserSetting) obj; 3560 return sus.pkgPrivateFlags; 3561 } else if (obj instanceof PackageSetting) { 3562 final PackageSetting ps = (PackageSetting) obj; 3563 return ps.pkgPrivateFlags; 3564 } 3565 } 3566 return 0; 3567 } 3568 3569 @Override 3570 public boolean isUidPrivileged(int uid) { 3571 uid = UserHandle.getAppId(uid); 3572 // reader 3573 synchronized (mPackages) { 3574 Object obj = mSettings.getUserIdLPr(uid); 3575 if (obj instanceof SharedUserSetting) { 3576 final SharedUserSetting sus = (SharedUserSetting) obj; 3577 final Iterator<PackageSetting> it = sus.packages.iterator(); 3578 while (it.hasNext()) { 3579 if (it.next().isPrivileged()) { 3580 return true; 3581 } 3582 } 3583 } else if (obj instanceof PackageSetting) { 3584 final PackageSetting ps = (PackageSetting) obj; 3585 return ps.isPrivileged(); 3586 } 3587 } 3588 return false; 3589 } 3590 3591 @Override 3592 public String[] getAppOpPermissionPackages(String permissionName) { 3593 synchronized (mPackages) { 3594 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3595 if (pkgs == null) { 3596 return null; 3597 } 3598 return pkgs.toArray(new String[pkgs.size()]); 3599 } 3600 } 3601 3602 @Override 3603 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3604 int flags, int userId) { 3605 if (!sUserManager.exists(userId)) return null; 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3607 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3608 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3609 } 3610 3611 @Override 3612 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3613 IntentFilter filter, int match, ComponentName activity) { 3614 final int userId = UserHandle.getCallingUserId(); 3615 if (DEBUG_PREFERRED) { 3616 Log.v(TAG, "setLastChosenActivity intent=" + intent 3617 + " resolvedType=" + resolvedType 3618 + " flags=" + flags 3619 + " filter=" + filter 3620 + " match=" + match 3621 + " activity=" + activity); 3622 filter.dump(new PrintStreamPrinter(System.out), " "); 3623 } 3624 intent.setComponent(null); 3625 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3626 // Find any earlier preferred or last chosen entries and nuke them 3627 findPreferredActivity(intent, resolvedType, 3628 flags, query, 0, false, true, false, userId); 3629 // Add the new activity as the last chosen for this filter 3630 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3631 "Setting last chosen"); 3632 } 3633 3634 @Override 3635 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3636 final int userId = UserHandle.getCallingUserId(); 3637 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3638 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3639 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3640 false, false, false, userId); 3641 } 3642 3643 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3644 int flags, List<ResolveInfo> query, int userId) { 3645 if (query != null) { 3646 final int N = query.size(); 3647 if (N == 1) { 3648 return query.get(0); 3649 } else if (N > 1) { 3650 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3651 // If there is more than one activity with the same priority, 3652 // then let the user decide between them. 3653 ResolveInfo r0 = query.get(0); 3654 ResolveInfo r1 = query.get(1); 3655 if (DEBUG_INTENT_MATCHING || debug) { 3656 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3657 + r1.activityInfo.name + "=" + r1.priority); 3658 } 3659 // If the first activity has a higher priority, or a different 3660 // default, then it is always desireable to pick it. 3661 if (r0.priority != r1.priority 3662 || r0.preferredOrder != r1.preferredOrder 3663 || r0.isDefault != r1.isDefault) { 3664 return query.get(0); 3665 } 3666 // If we have saved a preference for a preferred activity for 3667 // this Intent, use that. 3668 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3669 flags, query, r0.priority, true, false, debug, userId); 3670 if (ri != null) { 3671 return ri; 3672 } 3673 if (userId != 0) { 3674 ri = new ResolveInfo(mResolveInfo); 3675 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3676 ri.activityInfo.applicationInfo = new ApplicationInfo( 3677 ri.activityInfo.applicationInfo); 3678 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3679 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3680 return ri; 3681 } 3682 return mResolveInfo; 3683 } 3684 } 3685 return null; 3686 } 3687 3688 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3689 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3690 final int N = query.size(); 3691 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3692 .get(userId); 3693 // Get the list of persistent preferred activities that handle the intent 3694 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3695 List<PersistentPreferredActivity> pprefs = ppir != null 3696 ? ppir.queryIntent(intent, resolvedType, 3697 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3698 : null; 3699 if (pprefs != null && pprefs.size() > 0) { 3700 final int M = pprefs.size(); 3701 for (int i=0; i<M; i++) { 3702 final PersistentPreferredActivity ppa = pprefs.get(i); 3703 if (DEBUG_PREFERRED || debug) { 3704 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3705 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3706 + "\n component=" + ppa.mComponent); 3707 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3708 } 3709 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3710 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3711 if (DEBUG_PREFERRED || debug) { 3712 Slog.v(TAG, "Found persistent preferred activity:"); 3713 if (ai != null) { 3714 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3715 } else { 3716 Slog.v(TAG, " null"); 3717 } 3718 } 3719 if (ai == null) { 3720 // This previously registered persistent preferred activity 3721 // component is no longer known. Ignore it and do NOT remove it. 3722 continue; 3723 } 3724 for (int j=0; j<N; j++) { 3725 final ResolveInfo ri = query.get(j); 3726 if (!ri.activityInfo.applicationInfo.packageName 3727 .equals(ai.applicationInfo.packageName)) { 3728 continue; 3729 } 3730 if (!ri.activityInfo.name.equals(ai.name)) { 3731 continue; 3732 } 3733 // Found a persistent preference that can handle the intent. 3734 if (DEBUG_PREFERRED || debug) { 3735 Slog.v(TAG, "Returning persistent preferred activity: " + 3736 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3737 } 3738 return ri; 3739 } 3740 } 3741 } 3742 return null; 3743 } 3744 3745 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3746 List<ResolveInfo> query, int priority, boolean always, 3747 boolean removeMatches, boolean debug, int userId) { 3748 if (!sUserManager.exists(userId)) return null; 3749 // writer 3750 synchronized (mPackages) { 3751 if (intent.getSelector() != null) { 3752 intent = intent.getSelector(); 3753 } 3754 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3755 3756 // Try to find a matching persistent preferred activity. 3757 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3758 debug, userId); 3759 3760 // If a persistent preferred activity matched, use it. 3761 if (pri != null) { 3762 return pri; 3763 } 3764 3765 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3766 // Get the list of preferred activities that handle the intent 3767 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3768 List<PreferredActivity> prefs = pir != null 3769 ? pir.queryIntent(intent, resolvedType, 3770 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3771 : null; 3772 if (prefs != null && prefs.size() > 0) { 3773 boolean changed = false; 3774 try { 3775 // First figure out how good the original match set is. 3776 // We will only allow preferred activities that came 3777 // from the same match quality. 3778 int match = 0; 3779 3780 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3781 3782 final int N = query.size(); 3783 for (int j=0; j<N; j++) { 3784 final ResolveInfo ri = query.get(j); 3785 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3786 + ": 0x" + Integer.toHexString(match)); 3787 if (ri.match > match) { 3788 match = ri.match; 3789 } 3790 } 3791 3792 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3793 + Integer.toHexString(match)); 3794 3795 match &= IntentFilter.MATCH_CATEGORY_MASK; 3796 final int M = prefs.size(); 3797 for (int i=0; i<M; i++) { 3798 final PreferredActivity pa = prefs.get(i); 3799 if (DEBUG_PREFERRED || debug) { 3800 Slog.v(TAG, "Checking PreferredActivity ds=" 3801 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3802 + "\n component=" + pa.mPref.mComponent); 3803 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3804 } 3805 if (pa.mPref.mMatch != match) { 3806 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3807 + Integer.toHexString(pa.mPref.mMatch)); 3808 continue; 3809 } 3810 // If it's not an "always" type preferred activity and that's what we're 3811 // looking for, skip it. 3812 if (always && !pa.mPref.mAlways) { 3813 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3814 continue; 3815 } 3816 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3817 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3818 if (DEBUG_PREFERRED || debug) { 3819 Slog.v(TAG, "Found preferred activity:"); 3820 if (ai != null) { 3821 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3822 } else { 3823 Slog.v(TAG, " null"); 3824 } 3825 } 3826 if (ai == null) { 3827 // This previously registered preferred activity 3828 // component is no longer known. Most likely an update 3829 // to the app was installed and in the new version this 3830 // component no longer exists. Clean it up by removing 3831 // it from the preferred activities list, and skip it. 3832 Slog.w(TAG, "Removing dangling preferred activity: " 3833 + pa.mPref.mComponent); 3834 pir.removeFilter(pa); 3835 changed = true; 3836 continue; 3837 } 3838 for (int j=0; j<N; j++) { 3839 final ResolveInfo ri = query.get(j); 3840 if (!ri.activityInfo.applicationInfo.packageName 3841 .equals(ai.applicationInfo.packageName)) { 3842 continue; 3843 } 3844 if (!ri.activityInfo.name.equals(ai.name)) { 3845 continue; 3846 } 3847 3848 if (removeMatches) { 3849 pir.removeFilter(pa); 3850 changed = true; 3851 if (DEBUG_PREFERRED) { 3852 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3853 } 3854 break; 3855 } 3856 3857 // Okay we found a previously set preferred or last chosen app. 3858 // If the result set is different from when this 3859 // was created, we need to clear it and re-ask the 3860 // user their preference, if we're looking for an "always" type entry. 3861 if (always && !pa.mPref.sameSet(query)) { 3862 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3863 + intent + " type " + resolvedType); 3864 if (DEBUG_PREFERRED) { 3865 Slog.v(TAG, "Removing preferred activity since set changed " 3866 + pa.mPref.mComponent); 3867 } 3868 pir.removeFilter(pa); 3869 // Re-add the filter as a "last chosen" entry (!always) 3870 PreferredActivity lastChosen = new PreferredActivity( 3871 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3872 pir.addFilter(lastChosen); 3873 changed = true; 3874 return null; 3875 } 3876 3877 // Yay! Either the set matched or we're looking for the last chosen 3878 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3879 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3880 return ri; 3881 } 3882 } 3883 } finally { 3884 if (changed) { 3885 if (DEBUG_PREFERRED) { 3886 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3887 } 3888 scheduleWritePackageRestrictionsLocked(userId); 3889 } 3890 } 3891 } 3892 } 3893 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3894 return null; 3895 } 3896 3897 /* 3898 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3899 */ 3900 @Override 3901 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3902 int targetUserId) { 3903 mContext.enforceCallingOrSelfPermission( 3904 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3905 List<CrossProfileIntentFilter> matches = 3906 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3907 if (matches != null) { 3908 int size = matches.size(); 3909 for (int i = 0; i < size; i++) { 3910 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3911 } 3912 } 3913 return false; 3914 } 3915 3916 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3917 String resolvedType, int userId) { 3918 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3919 if (resolver != null) { 3920 return resolver.queryIntent(intent, resolvedType, false, userId); 3921 } 3922 return null; 3923 } 3924 3925 @Override 3926 public List<ResolveInfo> queryIntentActivities(Intent intent, 3927 String resolvedType, int flags, int userId) { 3928 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3929 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3930 ComponentName comp = intent.getComponent(); 3931 if (comp == null) { 3932 if (intent.getSelector() != null) { 3933 intent = intent.getSelector(); 3934 comp = intent.getComponent(); 3935 } 3936 } 3937 3938 if (comp != null) { 3939 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3940 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3941 if (ai != null) { 3942 final ResolveInfo ri = new ResolveInfo(); 3943 ri.activityInfo = ai; 3944 list.add(ri); 3945 } 3946 return list; 3947 } 3948 3949 // reader 3950 synchronized (mPackages) { 3951 final String pkgName = intent.getPackage(); 3952 if (pkgName == null) { 3953 List<CrossProfileIntentFilter> matchingFilters = 3954 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3955 // Check for results that need to skip the current profile. 3956 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3957 resolvedType, flags, userId); 3958 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3959 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3960 result.add(resolveInfo); 3961 return filterIfNotPrimaryUser(result, userId); 3962 } 3963 3964 // Check for results in the current profile. 3965 List<ResolveInfo> result = mActivities.queryIntent( 3966 intent, resolvedType, flags, userId); 3967 3968 // Check for cross profile results. 3969 resolveInfo = queryCrossProfileIntents( 3970 matchingFilters, intent, resolvedType, flags, userId); 3971 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 3972 result.add(resolveInfo); 3973 Collections.sort(result, mResolvePrioritySorter); 3974 } 3975 result = filterIfNotPrimaryUser(result, userId); 3976 if (result.size() > 1 && hasWebURI(intent)) { 3977 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 3978 } 3979 return result; 3980 } 3981 final PackageParser.Package pkg = mPackages.get(pkgName); 3982 if (pkg != null) { 3983 return filterIfNotPrimaryUser( 3984 mActivities.queryIntentForPackage( 3985 intent, resolvedType, flags, pkg.activities, userId), 3986 userId); 3987 } 3988 return new ArrayList<ResolveInfo>(); 3989 } 3990 } 3991 3992 private boolean isUserEnabled(int userId) { 3993 long callingId = Binder.clearCallingIdentity(); 3994 try { 3995 UserInfo userInfo = sUserManager.getUserInfo(userId); 3996 return userInfo != null && userInfo.isEnabled(); 3997 } finally { 3998 Binder.restoreCallingIdentity(callingId); 3999 } 4000 } 4001 4002 /** 4003 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4004 * 4005 * @return filtered list 4006 */ 4007 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4008 if (userId == UserHandle.USER_OWNER) { 4009 return resolveInfos; 4010 } 4011 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4012 ResolveInfo info = resolveInfos.get(i); 4013 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4014 resolveInfos.remove(i); 4015 } 4016 } 4017 return resolveInfos; 4018 } 4019 4020 private static boolean hasWebURI(Intent intent) { 4021 if (intent.getData() == null) { 4022 return false; 4023 } 4024 final String scheme = intent.getScheme(); 4025 if (TextUtils.isEmpty(scheme)) { 4026 return false; 4027 } 4028 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4029 } 4030 4031 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4032 int flags, List<ResolveInfo> candidates) { 4033 if (DEBUG_PREFERRED) { 4034 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4035 candidates.size()); 4036 } 4037 4038 final int userId = UserHandle.getCallingUserId(); 4039 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4040 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4041 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4042 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4043 4044 synchronized (mPackages) { 4045 final int count = candidates.size(); 4046 // First, try to use the domain prefered App 4047 for (int n=0; n<count; n++) { 4048 ResolveInfo info = candidates.get(n); 4049 String packageName = info.activityInfo.packageName; 4050 PackageSetting ps = mSettings.mPackages.get(packageName); 4051 if (ps != null) { 4052 // Add to the special match all list (Browser use case) 4053 if (info.handleAllWebDataURI) { 4054 matchAllList.add(info); 4055 continue; 4056 } 4057 // Try to get the status from User settings first 4058 int status = getDomainVerificationStatusLPr(ps, userId); 4059 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4060 result.add(info); 4061 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4062 neverList.add(info); 4063 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4064 undefinedList.add(info); 4065 } 4066 } 4067 } 4068 // If there is nothing selected, add all candidates and remove the ones that the User 4069 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4070 // also remove any Browser Apps ones. 4071 // If there is still none after this pass, add all undefined one and Browser Apps and 4072 // let the User decide with the Disambiguation dialog if there are several ones. 4073 if (result.size() == 0) { 4074 result.addAll(candidates); 4075 } 4076 result.removeAll(neverList); 4077 result.removeAll(matchAllList); 4078 if (result.size() == 0) { 4079 result.addAll(undefinedList); 4080 if ((flags & MATCH_ALL) != 0) { 4081 result.addAll(matchAllList); 4082 } else { 4083 // Try to add the Default Browser if we can 4084 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4085 UserHandle.myUserId()); 4086 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4087 boolean defaultBrowserFound = false; 4088 final int browserCount = matchAllList.size(); 4089 for (int n=0; n<browserCount; n++) { 4090 ResolveInfo browser = matchAllList.get(n); 4091 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4092 result.add(browser); 4093 defaultBrowserFound = true; 4094 break; 4095 } 4096 } 4097 if (!defaultBrowserFound) { 4098 result.addAll(matchAllList); 4099 } 4100 } else { 4101 result.addAll(matchAllList); 4102 } 4103 } 4104 } 4105 } 4106 if (DEBUG_PREFERRED) { 4107 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4108 result.size()); 4109 } 4110 return result; 4111 } 4112 4113 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4114 int status = ps.getDomainVerificationStatusForUser(userId); 4115 // if none available, get the master status 4116 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4117 if (ps.getIntentFilterVerificationInfo() != null) { 4118 status = ps.getIntentFilterVerificationInfo().getStatus(); 4119 } 4120 } 4121 return status; 4122 } 4123 4124 private ResolveInfo querySkipCurrentProfileIntents( 4125 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4126 int flags, int sourceUserId) { 4127 if (matchingFilters != null) { 4128 int size = matchingFilters.size(); 4129 for (int i = 0; i < size; i ++) { 4130 CrossProfileIntentFilter filter = matchingFilters.get(i); 4131 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4132 // Checking if there are activities in the target user that can handle the 4133 // intent. 4134 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4135 flags, sourceUserId); 4136 if (resolveInfo != null) { 4137 return resolveInfo; 4138 } 4139 } 4140 } 4141 } 4142 return null; 4143 } 4144 4145 // Return matching ResolveInfo if any for skip current profile intent filters. 4146 private ResolveInfo queryCrossProfileIntents( 4147 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4148 int flags, int sourceUserId) { 4149 if (matchingFilters != null) { 4150 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4151 // match the same intent. For performance reasons, it is better not to 4152 // run queryIntent twice for the same userId 4153 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4154 int size = matchingFilters.size(); 4155 for (int i = 0; i < size; i++) { 4156 CrossProfileIntentFilter filter = matchingFilters.get(i); 4157 int targetUserId = filter.getTargetUserId(); 4158 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4159 && !alreadyTriedUserIds.get(targetUserId)) { 4160 // Checking if there are activities in the target user that can handle the 4161 // intent. 4162 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4163 flags, sourceUserId); 4164 if (resolveInfo != null) return resolveInfo; 4165 alreadyTriedUserIds.put(targetUserId, true); 4166 } 4167 } 4168 } 4169 return null; 4170 } 4171 4172 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4173 String resolvedType, int flags, int sourceUserId) { 4174 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4175 resolvedType, flags, filter.getTargetUserId()); 4176 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4177 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4178 } 4179 return null; 4180 } 4181 4182 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4183 int sourceUserId, int targetUserId) { 4184 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4185 String className; 4186 if (targetUserId == UserHandle.USER_OWNER) { 4187 className = FORWARD_INTENT_TO_USER_OWNER; 4188 } else { 4189 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4190 } 4191 ComponentName forwardingActivityComponentName = new ComponentName( 4192 mAndroidApplication.packageName, className); 4193 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4194 sourceUserId); 4195 if (targetUserId == UserHandle.USER_OWNER) { 4196 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4197 forwardingResolveInfo.noResourceId = true; 4198 } 4199 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4200 forwardingResolveInfo.priority = 0; 4201 forwardingResolveInfo.preferredOrder = 0; 4202 forwardingResolveInfo.match = 0; 4203 forwardingResolveInfo.isDefault = true; 4204 forwardingResolveInfo.filter = filter; 4205 forwardingResolveInfo.targetUserId = targetUserId; 4206 return forwardingResolveInfo; 4207 } 4208 4209 @Override 4210 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4211 Intent[] specifics, String[] specificTypes, Intent intent, 4212 String resolvedType, int flags, int userId) { 4213 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4215 false, "query intent activity options"); 4216 final String resultsAction = intent.getAction(); 4217 4218 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4219 | PackageManager.GET_RESOLVED_FILTER, userId); 4220 4221 if (DEBUG_INTENT_MATCHING) { 4222 Log.v(TAG, "Query " + intent + ": " + results); 4223 } 4224 4225 int specificsPos = 0; 4226 int N; 4227 4228 // todo: note that the algorithm used here is O(N^2). This 4229 // isn't a problem in our current environment, but if we start running 4230 // into situations where we have more than 5 or 10 matches then this 4231 // should probably be changed to something smarter... 4232 4233 // First we go through and resolve each of the specific items 4234 // that were supplied, taking care of removing any corresponding 4235 // duplicate items in the generic resolve list. 4236 if (specifics != null) { 4237 for (int i=0; i<specifics.length; i++) { 4238 final Intent sintent = specifics[i]; 4239 if (sintent == null) { 4240 continue; 4241 } 4242 4243 if (DEBUG_INTENT_MATCHING) { 4244 Log.v(TAG, "Specific #" + i + ": " + sintent); 4245 } 4246 4247 String action = sintent.getAction(); 4248 if (resultsAction != null && resultsAction.equals(action)) { 4249 // If this action was explicitly requested, then don't 4250 // remove things that have it. 4251 action = null; 4252 } 4253 4254 ResolveInfo ri = null; 4255 ActivityInfo ai = null; 4256 4257 ComponentName comp = sintent.getComponent(); 4258 if (comp == null) { 4259 ri = resolveIntent( 4260 sintent, 4261 specificTypes != null ? specificTypes[i] : null, 4262 flags, userId); 4263 if (ri == null) { 4264 continue; 4265 } 4266 if (ri == mResolveInfo) { 4267 // ACK! Must do something better with this. 4268 } 4269 ai = ri.activityInfo; 4270 comp = new ComponentName(ai.applicationInfo.packageName, 4271 ai.name); 4272 } else { 4273 ai = getActivityInfo(comp, flags, userId); 4274 if (ai == null) { 4275 continue; 4276 } 4277 } 4278 4279 // Look for any generic query activities that are duplicates 4280 // of this specific one, and remove them from the results. 4281 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4282 N = results.size(); 4283 int j; 4284 for (j=specificsPos; j<N; j++) { 4285 ResolveInfo sri = results.get(j); 4286 if ((sri.activityInfo.name.equals(comp.getClassName()) 4287 && sri.activityInfo.applicationInfo.packageName.equals( 4288 comp.getPackageName())) 4289 || (action != null && sri.filter.matchAction(action))) { 4290 results.remove(j); 4291 if (DEBUG_INTENT_MATCHING) Log.v( 4292 TAG, "Removing duplicate item from " + j 4293 + " due to specific " + specificsPos); 4294 if (ri == null) { 4295 ri = sri; 4296 } 4297 j--; 4298 N--; 4299 } 4300 } 4301 4302 // Add this specific item to its proper place. 4303 if (ri == null) { 4304 ri = new ResolveInfo(); 4305 ri.activityInfo = ai; 4306 } 4307 results.add(specificsPos, ri); 4308 ri.specificIndex = i; 4309 specificsPos++; 4310 } 4311 } 4312 4313 // Now we go through the remaining generic results and remove any 4314 // duplicate actions that are found here. 4315 N = results.size(); 4316 for (int i=specificsPos; i<N-1; i++) { 4317 final ResolveInfo rii = results.get(i); 4318 if (rii.filter == null) { 4319 continue; 4320 } 4321 4322 // Iterate over all of the actions of this result's intent 4323 // filter... typically this should be just one. 4324 final Iterator<String> it = rii.filter.actionsIterator(); 4325 if (it == null) { 4326 continue; 4327 } 4328 while (it.hasNext()) { 4329 final String action = it.next(); 4330 if (resultsAction != null && resultsAction.equals(action)) { 4331 // If this action was explicitly requested, then don't 4332 // remove things that have it. 4333 continue; 4334 } 4335 for (int j=i+1; j<N; j++) { 4336 final ResolveInfo rij = results.get(j); 4337 if (rij.filter != null && rij.filter.hasAction(action)) { 4338 results.remove(j); 4339 if (DEBUG_INTENT_MATCHING) Log.v( 4340 TAG, "Removing duplicate item from " + j 4341 + " due to action " + action + " at " + i); 4342 j--; 4343 N--; 4344 } 4345 } 4346 } 4347 4348 // If the caller didn't request filter information, drop it now 4349 // so we don't have to marshall/unmarshall it. 4350 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4351 rii.filter = null; 4352 } 4353 } 4354 4355 // Filter out the caller activity if so requested. 4356 if (caller != null) { 4357 N = results.size(); 4358 for (int i=0; i<N; i++) { 4359 ActivityInfo ainfo = results.get(i).activityInfo; 4360 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4361 && caller.getClassName().equals(ainfo.name)) { 4362 results.remove(i); 4363 break; 4364 } 4365 } 4366 } 4367 4368 // If the caller didn't request filter information, 4369 // drop them now so we don't have to 4370 // marshall/unmarshall it. 4371 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4372 N = results.size(); 4373 for (int i=0; i<N; i++) { 4374 results.get(i).filter = null; 4375 } 4376 } 4377 4378 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4379 return results; 4380 } 4381 4382 @Override 4383 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4384 int userId) { 4385 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4386 ComponentName comp = intent.getComponent(); 4387 if (comp == null) { 4388 if (intent.getSelector() != null) { 4389 intent = intent.getSelector(); 4390 comp = intent.getComponent(); 4391 } 4392 } 4393 if (comp != null) { 4394 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4395 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4396 if (ai != null) { 4397 ResolveInfo ri = new ResolveInfo(); 4398 ri.activityInfo = ai; 4399 list.add(ri); 4400 } 4401 return list; 4402 } 4403 4404 // reader 4405 synchronized (mPackages) { 4406 String pkgName = intent.getPackage(); 4407 if (pkgName == null) { 4408 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4409 } 4410 final PackageParser.Package pkg = mPackages.get(pkgName); 4411 if (pkg != null) { 4412 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4413 userId); 4414 } 4415 return null; 4416 } 4417 } 4418 4419 @Override 4420 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4421 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4422 if (!sUserManager.exists(userId)) return null; 4423 if (query != null) { 4424 if (query.size() >= 1) { 4425 // If there is more than one service with the same priority, 4426 // just arbitrarily pick the first one. 4427 return query.get(0); 4428 } 4429 } 4430 return null; 4431 } 4432 4433 @Override 4434 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4435 int userId) { 4436 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4437 ComponentName comp = intent.getComponent(); 4438 if (comp == null) { 4439 if (intent.getSelector() != null) { 4440 intent = intent.getSelector(); 4441 comp = intent.getComponent(); 4442 } 4443 } 4444 if (comp != null) { 4445 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4446 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4447 if (si != null) { 4448 final ResolveInfo ri = new ResolveInfo(); 4449 ri.serviceInfo = si; 4450 list.add(ri); 4451 } 4452 return list; 4453 } 4454 4455 // reader 4456 synchronized (mPackages) { 4457 String pkgName = intent.getPackage(); 4458 if (pkgName == null) { 4459 return mServices.queryIntent(intent, resolvedType, flags, userId); 4460 } 4461 final PackageParser.Package pkg = mPackages.get(pkgName); 4462 if (pkg != null) { 4463 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4464 userId); 4465 } 4466 return null; 4467 } 4468 } 4469 4470 @Override 4471 public List<ResolveInfo> queryIntentContentProviders( 4472 Intent intent, String resolvedType, int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4474 ComponentName comp = intent.getComponent(); 4475 if (comp == null) { 4476 if (intent.getSelector() != null) { 4477 intent = intent.getSelector(); 4478 comp = intent.getComponent(); 4479 } 4480 } 4481 if (comp != null) { 4482 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4483 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4484 if (pi != null) { 4485 final ResolveInfo ri = new ResolveInfo(); 4486 ri.providerInfo = pi; 4487 list.add(ri); 4488 } 4489 return list; 4490 } 4491 4492 // reader 4493 synchronized (mPackages) { 4494 String pkgName = intent.getPackage(); 4495 if (pkgName == null) { 4496 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4497 } 4498 final PackageParser.Package pkg = mPackages.get(pkgName); 4499 if (pkg != null) { 4500 return mProviders.queryIntentForPackage( 4501 intent, resolvedType, flags, pkg.providers, userId); 4502 } 4503 return null; 4504 } 4505 } 4506 4507 @Override 4508 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4509 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4510 4511 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4512 4513 // writer 4514 synchronized (mPackages) { 4515 ArrayList<PackageInfo> list; 4516 if (listUninstalled) { 4517 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4518 for (PackageSetting ps : mSettings.mPackages.values()) { 4519 PackageInfo pi; 4520 if (ps.pkg != null) { 4521 pi = generatePackageInfo(ps.pkg, flags, userId); 4522 } else { 4523 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4524 } 4525 if (pi != null) { 4526 list.add(pi); 4527 } 4528 } 4529 } else { 4530 list = new ArrayList<PackageInfo>(mPackages.size()); 4531 for (PackageParser.Package p : mPackages.values()) { 4532 PackageInfo pi = generatePackageInfo(p, flags, userId); 4533 if (pi != null) { 4534 list.add(pi); 4535 } 4536 } 4537 } 4538 4539 return new ParceledListSlice<PackageInfo>(list); 4540 } 4541 } 4542 4543 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4544 String[] permissions, boolean[] tmp, int flags, int userId) { 4545 int numMatch = 0; 4546 final PermissionsState permissionsState = ps.getPermissionsState(); 4547 for (int i=0; i<permissions.length; i++) { 4548 final String permission = permissions[i]; 4549 if (permissionsState.hasPermission(permission, userId)) { 4550 tmp[i] = true; 4551 numMatch++; 4552 } else { 4553 tmp[i] = false; 4554 } 4555 } 4556 if (numMatch == 0) { 4557 return; 4558 } 4559 PackageInfo pi; 4560 if (ps.pkg != null) { 4561 pi = generatePackageInfo(ps.pkg, flags, userId); 4562 } else { 4563 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4564 } 4565 // The above might return null in cases of uninstalled apps or install-state 4566 // skew across users/profiles. 4567 if (pi != null) { 4568 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4569 if (numMatch == permissions.length) { 4570 pi.requestedPermissions = permissions; 4571 } else { 4572 pi.requestedPermissions = new String[numMatch]; 4573 numMatch = 0; 4574 for (int i=0; i<permissions.length; i++) { 4575 if (tmp[i]) { 4576 pi.requestedPermissions[numMatch] = permissions[i]; 4577 numMatch++; 4578 } 4579 } 4580 } 4581 } 4582 list.add(pi); 4583 } 4584 } 4585 4586 @Override 4587 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4588 String[] permissions, int flags, int userId) { 4589 if (!sUserManager.exists(userId)) return null; 4590 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4591 4592 // writer 4593 synchronized (mPackages) { 4594 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4595 boolean[] tmpBools = new boolean[permissions.length]; 4596 if (listUninstalled) { 4597 for (PackageSetting ps : mSettings.mPackages.values()) { 4598 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4599 } 4600 } else { 4601 for (PackageParser.Package pkg : mPackages.values()) { 4602 PackageSetting ps = (PackageSetting)pkg.mExtras; 4603 if (ps != null) { 4604 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4605 userId); 4606 } 4607 } 4608 } 4609 4610 return new ParceledListSlice<PackageInfo>(list); 4611 } 4612 } 4613 4614 @Override 4615 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4616 if (!sUserManager.exists(userId)) return null; 4617 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4618 4619 // writer 4620 synchronized (mPackages) { 4621 ArrayList<ApplicationInfo> list; 4622 if (listUninstalled) { 4623 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4624 for (PackageSetting ps : mSettings.mPackages.values()) { 4625 ApplicationInfo ai; 4626 if (ps.pkg != null) { 4627 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4628 ps.readUserState(userId), userId); 4629 } else { 4630 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4631 } 4632 if (ai != null) { 4633 list.add(ai); 4634 } 4635 } 4636 } else { 4637 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4638 for (PackageParser.Package p : mPackages.values()) { 4639 if (p.mExtras != null) { 4640 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4641 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4642 if (ai != null) { 4643 list.add(ai); 4644 } 4645 } 4646 } 4647 } 4648 4649 return new ParceledListSlice<ApplicationInfo>(list); 4650 } 4651 } 4652 4653 public List<ApplicationInfo> getPersistentApplications(int flags) { 4654 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4655 4656 // reader 4657 synchronized (mPackages) { 4658 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4659 final int userId = UserHandle.getCallingUserId(); 4660 while (i.hasNext()) { 4661 final PackageParser.Package p = i.next(); 4662 if (p.applicationInfo != null 4663 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4664 && (!mSafeMode || isSystemApp(p))) { 4665 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4666 if (ps != null) { 4667 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4668 ps.readUserState(userId), userId); 4669 if (ai != null) { 4670 finalList.add(ai); 4671 } 4672 } 4673 } 4674 } 4675 } 4676 4677 return finalList; 4678 } 4679 4680 @Override 4681 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4682 if (!sUserManager.exists(userId)) return null; 4683 // reader 4684 synchronized (mPackages) { 4685 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4686 PackageSetting ps = provider != null 4687 ? mSettings.mPackages.get(provider.owner.packageName) 4688 : null; 4689 return ps != null 4690 && mSettings.isEnabledLPr(provider.info, flags, userId) 4691 && (!mSafeMode || (provider.info.applicationInfo.flags 4692 &ApplicationInfo.FLAG_SYSTEM) != 0) 4693 ? PackageParser.generateProviderInfo(provider, flags, 4694 ps.readUserState(userId), userId) 4695 : null; 4696 } 4697 } 4698 4699 /** 4700 * @deprecated 4701 */ 4702 @Deprecated 4703 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4704 // reader 4705 synchronized (mPackages) { 4706 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4707 .entrySet().iterator(); 4708 final int userId = UserHandle.getCallingUserId(); 4709 while (i.hasNext()) { 4710 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4711 PackageParser.Provider p = entry.getValue(); 4712 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4713 4714 if (ps != null && p.syncable 4715 && (!mSafeMode || (p.info.applicationInfo.flags 4716 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4717 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4718 ps.readUserState(userId), userId); 4719 if (info != null) { 4720 outNames.add(entry.getKey()); 4721 outInfo.add(info); 4722 } 4723 } 4724 } 4725 } 4726 } 4727 4728 @Override 4729 public List<ProviderInfo> queryContentProviders(String processName, 4730 int uid, int flags) { 4731 ArrayList<ProviderInfo> finalList = null; 4732 // reader 4733 synchronized (mPackages) { 4734 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4735 final int userId = processName != null ? 4736 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4737 while (i.hasNext()) { 4738 final PackageParser.Provider p = i.next(); 4739 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4740 if (ps != null && p.info.authority != null 4741 && (processName == null 4742 || (p.info.processName.equals(processName) 4743 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4744 && mSettings.isEnabledLPr(p.info, flags, userId) 4745 && (!mSafeMode 4746 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4747 if (finalList == null) { 4748 finalList = new ArrayList<ProviderInfo>(3); 4749 } 4750 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4751 ps.readUserState(userId), userId); 4752 if (info != null) { 4753 finalList.add(info); 4754 } 4755 } 4756 } 4757 } 4758 4759 if (finalList != null) { 4760 Collections.sort(finalList, mProviderInitOrderSorter); 4761 } 4762 4763 return finalList; 4764 } 4765 4766 @Override 4767 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4768 int flags) { 4769 // reader 4770 synchronized (mPackages) { 4771 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4772 return PackageParser.generateInstrumentationInfo(i, flags); 4773 } 4774 } 4775 4776 @Override 4777 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4778 int flags) { 4779 ArrayList<InstrumentationInfo> finalList = 4780 new ArrayList<InstrumentationInfo>(); 4781 4782 // reader 4783 synchronized (mPackages) { 4784 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4785 while (i.hasNext()) { 4786 final PackageParser.Instrumentation p = i.next(); 4787 if (targetPackage == null 4788 || targetPackage.equals(p.info.targetPackage)) { 4789 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4790 flags); 4791 if (ii != null) { 4792 finalList.add(ii); 4793 } 4794 } 4795 } 4796 } 4797 4798 return finalList; 4799 } 4800 4801 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4802 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4803 if (overlays == null) { 4804 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4805 return; 4806 } 4807 for (PackageParser.Package opkg : overlays.values()) { 4808 // Not much to do if idmap fails: we already logged the error 4809 // and we certainly don't want to abort installation of pkg simply 4810 // because an overlay didn't fit properly. For these reasons, 4811 // ignore the return value of createIdmapForPackagePairLI. 4812 createIdmapForPackagePairLI(pkg, opkg); 4813 } 4814 } 4815 4816 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4817 PackageParser.Package opkg) { 4818 if (!opkg.mTrustedOverlay) { 4819 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4820 opkg.baseCodePath + ": overlay not trusted"); 4821 return false; 4822 } 4823 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4824 if (overlaySet == null) { 4825 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4826 opkg.baseCodePath + " but target package has no known overlays"); 4827 return false; 4828 } 4829 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4830 // TODO: generate idmap for split APKs 4831 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4832 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4833 + opkg.baseCodePath); 4834 return false; 4835 } 4836 PackageParser.Package[] overlayArray = 4837 overlaySet.values().toArray(new PackageParser.Package[0]); 4838 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4839 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4840 return p1.mOverlayPriority - p2.mOverlayPriority; 4841 } 4842 }; 4843 Arrays.sort(overlayArray, cmp); 4844 4845 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4846 int i = 0; 4847 for (PackageParser.Package p : overlayArray) { 4848 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4849 } 4850 return true; 4851 } 4852 4853 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4854 final File[] files = dir.listFiles(); 4855 if (ArrayUtils.isEmpty(files)) { 4856 Log.d(TAG, "No files in app dir " + dir); 4857 return; 4858 } 4859 4860 if (DEBUG_PACKAGE_SCANNING) { 4861 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4862 + " flags=0x" + Integer.toHexString(parseFlags)); 4863 } 4864 4865 for (File file : files) { 4866 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4867 && !PackageInstallerService.isStageName(file.getName()); 4868 if (!isPackage) { 4869 // Ignore entries which are not packages 4870 continue; 4871 } 4872 try { 4873 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4874 scanFlags, currentTime, null); 4875 } catch (PackageManagerException e) { 4876 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4877 4878 // Delete invalid userdata apps 4879 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4880 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4881 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4882 if (file.isDirectory()) { 4883 mInstaller.rmPackageDir(file.getAbsolutePath()); 4884 } else { 4885 file.delete(); 4886 } 4887 } 4888 } 4889 } 4890 } 4891 4892 private static File getSettingsProblemFile() { 4893 File dataDir = Environment.getDataDirectory(); 4894 File systemDir = new File(dataDir, "system"); 4895 File fname = new File(systemDir, "uiderrors.txt"); 4896 return fname; 4897 } 4898 4899 static void reportSettingsProblem(int priority, String msg) { 4900 logCriticalInfo(priority, msg); 4901 } 4902 4903 static void logCriticalInfo(int priority, String msg) { 4904 Slog.println(priority, TAG, msg); 4905 EventLogTags.writePmCriticalInfo(msg); 4906 try { 4907 File fname = getSettingsProblemFile(); 4908 FileOutputStream out = new FileOutputStream(fname, true); 4909 PrintWriter pw = new FastPrintWriter(out); 4910 SimpleDateFormat formatter = new SimpleDateFormat(); 4911 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4912 pw.println(dateString + ": " + msg); 4913 pw.close(); 4914 FileUtils.setPermissions( 4915 fname.toString(), 4916 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4917 -1, -1); 4918 } catch (java.io.IOException e) { 4919 } 4920 } 4921 4922 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4923 PackageParser.Package pkg, File srcFile, int parseFlags) 4924 throws PackageManagerException { 4925 if (ps != null 4926 && ps.codePath.equals(srcFile) 4927 && ps.timeStamp == srcFile.lastModified() 4928 && !isCompatSignatureUpdateNeeded(pkg) 4929 && !isRecoverSignatureUpdateNeeded(pkg)) { 4930 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4931 if (ps.signatures.mSignatures != null 4932 && ps.signatures.mSignatures.length != 0 4933 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4934 // Optimization: reuse the existing cached certificates 4935 // if the package appears to be unchanged. 4936 pkg.mSignatures = ps.signatures.mSignatures; 4937 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4938 synchronized (mPackages) { 4939 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4940 } 4941 return; 4942 } 4943 4944 Slog.w(TAG, "PackageSetting for " + ps.name 4945 + " is missing signatures. Collecting certs again to recover them."); 4946 } else { 4947 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4948 } 4949 4950 try { 4951 pp.collectCertificates(pkg, parseFlags); 4952 pp.collectManifestDigest(pkg); 4953 } catch (PackageParserException e) { 4954 throw PackageManagerException.from(e); 4955 } 4956 } 4957 4958 /* 4959 * Scan a package and return the newly parsed package. 4960 * Returns null in case of errors and the error code is stored in mLastScanError 4961 */ 4962 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4963 long currentTime, UserHandle user) throws PackageManagerException { 4964 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4965 parseFlags |= mDefParseFlags; 4966 PackageParser pp = new PackageParser(); 4967 pp.setSeparateProcesses(mSeparateProcesses); 4968 pp.setOnlyCoreApps(mOnlyCore); 4969 pp.setDisplayMetrics(mMetrics); 4970 4971 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4972 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4973 } 4974 4975 final PackageParser.Package pkg; 4976 try { 4977 pkg = pp.parsePackage(scanFile, parseFlags); 4978 } catch (PackageParserException e) { 4979 throw PackageManagerException.from(e); 4980 } 4981 4982 PackageSetting ps = null; 4983 PackageSetting updatedPkg; 4984 // reader 4985 synchronized (mPackages) { 4986 // Look to see if we already know about this package. 4987 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4988 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4989 // This package has been renamed to its original name. Let's 4990 // use that. 4991 ps = mSettings.peekPackageLPr(oldName); 4992 } 4993 // If there was no original package, see one for the real package name. 4994 if (ps == null) { 4995 ps = mSettings.peekPackageLPr(pkg.packageName); 4996 } 4997 // Check to see if this package could be hiding/updating a system 4998 // package. Must look for it either under the original or real 4999 // package name depending on our state. 5000 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5001 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5002 } 5003 boolean updatedPkgBetter = false; 5004 // First check if this is a system package that may involve an update 5005 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5006 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5007 // it needs to drop FLAG_PRIVILEGED. 5008 if (locationIsPrivileged(scanFile)) { 5009 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5010 } else { 5011 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5012 } 5013 5014 if (ps != null && !ps.codePath.equals(scanFile)) { 5015 // The path has changed from what was last scanned... check the 5016 // version of the new path against what we have stored to determine 5017 // what to do. 5018 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5019 if (pkg.mVersionCode <= ps.versionCode) { 5020 // The system package has been updated and the code path does not match 5021 // Ignore entry. Skip it. 5022 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5023 + " ignored: updated version " + ps.versionCode 5024 + " better than this " + pkg.mVersionCode); 5025 if (!updatedPkg.codePath.equals(scanFile)) { 5026 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5027 + ps.name + " changing from " + updatedPkg.codePathString 5028 + " to " + scanFile); 5029 updatedPkg.codePath = scanFile; 5030 updatedPkg.codePathString = scanFile.toString(); 5031 updatedPkg.resourcePath = scanFile; 5032 updatedPkg.resourcePathString = scanFile.toString(); 5033 } 5034 updatedPkg.pkg = pkg; 5035 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5036 } else { 5037 // The current app on the system partition is better than 5038 // what we have updated to on the data partition; switch 5039 // back to the system partition version. 5040 // At this point, its safely assumed that package installation for 5041 // apps in system partition will go through. If not there won't be a working 5042 // version of the app 5043 // writer 5044 synchronized (mPackages) { 5045 // Just remove the loaded entries from package lists. 5046 mPackages.remove(ps.name); 5047 } 5048 5049 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5050 + " reverting from " + ps.codePathString 5051 + ": new version " + pkg.mVersionCode 5052 + " better than installed " + ps.versionCode); 5053 5054 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5055 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5056 synchronized (mInstallLock) { 5057 args.cleanUpResourcesLI(); 5058 } 5059 synchronized (mPackages) { 5060 mSettings.enableSystemPackageLPw(ps.name); 5061 } 5062 updatedPkgBetter = true; 5063 } 5064 } 5065 } 5066 5067 if (updatedPkg != null) { 5068 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5069 // initially 5070 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5071 5072 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5073 // flag set initially 5074 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5075 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5076 } 5077 } 5078 5079 // Verify certificates against what was last scanned 5080 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5081 5082 /* 5083 * A new system app appeared, but we already had a non-system one of the 5084 * same name installed earlier. 5085 */ 5086 boolean shouldHideSystemApp = false; 5087 if (updatedPkg == null && ps != null 5088 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5089 /* 5090 * Check to make sure the signatures match first. If they don't, 5091 * wipe the installed application and its data. 5092 */ 5093 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5094 != PackageManager.SIGNATURE_MATCH) { 5095 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5096 + " signatures don't match existing userdata copy; removing"); 5097 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5098 ps = null; 5099 } else { 5100 /* 5101 * If the newly-added system app is an older version than the 5102 * already installed version, hide it. It will be scanned later 5103 * and re-added like an update. 5104 */ 5105 if (pkg.mVersionCode <= ps.versionCode) { 5106 shouldHideSystemApp = true; 5107 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5108 + " but new version " + pkg.mVersionCode + " better than installed " 5109 + ps.versionCode + "; hiding system"); 5110 } else { 5111 /* 5112 * The newly found system app is a newer version that the 5113 * one previously installed. Simply remove the 5114 * already-installed application and replace it with our own 5115 * while keeping the application data. 5116 */ 5117 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5118 + " reverting from " + ps.codePathString + ": new version " 5119 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5120 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5121 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5122 synchronized (mInstallLock) { 5123 args.cleanUpResourcesLI(); 5124 } 5125 } 5126 } 5127 } 5128 5129 // The apk is forward locked (not public) if its code and resources 5130 // are kept in different files. (except for app in either system or 5131 // vendor path). 5132 // TODO grab this value from PackageSettings 5133 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5134 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5135 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5136 } 5137 } 5138 5139 // TODO: extend to support forward-locked splits 5140 String resourcePath = null; 5141 String baseResourcePath = null; 5142 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5143 if (ps != null && ps.resourcePathString != null) { 5144 resourcePath = ps.resourcePathString; 5145 baseResourcePath = ps.resourcePathString; 5146 } else { 5147 // Should not happen at all. Just log an error. 5148 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5149 } 5150 } else { 5151 resourcePath = pkg.codePath; 5152 baseResourcePath = pkg.baseCodePath; 5153 } 5154 5155 // Set application objects path explicitly. 5156 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5157 pkg.applicationInfo.setCodePath(pkg.codePath); 5158 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5159 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5160 pkg.applicationInfo.setResourcePath(resourcePath); 5161 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5162 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5163 5164 // Note that we invoke the following method only if we are about to unpack an application 5165 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5166 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5167 5168 /* 5169 * If the system app should be overridden by a previously installed 5170 * data, hide the system app now and let the /data/app scan pick it up 5171 * again. 5172 */ 5173 if (shouldHideSystemApp) { 5174 synchronized (mPackages) { 5175 /* 5176 * We have to grant systems permissions before we hide, because 5177 * grantPermissions will assume the package update is trying to 5178 * expand its permissions. 5179 */ 5180 grantPermissionsLPw(pkg, true, pkg.packageName); 5181 mSettings.disableSystemPackageLPw(pkg.packageName); 5182 } 5183 } 5184 5185 return scannedPkg; 5186 } 5187 5188 private static String fixProcessName(String defProcessName, 5189 String processName, int uid) { 5190 if (processName == null) { 5191 return defProcessName; 5192 } 5193 return processName; 5194 } 5195 5196 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5197 throws PackageManagerException { 5198 if (pkgSetting.signatures.mSignatures != null) { 5199 // Already existing package. Make sure signatures match 5200 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5201 == PackageManager.SIGNATURE_MATCH; 5202 if (!match) { 5203 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5204 == PackageManager.SIGNATURE_MATCH; 5205 } 5206 if (!match) { 5207 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5208 == PackageManager.SIGNATURE_MATCH; 5209 } 5210 if (!match) { 5211 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5212 + pkg.packageName + " signatures do not match the " 5213 + "previously installed version; ignoring!"); 5214 } 5215 } 5216 5217 // Check for shared user signatures 5218 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5219 // Already existing package. Make sure signatures match 5220 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5221 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5222 if (!match) { 5223 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5224 == PackageManager.SIGNATURE_MATCH; 5225 } 5226 if (!match) { 5227 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5228 == PackageManager.SIGNATURE_MATCH; 5229 } 5230 if (!match) { 5231 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5232 "Package " + pkg.packageName 5233 + " has no signatures that match those in shared user " 5234 + pkgSetting.sharedUser.name + "; ignoring!"); 5235 } 5236 } 5237 } 5238 5239 /** 5240 * Enforces that only the system UID or root's UID can call a method exposed 5241 * via Binder. 5242 * 5243 * @param message used as message if SecurityException is thrown 5244 * @throws SecurityException if the caller is not system or root 5245 */ 5246 private static final void enforceSystemOrRoot(String message) { 5247 final int uid = Binder.getCallingUid(); 5248 if (uid != Process.SYSTEM_UID && uid != 0) { 5249 throw new SecurityException(message); 5250 } 5251 } 5252 5253 @Override 5254 public void performBootDexOpt() { 5255 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5256 5257 // Before everything else, see whether we need to fstrim. 5258 try { 5259 IMountService ms = PackageHelper.getMountService(); 5260 if (ms != null) { 5261 final boolean isUpgrade = isUpgrade(); 5262 boolean doTrim = isUpgrade; 5263 if (doTrim) { 5264 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5265 } else { 5266 final long interval = android.provider.Settings.Global.getLong( 5267 mContext.getContentResolver(), 5268 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5269 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5270 if (interval > 0) { 5271 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5272 if (timeSinceLast > interval) { 5273 doTrim = true; 5274 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5275 + "; running immediately"); 5276 } 5277 } 5278 } 5279 if (doTrim) { 5280 if (!isFirstBoot()) { 5281 try { 5282 ActivityManagerNative.getDefault().showBootMessage( 5283 mContext.getResources().getString( 5284 R.string.android_upgrading_fstrim), true); 5285 } catch (RemoteException e) { 5286 } 5287 } 5288 ms.runMaintenance(); 5289 } 5290 } else { 5291 Slog.e(TAG, "Mount service unavailable!"); 5292 } 5293 } catch (RemoteException e) { 5294 // Can't happen; MountService is local 5295 } 5296 5297 final ArraySet<PackageParser.Package> pkgs; 5298 synchronized (mPackages) { 5299 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5300 } 5301 5302 if (pkgs != null) { 5303 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5304 // in case the device runs out of space. 5305 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5306 // Give priority to core apps. 5307 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5308 PackageParser.Package pkg = it.next(); 5309 if (pkg.coreApp) { 5310 if (DEBUG_DEXOPT) { 5311 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5312 } 5313 sortedPkgs.add(pkg); 5314 it.remove(); 5315 } 5316 } 5317 // Give priority to system apps that listen for pre boot complete. 5318 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5319 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5320 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5321 PackageParser.Package pkg = it.next(); 5322 if (pkgNames.contains(pkg.packageName)) { 5323 if (DEBUG_DEXOPT) { 5324 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5325 } 5326 sortedPkgs.add(pkg); 5327 it.remove(); 5328 } 5329 } 5330 // Give priority to system apps. 5331 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5332 PackageParser.Package pkg = it.next(); 5333 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5334 if (DEBUG_DEXOPT) { 5335 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5336 } 5337 sortedPkgs.add(pkg); 5338 it.remove(); 5339 } 5340 } 5341 // Give priority to updated system apps. 5342 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5343 PackageParser.Package pkg = it.next(); 5344 if (pkg.isUpdatedSystemApp()) { 5345 if (DEBUG_DEXOPT) { 5346 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5347 } 5348 sortedPkgs.add(pkg); 5349 it.remove(); 5350 } 5351 } 5352 // Give priority to apps that listen for boot complete. 5353 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5354 pkgNames = getPackageNamesForIntent(intent); 5355 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5356 PackageParser.Package pkg = it.next(); 5357 if (pkgNames.contains(pkg.packageName)) { 5358 if (DEBUG_DEXOPT) { 5359 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5360 } 5361 sortedPkgs.add(pkg); 5362 it.remove(); 5363 } 5364 } 5365 // Filter out packages that aren't recently used. 5366 filterRecentlyUsedApps(pkgs); 5367 // Add all remaining apps. 5368 for (PackageParser.Package pkg : pkgs) { 5369 if (DEBUG_DEXOPT) { 5370 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5371 } 5372 sortedPkgs.add(pkg); 5373 } 5374 5375 // If we want to be lazy, filter everything that wasn't recently used. 5376 if (mLazyDexOpt) { 5377 filterRecentlyUsedApps(sortedPkgs); 5378 } 5379 5380 int i = 0; 5381 int total = sortedPkgs.size(); 5382 File dataDir = Environment.getDataDirectory(); 5383 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5384 if (lowThreshold == 0) { 5385 throw new IllegalStateException("Invalid low memory threshold"); 5386 } 5387 for (PackageParser.Package pkg : sortedPkgs) { 5388 long usableSpace = dataDir.getUsableSpace(); 5389 if (usableSpace < lowThreshold) { 5390 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5391 break; 5392 } 5393 performBootDexOpt(pkg, ++i, total); 5394 } 5395 } 5396 } 5397 5398 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5399 // Filter out packages that aren't recently used. 5400 // 5401 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5402 // should do a full dexopt. 5403 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5404 int total = pkgs.size(); 5405 int skipped = 0; 5406 long now = System.currentTimeMillis(); 5407 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5408 PackageParser.Package pkg = i.next(); 5409 long then = pkg.mLastPackageUsageTimeInMills; 5410 if (then + mDexOptLRUThresholdInMills < now) { 5411 if (DEBUG_DEXOPT) { 5412 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5413 ((then == 0) ? "never" : new Date(then))); 5414 } 5415 i.remove(); 5416 skipped++; 5417 } 5418 } 5419 if (DEBUG_DEXOPT) { 5420 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5421 } 5422 } 5423 } 5424 5425 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5426 List<ResolveInfo> ris = null; 5427 try { 5428 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5429 intent, null, 0, UserHandle.USER_OWNER); 5430 } catch (RemoteException e) { 5431 } 5432 ArraySet<String> pkgNames = new ArraySet<String>(); 5433 if (ris != null) { 5434 for (ResolveInfo ri : ris) { 5435 pkgNames.add(ri.activityInfo.packageName); 5436 } 5437 } 5438 return pkgNames; 5439 } 5440 5441 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5442 if (DEBUG_DEXOPT) { 5443 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5444 } 5445 if (!isFirstBoot()) { 5446 try { 5447 ActivityManagerNative.getDefault().showBootMessage( 5448 mContext.getResources().getString(R.string.android_upgrading_apk, 5449 curr, total), true); 5450 } catch (RemoteException e) { 5451 } 5452 } 5453 PackageParser.Package p = pkg; 5454 synchronized (mInstallLock) { 5455 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5456 false /* force dex */, false /* defer */, true /* include dependencies */); 5457 } 5458 } 5459 5460 @Override 5461 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5462 return performDexOpt(packageName, instructionSet, false); 5463 } 5464 5465 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5466 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5467 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5468 if (!dexopt && !updateUsage) { 5469 // We aren't going to dexopt or update usage, so bail early. 5470 return false; 5471 } 5472 PackageParser.Package p; 5473 final String targetInstructionSet; 5474 synchronized (mPackages) { 5475 p = mPackages.get(packageName); 5476 if (p == null) { 5477 return false; 5478 } 5479 if (updateUsage) { 5480 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5481 } 5482 mPackageUsage.write(false); 5483 if (!dexopt) { 5484 // We aren't going to dexopt, so bail early. 5485 return false; 5486 } 5487 5488 targetInstructionSet = instructionSet != null ? instructionSet : 5489 getPrimaryInstructionSet(p.applicationInfo); 5490 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5491 return false; 5492 } 5493 } 5494 5495 synchronized (mInstallLock) { 5496 final String[] instructionSets = new String[] { targetInstructionSet }; 5497 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5498 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5499 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5500 } 5501 } 5502 5503 public ArraySet<String> getPackagesThatNeedDexOpt() { 5504 ArraySet<String> pkgs = null; 5505 synchronized (mPackages) { 5506 for (PackageParser.Package p : mPackages.values()) { 5507 if (DEBUG_DEXOPT) { 5508 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5509 } 5510 if (!p.mDexOptPerformed.isEmpty()) { 5511 continue; 5512 } 5513 if (pkgs == null) { 5514 pkgs = new ArraySet<String>(); 5515 } 5516 pkgs.add(p.packageName); 5517 } 5518 } 5519 return pkgs; 5520 } 5521 5522 public void shutdown() { 5523 mPackageUsage.write(true); 5524 } 5525 5526 @Override 5527 public void forceDexOpt(String packageName) { 5528 enforceSystemOrRoot("forceDexOpt"); 5529 5530 PackageParser.Package pkg; 5531 synchronized (mPackages) { 5532 pkg = mPackages.get(packageName); 5533 if (pkg == null) { 5534 throw new IllegalArgumentException("Missing package: " + packageName); 5535 } 5536 } 5537 5538 synchronized (mInstallLock) { 5539 final String[] instructionSets = new String[] { 5540 getPrimaryInstructionSet(pkg.applicationInfo) }; 5541 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5542 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5543 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5544 throw new IllegalStateException("Failed to dexopt: " + res); 5545 } 5546 } 5547 } 5548 5549 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5550 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5551 Slog.w(TAG, "Unable to update from " + oldPkg.name 5552 + " to " + newPkg.packageName 5553 + ": old package not in system partition"); 5554 return false; 5555 } else if (mPackages.get(oldPkg.name) != null) { 5556 Slog.w(TAG, "Unable to update from " + oldPkg.name 5557 + " to " + newPkg.packageName 5558 + ": old package still exists"); 5559 return false; 5560 } 5561 return true; 5562 } 5563 5564 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5565 int[] users = sUserManager.getUserIds(); 5566 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5567 if (res < 0) { 5568 return res; 5569 } 5570 for (int user : users) { 5571 if (user != 0) { 5572 res = mInstaller.createUserData(volumeUuid, packageName, 5573 UserHandle.getUid(user, uid), user, seinfo); 5574 if (res < 0) { 5575 return res; 5576 } 5577 } 5578 } 5579 return res; 5580 } 5581 5582 private int removeDataDirsLI(String volumeUuid, String packageName) { 5583 int[] users = sUserManager.getUserIds(); 5584 int res = 0; 5585 for (int user : users) { 5586 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5587 if (resInner < 0) { 5588 res = resInner; 5589 } 5590 } 5591 5592 return res; 5593 } 5594 5595 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5596 int[] users = sUserManager.getUserIds(); 5597 int res = 0; 5598 for (int user : users) { 5599 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5600 if (resInner < 0) { 5601 res = resInner; 5602 } 5603 } 5604 return res; 5605 } 5606 5607 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5608 PackageParser.Package changingLib) { 5609 if (file.path != null) { 5610 usesLibraryFiles.add(file.path); 5611 return; 5612 } 5613 PackageParser.Package p = mPackages.get(file.apk); 5614 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5615 // If we are doing this while in the middle of updating a library apk, 5616 // then we need to make sure to use that new apk for determining the 5617 // dependencies here. (We haven't yet finished committing the new apk 5618 // to the package manager state.) 5619 if (p == null || p.packageName.equals(changingLib.packageName)) { 5620 p = changingLib; 5621 } 5622 } 5623 if (p != null) { 5624 usesLibraryFiles.addAll(p.getAllCodePaths()); 5625 } 5626 } 5627 5628 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5629 PackageParser.Package changingLib) throws PackageManagerException { 5630 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5631 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5632 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5633 for (int i=0; i<N; i++) { 5634 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5635 if (file == null) { 5636 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5637 "Package " + pkg.packageName + " requires unavailable shared library " 5638 + pkg.usesLibraries.get(i) + "; failing!"); 5639 } 5640 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5641 } 5642 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5643 for (int i=0; i<N; i++) { 5644 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5645 if (file == null) { 5646 Slog.w(TAG, "Package " + pkg.packageName 5647 + " desires unavailable shared library " 5648 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5649 } else { 5650 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5651 } 5652 } 5653 N = usesLibraryFiles.size(); 5654 if (N > 0) { 5655 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5656 } else { 5657 pkg.usesLibraryFiles = null; 5658 } 5659 } 5660 } 5661 5662 private static boolean hasString(List<String> list, List<String> which) { 5663 if (list == null) { 5664 return false; 5665 } 5666 for (int i=list.size()-1; i>=0; i--) { 5667 for (int j=which.size()-1; j>=0; j--) { 5668 if (which.get(j).equals(list.get(i))) { 5669 return true; 5670 } 5671 } 5672 } 5673 return false; 5674 } 5675 5676 private void updateAllSharedLibrariesLPw() { 5677 for (PackageParser.Package pkg : mPackages.values()) { 5678 try { 5679 updateSharedLibrariesLPw(pkg, null); 5680 } catch (PackageManagerException e) { 5681 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5682 } 5683 } 5684 } 5685 5686 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5687 PackageParser.Package changingPkg) { 5688 ArrayList<PackageParser.Package> res = null; 5689 for (PackageParser.Package pkg : mPackages.values()) { 5690 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5691 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5692 if (res == null) { 5693 res = new ArrayList<PackageParser.Package>(); 5694 } 5695 res.add(pkg); 5696 try { 5697 updateSharedLibrariesLPw(pkg, changingPkg); 5698 } catch (PackageManagerException e) { 5699 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5700 } 5701 } 5702 } 5703 return res; 5704 } 5705 5706 /** 5707 * Derive the value of the {@code cpuAbiOverride} based on the provided 5708 * value and an optional stored value from the package settings. 5709 */ 5710 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5711 String cpuAbiOverride = null; 5712 5713 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5714 cpuAbiOverride = null; 5715 } else if (abiOverride != null) { 5716 cpuAbiOverride = abiOverride; 5717 } else if (settings != null) { 5718 cpuAbiOverride = settings.cpuAbiOverrideString; 5719 } 5720 5721 return cpuAbiOverride; 5722 } 5723 5724 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5725 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5726 boolean success = false; 5727 try { 5728 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5729 currentTime, user); 5730 success = true; 5731 return res; 5732 } finally { 5733 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5734 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5735 } 5736 } 5737 } 5738 5739 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5740 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5741 final File scanFile = new File(pkg.codePath); 5742 if (pkg.applicationInfo.getCodePath() == null || 5743 pkg.applicationInfo.getResourcePath() == null) { 5744 // Bail out. The resource and code paths haven't been set. 5745 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5746 "Code and resource paths haven't been set correctly"); 5747 } 5748 5749 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5750 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5751 } else { 5752 // Only allow system apps to be flagged as core apps. 5753 pkg.coreApp = false; 5754 } 5755 5756 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5757 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5758 } 5759 5760 if (mCustomResolverComponentName != null && 5761 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5762 setUpCustomResolverActivity(pkg); 5763 } 5764 5765 if (pkg.packageName.equals("android")) { 5766 synchronized (mPackages) { 5767 if (mAndroidApplication != null) { 5768 Slog.w(TAG, "*************************************************"); 5769 Slog.w(TAG, "Core android package being redefined. Skipping."); 5770 Slog.w(TAG, " file=" + scanFile); 5771 Slog.w(TAG, "*************************************************"); 5772 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5773 "Core android package being redefined. Skipping."); 5774 } 5775 5776 // Set up information for our fall-back user intent resolution activity. 5777 mPlatformPackage = pkg; 5778 pkg.mVersionCode = mSdkVersion; 5779 mAndroidApplication = pkg.applicationInfo; 5780 5781 if (!mResolverReplaced) { 5782 mResolveActivity.applicationInfo = mAndroidApplication; 5783 mResolveActivity.name = ResolverActivity.class.getName(); 5784 mResolveActivity.packageName = mAndroidApplication.packageName; 5785 mResolveActivity.processName = "system:ui"; 5786 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5787 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5788 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5789 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5790 mResolveActivity.exported = true; 5791 mResolveActivity.enabled = true; 5792 mResolveInfo.activityInfo = mResolveActivity; 5793 mResolveInfo.priority = 0; 5794 mResolveInfo.preferredOrder = 0; 5795 mResolveInfo.match = 0; 5796 mResolveComponentName = new ComponentName( 5797 mAndroidApplication.packageName, mResolveActivity.name); 5798 } 5799 } 5800 } 5801 5802 if (DEBUG_PACKAGE_SCANNING) { 5803 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5804 Log.d(TAG, "Scanning package " + pkg.packageName); 5805 } 5806 5807 if (mPackages.containsKey(pkg.packageName) 5808 || mSharedLibraries.containsKey(pkg.packageName)) { 5809 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5810 "Application package " + pkg.packageName 5811 + " already installed. Skipping duplicate."); 5812 } 5813 5814 // If we're only installing presumed-existing packages, require that the 5815 // scanned APK is both already known and at the path previously established 5816 // for it. Previously unknown packages we pick up normally, but if we have an 5817 // a priori expectation about this package's install presence, enforce it. 5818 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5819 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5820 if (known != null) { 5821 if (DEBUG_PACKAGE_SCANNING) { 5822 Log.d(TAG, "Examining " + pkg.codePath 5823 + " and requiring known paths " + known.codePathString 5824 + " & " + known.resourcePathString); 5825 } 5826 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5827 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5828 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5829 "Application package " + pkg.packageName 5830 + " found at " + pkg.applicationInfo.getCodePath() 5831 + " but expected at " + known.codePathString + "; ignoring."); 5832 } 5833 } 5834 } 5835 5836 // Initialize package source and resource directories 5837 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5838 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5839 5840 SharedUserSetting suid = null; 5841 PackageSetting pkgSetting = null; 5842 5843 if (!isSystemApp(pkg)) { 5844 // Only system apps can use these features. 5845 pkg.mOriginalPackages = null; 5846 pkg.mRealPackage = null; 5847 pkg.mAdoptPermissions = null; 5848 } 5849 5850 // writer 5851 synchronized (mPackages) { 5852 if (pkg.mSharedUserId != null) { 5853 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5854 if (suid == null) { 5855 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5856 "Creating application package " + pkg.packageName 5857 + " for shared user failed"); 5858 } 5859 if (DEBUG_PACKAGE_SCANNING) { 5860 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5861 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5862 + "): packages=" + suid.packages); 5863 } 5864 } 5865 5866 // Check if we are renaming from an original package name. 5867 PackageSetting origPackage = null; 5868 String realName = null; 5869 if (pkg.mOriginalPackages != null) { 5870 // This package may need to be renamed to a previously 5871 // installed name. Let's check on that... 5872 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5873 if (pkg.mOriginalPackages.contains(renamed)) { 5874 // This package had originally been installed as the 5875 // original name, and we have already taken care of 5876 // transitioning to the new one. Just update the new 5877 // one to continue using the old name. 5878 realName = pkg.mRealPackage; 5879 if (!pkg.packageName.equals(renamed)) { 5880 // Callers into this function may have already taken 5881 // care of renaming the package; only do it here if 5882 // it is not already done. 5883 pkg.setPackageName(renamed); 5884 } 5885 5886 } else { 5887 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5888 if ((origPackage = mSettings.peekPackageLPr( 5889 pkg.mOriginalPackages.get(i))) != null) { 5890 // We do have the package already installed under its 5891 // original name... should we use it? 5892 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5893 // New package is not compatible with original. 5894 origPackage = null; 5895 continue; 5896 } else if (origPackage.sharedUser != null) { 5897 // Make sure uid is compatible between packages. 5898 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5899 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5900 + " to " + pkg.packageName + ": old uid " 5901 + origPackage.sharedUser.name 5902 + " differs from " + pkg.mSharedUserId); 5903 origPackage = null; 5904 continue; 5905 } 5906 } else { 5907 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5908 + pkg.packageName + " to old name " + origPackage.name); 5909 } 5910 break; 5911 } 5912 } 5913 } 5914 } 5915 5916 if (mTransferedPackages.contains(pkg.packageName)) { 5917 Slog.w(TAG, "Package " + pkg.packageName 5918 + " was transferred to another, but its .apk remains"); 5919 } 5920 5921 // Just create the setting, don't add it yet. For already existing packages 5922 // the PkgSetting exists already and doesn't have to be created. 5923 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5924 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5925 pkg.applicationInfo.primaryCpuAbi, 5926 pkg.applicationInfo.secondaryCpuAbi, 5927 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5928 user, false); 5929 if (pkgSetting == null) { 5930 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5931 "Creating application package " + pkg.packageName + " failed"); 5932 } 5933 5934 if (pkgSetting.origPackage != null) { 5935 // If we are first transitioning from an original package, 5936 // fix up the new package's name now. We need to do this after 5937 // looking up the package under its new name, so getPackageLP 5938 // can take care of fiddling things correctly. 5939 pkg.setPackageName(origPackage.name); 5940 5941 // File a report about this. 5942 String msg = "New package " + pkgSetting.realName 5943 + " renamed to replace old package " + pkgSetting.name; 5944 reportSettingsProblem(Log.WARN, msg); 5945 5946 // Make a note of it. 5947 mTransferedPackages.add(origPackage.name); 5948 5949 // No longer need to retain this. 5950 pkgSetting.origPackage = null; 5951 } 5952 5953 if (realName != null) { 5954 // Make a note of it. 5955 mTransferedPackages.add(pkg.packageName); 5956 } 5957 5958 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5959 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5960 } 5961 5962 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5963 // Check all shared libraries and map to their actual file path. 5964 // We only do this here for apps not on a system dir, because those 5965 // are the only ones that can fail an install due to this. We 5966 // will take care of the system apps by updating all of their 5967 // library paths after the scan is done. 5968 updateSharedLibrariesLPw(pkg, null); 5969 } 5970 5971 if (mFoundPolicyFile) { 5972 SELinuxMMAC.assignSeinfoValue(pkg); 5973 } 5974 5975 pkg.applicationInfo.uid = pkgSetting.appId; 5976 pkg.mExtras = pkgSetting; 5977 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5978 try { 5979 verifySignaturesLP(pkgSetting, pkg); 5980 // We just determined the app is signed correctly, so bring 5981 // over the latest parsed certs. 5982 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5983 } catch (PackageManagerException e) { 5984 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5985 throw e; 5986 } 5987 // The signature has changed, but this package is in the system 5988 // image... let's recover! 5989 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5990 // However... if this package is part of a shared user, but it 5991 // doesn't match the signature of the shared user, let's fail. 5992 // What this means is that you can't change the signatures 5993 // associated with an overall shared user, which doesn't seem all 5994 // that unreasonable. 5995 if (pkgSetting.sharedUser != null) { 5996 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5997 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5998 throw new PackageManagerException( 5999 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6000 "Signature mismatch for shared user : " 6001 + pkgSetting.sharedUser); 6002 } 6003 } 6004 // File a report about this. 6005 String msg = "System package " + pkg.packageName 6006 + " signature changed; retaining data."; 6007 reportSettingsProblem(Log.WARN, msg); 6008 } 6009 } else { 6010 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6011 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6012 + pkg.packageName + " upgrade keys do not match the " 6013 + "previously installed version"); 6014 } else { 6015 // We just determined the app is signed correctly, so bring 6016 // over the latest parsed certs. 6017 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6018 } 6019 } 6020 // Verify that this new package doesn't have any content providers 6021 // that conflict with existing packages. Only do this if the 6022 // package isn't already installed, since we don't want to break 6023 // things that are installed. 6024 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6025 final int N = pkg.providers.size(); 6026 int i; 6027 for (i=0; i<N; i++) { 6028 PackageParser.Provider p = pkg.providers.get(i); 6029 if (p.info.authority != null) { 6030 String names[] = p.info.authority.split(";"); 6031 for (int j = 0; j < names.length; j++) { 6032 if (mProvidersByAuthority.containsKey(names[j])) { 6033 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6034 final String otherPackageName = 6035 ((other != null && other.getComponentName() != null) ? 6036 other.getComponentName().getPackageName() : "?"); 6037 throw new PackageManagerException( 6038 INSTALL_FAILED_CONFLICTING_PROVIDER, 6039 "Can't install because provider name " + names[j] 6040 + " (in package " + pkg.applicationInfo.packageName 6041 + ") is already used by " + otherPackageName); 6042 } 6043 } 6044 } 6045 } 6046 } 6047 6048 if (pkg.mAdoptPermissions != null) { 6049 // This package wants to adopt ownership of permissions from 6050 // another package. 6051 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6052 final String origName = pkg.mAdoptPermissions.get(i); 6053 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6054 if (orig != null) { 6055 if (verifyPackageUpdateLPr(orig, pkg)) { 6056 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6057 + pkg.packageName); 6058 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6059 } 6060 } 6061 } 6062 } 6063 } 6064 6065 final String pkgName = pkg.packageName; 6066 6067 final long scanFileTime = scanFile.lastModified(); 6068 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6069 pkg.applicationInfo.processName = fixProcessName( 6070 pkg.applicationInfo.packageName, 6071 pkg.applicationInfo.processName, 6072 pkg.applicationInfo.uid); 6073 6074 File dataPath; 6075 if (mPlatformPackage == pkg) { 6076 // The system package is special. 6077 dataPath = new File(Environment.getDataDirectory(), "system"); 6078 6079 pkg.applicationInfo.dataDir = dataPath.getPath(); 6080 6081 } else { 6082 // This is a normal package, need to make its data directory. 6083 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6084 UserHandle.USER_OWNER); 6085 6086 boolean uidError = false; 6087 if (dataPath.exists()) { 6088 int currentUid = 0; 6089 try { 6090 StructStat stat = Os.stat(dataPath.getPath()); 6091 currentUid = stat.st_uid; 6092 } catch (ErrnoException e) { 6093 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6094 } 6095 6096 // If we have mismatched owners for the data path, we have a problem. 6097 if (currentUid != pkg.applicationInfo.uid) { 6098 boolean recovered = false; 6099 if (currentUid == 0) { 6100 // The directory somehow became owned by root. Wow. 6101 // This is probably because the system was stopped while 6102 // installd was in the middle of messing with its libs 6103 // directory. Ask installd to fix that. 6104 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6105 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6106 if (ret >= 0) { 6107 recovered = true; 6108 String msg = "Package " + pkg.packageName 6109 + " unexpectedly changed to uid 0; recovered to " + 6110 + pkg.applicationInfo.uid; 6111 reportSettingsProblem(Log.WARN, msg); 6112 } 6113 } 6114 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6115 || (scanFlags&SCAN_BOOTING) != 0)) { 6116 // If this is a system app, we can at least delete its 6117 // current data so the application will still work. 6118 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6119 if (ret >= 0) { 6120 // TODO: Kill the processes first 6121 // Old data gone! 6122 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6123 ? "System package " : "Third party package "; 6124 String msg = prefix + pkg.packageName 6125 + " has changed from uid: " 6126 + currentUid + " to " 6127 + pkg.applicationInfo.uid + "; old data erased"; 6128 reportSettingsProblem(Log.WARN, msg); 6129 recovered = true; 6130 6131 // And now re-install the app. 6132 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6133 pkg.applicationInfo.seinfo); 6134 if (ret == -1) { 6135 // Ack should not happen! 6136 msg = prefix + pkg.packageName 6137 + " could not have data directory re-created after delete."; 6138 reportSettingsProblem(Log.WARN, msg); 6139 throw new PackageManagerException( 6140 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6141 } 6142 } 6143 if (!recovered) { 6144 mHasSystemUidErrors = true; 6145 } 6146 } else if (!recovered) { 6147 // If we allow this install to proceed, we will be broken. 6148 // Abort, abort! 6149 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6150 "scanPackageLI"); 6151 } 6152 if (!recovered) { 6153 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6154 + pkg.applicationInfo.uid + "/fs_" 6155 + currentUid; 6156 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6157 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6158 String msg = "Package " + pkg.packageName 6159 + " has mismatched uid: " 6160 + currentUid + " on disk, " 6161 + pkg.applicationInfo.uid + " in settings"; 6162 // writer 6163 synchronized (mPackages) { 6164 mSettings.mReadMessages.append(msg); 6165 mSettings.mReadMessages.append('\n'); 6166 uidError = true; 6167 if (!pkgSetting.uidError) { 6168 reportSettingsProblem(Log.ERROR, msg); 6169 } 6170 } 6171 } 6172 } 6173 pkg.applicationInfo.dataDir = dataPath.getPath(); 6174 if (mShouldRestoreconData) { 6175 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6176 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6177 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6178 } 6179 } else { 6180 if (DEBUG_PACKAGE_SCANNING) { 6181 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6182 Log.v(TAG, "Want this data dir: " + dataPath); 6183 } 6184 //invoke installer to do the actual installation 6185 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6186 pkg.applicationInfo.seinfo); 6187 if (ret < 0) { 6188 // Error from installer 6189 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6190 "Unable to create data dirs [errorCode=" + ret + "]"); 6191 } 6192 6193 if (dataPath.exists()) { 6194 pkg.applicationInfo.dataDir = dataPath.getPath(); 6195 } else { 6196 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6197 pkg.applicationInfo.dataDir = null; 6198 } 6199 } 6200 6201 pkgSetting.uidError = uidError; 6202 } 6203 6204 final String path = scanFile.getPath(); 6205 final String codePath = pkg.applicationInfo.getCodePath(); 6206 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6207 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6208 setBundledAppAbisAndRoots(pkg, pkgSetting); 6209 6210 // If we haven't found any native libraries for the app, check if it has 6211 // renderscript code. We'll need to force the app to 32 bit if it has 6212 // renderscript bitcode. 6213 if (pkg.applicationInfo.primaryCpuAbi == null 6214 && pkg.applicationInfo.secondaryCpuAbi == null 6215 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6216 NativeLibraryHelper.Handle handle = null; 6217 try { 6218 handle = NativeLibraryHelper.Handle.create(scanFile); 6219 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6220 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6221 } 6222 } catch (IOException ioe) { 6223 Slog.w(TAG, "Error scanning system app : " + ioe); 6224 } finally { 6225 IoUtils.closeQuietly(handle); 6226 } 6227 } 6228 6229 setNativeLibraryPaths(pkg); 6230 } else { 6231 // TODO: We can probably be smarter about this stuff. For installed apps, 6232 // we can calculate this information at install time once and for all. For 6233 // system apps, we can probably assume that this information doesn't change 6234 // after the first boot scan. As things stand, we do lots of unnecessary work. 6235 6236 // Give ourselves some initial paths; we'll come back for another 6237 // pass once we've determined ABI below. 6238 setNativeLibraryPaths(pkg); 6239 6240 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6241 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6242 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6243 6244 NativeLibraryHelper.Handle handle = null; 6245 try { 6246 handle = NativeLibraryHelper.Handle.create(scanFile); 6247 // TODO(multiArch): This can be null for apps that didn't go through the 6248 // usual installation process. We can calculate it again, like we 6249 // do during install time. 6250 // 6251 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6252 // unnecessary. 6253 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6254 6255 // Null out the abis so that they can be recalculated. 6256 pkg.applicationInfo.primaryCpuAbi = null; 6257 pkg.applicationInfo.secondaryCpuAbi = null; 6258 if (isMultiArch(pkg.applicationInfo)) { 6259 // Warn if we've set an abiOverride for multi-lib packages.. 6260 // By definition, we need to copy both 32 and 64 bit libraries for 6261 // such packages. 6262 if (pkg.cpuAbiOverride != null 6263 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6264 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6265 } 6266 6267 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6268 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6269 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6270 if (isAsec) { 6271 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6272 } else { 6273 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6274 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6275 useIsaSpecificSubdirs); 6276 } 6277 } 6278 6279 maybeThrowExceptionForMultiArchCopy( 6280 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6281 6282 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6283 if (isAsec) { 6284 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6285 } else { 6286 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6287 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6288 useIsaSpecificSubdirs); 6289 } 6290 } 6291 6292 maybeThrowExceptionForMultiArchCopy( 6293 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6294 6295 if (abi64 >= 0) { 6296 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6297 } 6298 6299 if (abi32 >= 0) { 6300 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6301 if (abi64 >= 0) { 6302 pkg.applicationInfo.secondaryCpuAbi = abi; 6303 } else { 6304 pkg.applicationInfo.primaryCpuAbi = abi; 6305 } 6306 } 6307 } else { 6308 String[] abiList = (cpuAbiOverride != null) ? 6309 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6310 6311 // Enable gross and lame hacks for apps that are built with old 6312 // SDK tools. We must scan their APKs for renderscript bitcode and 6313 // not launch them if it's present. Don't bother checking on devices 6314 // that don't have 64 bit support. 6315 boolean needsRenderScriptOverride = false; 6316 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6317 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6318 abiList = Build.SUPPORTED_32_BIT_ABIS; 6319 needsRenderScriptOverride = true; 6320 } 6321 6322 final int copyRet; 6323 if (isAsec) { 6324 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6325 } else { 6326 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6327 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6328 } 6329 6330 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6331 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6332 "Error unpackaging native libs for app, errorCode=" + copyRet); 6333 } 6334 6335 if (copyRet >= 0) { 6336 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6337 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6338 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6339 } else if (needsRenderScriptOverride) { 6340 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6341 } 6342 } 6343 } catch (IOException ioe) { 6344 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6345 } finally { 6346 IoUtils.closeQuietly(handle); 6347 } 6348 6349 // Now that we've calculated the ABIs and determined if it's an internal app, 6350 // we will go ahead and populate the nativeLibraryPath. 6351 setNativeLibraryPaths(pkg); 6352 6353 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6354 final int[] userIds = sUserManager.getUserIds(); 6355 synchronized (mInstallLock) { 6356 // Create a native library symlink only if we have native libraries 6357 // and if the native libraries are 32 bit libraries. We do not provide 6358 // this symlink for 64 bit libraries. 6359 if (pkg.applicationInfo.primaryCpuAbi != null && 6360 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6361 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6362 for (int userId : userIds) { 6363 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6364 nativeLibPath, userId) < 0) { 6365 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6366 "Failed linking native library dir (user=" + userId + ")"); 6367 } 6368 } 6369 } 6370 } 6371 } 6372 6373 // This is a special case for the "system" package, where the ABI is 6374 // dictated by the zygote configuration (and init.rc). We should keep track 6375 // of this ABI so that we can deal with "normal" applications that run under 6376 // the same UID correctly. 6377 if (mPlatformPackage == pkg) { 6378 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6379 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6380 } 6381 6382 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6383 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6384 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6385 // Copy the derived override back to the parsed package, so that we can 6386 // update the package settings accordingly. 6387 pkg.cpuAbiOverride = cpuAbiOverride; 6388 6389 if (DEBUG_ABI_SELECTION) { 6390 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6391 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6392 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6393 } 6394 6395 // Push the derived path down into PackageSettings so we know what to 6396 // clean up at uninstall time. 6397 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6398 6399 if (DEBUG_ABI_SELECTION) { 6400 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6401 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6402 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6403 } 6404 6405 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6406 // We don't do this here during boot because we can do it all 6407 // at once after scanning all existing packages. 6408 // 6409 // We also do this *before* we perform dexopt on this package, so that 6410 // we can avoid redundant dexopts, and also to make sure we've got the 6411 // code and package path correct. 6412 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6413 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6414 } 6415 6416 if ((scanFlags & SCAN_NO_DEX) == 0) { 6417 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6418 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6419 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6420 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6421 } 6422 } 6423 if (mFactoryTest && pkg.requestedPermissions.contains( 6424 android.Manifest.permission.FACTORY_TEST)) { 6425 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6426 } 6427 6428 ArrayList<PackageParser.Package> clientLibPkgs = null; 6429 6430 // writer 6431 synchronized (mPackages) { 6432 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6433 // Only system apps can add new shared libraries. 6434 if (pkg.libraryNames != null) { 6435 for (int i=0; i<pkg.libraryNames.size(); i++) { 6436 String name = pkg.libraryNames.get(i); 6437 boolean allowed = false; 6438 if (pkg.isUpdatedSystemApp()) { 6439 // New library entries can only be added through the 6440 // system image. This is important to get rid of a lot 6441 // of nasty edge cases: for example if we allowed a non- 6442 // system update of the app to add a library, then uninstalling 6443 // the update would make the library go away, and assumptions 6444 // we made such as through app install filtering would now 6445 // have allowed apps on the device which aren't compatible 6446 // with it. Better to just have the restriction here, be 6447 // conservative, and create many fewer cases that can negatively 6448 // impact the user experience. 6449 final PackageSetting sysPs = mSettings 6450 .getDisabledSystemPkgLPr(pkg.packageName); 6451 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6452 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6453 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6454 allowed = true; 6455 allowed = true; 6456 break; 6457 } 6458 } 6459 } 6460 } else { 6461 allowed = true; 6462 } 6463 if (allowed) { 6464 if (!mSharedLibraries.containsKey(name)) { 6465 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6466 } else if (!name.equals(pkg.packageName)) { 6467 Slog.w(TAG, "Package " + pkg.packageName + " library " 6468 + name + " already exists; skipping"); 6469 } 6470 } else { 6471 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6472 + name + " that is not declared on system image; skipping"); 6473 } 6474 } 6475 if ((scanFlags&SCAN_BOOTING) == 0) { 6476 // If we are not booting, we need to update any applications 6477 // that are clients of our shared library. If we are booting, 6478 // this will all be done once the scan is complete. 6479 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6480 } 6481 } 6482 } 6483 } 6484 6485 // We also need to dexopt any apps that are dependent on this library. Note that 6486 // if these fail, we should abort the install since installing the library will 6487 // result in some apps being broken. 6488 if (clientLibPkgs != null) { 6489 if ((scanFlags & SCAN_NO_DEX) == 0) { 6490 for (int i = 0; i < clientLibPkgs.size(); i++) { 6491 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6492 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6493 null /* instruction sets */, forceDex, 6494 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6495 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6496 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6497 "scanPackageLI failed to dexopt clientLibPkgs"); 6498 } 6499 } 6500 } 6501 } 6502 6503 // Also need to kill any apps that are dependent on the library. 6504 if (clientLibPkgs != null) { 6505 for (int i=0; i<clientLibPkgs.size(); i++) { 6506 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6507 killApplication(clientPkg.applicationInfo.packageName, 6508 clientPkg.applicationInfo.uid, "update lib"); 6509 } 6510 } 6511 6512 // writer 6513 synchronized (mPackages) { 6514 // We don't expect installation to fail beyond this point 6515 6516 // Add the new setting to mSettings 6517 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6518 // Add the new setting to mPackages 6519 mPackages.put(pkg.applicationInfo.packageName, pkg); 6520 // Make sure we don't accidentally delete its data. 6521 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6522 while (iter.hasNext()) { 6523 PackageCleanItem item = iter.next(); 6524 if (pkgName.equals(item.packageName)) { 6525 iter.remove(); 6526 } 6527 } 6528 6529 // Take care of first install / last update times. 6530 if (currentTime != 0) { 6531 if (pkgSetting.firstInstallTime == 0) { 6532 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6533 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6534 pkgSetting.lastUpdateTime = currentTime; 6535 } 6536 } else if (pkgSetting.firstInstallTime == 0) { 6537 // We need *something*. Take time time stamp of the file. 6538 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6539 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6540 if (scanFileTime != pkgSetting.timeStamp) { 6541 // A package on the system image has changed; consider this 6542 // to be an update. 6543 pkgSetting.lastUpdateTime = scanFileTime; 6544 } 6545 } 6546 6547 // Add the package's KeySets to the global KeySetManagerService 6548 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6549 try { 6550 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6551 if (pkg.mKeySetMapping != null) { 6552 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6553 if (pkg.mUpgradeKeySets != null) { 6554 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6555 } 6556 } 6557 } catch (NullPointerException e) { 6558 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6559 } catch (IllegalArgumentException e) { 6560 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6561 } 6562 6563 int N = pkg.providers.size(); 6564 StringBuilder r = null; 6565 int i; 6566 for (i=0; i<N; i++) { 6567 PackageParser.Provider p = pkg.providers.get(i); 6568 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6569 p.info.processName, pkg.applicationInfo.uid); 6570 mProviders.addProvider(p); 6571 p.syncable = p.info.isSyncable; 6572 if (p.info.authority != null) { 6573 String names[] = p.info.authority.split(";"); 6574 p.info.authority = null; 6575 for (int j = 0; j < names.length; j++) { 6576 if (j == 1 && p.syncable) { 6577 // We only want the first authority for a provider to possibly be 6578 // syncable, so if we already added this provider using a different 6579 // authority clear the syncable flag. We copy the provider before 6580 // changing it because the mProviders object contains a reference 6581 // to a provider that we don't want to change. 6582 // Only do this for the second authority since the resulting provider 6583 // object can be the same for all future authorities for this provider. 6584 p = new PackageParser.Provider(p); 6585 p.syncable = false; 6586 } 6587 if (!mProvidersByAuthority.containsKey(names[j])) { 6588 mProvidersByAuthority.put(names[j], p); 6589 if (p.info.authority == null) { 6590 p.info.authority = names[j]; 6591 } else { 6592 p.info.authority = p.info.authority + ";" + names[j]; 6593 } 6594 if (DEBUG_PACKAGE_SCANNING) { 6595 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6596 Log.d(TAG, "Registered content provider: " + names[j] 6597 + ", className = " + p.info.name + ", isSyncable = " 6598 + p.info.isSyncable); 6599 } 6600 } else { 6601 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6602 Slog.w(TAG, "Skipping provider name " + names[j] + 6603 " (in package " + pkg.applicationInfo.packageName + 6604 "): name already used by " 6605 + ((other != null && other.getComponentName() != null) 6606 ? other.getComponentName().getPackageName() : "?")); 6607 } 6608 } 6609 } 6610 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6611 if (r == null) { 6612 r = new StringBuilder(256); 6613 } else { 6614 r.append(' '); 6615 } 6616 r.append(p.info.name); 6617 } 6618 } 6619 if (r != null) { 6620 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6621 } 6622 6623 N = pkg.services.size(); 6624 r = null; 6625 for (i=0; i<N; i++) { 6626 PackageParser.Service s = pkg.services.get(i); 6627 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6628 s.info.processName, pkg.applicationInfo.uid); 6629 mServices.addService(s); 6630 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6631 if (r == null) { 6632 r = new StringBuilder(256); 6633 } else { 6634 r.append(' '); 6635 } 6636 r.append(s.info.name); 6637 } 6638 } 6639 if (r != null) { 6640 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6641 } 6642 6643 N = pkg.receivers.size(); 6644 r = null; 6645 for (i=0; i<N; i++) { 6646 PackageParser.Activity a = pkg.receivers.get(i); 6647 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6648 a.info.processName, pkg.applicationInfo.uid); 6649 mReceivers.addActivity(a, "receiver"); 6650 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6651 if (r == null) { 6652 r = new StringBuilder(256); 6653 } else { 6654 r.append(' '); 6655 } 6656 r.append(a.info.name); 6657 } 6658 } 6659 if (r != null) { 6660 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6661 } 6662 6663 N = pkg.activities.size(); 6664 r = null; 6665 for (i=0; i<N; i++) { 6666 PackageParser.Activity a = pkg.activities.get(i); 6667 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6668 a.info.processName, pkg.applicationInfo.uid); 6669 mActivities.addActivity(a, "activity"); 6670 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6671 if (r == null) { 6672 r = new StringBuilder(256); 6673 } else { 6674 r.append(' '); 6675 } 6676 r.append(a.info.name); 6677 } 6678 } 6679 if (r != null) { 6680 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6681 } 6682 6683 N = pkg.permissionGroups.size(); 6684 r = null; 6685 for (i=0; i<N; i++) { 6686 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6687 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6688 if (cur == null) { 6689 mPermissionGroups.put(pg.info.name, pg); 6690 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6691 if (r == null) { 6692 r = new StringBuilder(256); 6693 } else { 6694 r.append(' '); 6695 } 6696 r.append(pg.info.name); 6697 } 6698 } else { 6699 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6700 + pg.info.packageName + " ignored: original from " 6701 + cur.info.packageName); 6702 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6703 if (r == null) { 6704 r = new StringBuilder(256); 6705 } else { 6706 r.append(' '); 6707 } 6708 r.append("DUP:"); 6709 r.append(pg.info.name); 6710 } 6711 } 6712 } 6713 if (r != null) { 6714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6715 } 6716 6717 N = pkg.permissions.size(); 6718 r = null; 6719 for (i=0; i<N; i++) { 6720 PackageParser.Permission p = pkg.permissions.get(i); 6721 6722 // Now that permission groups have a special meaning, we ignore permission 6723 // groups for legacy apps to prevent unexpected behavior. In particular, 6724 // permissions for one app being granted to someone just becuase they happen 6725 // to be in a group defined by another app (before this had no implications). 6726 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6727 p.group = mPermissionGroups.get(p.info.group); 6728 // Warn for a permission in an unknown group. 6729 if (p.info.group != null && p.group == null) { 6730 Slog.w(TAG, "Permission " + p.info.name + " from package " 6731 + p.info.packageName + " in an unknown group " + p.info.group); 6732 } 6733 } 6734 6735 ArrayMap<String, BasePermission> permissionMap = 6736 p.tree ? mSettings.mPermissionTrees 6737 : mSettings.mPermissions; 6738 BasePermission bp = permissionMap.get(p.info.name); 6739 6740 // Allow system apps to redefine non-system permissions 6741 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6742 final boolean currentOwnerIsSystem = (bp.perm != null 6743 && isSystemApp(bp.perm.owner)); 6744 if (isSystemApp(p.owner)) { 6745 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6746 // It's a built-in permission and no owner, take ownership now 6747 bp.packageSetting = pkgSetting; 6748 bp.perm = p; 6749 bp.uid = pkg.applicationInfo.uid; 6750 bp.sourcePackage = p.info.packageName; 6751 } else if (!currentOwnerIsSystem) { 6752 String msg = "New decl " + p.owner + " of permission " 6753 + p.info.name + " is system; overriding " + bp.sourcePackage; 6754 reportSettingsProblem(Log.WARN, msg); 6755 bp = null; 6756 } 6757 } 6758 } 6759 6760 if (bp == null) { 6761 bp = new BasePermission(p.info.name, p.info.packageName, 6762 BasePermission.TYPE_NORMAL); 6763 permissionMap.put(p.info.name, bp); 6764 } 6765 6766 if (bp.perm == null) { 6767 if (bp.sourcePackage == null 6768 || bp.sourcePackage.equals(p.info.packageName)) { 6769 BasePermission tree = findPermissionTreeLP(p.info.name); 6770 if (tree == null 6771 || tree.sourcePackage.equals(p.info.packageName)) { 6772 bp.packageSetting = pkgSetting; 6773 bp.perm = p; 6774 bp.uid = pkg.applicationInfo.uid; 6775 bp.sourcePackage = p.info.packageName; 6776 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6777 if (r == null) { 6778 r = new StringBuilder(256); 6779 } else { 6780 r.append(' '); 6781 } 6782 r.append(p.info.name); 6783 } 6784 } else { 6785 Slog.w(TAG, "Permission " + p.info.name + " from package " 6786 + p.info.packageName + " ignored: base tree " 6787 + tree.name + " is from package " 6788 + tree.sourcePackage); 6789 } 6790 } else { 6791 Slog.w(TAG, "Permission " + p.info.name + " from package " 6792 + p.info.packageName + " ignored: original from " 6793 + bp.sourcePackage); 6794 } 6795 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6796 if (r == null) { 6797 r = new StringBuilder(256); 6798 } else { 6799 r.append(' '); 6800 } 6801 r.append("DUP:"); 6802 r.append(p.info.name); 6803 } 6804 if (bp.perm == p) { 6805 bp.protectionLevel = p.info.protectionLevel; 6806 } 6807 } 6808 6809 if (r != null) { 6810 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6811 } 6812 6813 N = pkg.instrumentation.size(); 6814 r = null; 6815 for (i=0; i<N; i++) { 6816 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6817 a.info.packageName = pkg.applicationInfo.packageName; 6818 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6819 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6820 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6821 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6822 a.info.dataDir = pkg.applicationInfo.dataDir; 6823 6824 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6825 // need other information about the application, like the ABI and what not ? 6826 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6827 mInstrumentation.put(a.getComponentName(), a); 6828 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6829 if (r == null) { 6830 r = new StringBuilder(256); 6831 } else { 6832 r.append(' '); 6833 } 6834 r.append(a.info.name); 6835 } 6836 } 6837 if (r != null) { 6838 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6839 } 6840 6841 if (pkg.protectedBroadcasts != null) { 6842 N = pkg.protectedBroadcasts.size(); 6843 for (i=0; i<N; i++) { 6844 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6845 } 6846 } 6847 6848 pkgSetting.setTimeStamp(scanFileTime); 6849 6850 // Create idmap files for pairs of (packages, overlay packages). 6851 // Note: "android", ie framework-res.apk, is handled by native layers. 6852 if (pkg.mOverlayTarget != null) { 6853 // This is an overlay package. 6854 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6855 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6856 mOverlays.put(pkg.mOverlayTarget, 6857 new ArrayMap<String, PackageParser.Package>()); 6858 } 6859 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6860 map.put(pkg.packageName, pkg); 6861 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6862 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6863 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6864 "scanPackageLI failed to createIdmap"); 6865 } 6866 } 6867 } else if (mOverlays.containsKey(pkg.packageName) && 6868 !pkg.packageName.equals("android")) { 6869 // This is a regular package, with one or more known overlay packages. 6870 createIdmapsForPackageLI(pkg); 6871 } 6872 } 6873 6874 return pkg; 6875 } 6876 6877 /** 6878 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6879 * i.e, so that all packages can be run inside a single process if required. 6880 * 6881 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6882 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6883 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6884 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6885 * updating a package that belongs to a shared user. 6886 * 6887 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6888 * adds unnecessary complexity. 6889 */ 6890 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6891 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6892 String requiredInstructionSet = null; 6893 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6894 requiredInstructionSet = VMRuntime.getInstructionSet( 6895 scannedPackage.applicationInfo.primaryCpuAbi); 6896 } 6897 6898 PackageSetting requirer = null; 6899 for (PackageSetting ps : packagesForUser) { 6900 // If packagesForUser contains scannedPackage, we skip it. This will happen 6901 // when scannedPackage is an update of an existing package. Without this check, 6902 // we will never be able to change the ABI of any package belonging to a shared 6903 // user, even if it's compatible with other packages. 6904 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6905 if (ps.primaryCpuAbiString == null) { 6906 continue; 6907 } 6908 6909 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6910 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6911 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6912 // this but there's not much we can do. 6913 String errorMessage = "Instruction set mismatch, " 6914 + ((requirer == null) ? "[caller]" : requirer) 6915 + " requires " + requiredInstructionSet + " whereas " + ps 6916 + " requires " + instructionSet; 6917 Slog.w(TAG, errorMessage); 6918 } 6919 6920 if (requiredInstructionSet == null) { 6921 requiredInstructionSet = instructionSet; 6922 requirer = ps; 6923 } 6924 } 6925 } 6926 6927 if (requiredInstructionSet != null) { 6928 String adjustedAbi; 6929 if (requirer != null) { 6930 // requirer != null implies that either scannedPackage was null or that scannedPackage 6931 // did not require an ABI, in which case we have to adjust scannedPackage to match 6932 // the ABI of the set (which is the same as requirer's ABI) 6933 adjustedAbi = requirer.primaryCpuAbiString; 6934 if (scannedPackage != null) { 6935 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6936 } 6937 } else { 6938 // requirer == null implies that we're updating all ABIs in the set to 6939 // match scannedPackage. 6940 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6941 } 6942 6943 for (PackageSetting ps : packagesForUser) { 6944 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6945 if (ps.primaryCpuAbiString != null) { 6946 continue; 6947 } 6948 6949 ps.primaryCpuAbiString = adjustedAbi; 6950 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6951 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6952 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6953 6954 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 6955 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 6956 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6957 ps.primaryCpuAbiString = null; 6958 ps.pkg.applicationInfo.primaryCpuAbi = null; 6959 return; 6960 } else { 6961 mInstaller.rmdex(ps.codePathString, 6962 getDexCodeInstructionSet(getPreferredInstructionSet())); 6963 } 6964 } 6965 } 6966 } 6967 } 6968 } 6969 6970 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6971 synchronized (mPackages) { 6972 mResolverReplaced = true; 6973 // Set up information for custom user intent resolution activity. 6974 mResolveActivity.applicationInfo = pkg.applicationInfo; 6975 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6976 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6977 mResolveActivity.processName = pkg.applicationInfo.packageName; 6978 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6979 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6980 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6981 mResolveActivity.theme = 0; 6982 mResolveActivity.exported = true; 6983 mResolveActivity.enabled = true; 6984 mResolveInfo.activityInfo = mResolveActivity; 6985 mResolveInfo.priority = 0; 6986 mResolveInfo.preferredOrder = 0; 6987 mResolveInfo.match = 0; 6988 mResolveComponentName = mCustomResolverComponentName; 6989 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6990 mResolveComponentName); 6991 } 6992 } 6993 6994 private static String calculateBundledApkRoot(final String codePathString) { 6995 final File codePath = new File(codePathString); 6996 final File codeRoot; 6997 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6998 codeRoot = Environment.getRootDirectory(); 6999 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7000 codeRoot = Environment.getOemDirectory(); 7001 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7002 codeRoot = Environment.getVendorDirectory(); 7003 } else { 7004 // Unrecognized code path; take its top real segment as the apk root: 7005 // e.g. /something/app/blah.apk => /something 7006 try { 7007 File f = codePath.getCanonicalFile(); 7008 File parent = f.getParentFile(); // non-null because codePath is a file 7009 File tmp; 7010 while ((tmp = parent.getParentFile()) != null) { 7011 f = parent; 7012 parent = tmp; 7013 } 7014 codeRoot = f; 7015 Slog.w(TAG, "Unrecognized code path " 7016 + codePath + " - using " + codeRoot); 7017 } catch (IOException e) { 7018 // Can't canonicalize the code path -- shenanigans? 7019 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7020 return Environment.getRootDirectory().getPath(); 7021 } 7022 } 7023 return codeRoot.getPath(); 7024 } 7025 7026 /** 7027 * Derive and set the location of native libraries for the given package, 7028 * which varies depending on where and how the package was installed. 7029 */ 7030 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7031 final ApplicationInfo info = pkg.applicationInfo; 7032 final String codePath = pkg.codePath; 7033 final File codeFile = new File(codePath); 7034 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7035 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7036 7037 info.nativeLibraryRootDir = null; 7038 info.nativeLibraryRootRequiresIsa = false; 7039 info.nativeLibraryDir = null; 7040 info.secondaryNativeLibraryDir = null; 7041 7042 if (isApkFile(codeFile)) { 7043 // Monolithic install 7044 if (bundledApp) { 7045 // If "/system/lib64/apkname" exists, assume that is the per-package 7046 // native library directory to use; otherwise use "/system/lib/apkname". 7047 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7048 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7049 getPrimaryInstructionSet(info)); 7050 7051 // This is a bundled system app so choose the path based on the ABI. 7052 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7053 // is just the default path. 7054 final String apkName = deriveCodePathName(codePath); 7055 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7056 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7057 apkName).getAbsolutePath(); 7058 7059 if (info.secondaryCpuAbi != null) { 7060 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7061 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7062 secondaryLibDir, apkName).getAbsolutePath(); 7063 } 7064 } else if (asecApp) { 7065 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7066 .getAbsolutePath(); 7067 } else { 7068 final String apkName = deriveCodePathName(codePath); 7069 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7070 .getAbsolutePath(); 7071 } 7072 7073 info.nativeLibraryRootRequiresIsa = false; 7074 info.nativeLibraryDir = info.nativeLibraryRootDir; 7075 } else { 7076 // Cluster install 7077 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7078 info.nativeLibraryRootRequiresIsa = true; 7079 7080 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7081 getPrimaryInstructionSet(info)).getAbsolutePath(); 7082 7083 if (info.secondaryCpuAbi != null) { 7084 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7085 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7086 } 7087 } 7088 } 7089 7090 /** 7091 * Calculate the abis and roots for a bundled app. These can uniquely 7092 * be determined from the contents of the system partition, i.e whether 7093 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7094 * of this information, and instead assume that the system was built 7095 * sensibly. 7096 */ 7097 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7098 PackageSetting pkgSetting) { 7099 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7100 7101 // If "/system/lib64/apkname" exists, assume that is the per-package 7102 // native library directory to use; otherwise use "/system/lib/apkname". 7103 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7104 setBundledAppAbi(pkg, apkRoot, apkName); 7105 // pkgSetting might be null during rescan following uninstall of updates 7106 // to a bundled app, so accommodate that possibility. The settings in 7107 // that case will be established later from the parsed package. 7108 // 7109 // If the settings aren't null, sync them up with what we've just derived. 7110 // note that apkRoot isn't stored in the package settings. 7111 if (pkgSetting != null) { 7112 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7113 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7114 } 7115 } 7116 7117 /** 7118 * Deduces the ABI of a bundled app and sets the relevant fields on the 7119 * parsed pkg object. 7120 * 7121 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7122 * under which system libraries are installed. 7123 * @param apkName the name of the installed package. 7124 */ 7125 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7126 final File codeFile = new File(pkg.codePath); 7127 7128 final boolean has64BitLibs; 7129 final boolean has32BitLibs; 7130 if (isApkFile(codeFile)) { 7131 // Monolithic install 7132 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7133 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7134 } else { 7135 // Cluster install 7136 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7137 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7138 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7139 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7140 has64BitLibs = (new File(rootDir, isa)).exists(); 7141 } else { 7142 has64BitLibs = false; 7143 } 7144 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7145 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7146 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7147 has32BitLibs = (new File(rootDir, isa)).exists(); 7148 } else { 7149 has32BitLibs = false; 7150 } 7151 } 7152 7153 if (has64BitLibs && !has32BitLibs) { 7154 // The package has 64 bit libs, but not 32 bit libs. Its primary 7155 // ABI should be 64 bit. We can safely assume here that the bundled 7156 // native libraries correspond to the most preferred ABI in the list. 7157 7158 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7159 pkg.applicationInfo.secondaryCpuAbi = null; 7160 } else if (has32BitLibs && !has64BitLibs) { 7161 // The package has 32 bit libs but not 64 bit libs. Its primary 7162 // ABI should be 32 bit. 7163 7164 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7165 pkg.applicationInfo.secondaryCpuAbi = null; 7166 } else if (has32BitLibs && has64BitLibs) { 7167 // The application has both 64 and 32 bit bundled libraries. We check 7168 // here that the app declares multiArch support, and warn if it doesn't. 7169 // 7170 // We will be lenient here and record both ABIs. The primary will be the 7171 // ABI that's higher on the list, i.e, a device that's configured to prefer 7172 // 64 bit apps will see a 64 bit primary ABI, 7173 7174 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7175 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7176 } 7177 7178 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7179 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7180 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7181 } else { 7182 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7183 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7184 } 7185 } else { 7186 pkg.applicationInfo.primaryCpuAbi = null; 7187 pkg.applicationInfo.secondaryCpuAbi = null; 7188 } 7189 } 7190 7191 private void killApplication(String pkgName, int appId, String reason) { 7192 // Request the ActivityManager to kill the process(only for existing packages) 7193 // so that we do not end up in a confused state while the user is still using the older 7194 // version of the application while the new one gets installed. 7195 IActivityManager am = ActivityManagerNative.getDefault(); 7196 if (am != null) { 7197 try { 7198 am.killApplicationWithAppId(pkgName, appId, reason); 7199 } catch (RemoteException e) { 7200 } 7201 } 7202 } 7203 7204 void removePackageLI(PackageSetting ps, boolean chatty) { 7205 if (DEBUG_INSTALL) { 7206 if (chatty) 7207 Log.d(TAG, "Removing package " + ps.name); 7208 } 7209 7210 // writer 7211 synchronized (mPackages) { 7212 mPackages.remove(ps.name); 7213 final PackageParser.Package pkg = ps.pkg; 7214 if (pkg != null) { 7215 cleanPackageDataStructuresLILPw(pkg, chatty); 7216 } 7217 } 7218 } 7219 7220 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7221 if (DEBUG_INSTALL) { 7222 if (chatty) 7223 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7224 } 7225 7226 // writer 7227 synchronized (mPackages) { 7228 mPackages.remove(pkg.applicationInfo.packageName); 7229 cleanPackageDataStructuresLILPw(pkg, chatty); 7230 } 7231 } 7232 7233 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7234 int N = pkg.providers.size(); 7235 StringBuilder r = null; 7236 int i; 7237 for (i=0; i<N; i++) { 7238 PackageParser.Provider p = pkg.providers.get(i); 7239 mProviders.removeProvider(p); 7240 if (p.info.authority == null) { 7241 7242 /* There was another ContentProvider with this authority when 7243 * this app was installed so this authority is null, 7244 * Ignore it as we don't have to unregister the provider. 7245 */ 7246 continue; 7247 } 7248 String names[] = p.info.authority.split(";"); 7249 for (int j = 0; j < names.length; j++) { 7250 if (mProvidersByAuthority.get(names[j]) == p) { 7251 mProvidersByAuthority.remove(names[j]); 7252 if (DEBUG_REMOVE) { 7253 if (chatty) 7254 Log.d(TAG, "Unregistered content provider: " + names[j] 7255 + ", className = " + p.info.name + ", isSyncable = " 7256 + p.info.isSyncable); 7257 } 7258 } 7259 } 7260 if (DEBUG_REMOVE && chatty) { 7261 if (r == null) { 7262 r = new StringBuilder(256); 7263 } else { 7264 r.append(' '); 7265 } 7266 r.append(p.info.name); 7267 } 7268 } 7269 if (r != null) { 7270 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7271 } 7272 7273 N = pkg.services.size(); 7274 r = null; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Service s = pkg.services.get(i); 7277 mServices.removeService(s); 7278 if (chatty) { 7279 if (r == null) { 7280 r = new StringBuilder(256); 7281 } else { 7282 r.append(' '); 7283 } 7284 r.append(s.info.name); 7285 } 7286 } 7287 if (r != null) { 7288 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7289 } 7290 7291 N = pkg.receivers.size(); 7292 r = null; 7293 for (i=0; i<N; i++) { 7294 PackageParser.Activity a = pkg.receivers.get(i); 7295 mReceivers.removeActivity(a, "receiver"); 7296 if (DEBUG_REMOVE && chatty) { 7297 if (r == null) { 7298 r = new StringBuilder(256); 7299 } else { 7300 r.append(' '); 7301 } 7302 r.append(a.info.name); 7303 } 7304 } 7305 if (r != null) { 7306 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7307 } 7308 7309 N = pkg.activities.size(); 7310 r = null; 7311 for (i=0; i<N; i++) { 7312 PackageParser.Activity a = pkg.activities.get(i); 7313 mActivities.removeActivity(a, "activity"); 7314 if (DEBUG_REMOVE && chatty) { 7315 if (r == null) { 7316 r = new StringBuilder(256); 7317 } else { 7318 r.append(' '); 7319 } 7320 r.append(a.info.name); 7321 } 7322 } 7323 if (r != null) { 7324 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7325 } 7326 7327 N = pkg.permissions.size(); 7328 r = null; 7329 for (i=0; i<N; i++) { 7330 PackageParser.Permission p = pkg.permissions.get(i); 7331 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7332 if (bp == null) { 7333 bp = mSettings.mPermissionTrees.get(p.info.name); 7334 } 7335 if (bp != null && bp.perm == p) { 7336 bp.perm = null; 7337 if (DEBUG_REMOVE && chatty) { 7338 if (r == null) { 7339 r = new StringBuilder(256); 7340 } else { 7341 r.append(' '); 7342 } 7343 r.append(p.info.name); 7344 } 7345 } 7346 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7347 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7348 if (appOpPerms != null) { 7349 appOpPerms.remove(pkg.packageName); 7350 } 7351 } 7352 } 7353 if (r != null) { 7354 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7355 } 7356 7357 N = pkg.requestedPermissions.size(); 7358 r = null; 7359 for (i=0; i<N; i++) { 7360 String perm = pkg.requestedPermissions.get(i); 7361 BasePermission bp = mSettings.mPermissions.get(perm); 7362 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7363 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7364 if (appOpPerms != null) { 7365 appOpPerms.remove(pkg.packageName); 7366 if (appOpPerms.isEmpty()) { 7367 mAppOpPermissionPackages.remove(perm); 7368 } 7369 } 7370 } 7371 } 7372 if (r != null) { 7373 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7374 } 7375 7376 N = pkg.instrumentation.size(); 7377 r = null; 7378 for (i=0; i<N; i++) { 7379 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7380 mInstrumentation.remove(a.getComponentName()); 7381 if (DEBUG_REMOVE && chatty) { 7382 if (r == null) { 7383 r = new StringBuilder(256); 7384 } else { 7385 r.append(' '); 7386 } 7387 r.append(a.info.name); 7388 } 7389 } 7390 if (r != null) { 7391 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7392 } 7393 7394 r = null; 7395 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7396 // Only system apps can hold shared libraries. 7397 if (pkg.libraryNames != null) { 7398 for (i=0; i<pkg.libraryNames.size(); i++) { 7399 String name = pkg.libraryNames.get(i); 7400 SharedLibraryEntry cur = mSharedLibraries.get(name); 7401 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7402 mSharedLibraries.remove(name); 7403 if (DEBUG_REMOVE && chatty) { 7404 if (r == null) { 7405 r = new StringBuilder(256); 7406 } else { 7407 r.append(' '); 7408 } 7409 r.append(name); 7410 } 7411 } 7412 } 7413 } 7414 } 7415 if (r != null) { 7416 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7417 } 7418 } 7419 7420 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7421 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7422 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7423 return true; 7424 } 7425 } 7426 return false; 7427 } 7428 7429 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7430 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7431 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7432 7433 private void updatePermissionsLPw(String changingPkg, 7434 PackageParser.Package pkgInfo, int flags) { 7435 // Make sure there are no dangling permission trees. 7436 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7437 while (it.hasNext()) { 7438 final BasePermission bp = it.next(); 7439 if (bp.packageSetting == null) { 7440 // We may not yet have parsed the package, so just see if 7441 // we still know about its settings. 7442 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7443 } 7444 if (bp.packageSetting == null) { 7445 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7446 + " from package " + bp.sourcePackage); 7447 it.remove(); 7448 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7449 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7450 Slog.i(TAG, "Removing old permission tree: " + bp.name 7451 + " from package " + bp.sourcePackage); 7452 flags |= UPDATE_PERMISSIONS_ALL; 7453 it.remove(); 7454 } 7455 } 7456 } 7457 7458 // Make sure all dynamic permissions have been assigned to a package, 7459 // and make sure there are no dangling permissions. 7460 it = mSettings.mPermissions.values().iterator(); 7461 while (it.hasNext()) { 7462 final BasePermission bp = it.next(); 7463 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7464 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7465 + bp.name + " pkg=" + bp.sourcePackage 7466 + " info=" + bp.pendingInfo); 7467 if (bp.packageSetting == null && bp.pendingInfo != null) { 7468 final BasePermission tree = findPermissionTreeLP(bp.name); 7469 if (tree != null && tree.perm != null) { 7470 bp.packageSetting = tree.packageSetting; 7471 bp.perm = new PackageParser.Permission(tree.perm.owner, 7472 new PermissionInfo(bp.pendingInfo)); 7473 bp.perm.info.packageName = tree.perm.info.packageName; 7474 bp.perm.info.name = bp.name; 7475 bp.uid = tree.uid; 7476 } 7477 } 7478 } 7479 if (bp.packageSetting == null) { 7480 // We may not yet have parsed the package, so just see if 7481 // we still know about its settings. 7482 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7483 } 7484 if (bp.packageSetting == null) { 7485 Slog.w(TAG, "Removing dangling permission: " + bp.name 7486 + " from package " + bp.sourcePackage); 7487 it.remove(); 7488 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7489 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7490 Slog.i(TAG, "Removing old permission: " + bp.name 7491 + " from package " + bp.sourcePackage); 7492 flags |= UPDATE_PERMISSIONS_ALL; 7493 it.remove(); 7494 } 7495 } 7496 } 7497 7498 // Now update the permissions for all packages, in particular 7499 // replace the granted permissions of the system packages. 7500 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7501 for (PackageParser.Package pkg : mPackages.values()) { 7502 if (pkg != pkgInfo) { 7503 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7504 changingPkg); 7505 } 7506 } 7507 } 7508 7509 if (pkgInfo != null) { 7510 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7511 } 7512 } 7513 7514 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7515 String packageOfInterest) { 7516 // IMPORTANT: There are two types of permissions: install and runtime. 7517 // Install time permissions are granted when the app is installed to 7518 // all device users and users added in the future. Runtime permissions 7519 // are granted at runtime explicitly to specific users. Normal and signature 7520 // protected permissions are install time permissions. Dangerous permissions 7521 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7522 // otherwise they are runtime permissions. This function does not manage 7523 // runtime permissions except for the case an app targeting Lollipop MR1 7524 // being upgraded to target a newer SDK, in which case dangerous permissions 7525 // are transformed from install time to runtime ones. 7526 7527 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7528 if (ps == null) { 7529 return; 7530 } 7531 7532 PermissionsState permissionsState = ps.getPermissionsState(); 7533 PermissionsState origPermissions = permissionsState; 7534 7535 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7536 7537 int[] upgradeUserIds = PermissionsState.USERS_NONE; 7538 int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE; 7539 7540 boolean changedInstallPermission = false; 7541 7542 if (replace) { 7543 ps.installPermissionsFixed = false; 7544 if (!ps.isSharedUser()) { 7545 origPermissions = new PermissionsState(permissionsState); 7546 permissionsState.reset(); 7547 } 7548 } 7549 7550 permissionsState.setGlobalGids(mGlobalGids); 7551 7552 final int N = pkg.requestedPermissions.size(); 7553 for (int i=0; i<N; i++) { 7554 final String name = pkg.requestedPermissions.get(i); 7555 final BasePermission bp = mSettings.mPermissions.get(name); 7556 7557 if (DEBUG_INSTALL) { 7558 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7559 } 7560 7561 if (bp == null || bp.packageSetting == null) { 7562 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7563 Slog.w(TAG, "Unknown permission " + name 7564 + " in package " + pkg.packageName); 7565 } 7566 continue; 7567 } 7568 7569 final String perm = bp.name; 7570 boolean allowedSig = false; 7571 int grant = GRANT_DENIED; 7572 7573 // Keep track of app op permissions. 7574 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7575 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7576 if (pkgs == null) { 7577 pkgs = new ArraySet<>(); 7578 mAppOpPermissionPackages.put(bp.name, pkgs); 7579 } 7580 pkgs.add(pkg.packageName); 7581 } 7582 7583 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7584 switch (level) { 7585 case PermissionInfo.PROTECTION_NORMAL: { 7586 // For all apps normal permissions are install time ones. 7587 grant = GRANT_INSTALL; 7588 } break; 7589 7590 case PermissionInfo.PROTECTION_DANGEROUS: { 7591 if (!RUNTIME_PERMISSIONS_ENABLED 7592 || pkg.applicationInfo.targetSdkVersion 7593 <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7594 // For legacy apps dangerous permissions are install time ones. 7595 grant = GRANT_INSTALL; 7596 } else if (ps.isSystem()) { 7597 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7598 if (origPermissions.hasInstallPermission(bp.name)) { 7599 // If a system app had an install permission, then the app was 7600 // upgraded and we grant the permissions as runtime to all users. 7601 grant = GRANT_UPGRADE; 7602 upgradeUserIds = currentUserIds; 7603 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7604 // If users changed since the last permissions update for a 7605 // system app, we grant the permission as runtime to the new users. 7606 grant = GRANT_UPGRADE; 7607 upgradeUserIds = currentUserIds; 7608 for (int userId : updatedUserIds) { 7609 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7610 } 7611 } else { 7612 // Otherwise, we grant the permission as runtime if the app 7613 // already had it, i.e. we preserve runtime permissions. 7614 grant = GRANT_RUNTIME; 7615 } 7616 } else if (origPermissions.hasInstallPermission(bp.name)) { 7617 // For legacy apps that became modern, install becomes runtime. 7618 grant = GRANT_UPGRADE; 7619 upgradeUserIds = currentUserIds; 7620 } else if (replace) { 7621 // For upgraded modern apps keep runtime permissions unchanged. 7622 grant = GRANT_RUNTIME; 7623 } 7624 } break; 7625 7626 case PermissionInfo.PROTECTION_SIGNATURE: { 7627 // For all apps signature permissions are install time ones. 7628 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7629 if (allowedSig) { 7630 grant = GRANT_INSTALL; 7631 } 7632 } break; 7633 } 7634 7635 if (DEBUG_INSTALL) { 7636 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7637 } 7638 7639 if (grant != GRANT_DENIED) { 7640 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7641 // If this is an existing, non-system package, then 7642 // we can't add any new permissions to it. 7643 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7644 // Except... if this is a permission that was added 7645 // to the platform (note: need to only do this when 7646 // updating the platform). 7647 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7648 grant = GRANT_DENIED; 7649 } 7650 } 7651 } 7652 7653 switch (grant) { 7654 case GRANT_INSTALL: { 7655 // Grant an install permission. 7656 if (permissionsState.grantInstallPermission(bp) != 7657 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7658 changedInstallPermission = true; 7659 } 7660 } break; 7661 7662 case GRANT_RUNTIME: { 7663 // Grant previously granted runtime permissions. 7664 for (int userId : UserManagerService.getInstance().getUserIds()) { 7665 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7666 if (permissionsState.grantRuntimePermission(bp, userId) == 7667 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7668 // If we cannot put the permission as it was, we have to write. 7669 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7670 changedRuntimePermissionUserIds, userId); 7671 } 7672 } 7673 } 7674 } break; 7675 7676 case GRANT_UPGRADE: { 7677 // Grant runtime permissions for a previously held install permission. 7678 permissionsState.revokeInstallPermission(bp); 7679 for (int userId : upgradeUserIds) { 7680 if (permissionsState.grantRuntimePermission(bp, userId) != 7681 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7682 // If we granted the permission, we have to write. 7683 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7684 changedRuntimePermissionUserIds, userId); 7685 } 7686 } 7687 } break; 7688 7689 default: { 7690 if (packageOfInterest == null 7691 || packageOfInterest.equals(pkg.packageName)) { 7692 Slog.w(TAG, "Not granting permission " + perm 7693 + " to package " + pkg.packageName 7694 + " because it was previously installed without"); 7695 } 7696 } break; 7697 } 7698 } else { 7699 if (permissionsState.revokeInstallPermission(bp) != 7700 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7701 changedInstallPermission = true; 7702 Slog.i(TAG, "Un-granting permission " + perm 7703 + " from package " + pkg.packageName 7704 + " (protectionLevel=" + bp.protectionLevel 7705 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7706 + ")"); 7707 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7708 // Don't print warning for app op permissions, since it is fine for them 7709 // not to be granted, there is a UI for the user to decide. 7710 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7711 Slog.w(TAG, "Not granting permission " + perm 7712 + " to package " + pkg.packageName 7713 + " (protectionLevel=" + bp.protectionLevel 7714 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7715 + ")"); 7716 } 7717 } 7718 } 7719 } 7720 7721 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7722 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7723 // This is the first that we have heard about this package, so the 7724 // permissions we have now selected are fixed until explicitly 7725 // changed. 7726 ps.installPermissionsFixed = true; 7727 } 7728 7729 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7730 7731 // Persist the runtime permissions state for users with changes. 7732 if (RUNTIME_PERMISSIONS_ENABLED) { 7733 for (int userId : changedRuntimePermissionUserIds) { 7734 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7735 } 7736 } 7737 } 7738 7739 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7740 boolean allowed = false; 7741 final int NP = PackageParser.NEW_PERMISSIONS.length; 7742 for (int ip=0; ip<NP; ip++) { 7743 final PackageParser.NewPermissionInfo npi 7744 = PackageParser.NEW_PERMISSIONS[ip]; 7745 if (npi.name.equals(perm) 7746 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7747 allowed = true; 7748 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7749 + pkg.packageName); 7750 break; 7751 } 7752 } 7753 return allowed; 7754 } 7755 7756 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7757 BasePermission bp, PermissionsState origPermissions) { 7758 boolean allowed; 7759 allowed = (compareSignatures( 7760 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7761 == PackageManager.SIGNATURE_MATCH) 7762 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7763 == PackageManager.SIGNATURE_MATCH); 7764 if (!allowed && (bp.protectionLevel 7765 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7766 if (isSystemApp(pkg)) { 7767 // For updated system applications, a system permission 7768 // is granted only if it had been defined by the original application. 7769 if (pkg.isUpdatedSystemApp()) { 7770 final PackageSetting sysPs = mSettings 7771 .getDisabledSystemPkgLPr(pkg.packageName); 7772 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7773 // If the original was granted this permission, we take 7774 // that grant decision as read and propagate it to the 7775 // update. 7776 if (sysPs.isPrivileged()) { 7777 allowed = true; 7778 } 7779 } else { 7780 // The system apk may have been updated with an older 7781 // version of the one on the data partition, but which 7782 // granted a new system permission that it didn't have 7783 // before. In this case we do want to allow the app to 7784 // now get the new permission if the ancestral apk is 7785 // privileged to get it. 7786 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7787 for (int j=0; 7788 j<sysPs.pkg.requestedPermissions.size(); j++) { 7789 if (perm.equals( 7790 sysPs.pkg.requestedPermissions.get(j))) { 7791 allowed = true; 7792 break; 7793 } 7794 } 7795 } 7796 } 7797 } else { 7798 allowed = isPrivilegedApp(pkg); 7799 } 7800 } 7801 } 7802 if (!allowed && (bp.protectionLevel 7803 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7804 // For development permissions, a development permission 7805 // is granted only if it was already granted. 7806 allowed = origPermissions.hasInstallPermission(perm); 7807 } 7808 return allowed; 7809 } 7810 7811 final class ActivityIntentResolver 7812 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7813 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7814 boolean defaultOnly, int userId) { 7815 if (!sUserManager.exists(userId)) return null; 7816 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7817 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7818 } 7819 7820 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7821 int userId) { 7822 if (!sUserManager.exists(userId)) return null; 7823 mFlags = flags; 7824 return super.queryIntent(intent, resolvedType, 7825 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7826 } 7827 7828 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7829 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7830 if (!sUserManager.exists(userId)) return null; 7831 if (packageActivities == null) { 7832 return null; 7833 } 7834 mFlags = flags; 7835 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7836 final int N = packageActivities.size(); 7837 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7838 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7839 7840 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7841 for (int i = 0; i < N; ++i) { 7842 intentFilters = packageActivities.get(i).intents; 7843 if (intentFilters != null && intentFilters.size() > 0) { 7844 PackageParser.ActivityIntentInfo[] array = 7845 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7846 intentFilters.toArray(array); 7847 listCut.add(array); 7848 } 7849 } 7850 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7851 } 7852 7853 public final void addActivity(PackageParser.Activity a, String type) { 7854 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7855 mActivities.put(a.getComponentName(), a); 7856 if (DEBUG_SHOW_INFO) 7857 Log.v( 7858 TAG, " " + type + " " + 7859 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7860 if (DEBUG_SHOW_INFO) 7861 Log.v(TAG, " Class=" + a.info.name); 7862 final int NI = a.intents.size(); 7863 for (int j=0; j<NI; j++) { 7864 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7865 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7866 intent.setPriority(0); 7867 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7868 + a.className + " with priority > 0, forcing to 0"); 7869 } 7870 if (DEBUG_SHOW_INFO) { 7871 Log.v(TAG, " IntentFilter:"); 7872 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7873 } 7874 if (!intent.debugCheck()) { 7875 Log.w(TAG, "==> For Activity " + a.info.name); 7876 } 7877 addFilter(intent); 7878 } 7879 } 7880 7881 public final void removeActivity(PackageParser.Activity a, String type) { 7882 mActivities.remove(a.getComponentName()); 7883 if (DEBUG_SHOW_INFO) { 7884 Log.v(TAG, " " + type + " " 7885 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7886 : a.info.name) + ":"); 7887 Log.v(TAG, " Class=" + a.info.name); 7888 } 7889 final int NI = a.intents.size(); 7890 for (int j=0; j<NI; j++) { 7891 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7892 if (DEBUG_SHOW_INFO) { 7893 Log.v(TAG, " IntentFilter:"); 7894 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7895 } 7896 removeFilter(intent); 7897 } 7898 } 7899 7900 @Override 7901 protected boolean allowFilterResult( 7902 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7903 ActivityInfo filterAi = filter.activity.info; 7904 for (int i=dest.size()-1; i>=0; i--) { 7905 ActivityInfo destAi = dest.get(i).activityInfo; 7906 if (destAi.name == filterAi.name 7907 && destAi.packageName == filterAi.packageName) { 7908 return false; 7909 } 7910 } 7911 return true; 7912 } 7913 7914 @Override 7915 protected ActivityIntentInfo[] newArray(int size) { 7916 return new ActivityIntentInfo[size]; 7917 } 7918 7919 @Override 7920 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7921 if (!sUserManager.exists(userId)) return true; 7922 PackageParser.Package p = filter.activity.owner; 7923 if (p != null) { 7924 PackageSetting ps = (PackageSetting)p.mExtras; 7925 if (ps != null) { 7926 // System apps are never considered stopped for purposes of 7927 // filtering, because there may be no way for the user to 7928 // actually re-launch them. 7929 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7930 && ps.getStopped(userId); 7931 } 7932 } 7933 return false; 7934 } 7935 7936 @Override 7937 protected boolean isPackageForFilter(String packageName, 7938 PackageParser.ActivityIntentInfo info) { 7939 return packageName.equals(info.activity.owner.packageName); 7940 } 7941 7942 @Override 7943 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7944 int match, int userId) { 7945 if (!sUserManager.exists(userId)) return null; 7946 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7947 return null; 7948 } 7949 final PackageParser.Activity activity = info.activity; 7950 if (mSafeMode && (activity.info.applicationInfo.flags 7951 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7952 return null; 7953 } 7954 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7955 if (ps == null) { 7956 return null; 7957 } 7958 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7959 ps.readUserState(userId), userId); 7960 if (ai == null) { 7961 return null; 7962 } 7963 final ResolveInfo res = new ResolveInfo(); 7964 res.activityInfo = ai; 7965 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7966 res.filter = info; 7967 } 7968 if (info != null) { 7969 res.handleAllWebDataURI = info.handleAllWebDataURI(); 7970 } 7971 res.priority = info.getPriority(); 7972 res.preferredOrder = activity.owner.mPreferredOrder; 7973 //System.out.println("Result: " + res.activityInfo.className + 7974 // " = " + res.priority); 7975 res.match = match; 7976 res.isDefault = info.hasDefault; 7977 res.labelRes = info.labelRes; 7978 res.nonLocalizedLabel = info.nonLocalizedLabel; 7979 if (userNeedsBadging(userId)) { 7980 res.noResourceId = true; 7981 } else { 7982 res.icon = info.icon; 7983 } 7984 res.system = res.activityInfo.applicationInfo.isSystemApp(); 7985 return res; 7986 } 7987 7988 @Override 7989 protected void sortResults(List<ResolveInfo> results) { 7990 Collections.sort(results, mResolvePrioritySorter); 7991 } 7992 7993 @Override 7994 protected void dumpFilter(PrintWriter out, String prefix, 7995 PackageParser.ActivityIntentInfo filter) { 7996 out.print(prefix); out.print( 7997 Integer.toHexString(System.identityHashCode(filter.activity))); 7998 out.print(' '); 7999 filter.activity.printComponentShortName(out); 8000 out.print(" filter "); 8001 out.println(Integer.toHexString(System.identityHashCode(filter))); 8002 } 8003 8004 @Override 8005 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8006 return filter.activity; 8007 } 8008 8009 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8010 PackageParser.Activity activity = (PackageParser.Activity)label; 8011 out.print(prefix); out.print( 8012 Integer.toHexString(System.identityHashCode(activity))); 8013 out.print(' '); 8014 activity.printComponentShortName(out); 8015 if (count > 1) { 8016 out.print(" ("); out.print(count); out.print(" filters)"); 8017 } 8018 out.println(); 8019 } 8020 8021// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8022// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8023// final List<ResolveInfo> retList = Lists.newArrayList(); 8024// while (i.hasNext()) { 8025// final ResolveInfo resolveInfo = i.next(); 8026// if (isEnabledLP(resolveInfo.activityInfo)) { 8027// retList.add(resolveInfo); 8028// } 8029// } 8030// return retList; 8031// } 8032 8033 // Keys are String (activity class name), values are Activity. 8034 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8035 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8036 private int mFlags; 8037 } 8038 8039 private final class ServiceIntentResolver 8040 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8041 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8042 boolean defaultOnly, int userId) { 8043 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8044 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8045 } 8046 8047 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8048 int userId) { 8049 if (!sUserManager.exists(userId)) return null; 8050 mFlags = flags; 8051 return super.queryIntent(intent, resolvedType, 8052 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8053 } 8054 8055 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8056 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8057 if (!sUserManager.exists(userId)) return null; 8058 if (packageServices == null) { 8059 return null; 8060 } 8061 mFlags = flags; 8062 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8063 final int N = packageServices.size(); 8064 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8065 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8066 8067 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8068 for (int i = 0; i < N; ++i) { 8069 intentFilters = packageServices.get(i).intents; 8070 if (intentFilters != null && intentFilters.size() > 0) { 8071 PackageParser.ServiceIntentInfo[] array = 8072 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8073 intentFilters.toArray(array); 8074 listCut.add(array); 8075 } 8076 } 8077 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8078 } 8079 8080 public final void addService(PackageParser.Service s) { 8081 mServices.put(s.getComponentName(), s); 8082 if (DEBUG_SHOW_INFO) { 8083 Log.v(TAG, " " 8084 + (s.info.nonLocalizedLabel != null 8085 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8086 Log.v(TAG, " Class=" + s.info.name); 8087 } 8088 final int NI = s.intents.size(); 8089 int j; 8090 for (j=0; j<NI; j++) { 8091 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8092 if (DEBUG_SHOW_INFO) { 8093 Log.v(TAG, " IntentFilter:"); 8094 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8095 } 8096 if (!intent.debugCheck()) { 8097 Log.w(TAG, "==> For Service " + s.info.name); 8098 } 8099 addFilter(intent); 8100 } 8101 } 8102 8103 public final void removeService(PackageParser.Service s) { 8104 mServices.remove(s.getComponentName()); 8105 if (DEBUG_SHOW_INFO) { 8106 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8107 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8108 Log.v(TAG, " Class=" + s.info.name); 8109 } 8110 final int NI = s.intents.size(); 8111 int j; 8112 for (j=0; j<NI; j++) { 8113 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8114 if (DEBUG_SHOW_INFO) { 8115 Log.v(TAG, " IntentFilter:"); 8116 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8117 } 8118 removeFilter(intent); 8119 } 8120 } 8121 8122 @Override 8123 protected boolean allowFilterResult( 8124 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8125 ServiceInfo filterSi = filter.service.info; 8126 for (int i=dest.size()-1; i>=0; i--) { 8127 ServiceInfo destAi = dest.get(i).serviceInfo; 8128 if (destAi.name == filterSi.name 8129 && destAi.packageName == filterSi.packageName) { 8130 return false; 8131 } 8132 } 8133 return true; 8134 } 8135 8136 @Override 8137 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8138 return new PackageParser.ServiceIntentInfo[size]; 8139 } 8140 8141 @Override 8142 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8143 if (!sUserManager.exists(userId)) return true; 8144 PackageParser.Package p = filter.service.owner; 8145 if (p != null) { 8146 PackageSetting ps = (PackageSetting)p.mExtras; 8147 if (ps != null) { 8148 // System apps are never considered stopped for purposes of 8149 // filtering, because there may be no way for the user to 8150 // actually re-launch them. 8151 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8152 && ps.getStopped(userId); 8153 } 8154 } 8155 return false; 8156 } 8157 8158 @Override 8159 protected boolean isPackageForFilter(String packageName, 8160 PackageParser.ServiceIntentInfo info) { 8161 return packageName.equals(info.service.owner.packageName); 8162 } 8163 8164 @Override 8165 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8166 int match, int userId) { 8167 if (!sUserManager.exists(userId)) return null; 8168 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8169 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8170 return null; 8171 } 8172 final PackageParser.Service service = info.service; 8173 if (mSafeMode && (service.info.applicationInfo.flags 8174 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8175 return null; 8176 } 8177 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8178 if (ps == null) { 8179 return null; 8180 } 8181 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8182 ps.readUserState(userId), userId); 8183 if (si == null) { 8184 return null; 8185 } 8186 final ResolveInfo res = new ResolveInfo(); 8187 res.serviceInfo = si; 8188 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8189 res.filter = filter; 8190 } 8191 res.priority = info.getPriority(); 8192 res.preferredOrder = service.owner.mPreferredOrder; 8193 res.match = match; 8194 res.isDefault = info.hasDefault; 8195 res.labelRes = info.labelRes; 8196 res.nonLocalizedLabel = info.nonLocalizedLabel; 8197 res.icon = info.icon; 8198 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8199 return res; 8200 } 8201 8202 @Override 8203 protected void sortResults(List<ResolveInfo> results) { 8204 Collections.sort(results, mResolvePrioritySorter); 8205 } 8206 8207 @Override 8208 protected void dumpFilter(PrintWriter out, String prefix, 8209 PackageParser.ServiceIntentInfo filter) { 8210 out.print(prefix); out.print( 8211 Integer.toHexString(System.identityHashCode(filter.service))); 8212 out.print(' '); 8213 filter.service.printComponentShortName(out); 8214 out.print(" filter "); 8215 out.println(Integer.toHexString(System.identityHashCode(filter))); 8216 } 8217 8218 @Override 8219 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8220 return filter.service; 8221 } 8222 8223 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8224 PackageParser.Service service = (PackageParser.Service)label; 8225 out.print(prefix); out.print( 8226 Integer.toHexString(System.identityHashCode(service))); 8227 out.print(' '); 8228 service.printComponentShortName(out); 8229 if (count > 1) { 8230 out.print(" ("); out.print(count); out.print(" filters)"); 8231 } 8232 out.println(); 8233 } 8234 8235// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8236// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8237// final List<ResolveInfo> retList = Lists.newArrayList(); 8238// while (i.hasNext()) { 8239// final ResolveInfo resolveInfo = (ResolveInfo) i; 8240// if (isEnabledLP(resolveInfo.serviceInfo)) { 8241// retList.add(resolveInfo); 8242// } 8243// } 8244// return retList; 8245// } 8246 8247 // Keys are String (activity class name), values are Activity. 8248 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8249 = new ArrayMap<ComponentName, PackageParser.Service>(); 8250 private int mFlags; 8251 }; 8252 8253 private final class ProviderIntentResolver 8254 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8255 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8256 boolean defaultOnly, int userId) { 8257 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8258 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8259 } 8260 8261 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8262 int userId) { 8263 if (!sUserManager.exists(userId)) 8264 return null; 8265 mFlags = flags; 8266 return super.queryIntent(intent, resolvedType, 8267 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8268 } 8269 8270 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8271 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8272 if (!sUserManager.exists(userId)) 8273 return null; 8274 if (packageProviders == null) { 8275 return null; 8276 } 8277 mFlags = flags; 8278 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8279 final int N = packageProviders.size(); 8280 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8281 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8282 8283 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8284 for (int i = 0; i < N; ++i) { 8285 intentFilters = packageProviders.get(i).intents; 8286 if (intentFilters != null && intentFilters.size() > 0) { 8287 PackageParser.ProviderIntentInfo[] array = 8288 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8289 intentFilters.toArray(array); 8290 listCut.add(array); 8291 } 8292 } 8293 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8294 } 8295 8296 public final void addProvider(PackageParser.Provider p) { 8297 if (mProviders.containsKey(p.getComponentName())) { 8298 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8299 return; 8300 } 8301 8302 mProviders.put(p.getComponentName(), p); 8303 if (DEBUG_SHOW_INFO) { 8304 Log.v(TAG, " " 8305 + (p.info.nonLocalizedLabel != null 8306 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8307 Log.v(TAG, " Class=" + p.info.name); 8308 } 8309 final int NI = p.intents.size(); 8310 int j; 8311 for (j = 0; j < NI; j++) { 8312 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8313 if (DEBUG_SHOW_INFO) { 8314 Log.v(TAG, " IntentFilter:"); 8315 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8316 } 8317 if (!intent.debugCheck()) { 8318 Log.w(TAG, "==> For Provider " + p.info.name); 8319 } 8320 addFilter(intent); 8321 } 8322 } 8323 8324 public final void removeProvider(PackageParser.Provider p) { 8325 mProviders.remove(p.getComponentName()); 8326 if (DEBUG_SHOW_INFO) { 8327 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8328 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8329 Log.v(TAG, " Class=" + p.info.name); 8330 } 8331 final int NI = p.intents.size(); 8332 int j; 8333 for (j = 0; j < NI; j++) { 8334 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8335 if (DEBUG_SHOW_INFO) { 8336 Log.v(TAG, " IntentFilter:"); 8337 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8338 } 8339 removeFilter(intent); 8340 } 8341 } 8342 8343 @Override 8344 protected boolean allowFilterResult( 8345 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8346 ProviderInfo filterPi = filter.provider.info; 8347 for (int i = dest.size() - 1; i >= 0; i--) { 8348 ProviderInfo destPi = dest.get(i).providerInfo; 8349 if (destPi.name == filterPi.name 8350 && destPi.packageName == filterPi.packageName) { 8351 return false; 8352 } 8353 } 8354 return true; 8355 } 8356 8357 @Override 8358 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8359 return new PackageParser.ProviderIntentInfo[size]; 8360 } 8361 8362 @Override 8363 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8364 if (!sUserManager.exists(userId)) 8365 return true; 8366 PackageParser.Package p = filter.provider.owner; 8367 if (p != null) { 8368 PackageSetting ps = (PackageSetting) p.mExtras; 8369 if (ps != null) { 8370 // System apps are never considered stopped for purposes of 8371 // filtering, because there may be no way for the user to 8372 // actually re-launch them. 8373 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8374 && ps.getStopped(userId); 8375 } 8376 } 8377 return false; 8378 } 8379 8380 @Override 8381 protected boolean isPackageForFilter(String packageName, 8382 PackageParser.ProviderIntentInfo info) { 8383 return packageName.equals(info.provider.owner.packageName); 8384 } 8385 8386 @Override 8387 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8388 int match, int userId) { 8389 if (!sUserManager.exists(userId)) 8390 return null; 8391 final PackageParser.ProviderIntentInfo info = filter; 8392 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8393 return null; 8394 } 8395 final PackageParser.Provider provider = info.provider; 8396 if (mSafeMode && (provider.info.applicationInfo.flags 8397 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8398 return null; 8399 } 8400 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8401 if (ps == null) { 8402 return null; 8403 } 8404 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8405 ps.readUserState(userId), userId); 8406 if (pi == null) { 8407 return null; 8408 } 8409 final ResolveInfo res = new ResolveInfo(); 8410 res.providerInfo = pi; 8411 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8412 res.filter = filter; 8413 } 8414 res.priority = info.getPriority(); 8415 res.preferredOrder = provider.owner.mPreferredOrder; 8416 res.match = match; 8417 res.isDefault = info.hasDefault; 8418 res.labelRes = info.labelRes; 8419 res.nonLocalizedLabel = info.nonLocalizedLabel; 8420 res.icon = info.icon; 8421 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8422 return res; 8423 } 8424 8425 @Override 8426 protected void sortResults(List<ResolveInfo> results) { 8427 Collections.sort(results, mResolvePrioritySorter); 8428 } 8429 8430 @Override 8431 protected void dumpFilter(PrintWriter out, String prefix, 8432 PackageParser.ProviderIntentInfo filter) { 8433 out.print(prefix); 8434 out.print( 8435 Integer.toHexString(System.identityHashCode(filter.provider))); 8436 out.print(' '); 8437 filter.provider.printComponentShortName(out); 8438 out.print(" filter "); 8439 out.println(Integer.toHexString(System.identityHashCode(filter))); 8440 } 8441 8442 @Override 8443 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8444 return filter.provider; 8445 } 8446 8447 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8448 PackageParser.Provider provider = (PackageParser.Provider)label; 8449 out.print(prefix); out.print( 8450 Integer.toHexString(System.identityHashCode(provider))); 8451 out.print(' '); 8452 provider.printComponentShortName(out); 8453 if (count > 1) { 8454 out.print(" ("); out.print(count); out.print(" filters)"); 8455 } 8456 out.println(); 8457 } 8458 8459 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8460 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8461 private int mFlags; 8462 }; 8463 8464 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8465 new Comparator<ResolveInfo>() { 8466 public int compare(ResolveInfo r1, ResolveInfo r2) { 8467 int v1 = r1.priority; 8468 int v2 = r2.priority; 8469 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8470 if (v1 != v2) { 8471 return (v1 > v2) ? -1 : 1; 8472 } 8473 v1 = r1.preferredOrder; 8474 v2 = r2.preferredOrder; 8475 if (v1 != v2) { 8476 return (v1 > v2) ? -1 : 1; 8477 } 8478 if (r1.isDefault != r2.isDefault) { 8479 return r1.isDefault ? -1 : 1; 8480 } 8481 v1 = r1.match; 8482 v2 = r2.match; 8483 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8484 if (v1 != v2) { 8485 return (v1 > v2) ? -1 : 1; 8486 } 8487 if (r1.system != r2.system) { 8488 return r1.system ? -1 : 1; 8489 } 8490 return 0; 8491 } 8492 }; 8493 8494 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8495 new Comparator<ProviderInfo>() { 8496 public int compare(ProviderInfo p1, ProviderInfo p2) { 8497 final int v1 = p1.initOrder; 8498 final int v2 = p2.initOrder; 8499 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8500 } 8501 }; 8502 8503 final void sendPackageBroadcast(final String action, final String pkg, 8504 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8505 final int[] userIds) { 8506 mHandler.post(new Runnable() { 8507 @Override 8508 public void run() { 8509 try { 8510 final IActivityManager am = ActivityManagerNative.getDefault(); 8511 if (am == null) return; 8512 final int[] resolvedUserIds; 8513 if (userIds == null) { 8514 resolvedUserIds = am.getRunningUserIds(); 8515 } else { 8516 resolvedUserIds = userIds; 8517 } 8518 for (int id : resolvedUserIds) { 8519 final Intent intent = new Intent(action, 8520 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8521 if (extras != null) { 8522 intent.putExtras(extras); 8523 } 8524 if (targetPkg != null) { 8525 intent.setPackage(targetPkg); 8526 } 8527 // Modify the UID when posting to other users 8528 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8529 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8530 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8531 intent.putExtra(Intent.EXTRA_UID, uid); 8532 } 8533 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8534 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8535 if (DEBUG_BROADCASTS) { 8536 RuntimeException here = new RuntimeException("here"); 8537 here.fillInStackTrace(); 8538 Slog.d(TAG, "Sending to user " + id + ": " 8539 + intent.toShortString(false, true, false, false) 8540 + " " + intent.getExtras(), here); 8541 } 8542 am.broadcastIntent(null, intent, null, finishedReceiver, 8543 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8544 finishedReceiver != null, false, id); 8545 } 8546 } catch (RemoteException ex) { 8547 } 8548 } 8549 }); 8550 } 8551 8552 /** 8553 * Check if the external storage media is available. This is true if there 8554 * is a mounted external storage medium or if the external storage is 8555 * emulated. 8556 */ 8557 private boolean isExternalMediaAvailable() { 8558 return mMediaMounted || Environment.isExternalStorageEmulated(); 8559 } 8560 8561 @Override 8562 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8563 // writer 8564 synchronized (mPackages) { 8565 if (!isExternalMediaAvailable()) { 8566 // If the external storage is no longer mounted at this point, 8567 // the caller may not have been able to delete all of this 8568 // packages files and can not delete any more. Bail. 8569 return null; 8570 } 8571 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8572 if (lastPackage != null) { 8573 pkgs.remove(lastPackage); 8574 } 8575 if (pkgs.size() > 0) { 8576 return pkgs.get(0); 8577 } 8578 } 8579 return null; 8580 } 8581 8582 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8583 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8584 userId, andCode ? 1 : 0, packageName); 8585 if (mSystemReady) { 8586 msg.sendToTarget(); 8587 } else { 8588 if (mPostSystemReadyMessages == null) { 8589 mPostSystemReadyMessages = new ArrayList<>(); 8590 } 8591 mPostSystemReadyMessages.add(msg); 8592 } 8593 } 8594 8595 void startCleaningPackages() { 8596 // reader 8597 synchronized (mPackages) { 8598 if (!isExternalMediaAvailable()) { 8599 return; 8600 } 8601 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8602 return; 8603 } 8604 } 8605 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8606 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8607 IActivityManager am = ActivityManagerNative.getDefault(); 8608 if (am != null) { 8609 try { 8610 am.startService(null, intent, null, UserHandle.USER_OWNER); 8611 } catch (RemoteException e) { 8612 } 8613 } 8614 } 8615 8616 @Override 8617 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8618 int installFlags, String installerPackageName, VerificationParams verificationParams, 8619 String packageAbiOverride) { 8620 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8621 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8622 } 8623 8624 @Override 8625 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8626 int installFlags, String installerPackageName, VerificationParams verificationParams, 8627 String packageAbiOverride, int userId) { 8628 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8629 8630 final int callingUid = Binder.getCallingUid(); 8631 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8632 8633 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8634 try { 8635 if (observer != null) { 8636 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8637 } 8638 } catch (RemoteException re) { 8639 } 8640 return; 8641 } 8642 8643 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8644 installFlags |= PackageManager.INSTALL_FROM_ADB; 8645 8646 } else { 8647 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8648 // about installerPackageName. 8649 8650 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8651 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8652 } 8653 8654 UserHandle user; 8655 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8656 user = UserHandle.ALL; 8657 } else { 8658 user = new UserHandle(userId); 8659 } 8660 8661 // Only system components can circumvent runtime permissions when installing. 8662 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8663 && mContext.checkCallingOrSelfPermission(Manifest.permission 8664 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8665 throw new SecurityException("You need the " 8666 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8667 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8668 } 8669 8670 verificationParams.setInstallerUid(callingUid); 8671 8672 final File originFile = new File(originPath); 8673 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8674 8675 final Message msg = mHandler.obtainMessage(INIT_COPY); 8676 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8677 null, verificationParams, user, packageAbiOverride); 8678 mHandler.sendMessage(msg); 8679 } 8680 8681 void installStage(String packageName, File stagedDir, String stagedCid, 8682 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8683 String installerPackageName, int installerUid, UserHandle user) { 8684 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8685 params.referrerUri, installerUid, null); 8686 8687 final OriginInfo origin; 8688 if (stagedDir != null) { 8689 origin = OriginInfo.fromStagedFile(stagedDir); 8690 } else { 8691 origin = OriginInfo.fromStagedContainer(stagedCid); 8692 } 8693 8694 final Message msg = mHandler.obtainMessage(INIT_COPY); 8695 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8696 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8697 mHandler.sendMessage(msg); 8698 } 8699 8700 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8701 Bundle extras = new Bundle(1); 8702 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8703 8704 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8705 packageName, extras, null, null, new int[] {userId}); 8706 try { 8707 IActivityManager am = ActivityManagerNative.getDefault(); 8708 final boolean isSystem = 8709 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8710 if (isSystem && am.isUserRunning(userId, false)) { 8711 // The just-installed/enabled app is bundled on the system, so presumed 8712 // to be able to run automatically without needing an explicit launch. 8713 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8714 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8715 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8716 .setPackage(packageName); 8717 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8718 android.app.AppOpsManager.OP_NONE, false, false, userId); 8719 } 8720 } catch (RemoteException e) { 8721 // shouldn't happen 8722 Slog.w(TAG, "Unable to bootstrap installed package", e); 8723 } 8724 } 8725 8726 @Override 8727 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8728 int userId) { 8729 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8730 PackageSetting pkgSetting; 8731 final int uid = Binder.getCallingUid(); 8732 enforceCrossUserPermission(uid, userId, true, true, 8733 "setApplicationHiddenSetting for user " + userId); 8734 8735 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8736 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8737 return false; 8738 } 8739 8740 long callingId = Binder.clearCallingIdentity(); 8741 try { 8742 boolean sendAdded = false; 8743 boolean sendRemoved = false; 8744 // writer 8745 synchronized (mPackages) { 8746 pkgSetting = mSettings.mPackages.get(packageName); 8747 if (pkgSetting == null) { 8748 return false; 8749 } 8750 if (pkgSetting.getHidden(userId) != hidden) { 8751 pkgSetting.setHidden(hidden, userId); 8752 mSettings.writePackageRestrictionsLPr(userId); 8753 if (hidden) { 8754 sendRemoved = true; 8755 } else { 8756 sendAdded = true; 8757 } 8758 } 8759 } 8760 if (sendAdded) { 8761 sendPackageAddedForUser(packageName, pkgSetting, userId); 8762 return true; 8763 } 8764 if (sendRemoved) { 8765 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8766 "hiding pkg"); 8767 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8768 } 8769 } finally { 8770 Binder.restoreCallingIdentity(callingId); 8771 } 8772 return false; 8773 } 8774 8775 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8776 int userId) { 8777 final PackageRemovedInfo info = new PackageRemovedInfo(); 8778 info.removedPackage = packageName; 8779 info.removedUsers = new int[] {userId}; 8780 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8781 info.sendBroadcast(false, false, false); 8782 } 8783 8784 /** 8785 * Returns true if application is not found or there was an error. Otherwise it returns 8786 * the hidden state of the package for the given user. 8787 */ 8788 @Override 8789 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8790 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8791 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8792 false, "getApplicationHidden for user " + userId); 8793 PackageSetting pkgSetting; 8794 long callingId = Binder.clearCallingIdentity(); 8795 try { 8796 // writer 8797 synchronized (mPackages) { 8798 pkgSetting = mSettings.mPackages.get(packageName); 8799 if (pkgSetting == null) { 8800 return true; 8801 } 8802 return pkgSetting.getHidden(userId); 8803 } 8804 } finally { 8805 Binder.restoreCallingIdentity(callingId); 8806 } 8807 } 8808 8809 /** 8810 * @hide 8811 */ 8812 @Override 8813 public int installExistingPackageAsUser(String packageName, int userId) { 8814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8815 null); 8816 PackageSetting pkgSetting; 8817 final int uid = Binder.getCallingUid(); 8818 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8819 + userId); 8820 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8821 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8822 } 8823 8824 long callingId = Binder.clearCallingIdentity(); 8825 try { 8826 boolean sendAdded = false; 8827 8828 // writer 8829 synchronized (mPackages) { 8830 pkgSetting = mSettings.mPackages.get(packageName); 8831 if (pkgSetting == null) { 8832 return PackageManager.INSTALL_FAILED_INVALID_URI; 8833 } 8834 if (!pkgSetting.getInstalled(userId)) { 8835 pkgSetting.setInstalled(true, userId); 8836 pkgSetting.setHidden(false, userId); 8837 mSettings.writePackageRestrictionsLPr(userId); 8838 sendAdded = true; 8839 } 8840 } 8841 8842 if (sendAdded) { 8843 sendPackageAddedForUser(packageName, pkgSetting, userId); 8844 } 8845 } finally { 8846 Binder.restoreCallingIdentity(callingId); 8847 } 8848 8849 return PackageManager.INSTALL_SUCCEEDED; 8850 } 8851 8852 boolean isUserRestricted(int userId, String restrictionKey) { 8853 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8854 if (restrictions.getBoolean(restrictionKey, false)) { 8855 Log.w(TAG, "User is restricted: " + restrictionKey); 8856 return true; 8857 } 8858 return false; 8859 } 8860 8861 @Override 8862 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8863 mContext.enforceCallingOrSelfPermission( 8864 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8865 "Only package verification agents can verify applications"); 8866 8867 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8868 final PackageVerificationResponse response = new PackageVerificationResponse( 8869 verificationCode, Binder.getCallingUid()); 8870 msg.arg1 = id; 8871 msg.obj = response; 8872 mHandler.sendMessage(msg); 8873 } 8874 8875 @Override 8876 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8877 long millisecondsToDelay) { 8878 mContext.enforceCallingOrSelfPermission( 8879 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8880 "Only package verification agents can extend verification timeouts"); 8881 8882 final PackageVerificationState state = mPendingVerification.get(id); 8883 final PackageVerificationResponse response = new PackageVerificationResponse( 8884 verificationCodeAtTimeout, Binder.getCallingUid()); 8885 8886 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8887 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8888 } 8889 if (millisecondsToDelay < 0) { 8890 millisecondsToDelay = 0; 8891 } 8892 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8893 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8894 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8895 } 8896 8897 if ((state != null) && !state.timeoutExtended()) { 8898 state.extendTimeout(); 8899 8900 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8901 msg.arg1 = id; 8902 msg.obj = response; 8903 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8904 } 8905 } 8906 8907 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8908 int verificationCode, UserHandle user) { 8909 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8910 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8911 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8912 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8913 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8914 8915 mContext.sendBroadcastAsUser(intent, user, 8916 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8917 } 8918 8919 private ComponentName matchComponentForVerifier(String packageName, 8920 List<ResolveInfo> receivers) { 8921 ActivityInfo targetReceiver = null; 8922 8923 final int NR = receivers.size(); 8924 for (int i = 0; i < NR; i++) { 8925 final ResolveInfo info = receivers.get(i); 8926 if (info.activityInfo == null) { 8927 continue; 8928 } 8929 8930 if (packageName.equals(info.activityInfo.packageName)) { 8931 targetReceiver = info.activityInfo; 8932 break; 8933 } 8934 } 8935 8936 if (targetReceiver == null) { 8937 return null; 8938 } 8939 8940 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8941 } 8942 8943 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8944 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8945 if (pkgInfo.verifiers.length == 0) { 8946 return null; 8947 } 8948 8949 final int N = pkgInfo.verifiers.length; 8950 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8951 for (int i = 0; i < N; i++) { 8952 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8953 8954 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8955 receivers); 8956 if (comp == null) { 8957 continue; 8958 } 8959 8960 final int verifierUid = getUidForVerifier(verifierInfo); 8961 if (verifierUid == -1) { 8962 continue; 8963 } 8964 8965 if (DEBUG_VERIFY) { 8966 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8967 + " with the correct signature"); 8968 } 8969 sufficientVerifiers.add(comp); 8970 verificationState.addSufficientVerifier(verifierUid); 8971 } 8972 8973 return sufficientVerifiers; 8974 } 8975 8976 private int getUidForVerifier(VerifierInfo verifierInfo) { 8977 synchronized (mPackages) { 8978 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8979 if (pkg == null) { 8980 return -1; 8981 } else if (pkg.mSignatures.length != 1) { 8982 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8983 + " has more than one signature; ignoring"); 8984 return -1; 8985 } 8986 8987 /* 8988 * If the public key of the package's signature does not match 8989 * our expected public key, then this is a different package and 8990 * we should skip. 8991 */ 8992 8993 final byte[] expectedPublicKey; 8994 try { 8995 final Signature verifierSig = pkg.mSignatures[0]; 8996 final PublicKey publicKey = verifierSig.getPublicKey(); 8997 expectedPublicKey = publicKey.getEncoded(); 8998 } catch (CertificateException e) { 8999 return -1; 9000 } 9001 9002 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9003 9004 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9005 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9006 + " does not have the expected public key; ignoring"); 9007 return -1; 9008 } 9009 9010 return pkg.applicationInfo.uid; 9011 } 9012 } 9013 9014 @Override 9015 public void finishPackageInstall(int token) { 9016 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9017 9018 if (DEBUG_INSTALL) { 9019 Slog.v(TAG, "BM finishing package install for " + token); 9020 } 9021 9022 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9023 mHandler.sendMessage(msg); 9024 } 9025 9026 /** 9027 * Get the verification agent timeout. 9028 * 9029 * @return verification timeout in milliseconds 9030 */ 9031 private long getVerificationTimeout() { 9032 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9033 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9034 DEFAULT_VERIFICATION_TIMEOUT); 9035 } 9036 9037 /** 9038 * Get the default verification agent response code. 9039 * 9040 * @return default verification response code 9041 */ 9042 private int getDefaultVerificationResponse() { 9043 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9044 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9045 DEFAULT_VERIFICATION_RESPONSE); 9046 } 9047 9048 /** 9049 * Check whether or not package verification has been enabled. 9050 * 9051 * @return true if verification should be performed 9052 */ 9053 private boolean isVerificationEnabled(int userId, int installFlags) { 9054 if (!DEFAULT_VERIFY_ENABLE) { 9055 return false; 9056 } 9057 9058 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9059 9060 // Check if installing from ADB 9061 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9062 // Do not run verification in a test harness environment 9063 if (ActivityManager.isRunningInTestHarness()) { 9064 return false; 9065 } 9066 if (ensureVerifyAppsEnabled) { 9067 return true; 9068 } 9069 // Check if the developer does not want package verification for ADB installs 9070 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9071 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9072 return false; 9073 } 9074 } 9075 9076 if (ensureVerifyAppsEnabled) { 9077 return true; 9078 } 9079 9080 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9081 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9082 } 9083 9084 @Override 9085 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9086 throws RemoteException { 9087 mContext.enforceCallingOrSelfPermission( 9088 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9089 "Only intentfilter verification agents can verify applications"); 9090 9091 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9092 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9093 Binder.getCallingUid(), verificationCode, failedDomains); 9094 msg.arg1 = id; 9095 msg.obj = response; 9096 mHandler.sendMessage(msg); 9097 } 9098 9099 @Override 9100 public int getIntentVerificationStatus(String packageName, int userId) { 9101 synchronized (mPackages) { 9102 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9103 } 9104 } 9105 9106 @Override 9107 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9108 boolean result = false; 9109 synchronized (mPackages) { 9110 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9111 } 9112 scheduleWritePackageRestrictionsLocked(userId); 9113 return result; 9114 } 9115 9116 @Override 9117 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9118 synchronized (mPackages) { 9119 return mSettings.getIntentFilterVerificationsLPr(packageName); 9120 } 9121 } 9122 9123 @Override 9124 public List<IntentFilter> getAllIntentFilters(String packageName) { 9125 if (TextUtils.isEmpty(packageName)) { 9126 return Collections.<IntentFilter>emptyList(); 9127 } 9128 synchronized (mPackages) { 9129 PackageParser.Package pkg = mPackages.get(packageName); 9130 if (pkg == null || pkg.activities == null) { 9131 return Collections.<IntentFilter>emptyList(); 9132 } 9133 final int count = pkg.activities.size(); 9134 ArrayList<IntentFilter> result = new ArrayList<>(); 9135 for (int n=0; n<count; n++) { 9136 PackageParser.Activity activity = pkg.activities.get(n); 9137 if (activity.intents != null || activity.intents.size() > 0) { 9138 result.addAll(activity.intents); 9139 } 9140 } 9141 return result; 9142 } 9143 } 9144 9145 @Override 9146 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9147 synchronized (mPackages) { 9148 return mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9149 } 9150 } 9151 9152 @Override 9153 public String getDefaultBrowserPackageName(int userId) { 9154 synchronized (mPackages) { 9155 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9156 } 9157 } 9158 9159 /** 9160 * Get the "allow unknown sources" setting. 9161 * 9162 * @return the current "allow unknown sources" setting 9163 */ 9164 private int getUnknownSourcesSettings() { 9165 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9166 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9167 -1); 9168 } 9169 9170 @Override 9171 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9172 final int uid = Binder.getCallingUid(); 9173 // writer 9174 synchronized (mPackages) { 9175 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9176 if (targetPackageSetting == null) { 9177 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9178 } 9179 9180 PackageSetting installerPackageSetting; 9181 if (installerPackageName != null) { 9182 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9183 if (installerPackageSetting == null) { 9184 throw new IllegalArgumentException("Unknown installer package: " 9185 + installerPackageName); 9186 } 9187 } else { 9188 installerPackageSetting = null; 9189 } 9190 9191 Signature[] callerSignature; 9192 Object obj = mSettings.getUserIdLPr(uid); 9193 if (obj != null) { 9194 if (obj instanceof SharedUserSetting) { 9195 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9196 } else if (obj instanceof PackageSetting) { 9197 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9198 } else { 9199 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9200 } 9201 } else { 9202 throw new SecurityException("Unknown calling uid " + uid); 9203 } 9204 9205 // Verify: can't set installerPackageName to a package that is 9206 // not signed with the same cert as the caller. 9207 if (installerPackageSetting != null) { 9208 if (compareSignatures(callerSignature, 9209 installerPackageSetting.signatures.mSignatures) 9210 != PackageManager.SIGNATURE_MATCH) { 9211 throw new SecurityException( 9212 "Caller does not have same cert as new installer package " 9213 + installerPackageName); 9214 } 9215 } 9216 9217 // Verify: if target already has an installer package, it must 9218 // be signed with the same cert as the caller. 9219 if (targetPackageSetting.installerPackageName != null) { 9220 PackageSetting setting = mSettings.mPackages.get( 9221 targetPackageSetting.installerPackageName); 9222 // If the currently set package isn't valid, then it's always 9223 // okay to change it. 9224 if (setting != null) { 9225 if (compareSignatures(callerSignature, 9226 setting.signatures.mSignatures) 9227 != PackageManager.SIGNATURE_MATCH) { 9228 throw new SecurityException( 9229 "Caller does not have same cert as old installer package " 9230 + targetPackageSetting.installerPackageName); 9231 } 9232 } 9233 } 9234 9235 // Okay! 9236 targetPackageSetting.installerPackageName = installerPackageName; 9237 scheduleWriteSettingsLocked(); 9238 } 9239 } 9240 9241 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9242 // Queue up an async operation since the package installation may take a little while. 9243 mHandler.post(new Runnable() { 9244 public void run() { 9245 mHandler.removeCallbacks(this); 9246 // Result object to be returned 9247 PackageInstalledInfo res = new PackageInstalledInfo(); 9248 res.returnCode = currentStatus; 9249 res.uid = -1; 9250 res.pkg = null; 9251 res.removedInfo = new PackageRemovedInfo(); 9252 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9253 args.doPreInstall(res.returnCode); 9254 synchronized (mInstallLock) { 9255 installPackageLI(args, res); 9256 } 9257 args.doPostInstall(res.returnCode, res.uid); 9258 } 9259 9260 // A restore should be performed at this point if (a) the install 9261 // succeeded, (b) the operation is not an update, and (c) the new 9262 // package has not opted out of backup participation. 9263 final boolean update = res.removedInfo.removedPackage != null; 9264 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9265 boolean doRestore = !update 9266 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9267 9268 // Set up the post-install work request bookkeeping. This will be used 9269 // and cleaned up by the post-install event handling regardless of whether 9270 // there's a restore pass performed. Token values are >= 1. 9271 int token; 9272 if (mNextInstallToken < 0) mNextInstallToken = 1; 9273 token = mNextInstallToken++; 9274 9275 PostInstallData data = new PostInstallData(args, res); 9276 mRunningInstalls.put(token, data); 9277 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9278 9279 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9280 // Pass responsibility to the Backup Manager. It will perform a 9281 // restore if appropriate, then pass responsibility back to the 9282 // Package Manager to run the post-install observer callbacks 9283 // and broadcasts. 9284 IBackupManager bm = IBackupManager.Stub.asInterface( 9285 ServiceManager.getService(Context.BACKUP_SERVICE)); 9286 if (bm != null) { 9287 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9288 + " to BM for possible restore"); 9289 try { 9290 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9291 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9292 } else { 9293 doRestore = false; 9294 } 9295 } catch (RemoteException e) { 9296 // can't happen; the backup manager is local 9297 } catch (Exception e) { 9298 Slog.e(TAG, "Exception trying to enqueue restore", e); 9299 doRestore = false; 9300 } 9301 } else { 9302 Slog.e(TAG, "Backup Manager not found!"); 9303 doRestore = false; 9304 } 9305 } 9306 9307 if (!doRestore) { 9308 // No restore possible, or the Backup Manager was mysteriously not 9309 // available -- just fire the post-install work request directly. 9310 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9311 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9312 mHandler.sendMessage(msg); 9313 } 9314 } 9315 }); 9316 } 9317 9318 private abstract class HandlerParams { 9319 private static final int MAX_RETRIES = 4; 9320 9321 /** 9322 * Number of times startCopy() has been attempted and had a non-fatal 9323 * error. 9324 */ 9325 private int mRetries = 0; 9326 9327 /** User handle for the user requesting the information or installation. */ 9328 private final UserHandle mUser; 9329 9330 HandlerParams(UserHandle user) { 9331 mUser = user; 9332 } 9333 9334 UserHandle getUser() { 9335 return mUser; 9336 } 9337 9338 final boolean startCopy() { 9339 boolean res; 9340 try { 9341 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9342 9343 if (++mRetries > MAX_RETRIES) { 9344 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9345 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9346 handleServiceError(); 9347 return false; 9348 } else { 9349 handleStartCopy(); 9350 res = true; 9351 } 9352 } catch (RemoteException e) { 9353 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9354 mHandler.sendEmptyMessage(MCS_RECONNECT); 9355 res = false; 9356 } 9357 handleReturnCode(); 9358 return res; 9359 } 9360 9361 final void serviceError() { 9362 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9363 handleServiceError(); 9364 handleReturnCode(); 9365 } 9366 9367 abstract void handleStartCopy() throws RemoteException; 9368 abstract void handleServiceError(); 9369 abstract void handleReturnCode(); 9370 } 9371 9372 class MeasureParams extends HandlerParams { 9373 private final PackageStats mStats; 9374 private boolean mSuccess; 9375 9376 private final IPackageStatsObserver mObserver; 9377 9378 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9379 super(new UserHandle(stats.userHandle)); 9380 mObserver = observer; 9381 mStats = stats; 9382 } 9383 9384 @Override 9385 public String toString() { 9386 return "MeasureParams{" 9387 + Integer.toHexString(System.identityHashCode(this)) 9388 + " " + mStats.packageName + "}"; 9389 } 9390 9391 @Override 9392 void handleStartCopy() throws RemoteException { 9393 synchronized (mInstallLock) { 9394 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9395 } 9396 9397 if (mSuccess) { 9398 final boolean mounted; 9399 if (Environment.isExternalStorageEmulated()) { 9400 mounted = true; 9401 } else { 9402 final String status = Environment.getExternalStorageState(); 9403 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9404 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9405 } 9406 9407 if (mounted) { 9408 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9409 9410 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9411 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9412 9413 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9414 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9415 9416 // Always subtract cache size, since it's a subdirectory 9417 mStats.externalDataSize -= mStats.externalCacheSize; 9418 9419 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9420 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9421 9422 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9423 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9424 } 9425 } 9426 } 9427 9428 @Override 9429 void handleReturnCode() { 9430 if (mObserver != null) { 9431 try { 9432 mObserver.onGetStatsCompleted(mStats, mSuccess); 9433 } catch (RemoteException e) { 9434 Slog.i(TAG, "Observer no longer exists."); 9435 } 9436 } 9437 } 9438 9439 @Override 9440 void handleServiceError() { 9441 Slog.e(TAG, "Could not measure application " + mStats.packageName 9442 + " external storage"); 9443 } 9444 } 9445 9446 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9447 throws RemoteException { 9448 long result = 0; 9449 for (File path : paths) { 9450 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9451 } 9452 return result; 9453 } 9454 9455 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9456 for (File path : paths) { 9457 try { 9458 mcs.clearDirectory(path.getAbsolutePath()); 9459 } catch (RemoteException e) { 9460 } 9461 } 9462 } 9463 9464 static class OriginInfo { 9465 /** 9466 * Location where install is coming from, before it has been 9467 * copied/renamed into place. This could be a single monolithic APK 9468 * file, or a cluster directory. This location may be untrusted. 9469 */ 9470 final File file; 9471 final String cid; 9472 9473 /** 9474 * Flag indicating that {@link #file} or {@link #cid} has already been 9475 * staged, meaning downstream users don't need to defensively copy the 9476 * contents. 9477 */ 9478 final boolean staged; 9479 9480 /** 9481 * Flag indicating that {@link #file} or {@link #cid} is an already 9482 * installed app that is being moved. 9483 */ 9484 final boolean existing; 9485 9486 final String resolvedPath; 9487 final File resolvedFile; 9488 9489 static OriginInfo fromNothing() { 9490 return new OriginInfo(null, null, false, false); 9491 } 9492 9493 static OriginInfo fromUntrustedFile(File file) { 9494 return new OriginInfo(file, null, false, false); 9495 } 9496 9497 static OriginInfo fromExistingFile(File file) { 9498 return new OriginInfo(file, null, false, true); 9499 } 9500 9501 static OriginInfo fromStagedFile(File file) { 9502 return new OriginInfo(file, null, true, false); 9503 } 9504 9505 static OriginInfo fromStagedContainer(String cid) { 9506 return new OriginInfo(null, cid, true, false); 9507 } 9508 9509 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9510 this.file = file; 9511 this.cid = cid; 9512 this.staged = staged; 9513 this.existing = existing; 9514 9515 if (cid != null) { 9516 resolvedPath = PackageHelper.getSdDir(cid); 9517 resolvedFile = new File(resolvedPath); 9518 } else if (file != null) { 9519 resolvedPath = file.getAbsolutePath(); 9520 resolvedFile = file; 9521 } else { 9522 resolvedPath = null; 9523 resolvedFile = null; 9524 } 9525 } 9526 } 9527 9528 class MoveInfo { 9529 final int moveId; 9530 final String fromUuid; 9531 final String toUuid; 9532 final String packageName; 9533 final String dataAppName; 9534 final int appId; 9535 final String seinfo; 9536 9537 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9538 String dataAppName, int appId, String seinfo) { 9539 this.moveId = moveId; 9540 this.fromUuid = fromUuid; 9541 this.toUuid = toUuid; 9542 this.packageName = packageName; 9543 this.dataAppName = dataAppName; 9544 this.appId = appId; 9545 this.seinfo = seinfo; 9546 } 9547 } 9548 9549 class InstallParams extends HandlerParams { 9550 final OriginInfo origin; 9551 final MoveInfo move; 9552 final IPackageInstallObserver2 observer; 9553 int installFlags; 9554 final String installerPackageName; 9555 final String volumeUuid; 9556 final VerificationParams verificationParams; 9557 private InstallArgs mArgs; 9558 private int mRet; 9559 final String packageAbiOverride; 9560 9561 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9562 int installFlags, String installerPackageName, String volumeUuid, 9563 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9564 super(user); 9565 this.origin = origin; 9566 this.move = move; 9567 this.observer = observer; 9568 this.installFlags = installFlags; 9569 this.installerPackageName = installerPackageName; 9570 this.volumeUuid = volumeUuid; 9571 this.verificationParams = verificationParams; 9572 this.packageAbiOverride = packageAbiOverride; 9573 } 9574 9575 @Override 9576 public String toString() { 9577 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9578 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9579 } 9580 9581 public ManifestDigest getManifestDigest() { 9582 if (verificationParams == null) { 9583 return null; 9584 } 9585 return verificationParams.getManifestDigest(); 9586 } 9587 9588 private int installLocationPolicy(PackageInfoLite pkgLite) { 9589 String packageName = pkgLite.packageName; 9590 int installLocation = pkgLite.installLocation; 9591 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9592 // reader 9593 synchronized (mPackages) { 9594 PackageParser.Package pkg = mPackages.get(packageName); 9595 if (pkg != null) { 9596 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9597 // Check for downgrading. 9598 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9599 try { 9600 checkDowngrade(pkg, pkgLite); 9601 } catch (PackageManagerException e) { 9602 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9603 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9604 } 9605 } 9606 // Check for updated system application. 9607 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9608 if (onSd) { 9609 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9610 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9611 } 9612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9613 } else { 9614 if (onSd) { 9615 // Install flag overrides everything. 9616 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9617 } 9618 // If current upgrade specifies particular preference 9619 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9620 // Application explicitly specified internal. 9621 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9622 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9623 // App explictly prefers external. Let policy decide 9624 } else { 9625 // Prefer previous location 9626 if (isExternal(pkg)) { 9627 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9628 } 9629 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9630 } 9631 } 9632 } else { 9633 // Invalid install. Return error code 9634 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9635 } 9636 } 9637 } 9638 // All the special cases have been taken care of. 9639 // Return result based on recommended install location. 9640 if (onSd) { 9641 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9642 } 9643 return pkgLite.recommendedInstallLocation; 9644 } 9645 9646 /* 9647 * Invoke remote method to get package information and install 9648 * location values. Override install location based on default 9649 * policy if needed and then create install arguments based 9650 * on the install location. 9651 */ 9652 public void handleStartCopy() throws RemoteException { 9653 int ret = PackageManager.INSTALL_SUCCEEDED; 9654 9655 // If we're already staged, we've firmly committed to an install location 9656 if (origin.staged) { 9657 if (origin.file != null) { 9658 installFlags |= PackageManager.INSTALL_INTERNAL; 9659 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9660 } else if (origin.cid != null) { 9661 installFlags |= PackageManager.INSTALL_EXTERNAL; 9662 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9663 } else { 9664 throw new IllegalStateException("Invalid stage location"); 9665 } 9666 } 9667 9668 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9669 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9670 9671 PackageInfoLite pkgLite = null; 9672 9673 if (onInt && onSd) { 9674 // Check if both bits are set. 9675 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9676 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9677 } else { 9678 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9679 packageAbiOverride); 9680 9681 /* 9682 * If we have too little free space, try to free cache 9683 * before giving up. 9684 */ 9685 if (!origin.staged && pkgLite.recommendedInstallLocation 9686 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9687 // TODO: focus freeing disk space on the target device 9688 final StorageManager storage = StorageManager.from(mContext); 9689 final long lowThreshold = storage.getStorageLowBytes( 9690 Environment.getDataDirectory()); 9691 9692 final long sizeBytes = mContainerService.calculateInstalledSize( 9693 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9694 9695 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9696 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9697 installFlags, packageAbiOverride); 9698 } 9699 9700 /* 9701 * The cache free must have deleted the file we 9702 * downloaded to install. 9703 * 9704 * TODO: fix the "freeCache" call to not delete 9705 * the file we care about. 9706 */ 9707 if (pkgLite.recommendedInstallLocation 9708 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9709 pkgLite.recommendedInstallLocation 9710 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9711 } 9712 } 9713 } 9714 9715 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9716 int loc = pkgLite.recommendedInstallLocation; 9717 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9718 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9719 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9720 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9721 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9722 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9723 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9724 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9725 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9726 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9727 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9728 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9729 } else { 9730 // Override with defaults if needed. 9731 loc = installLocationPolicy(pkgLite); 9732 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9733 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9734 } else if (!onSd && !onInt) { 9735 // Override install location with flags 9736 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9737 // Set the flag to install on external media. 9738 installFlags |= PackageManager.INSTALL_EXTERNAL; 9739 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9740 } else { 9741 // Make sure the flag for installing on external 9742 // media is unset 9743 installFlags |= PackageManager.INSTALL_INTERNAL; 9744 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9745 } 9746 } 9747 } 9748 } 9749 9750 final InstallArgs args = createInstallArgs(this); 9751 mArgs = args; 9752 9753 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9754 /* 9755 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9756 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9757 */ 9758 int userIdentifier = getUser().getIdentifier(); 9759 if (userIdentifier == UserHandle.USER_ALL 9760 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9761 userIdentifier = UserHandle.USER_OWNER; 9762 } 9763 9764 /* 9765 * Determine if we have any installed package verifiers. If we 9766 * do, then we'll defer to them to verify the packages. 9767 */ 9768 final int requiredUid = mRequiredVerifierPackage == null ? -1 9769 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9770 if (!origin.existing && requiredUid != -1 9771 && isVerificationEnabled(userIdentifier, installFlags)) { 9772 final Intent verification = new Intent( 9773 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9774 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9775 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9776 PACKAGE_MIME_TYPE); 9777 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9778 9779 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9780 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9781 0 /* TODO: Which userId? */); 9782 9783 if (DEBUG_VERIFY) { 9784 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9785 + verification.toString() + " with " + pkgLite.verifiers.length 9786 + " optional verifiers"); 9787 } 9788 9789 final int verificationId = mPendingVerificationToken++; 9790 9791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9792 9793 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9794 installerPackageName); 9795 9796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9797 installFlags); 9798 9799 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9800 pkgLite.packageName); 9801 9802 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9803 pkgLite.versionCode); 9804 9805 if (verificationParams != null) { 9806 if (verificationParams.getVerificationURI() != null) { 9807 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9808 verificationParams.getVerificationURI()); 9809 } 9810 if (verificationParams.getOriginatingURI() != null) { 9811 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9812 verificationParams.getOriginatingURI()); 9813 } 9814 if (verificationParams.getReferrer() != null) { 9815 verification.putExtra(Intent.EXTRA_REFERRER, 9816 verificationParams.getReferrer()); 9817 } 9818 if (verificationParams.getOriginatingUid() >= 0) { 9819 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9820 verificationParams.getOriginatingUid()); 9821 } 9822 if (verificationParams.getInstallerUid() >= 0) { 9823 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9824 verificationParams.getInstallerUid()); 9825 } 9826 } 9827 9828 final PackageVerificationState verificationState = new PackageVerificationState( 9829 requiredUid, args); 9830 9831 mPendingVerification.append(verificationId, verificationState); 9832 9833 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9834 receivers, verificationState); 9835 9836 /* 9837 * If any sufficient verifiers were listed in the package 9838 * manifest, attempt to ask them. 9839 */ 9840 if (sufficientVerifiers != null) { 9841 final int N = sufficientVerifiers.size(); 9842 if (N == 0) { 9843 Slog.i(TAG, "Additional verifiers required, but none installed."); 9844 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9845 } else { 9846 for (int i = 0; i < N; i++) { 9847 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9848 9849 final Intent sufficientIntent = new Intent(verification); 9850 sufficientIntent.setComponent(verifierComponent); 9851 9852 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9853 } 9854 } 9855 } 9856 9857 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9858 mRequiredVerifierPackage, receivers); 9859 if (ret == PackageManager.INSTALL_SUCCEEDED 9860 && mRequiredVerifierPackage != null) { 9861 /* 9862 * Send the intent to the required verification agent, 9863 * but only start the verification timeout after the 9864 * target BroadcastReceivers have run. 9865 */ 9866 verification.setComponent(requiredVerifierComponent); 9867 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9868 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9869 new BroadcastReceiver() { 9870 @Override 9871 public void onReceive(Context context, Intent intent) { 9872 final Message msg = mHandler 9873 .obtainMessage(CHECK_PENDING_VERIFICATION); 9874 msg.arg1 = verificationId; 9875 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9876 } 9877 }, null, 0, null, null); 9878 9879 /* 9880 * We don't want the copy to proceed until verification 9881 * succeeds, so null out this field. 9882 */ 9883 mArgs = null; 9884 } 9885 } else { 9886 /* 9887 * No package verification is enabled, so immediately start 9888 * the remote call to initiate copy using temporary file. 9889 */ 9890 ret = args.copyApk(mContainerService, true); 9891 } 9892 } 9893 9894 mRet = ret; 9895 } 9896 9897 @Override 9898 void handleReturnCode() { 9899 // If mArgs is null, then MCS couldn't be reached. When it 9900 // reconnects, it will try again to install. At that point, this 9901 // will succeed. 9902 if (mArgs != null) { 9903 processPendingInstall(mArgs, mRet); 9904 } 9905 } 9906 9907 @Override 9908 void handleServiceError() { 9909 mArgs = createInstallArgs(this); 9910 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9911 } 9912 9913 public boolean isForwardLocked() { 9914 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9915 } 9916 } 9917 9918 /** 9919 * Used during creation of InstallArgs 9920 * 9921 * @param installFlags package installation flags 9922 * @return true if should be installed on external storage 9923 */ 9924 private static boolean installOnExternalAsec(int installFlags) { 9925 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9926 return false; 9927 } 9928 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9929 return true; 9930 } 9931 return false; 9932 } 9933 9934 /** 9935 * Used during creation of InstallArgs 9936 * 9937 * @param installFlags package installation flags 9938 * @return true if should be installed as forward locked 9939 */ 9940 private static boolean installForwardLocked(int installFlags) { 9941 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9942 } 9943 9944 private InstallArgs createInstallArgs(InstallParams params) { 9945 if (params.move != null) { 9946 return new MoveInstallArgs(params); 9947 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 9948 return new AsecInstallArgs(params); 9949 } else { 9950 return new FileInstallArgs(params); 9951 } 9952 } 9953 9954 /** 9955 * Create args that describe an existing installed package. Typically used 9956 * when cleaning up old installs, or used as a move source. 9957 */ 9958 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9959 String resourcePath, String[] instructionSets) { 9960 final boolean isInAsec; 9961 if (installOnExternalAsec(installFlags)) { 9962 /* Apps on SD card are always in ASEC containers. */ 9963 isInAsec = true; 9964 } else if (installForwardLocked(installFlags) 9965 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9966 /* 9967 * Forward-locked apps are only in ASEC containers if they're the 9968 * new style 9969 */ 9970 isInAsec = true; 9971 } else { 9972 isInAsec = false; 9973 } 9974 9975 if (isInAsec) { 9976 return new AsecInstallArgs(codePath, instructionSets, 9977 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 9978 } else { 9979 return new FileInstallArgs(codePath, resourcePath, instructionSets); 9980 } 9981 } 9982 9983 static abstract class InstallArgs { 9984 /** @see InstallParams#origin */ 9985 final OriginInfo origin; 9986 /** @see InstallParams#move */ 9987 final MoveInfo move; 9988 9989 final IPackageInstallObserver2 observer; 9990 // Always refers to PackageManager flags only 9991 final int installFlags; 9992 final String installerPackageName; 9993 final String volumeUuid; 9994 final ManifestDigest manifestDigest; 9995 final UserHandle user; 9996 final String abiOverride; 9997 9998 // The list of instruction sets supported by this app. This is currently 9999 // only used during the rmdex() phase to clean up resources. We can get rid of this 10000 // if we move dex files under the common app path. 10001 /* nullable */ String[] instructionSets; 10002 10003 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10004 int installFlags, String installerPackageName, String volumeUuid, 10005 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10006 String abiOverride) { 10007 this.origin = origin; 10008 this.move = move; 10009 this.installFlags = installFlags; 10010 this.observer = observer; 10011 this.installerPackageName = installerPackageName; 10012 this.volumeUuid = volumeUuid; 10013 this.manifestDigest = manifestDigest; 10014 this.user = user; 10015 this.instructionSets = instructionSets; 10016 this.abiOverride = abiOverride; 10017 } 10018 10019 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10020 abstract int doPreInstall(int status); 10021 10022 /** 10023 * Rename package into final resting place. All paths on the given 10024 * scanned package should be updated to reflect the rename. 10025 */ 10026 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10027 abstract int doPostInstall(int status, int uid); 10028 10029 /** @see PackageSettingBase#codePathString */ 10030 abstract String getCodePath(); 10031 /** @see PackageSettingBase#resourcePathString */ 10032 abstract String getResourcePath(); 10033 10034 // Need installer lock especially for dex file removal. 10035 abstract void cleanUpResourcesLI(); 10036 abstract boolean doPostDeleteLI(boolean delete); 10037 10038 /** 10039 * Called before the source arguments are copied. This is used mostly 10040 * for MoveParams when it needs to read the source file to put it in the 10041 * destination. 10042 */ 10043 int doPreCopy() { 10044 return PackageManager.INSTALL_SUCCEEDED; 10045 } 10046 10047 /** 10048 * Called after the source arguments are copied. This is used mostly for 10049 * MoveParams when it needs to read the source file to put it in the 10050 * destination. 10051 * 10052 * @return 10053 */ 10054 int doPostCopy(int uid) { 10055 return PackageManager.INSTALL_SUCCEEDED; 10056 } 10057 10058 protected boolean isFwdLocked() { 10059 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10060 } 10061 10062 protected boolean isExternalAsec() { 10063 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10064 } 10065 10066 UserHandle getUser() { 10067 return user; 10068 } 10069 } 10070 10071 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10072 if (!allCodePaths.isEmpty()) { 10073 if (instructionSets == null) { 10074 throw new IllegalStateException("instructionSet == null"); 10075 } 10076 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10077 for (String codePath : allCodePaths) { 10078 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10079 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10080 if (retCode < 0) { 10081 Slog.w(TAG, "Couldn't remove dex file for package: " 10082 + " at location " + codePath + ", retcode=" + retCode); 10083 // we don't consider this to be a failure of the core package deletion 10084 } 10085 } 10086 } 10087 } 10088 } 10089 10090 /** 10091 * Logic to handle installation of non-ASEC applications, including copying 10092 * and renaming logic. 10093 */ 10094 class FileInstallArgs extends InstallArgs { 10095 private File codeFile; 10096 private File resourceFile; 10097 10098 // Example topology: 10099 // /data/app/com.example/base.apk 10100 // /data/app/com.example/split_foo.apk 10101 // /data/app/com.example/lib/arm/libfoo.so 10102 // /data/app/com.example/lib/arm64/libfoo.so 10103 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10104 10105 /** New install */ 10106 FileInstallArgs(InstallParams params) { 10107 super(params.origin, params.move, params.observer, params.installFlags, 10108 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10109 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10110 if (isFwdLocked()) { 10111 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10112 } 10113 } 10114 10115 /** Existing install */ 10116 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10117 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10118 null); 10119 this.codeFile = (codePath != null) ? new File(codePath) : null; 10120 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10121 } 10122 10123 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10124 if (origin.staged) { 10125 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10126 codeFile = origin.file; 10127 resourceFile = origin.file; 10128 return PackageManager.INSTALL_SUCCEEDED; 10129 } 10130 10131 try { 10132 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10133 codeFile = tempDir; 10134 resourceFile = tempDir; 10135 } catch (IOException e) { 10136 Slog.w(TAG, "Failed to create copy file: " + e); 10137 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10138 } 10139 10140 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10141 @Override 10142 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10143 if (!FileUtils.isValidExtFilename(name)) { 10144 throw new IllegalArgumentException("Invalid filename: " + name); 10145 } 10146 try { 10147 final File file = new File(codeFile, name); 10148 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10149 O_RDWR | O_CREAT, 0644); 10150 Os.chmod(file.getAbsolutePath(), 0644); 10151 return new ParcelFileDescriptor(fd); 10152 } catch (ErrnoException e) { 10153 throw new RemoteException("Failed to open: " + e.getMessage()); 10154 } 10155 } 10156 }; 10157 10158 int ret = PackageManager.INSTALL_SUCCEEDED; 10159 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10160 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10161 Slog.e(TAG, "Failed to copy package"); 10162 return ret; 10163 } 10164 10165 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10166 NativeLibraryHelper.Handle handle = null; 10167 try { 10168 handle = NativeLibraryHelper.Handle.create(codeFile); 10169 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10170 abiOverride); 10171 } catch (IOException e) { 10172 Slog.e(TAG, "Copying native libraries failed", e); 10173 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10174 } finally { 10175 IoUtils.closeQuietly(handle); 10176 } 10177 10178 return ret; 10179 } 10180 10181 int doPreInstall(int status) { 10182 if (status != PackageManager.INSTALL_SUCCEEDED) { 10183 cleanUp(); 10184 } 10185 return status; 10186 } 10187 10188 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10189 if (status != PackageManager.INSTALL_SUCCEEDED) { 10190 cleanUp(); 10191 return false; 10192 } 10193 10194 final File targetDir = codeFile.getParentFile(); 10195 final File beforeCodeFile = codeFile; 10196 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10197 10198 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10199 try { 10200 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10201 } catch (ErrnoException e) { 10202 Slog.d(TAG, "Failed to rename", e); 10203 return false; 10204 } 10205 10206 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10207 Slog.d(TAG, "Failed to restorecon"); 10208 return false; 10209 } 10210 10211 // Reflect the rename internally 10212 codeFile = afterCodeFile; 10213 resourceFile = afterCodeFile; 10214 10215 // Reflect the rename in scanned details 10216 pkg.codePath = afterCodeFile.getAbsolutePath(); 10217 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10218 pkg.baseCodePath); 10219 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10220 pkg.splitCodePaths); 10221 10222 // Reflect the rename in app info 10223 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10224 pkg.applicationInfo.setCodePath(pkg.codePath); 10225 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10226 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10227 pkg.applicationInfo.setResourcePath(pkg.codePath); 10228 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10229 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10230 10231 return true; 10232 } 10233 10234 int doPostInstall(int status, int uid) { 10235 if (status != PackageManager.INSTALL_SUCCEEDED) { 10236 cleanUp(); 10237 } 10238 return status; 10239 } 10240 10241 @Override 10242 String getCodePath() { 10243 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10244 } 10245 10246 @Override 10247 String getResourcePath() { 10248 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10249 } 10250 10251 private boolean cleanUp() { 10252 if (codeFile == null || !codeFile.exists()) { 10253 return false; 10254 } 10255 10256 if (codeFile.isDirectory()) { 10257 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10258 } else { 10259 codeFile.delete(); 10260 } 10261 10262 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10263 resourceFile.delete(); 10264 } 10265 10266 return true; 10267 } 10268 10269 void cleanUpResourcesLI() { 10270 // Try enumerating all code paths before deleting 10271 List<String> allCodePaths = Collections.EMPTY_LIST; 10272 if (codeFile != null && codeFile.exists()) { 10273 try { 10274 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10275 allCodePaths = pkg.getAllCodePaths(); 10276 } catch (PackageParserException e) { 10277 // Ignored; we tried our best 10278 } 10279 } 10280 10281 cleanUp(); 10282 removeDexFiles(allCodePaths, instructionSets); 10283 } 10284 10285 boolean doPostDeleteLI(boolean delete) { 10286 // XXX err, shouldn't we respect the delete flag? 10287 cleanUpResourcesLI(); 10288 return true; 10289 } 10290 } 10291 10292 private boolean isAsecExternal(String cid) { 10293 final String asecPath = PackageHelper.getSdFilesystem(cid); 10294 return !asecPath.startsWith(mAsecInternalPath); 10295 } 10296 10297 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10298 PackageManagerException { 10299 if (copyRet < 0) { 10300 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10301 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10302 throw new PackageManagerException(copyRet, message); 10303 } 10304 } 10305 } 10306 10307 /** 10308 * Extract the MountService "container ID" from the full code path of an 10309 * .apk. 10310 */ 10311 static String cidFromCodePath(String fullCodePath) { 10312 int eidx = fullCodePath.lastIndexOf("/"); 10313 String subStr1 = fullCodePath.substring(0, eidx); 10314 int sidx = subStr1.lastIndexOf("/"); 10315 return subStr1.substring(sidx+1, eidx); 10316 } 10317 10318 /** 10319 * Logic to handle installation of ASEC applications, including copying and 10320 * renaming logic. 10321 */ 10322 class AsecInstallArgs extends InstallArgs { 10323 static final String RES_FILE_NAME = "pkg.apk"; 10324 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10325 10326 String cid; 10327 String packagePath; 10328 String resourcePath; 10329 10330 /** New install */ 10331 AsecInstallArgs(InstallParams params) { 10332 super(params.origin, params.move, params.observer, params.installFlags, 10333 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10334 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10335 } 10336 10337 /** Existing install */ 10338 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10339 boolean isExternal, boolean isForwardLocked) { 10340 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10341 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10342 instructionSets, null); 10343 // Hackily pretend we're still looking at a full code path 10344 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10345 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10346 } 10347 10348 // Extract cid from fullCodePath 10349 int eidx = fullCodePath.lastIndexOf("/"); 10350 String subStr1 = fullCodePath.substring(0, eidx); 10351 int sidx = subStr1.lastIndexOf("/"); 10352 cid = subStr1.substring(sidx+1, eidx); 10353 setMountPath(subStr1); 10354 } 10355 10356 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10357 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10358 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10359 instructionSets, null); 10360 this.cid = cid; 10361 setMountPath(PackageHelper.getSdDir(cid)); 10362 } 10363 10364 void createCopyFile() { 10365 cid = mInstallerService.allocateExternalStageCidLegacy(); 10366 } 10367 10368 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10369 if (origin.staged) { 10370 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10371 cid = origin.cid; 10372 setMountPath(PackageHelper.getSdDir(cid)); 10373 return PackageManager.INSTALL_SUCCEEDED; 10374 } 10375 10376 if (temp) { 10377 createCopyFile(); 10378 } else { 10379 /* 10380 * Pre-emptively destroy the container since it's destroyed if 10381 * copying fails due to it existing anyway. 10382 */ 10383 PackageHelper.destroySdDir(cid); 10384 } 10385 10386 final String newMountPath = imcs.copyPackageToContainer( 10387 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10388 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10389 10390 if (newMountPath != null) { 10391 setMountPath(newMountPath); 10392 return PackageManager.INSTALL_SUCCEEDED; 10393 } else { 10394 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10395 } 10396 } 10397 10398 @Override 10399 String getCodePath() { 10400 return packagePath; 10401 } 10402 10403 @Override 10404 String getResourcePath() { 10405 return resourcePath; 10406 } 10407 10408 int doPreInstall(int status) { 10409 if (status != PackageManager.INSTALL_SUCCEEDED) { 10410 // Destroy container 10411 PackageHelper.destroySdDir(cid); 10412 } else { 10413 boolean mounted = PackageHelper.isContainerMounted(cid); 10414 if (!mounted) { 10415 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10416 Process.SYSTEM_UID); 10417 if (newMountPath != null) { 10418 setMountPath(newMountPath); 10419 } else { 10420 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10421 } 10422 } 10423 } 10424 return status; 10425 } 10426 10427 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10428 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10429 String newMountPath = null; 10430 if (PackageHelper.isContainerMounted(cid)) { 10431 // Unmount the container 10432 if (!PackageHelper.unMountSdDir(cid)) { 10433 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10434 return false; 10435 } 10436 } 10437 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10438 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10439 " which might be stale. Will try to clean up."); 10440 // Clean up the stale container and proceed to recreate. 10441 if (!PackageHelper.destroySdDir(newCacheId)) { 10442 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10443 return false; 10444 } 10445 // Successfully cleaned up stale container. Try to rename again. 10446 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10447 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10448 + " inspite of cleaning it up."); 10449 return false; 10450 } 10451 } 10452 if (!PackageHelper.isContainerMounted(newCacheId)) { 10453 Slog.w(TAG, "Mounting container " + newCacheId); 10454 newMountPath = PackageHelper.mountSdDir(newCacheId, 10455 getEncryptKey(), Process.SYSTEM_UID); 10456 } else { 10457 newMountPath = PackageHelper.getSdDir(newCacheId); 10458 } 10459 if (newMountPath == null) { 10460 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10461 return false; 10462 } 10463 Log.i(TAG, "Succesfully renamed " + cid + 10464 " to " + newCacheId + 10465 " at new path: " + newMountPath); 10466 cid = newCacheId; 10467 10468 final File beforeCodeFile = new File(packagePath); 10469 setMountPath(newMountPath); 10470 final File afterCodeFile = new File(packagePath); 10471 10472 // Reflect the rename in scanned details 10473 pkg.codePath = afterCodeFile.getAbsolutePath(); 10474 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10475 pkg.baseCodePath); 10476 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10477 pkg.splitCodePaths); 10478 10479 // Reflect the rename in app info 10480 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10481 pkg.applicationInfo.setCodePath(pkg.codePath); 10482 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10483 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10484 pkg.applicationInfo.setResourcePath(pkg.codePath); 10485 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10486 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10487 10488 return true; 10489 } 10490 10491 private void setMountPath(String mountPath) { 10492 final File mountFile = new File(mountPath); 10493 10494 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10495 if (monolithicFile.exists()) { 10496 packagePath = monolithicFile.getAbsolutePath(); 10497 if (isFwdLocked()) { 10498 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10499 } else { 10500 resourcePath = packagePath; 10501 } 10502 } else { 10503 packagePath = mountFile.getAbsolutePath(); 10504 resourcePath = packagePath; 10505 } 10506 } 10507 10508 int doPostInstall(int status, int uid) { 10509 if (status != PackageManager.INSTALL_SUCCEEDED) { 10510 cleanUp(); 10511 } else { 10512 final int groupOwner; 10513 final String protectedFile; 10514 if (isFwdLocked()) { 10515 groupOwner = UserHandle.getSharedAppGid(uid); 10516 protectedFile = RES_FILE_NAME; 10517 } else { 10518 groupOwner = -1; 10519 protectedFile = null; 10520 } 10521 10522 if (uid < Process.FIRST_APPLICATION_UID 10523 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10524 Slog.e(TAG, "Failed to finalize " + cid); 10525 PackageHelper.destroySdDir(cid); 10526 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10527 } 10528 10529 boolean mounted = PackageHelper.isContainerMounted(cid); 10530 if (!mounted) { 10531 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10532 } 10533 } 10534 return status; 10535 } 10536 10537 private void cleanUp() { 10538 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10539 10540 // Destroy secure container 10541 PackageHelper.destroySdDir(cid); 10542 } 10543 10544 private List<String> getAllCodePaths() { 10545 final File codeFile = new File(getCodePath()); 10546 if (codeFile != null && codeFile.exists()) { 10547 try { 10548 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10549 return pkg.getAllCodePaths(); 10550 } catch (PackageParserException e) { 10551 // Ignored; we tried our best 10552 } 10553 } 10554 return Collections.EMPTY_LIST; 10555 } 10556 10557 void cleanUpResourcesLI() { 10558 // Enumerate all code paths before deleting 10559 cleanUpResourcesLI(getAllCodePaths()); 10560 } 10561 10562 private void cleanUpResourcesLI(List<String> allCodePaths) { 10563 cleanUp(); 10564 removeDexFiles(allCodePaths, instructionSets); 10565 } 10566 10567 String getPackageName() { 10568 return getAsecPackageName(cid); 10569 } 10570 10571 boolean doPostDeleteLI(boolean delete) { 10572 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10573 final List<String> allCodePaths = getAllCodePaths(); 10574 boolean mounted = PackageHelper.isContainerMounted(cid); 10575 if (mounted) { 10576 // Unmount first 10577 if (PackageHelper.unMountSdDir(cid)) { 10578 mounted = false; 10579 } 10580 } 10581 if (!mounted && delete) { 10582 cleanUpResourcesLI(allCodePaths); 10583 } 10584 return !mounted; 10585 } 10586 10587 @Override 10588 int doPreCopy() { 10589 if (isFwdLocked()) { 10590 if (!PackageHelper.fixSdPermissions(cid, 10591 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10592 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10593 } 10594 } 10595 10596 return PackageManager.INSTALL_SUCCEEDED; 10597 } 10598 10599 @Override 10600 int doPostCopy(int uid) { 10601 if (isFwdLocked()) { 10602 if (uid < Process.FIRST_APPLICATION_UID 10603 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10604 RES_FILE_NAME)) { 10605 Slog.e(TAG, "Failed to finalize " + cid); 10606 PackageHelper.destroySdDir(cid); 10607 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10608 } 10609 } 10610 10611 return PackageManager.INSTALL_SUCCEEDED; 10612 } 10613 } 10614 10615 /** 10616 * Logic to handle movement of existing installed applications. 10617 */ 10618 class MoveInstallArgs extends InstallArgs { 10619 private File codeFile; 10620 private File resourceFile; 10621 10622 /** New install */ 10623 MoveInstallArgs(InstallParams params) { 10624 super(params.origin, params.move, params.observer, params.installFlags, 10625 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10626 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10627 } 10628 10629 int copyApk(IMediaContainerService imcs, boolean temp) { 10630 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10631 + move.toUuid); 10632 synchronized (mInstaller) { 10633 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10634 move.dataAppName, move.appId, move.seinfo) != 0) { 10635 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10636 } 10637 } 10638 10639 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10640 resourceFile = codeFile; 10641 Slog.d(TAG, "codeFile after move is " + codeFile); 10642 10643 return PackageManager.INSTALL_SUCCEEDED; 10644 } 10645 10646 int doPreInstall(int status) { 10647 if (status != PackageManager.INSTALL_SUCCEEDED) { 10648 cleanUp(); 10649 } 10650 return status; 10651 } 10652 10653 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10654 if (status != PackageManager.INSTALL_SUCCEEDED) { 10655 cleanUp(); 10656 return false; 10657 } 10658 10659 // Reflect the move in app info 10660 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10661 pkg.applicationInfo.setCodePath(pkg.codePath); 10662 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10663 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10664 pkg.applicationInfo.setResourcePath(pkg.codePath); 10665 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10666 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10667 10668 return true; 10669 } 10670 10671 int doPostInstall(int status, int uid) { 10672 if (status != PackageManager.INSTALL_SUCCEEDED) { 10673 cleanUp(); 10674 } 10675 return status; 10676 } 10677 10678 @Override 10679 String getCodePath() { 10680 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10681 } 10682 10683 @Override 10684 String getResourcePath() { 10685 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10686 } 10687 10688 private boolean cleanUp() { 10689 if (codeFile == null || !codeFile.exists()) { 10690 return false; 10691 } 10692 10693 if (codeFile.isDirectory()) { 10694 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10695 } else { 10696 codeFile.delete(); 10697 } 10698 10699 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10700 resourceFile.delete(); 10701 } 10702 10703 return true; 10704 } 10705 10706 void cleanUpResourcesLI() { 10707 cleanUp(); 10708 } 10709 10710 boolean doPostDeleteLI(boolean delete) { 10711 // XXX err, shouldn't we respect the delete flag? 10712 cleanUpResourcesLI(); 10713 return true; 10714 } 10715 } 10716 10717 static String getAsecPackageName(String packageCid) { 10718 int idx = packageCid.lastIndexOf("-"); 10719 if (idx == -1) { 10720 return packageCid; 10721 } 10722 return packageCid.substring(0, idx); 10723 } 10724 10725 // Utility method used to create code paths based on package name and available index. 10726 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10727 String idxStr = ""; 10728 int idx = 1; 10729 // Fall back to default value of idx=1 if prefix is not 10730 // part of oldCodePath 10731 if (oldCodePath != null) { 10732 String subStr = oldCodePath; 10733 // Drop the suffix right away 10734 if (suffix != null && subStr.endsWith(suffix)) { 10735 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10736 } 10737 // If oldCodePath already contains prefix find out the 10738 // ending index to either increment or decrement. 10739 int sidx = subStr.lastIndexOf(prefix); 10740 if (sidx != -1) { 10741 subStr = subStr.substring(sidx + prefix.length()); 10742 if (subStr != null) { 10743 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10744 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10745 } 10746 try { 10747 idx = Integer.parseInt(subStr); 10748 if (idx <= 1) { 10749 idx++; 10750 } else { 10751 idx--; 10752 } 10753 } catch(NumberFormatException e) { 10754 } 10755 } 10756 } 10757 } 10758 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10759 return prefix + idxStr; 10760 } 10761 10762 private File getNextCodePath(File targetDir, String packageName) { 10763 int suffix = 1; 10764 File result; 10765 do { 10766 result = new File(targetDir, packageName + "-" + suffix); 10767 suffix++; 10768 } while (result.exists()); 10769 return result; 10770 } 10771 10772 // Utility method that returns the relative package path with respect 10773 // to the installation directory. Like say for /data/data/com.test-1.apk 10774 // string com.test-1 is returned. 10775 static String deriveCodePathName(String codePath) { 10776 if (codePath == null) { 10777 return null; 10778 } 10779 final File codeFile = new File(codePath); 10780 final String name = codeFile.getName(); 10781 if (codeFile.isDirectory()) { 10782 return name; 10783 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10784 final int lastDot = name.lastIndexOf('.'); 10785 return name.substring(0, lastDot); 10786 } else { 10787 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10788 return null; 10789 } 10790 } 10791 10792 class PackageInstalledInfo { 10793 String name; 10794 int uid; 10795 // The set of users that originally had this package installed. 10796 int[] origUsers; 10797 // The set of users that now have this package installed. 10798 int[] newUsers; 10799 PackageParser.Package pkg; 10800 int returnCode; 10801 String returnMsg; 10802 PackageRemovedInfo removedInfo; 10803 10804 public void setError(int code, String msg) { 10805 returnCode = code; 10806 returnMsg = msg; 10807 Slog.w(TAG, msg); 10808 } 10809 10810 public void setError(String msg, PackageParserException e) { 10811 returnCode = e.error; 10812 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10813 Slog.w(TAG, msg, e); 10814 } 10815 10816 public void setError(String msg, PackageManagerException e) { 10817 returnCode = e.error; 10818 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10819 Slog.w(TAG, msg, e); 10820 } 10821 10822 // In some error cases we want to convey more info back to the observer 10823 String origPackage; 10824 String origPermission; 10825 } 10826 10827 /* 10828 * Install a non-existing package. 10829 */ 10830 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10831 UserHandle user, String installerPackageName, String volumeUuid, 10832 PackageInstalledInfo res) { 10833 // Remember this for later, in case we need to rollback this install 10834 String pkgName = pkg.packageName; 10835 10836 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10837 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10838 UserHandle.USER_OWNER).exists(); 10839 synchronized(mPackages) { 10840 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10841 // A package with the same name is already installed, though 10842 // it has been renamed to an older name. The package we 10843 // are trying to install should be installed as an update to 10844 // the existing one, but that has not been requested, so bail. 10845 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10846 + " without first uninstalling package running as " 10847 + mSettings.mRenamedPackages.get(pkgName)); 10848 return; 10849 } 10850 if (mPackages.containsKey(pkgName)) { 10851 // Don't allow installation over an existing package with the same name. 10852 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10853 + " without first uninstalling."); 10854 return; 10855 } 10856 } 10857 10858 try { 10859 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10860 System.currentTimeMillis(), user); 10861 10862 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10863 // delete the partially installed application. the data directory will have to be 10864 // restored if it was already existing 10865 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10866 // remove package from internal structures. Note that we want deletePackageX to 10867 // delete the package data and cache directories that it created in 10868 // scanPackageLocked, unless those directories existed before we even tried to 10869 // install. 10870 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10871 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10872 res.removedInfo, true); 10873 } 10874 10875 } catch (PackageManagerException e) { 10876 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10877 } 10878 } 10879 10880 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10881 // Upgrade keysets are being used. Determine if new package has a superset of the 10882 // required keys. 10883 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10884 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10885 for (int i = 0; i < upgradeKeySets.length; i++) { 10886 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10887 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10888 return true; 10889 } 10890 } 10891 return false; 10892 } 10893 10894 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10895 UserHandle user, String installerPackageName, String volumeUuid, 10896 PackageInstalledInfo res) { 10897 final PackageParser.Package oldPackage; 10898 final String pkgName = pkg.packageName; 10899 final int[] allUsers; 10900 final boolean[] perUserInstalled; 10901 final boolean weFroze; 10902 10903 // First find the old package info and check signatures 10904 synchronized(mPackages) { 10905 oldPackage = mPackages.get(pkgName); 10906 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10907 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10908 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10909 // default to original signature matching 10910 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10911 != PackageManager.SIGNATURE_MATCH) { 10912 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10913 "New package has a different signature: " + pkgName); 10914 return; 10915 } 10916 } else { 10917 if(!checkUpgradeKeySetLP(ps, pkg)) { 10918 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10919 "New package not signed by keys specified by upgrade-keysets: " 10920 + pkgName); 10921 return; 10922 } 10923 } 10924 10925 // In case of rollback, remember per-user/profile install state 10926 allUsers = sUserManager.getUserIds(); 10927 perUserInstalled = new boolean[allUsers.length]; 10928 for (int i = 0; i < allUsers.length; i++) { 10929 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10930 } 10931 10932 // Mark the app as frozen to prevent launching during the upgrade 10933 // process, and then kill all running instances 10934 if (!ps.frozen) { 10935 ps.frozen = true; 10936 weFroze = true; 10937 } else { 10938 weFroze = false; 10939 } 10940 } 10941 10942 // Now that we're guarded by frozen state, kill app during upgrade 10943 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 10944 10945 try { 10946 boolean sysPkg = (isSystemApp(oldPackage)); 10947 if (sysPkg) { 10948 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10949 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10950 } else { 10951 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10952 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 10953 } 10954 } finally { 10955 // Regardless of success or failure of upgrade steps above, always 10956 // unfreeze the package if we froze it 10957 if (weFroze) { 10958 unfreezePackage(pkgName); 10959 } 10960 } 10961 } 10962 10963 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10964 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10965 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 10966 String volumeUuid, PackageInstalledInfo res) { 10967 String pkgName = deletedPackage.packageName; 10968 boolean deletedPkg = true; 10969 boolean updatedSettings = false; 10970 10971 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10972 + deletedPackage); 10973 long origUpdateTime; 10974 if (pkg.mExtras != null) { 10975 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10976 } else { 10977 origUpdateTime = 0; 10978 } 10979 10980 // First delete the existing package while retaining the data directory 10981 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10982 res.removedInfo, true)) { 10983 // If the existing package wasn't successfully deleted 10984 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10985 deletedPkg = false; 10986 } else { 10987 // Successfully deleted the old package; proceed with replace. 10988 10989 // If deleted package lived in a container, give users a chance to 10990 // relinquish resources before killing. 10991 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 10992 if (DEBUG_INSTALL) { 10993 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10994 } 10995 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10996 final ArrayList<String> pkgList = new ArrayList<String>(1); 10997 pkgList.add(deletedPackage.applicationInfo.packageName); 10998 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10999 } 11000 11001 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11002 try { 11003 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11004 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11005 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11006 perUserInstalled, res, user); 11007 updatedSettings = true; 11008 } catch (PackageManagerException e) { 11009 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11010 } 11011 } 11012 11013 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11014 // remove package from internal structures. Note that we want deletePackageX to 11015 // delete the package data and cache directories that it created in 11016 // scanPackageLocked, unless those directories existed before we even tried to 11017 // install. 11018 if(updatedSettings) { 11019 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11020 deletePackageLI( 11021 pkgName, null, true, allUsers, perUserInstalled, 11022 PackageManager.DELETE_KEEP_DATA, 11023 res.removedInfo, true); 11024 } 11025 // Since we failed to install the new package we need to restore the old 11026 // package that we deleted. 11027 if (deletedPkg) { 11028 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11029 File restoreFile = new File(deletedPackage.codePath); 11030 // Parse old package 11031 boolean oldExternal = isExternal(deletedPackage); 11032 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11033 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11034 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11035 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11036 try { 11037 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11038 } catch (PackageManagerException e) { 11039 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11040 + e.getMessage()); 11041 return; 11042 } 11043 // Restore of old package succeeded. Update permissions. 11044 // writer 11045 synchronized (mPackages) { 11046 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11047 UPDATE_PERMISSIONS_ALL); 11048 // can downgrade to reader 11049 mSettings.writeLPr(); 11050 } 11051 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11052 } 11053 } 11054 } 11055 11056 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11057 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11058 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11059 String volumeUuid, PackageInstalledInfo res) { 11060 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11061 + ", old=" + deletedPackage); 11062 boolean disabledSystem = false; 11063 boolean updatedSettings = false; 11064 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11065 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11066 != 0) { 11067 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11068 } 11069 String packageName = deletedPackage.packageName; 11070 if (packageName == null) { 11071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11072 "Attempt to delete null packageName."); 11073 return; 11074 } 11075 PackageParser.Package oldPkg; 11076 PackageSetting oldPkgSetting; 11077 // reader 11078 synchronized (mPackages) { 11079 oldPkg = mPackages.get(packageName); 11080 oldPkgSetting = mSettings.mPackages.get(packageName); 11081 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11082 (oldPkgSetting == null)) { 11083 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11084 "Couldn't find package:" + packageName + " information"); 11085 return; 11086 } 11087 } 11088 11089 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11090 res.removedInfo.removedPackage = packageName; 11091 // Remove existing system package 11092 removePackageLI(oldPkgSetting, true); 11093 // writer 11094 synchronized (mPackages) { 11095 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11096 if (!disabledSystem && deletedPackage != null) { 11097 // We didn't need to disable the .apk as a current system package, 11098 // which means we are replacing another update that is already 11099 // installed. We need to make sure to delete the older one's .apk. 11100 res.removedInfo.args = createInstallArgsForExisting(0, 11101 deletedPackage.applicationInfo.getCodePath(), 11102 deletedPackage.applicationInfo.getResourcePath(), 11103 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11104 } else { 11105 res.removedInfo.args = null; 11106 } 11107 } 11108 11109 // Successfully disabled the old package. Now proceed with re-installation 11110 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11111 11112 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11113 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11114 11115 PackageParser.Package newPackage = null; 11116 try { 11117 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11118 if (newPackage.mExtras != null) { 11119 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11120 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11121 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11122 11123 // is the update attempting to change shared user? that isn't going to work... 11124 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11125 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11126 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11127 + " to " + newPkgSetting.sharedUser); 11128 updatedSettings = true; 11129 } 11130 } 11131 11132 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11133 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11134 perUserInstalled, res, user); 11135 updatedSettings = true; 11136 } 11137 11138 } catch (PackageManagerException e) { 11139 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11140 } 11141 11142 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11143 // Re installation failed. Restore old information 11144 // Remove new pkg information 11145 if (newPackage != null) { 11146 removeInstalledPackageLI(newPackage, true); 11147 } 11148 // Add back the old system package 11149 try { 11150 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11151 } catch (PackageManagerException e) { 11152 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11153 } 11154 // Restore the old system information in Settings 11155 synchronized (mPackages) { 11156 if (disabledSystem) { 11157 mSettings.enableSystemPackageLPw(packageName); 11158 } 11159 if (updatedSettings) { 11160 mSettings.setInstallerPackageName(packageName, 11161 oldPkgSetting.installerPackageName); 11162 } 11163 mSettings.writeLPr(); 11164 } 11165 } 11166 } 11167 11168 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11169 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11170 UserHandle user) { 11171 String pkgName = newPackage.packageName; 11172 synchronized (mPackages) { 11173 //write settings. the installStatus will be incomplete at this stage. 11174 //note that the new package setting would have already been 11175 //added to mPackages. It hasn't been persisted yet. 11176 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11177 mSettings.writeLPr(); 11178 } 11179 11180 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11181 11182 synchronized (mPackages) { 11183 updatePermissionsLPw(newPackage.packageName, newPackage, 11184 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11185 ? UPDATE_PERMISSIONS_ALL : 0)); 11186 // For system-bundled packages, we assume that installing an upgraded version 11187 // of the package implies that the user actually wants to run that new code, 11188 // so we enable the package. 11189 PackageSetting ps = mSettings.mPackages.get(pkgName); 11190 if (ps != null) { 11191 if (isSystemApp(newPackage)) { 11192 // NB: implicit assumption that system package upgrades apply to all users 11193 if (DEBUG_INSTALL) { 11194 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11195 } 11196 if (res.origUsers != null) { 11197 for (int userHandle : res.origUsers) { 11198 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11199 userHandle, installerPackageName); 11200 } 11201 } 11202 // Also convey the prior install/uninstall state 11203 if (allUsers != null && perUserInstalled != null) { 11204 for (int i = 0; i < allUsers.length; i++) { 11205 if (DEBUG_INSTALL) { 11206 Slog.d(TAG, " user " + allUsers[i] 11207 + " => " + perUserInstalled[i]); 11208 } 11209 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11210 } 11211 // these install state changes will be persisted in the 11212 // upcoming call to mSettings.writeLPr(). 11213 } 11214 } 11215 // It's implied that when a user requests installation, they want the app to be 11216 // installed and enabled. 11217 int userId = user.getIdentifier(); 11218 if (userId != UserHandle.USER_ALL) { 11219 ps.setInstalled(true, userId); 11220 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11221 } 11222 } 11223 res.name = pkgName; 11224 res.uid = newPackage.applicationInfo.uid; 11225 res.pkg = newPackage; 11226 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11227 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11228 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11229 //to update install status 11230 mSettings.writeLPr(); 11231 } 11232 } 11233 11234 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11235 final int installFlags = args.installFlags; 11236 final String installerPackageName = args.installerPackageName; 11237 final String volumeUuid = args.volumeUuid; 11238 final File tmpPackageFile = new File(args.getCodePath()); 11239 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11240 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11241 || (args.volumeUuid != null)); 11242 boolean replace = false; 11243 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11244 // Result object to be returned 11245 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11246 11247 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11248 // Retrieve PackageSettings and parse package 11249 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11250 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11251 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11252 PackageParser pp = new PackageParser(); 11253 pp.setSeparateProcesses(mSeparateProcesses); 11254 pp.setDisplayMetrics(mMetrics); 11255 11256 final PackageParser.Package pkg; 11257 try { 11258 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11259 } catch (PackageParserException e) { 11260 res.setError("Failed parse during installPackageLI", e); 11261 return; 11262 } 11263 11264 // Mark that we have an install time CPU ABI override. 11265 pkg.cpuAbiOverride = args.abiOverride; 11266 11267 String pkgName = res.name = pkg.packageName; 11268 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11269 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11270 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11271 return; 11272 } 11273 } 11274 11275 try { 11276 pp.collectCertificates(pkg, parseFlags); 11277 pp.collectManifestDigest(pkg); 11278 } catch (PackageParserException e) { 11279 res.setError("Failed collect during installPackageLI", e); 11280 return; 11281 } 11282 11283 /* If the installer passed in a manifest digest, compare it now. */ 11284 if (args.manifestDigest != null) { 11285 if (DEBUG_INSTALL) { 11286 final String parsedManifest = pkg.manifestDigest == null ? "null" 11287 : pkg.manifestDigest.toString(); 11288 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11289 + parsedManifest); 11290 } 11291 11292 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11293 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11294 return; 11295 } 11296 } else if (DEBUG_INSTALL) { 11297 final String parsedManifest = pkg.manifestDigest == null 11298 ? "null" : pkg.manifestDigest.toString(); 11299 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11300 } 11301 11302 // Get rid of all references to package scan path via parser. 11303 pp = null; 11304 String oldCodePath = null; 11305 boolean systemApp = false; 11306 synchronized (mPackages) { 11307 // Check if installing already existing package 11308 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11309 String oldName = mSettings.mRenamedPackages.get(pkgName); 11310 if (pkg.mOriginalPackages != null 11311 && pkg.mOriginalPackages.contains(oldName) 11312 && mPackages.containsKey(oldName)) { 11313 // This package is derived from an original package, 11314 // and this device has been updating from that original 11315 // name. We must continue using the original name, so 11316 // rename the new package here. 11317 pkg.setPackageName(oldName); 11318 pkgName = pkg.packageName; 11319 replace = true; 11320 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11321 + oldName + " pkgName=" + pkgName); 11322 } else if (mPackages.containsKey(pkgName)) { 11323 // This package, under its official name, already exists 11324 // on the device; we should replace it. 11325 replace = true; 11326 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11327 } 11328 } 11329 11330 PackageSetting ps = mSettings.mPackages.get(pkgName); 11331 if (ps != null) { 11332 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11333 11334 // Quick sanity check that we're signed correctly if updating; 11335 // we'll check this again later when scanning, but we want to 11336 // bail early here before tripping over redefined permissions. 11337 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11338 try { 11339 verifySignaturesLP(ps, pkg); 11340 } catch (PackageManagerException e) { 11341 res.setError(e.error, e.getMessage()); 11342 return; 11343 } 11344 } else { 11345 if (!checkUpgradeKeySetLP(ps, pkg)) { 11346 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11347 + pkg.packageName + " upgrade keys do not match the " 11348 + "previously installed version"); 11349 return; 11350 } 11351 } 11352 11353 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11354 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11355 systemApp = (ps.pkg.applicationInfo.flags & 11356 ApplicationInfo.FLAG_SYSTEM) != 0; 11357 } 11358 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11359 } 11360 11361 // Check whether the newly-scanned package wants to define an already-defined perm 11362 int N = pkg.permissions.size(); 11363 for (int i = N-1; i >= 0; i--) { 11364 PackageParser.Permission perm = pkg.permissions.get(i); 11365 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11366 if (bp != null) { 11367 // If the defining package is signed with our cert, it's okay. This 11368 // also includes the "updating the same package" case, of course. 11369 // "updating same package" could also involve key-rotation. 11370 final boolean sigsOk; 11371 if (!bp.sourcePackage.equals(pkg.packageName) 11372 || !(bp.packageSetting instanceof PackageSetting) 11373 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11374 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11375 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11376 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11377 } else { 11378 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11379 } 11380 if (!sigsOk) { 11381 // If the owning package is the system itself, we log but allow 11382 // install to proceed; we fail the install on all other permission 11383 // redefinitions. 11384 if (!bp.sourcePackage.equals("android")) { 11385 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11386 + pkg.packageName + " attempting to redeclare permission " 11387 + perm.info.name + " already owned by " + bp.sourcePackage); 11388 res.origPermission = perm.info.name; 11389 res.origPackage = bp.sourcePackage; 11390 return; 11391 } else { 11392 Slog.w(TAG, "Package " + pkg.packageName 11393 + " attempting to redeclare system permission " 11394 + perm.info.name + "; ignoring new declaration"); 11395 pkg.permissions.remove(i); 11396 } 11397 } 11398 } 11399 } 11400 11401 } 11402 11403 if (systemApp && onExternal) { 11404 // Disable updates to system apps on sdcard 11405 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11406 "Cannot install updates to system apps on sdcard"); 11407 return; 11408 } 11409 11410 if (args.move != null) { 11411 // We did an in-place move, so dex is ready to roll 11412 scanFlags |= SCAN_NO_DEX; 11413 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11414 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11415 scanFlags |= SCAN_NO_DEX; 11416 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11417 int result = mPackageDexOptimizer 11418 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11419 false /* defer */, false /* inclDependencies */); 11420 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11421 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11422 return; 11423 } 11424 } 11425 11426 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11427 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11428 return; 11429 } 11430 11431 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11432 11433 if (replace) { 11434 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11435 installerPackageName, volumeUuid, res); 11436 } else { 11437 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11438 args.user, installerPackageName, volumeUuid, res); 11439 } 11440 synchronized (mPackages) { 11441 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11442 if (ps != null) { 11443 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11444 } 11445 } 11446 } 11447 11448 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11449 if (mIntentFilterVerifierComponent == null) { 11450 Slog.d(TAG, "No IntentFilter verification will not be done as " 11451 + "there is no IntentFilterVerifier available!"); 11452 return; 11453 } 11454 11455 final int verifierUid = getPackageUid( 11456 mIntentFilterVerifierComponent.getPackageName(), 11457 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11458 11459 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11460 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11461 msg.obj = pkg; 11462 msg.arg1 = userId; 11463 msg.arg2 = verifierUid; 11464 11465 mHandler.sendMessage(msg); 11466 } 11467 11468 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11469 PackageParser.Package pkg) { 11470 int size = pkg.activities.size(); 11471 if (size == 0) { 11472 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11473 return; 11474 } 11475 11476 final boolean hasDomainURLs = hasDomainURLs(pkg); 11477 if (!hasDomainURLs) { 11478 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11479 return; 11480 } 11481 11482 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11483 + " Activities needs verification ..."); 11484 11485 final int verificationId = mIntentFilterVerificationToken++; 11486 int count = 0; 11487 final String packageName = pkg.packageName; 11488 ArrayList<String> allHosts = new ArrayList<>(); 11489 11490 synchronized (mPackages) { 11491 for (PackageParser.Activity a : pkg.activities) { 11492 for (ActivityIntentInfo filter : a.intents) { 11493 boolean needsFilterVerification = filter.needsVerification(); 11494 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11495 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11496 mIntentFilterVerifier.addOneIntentFilterVerification( 11497 verifierUid, userId, verificationId, filter, packageName); 11498 count++; 11499 } else if (!needsFilterVerification) { 11500 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11501 if (hasValidDomains(filter)) { 11502 ArrayList<String> hosts = filter.getHostsList(); 11503 if (hosts.size() > 0) { 11504 allHosts.addAll(hosts); 11505 } else { 11506 if (allHosts.isEmpty()) { 11507 allHosts.add("*"); 11508 } 11509 } 11510 } 11511 } else { 11512 Slog.d(TAG, "Verification already done for IntentFilter:" 11513 + filter.toString()); 11514 } 11515 } 11516 } 11517 } 11518 11519 if (count > 0) { 11520 mIntentFilterVerifier.startVerifications(userId); 11521 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11522 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11523 } else { 11524 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11525 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11526 packageName, allHosts) != null) { 11527 scheduleWriteSettingsLocked(); 11528 } 11529 } 11530 } 11531 11532 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11533 final ComponentName cn = filter.activity.getComponentName(); 11534 final String packageName = cn.getPackageName(); 11535 11536 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11537 packageName); 11538 if (ivi == null) { 11539 return true; 11540 } 11541 int status = ivi.getStatus(); 11542 switch (status) { 11543 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11544 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11545 return true; 11546 11547 default: 11548 // Nothing to do 11549 return false; 11550 } 11551 } 11552 11553 private static boolean isMultiArch(PackageSetting ps) { 11554 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11555 } 11556 11557 private static boolean isMultiArch(ApplicationInfo info) { 11558 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11559 } 11560 11561 private static boolean isExternal(PackageParser.Package pkg) { 11562 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11563 } 11564 11565 private static boolean isExternal(PackageSetting ps) { 11566 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11567 } 11568 11569 private static boolean isExternal(ApplicationInfo info) { 11570 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11571 } 11572 11573 private static boolean isSystemApp(PackageParser.Package pkg) { 11574 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11575 } 11576 11577 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11578 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11579 } 11580 11581 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11582 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11583 } 11584 11585 private static boolean isSystemApp(PackageSetting ps) { 11586 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11587 } 11588 11589 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11590 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11591 } 11592 11593 private int packageFlagsToInstallFlags(PackageSetting ps) { 11594 int installFlags = 0; 11595 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11596 // This existing package was an external ASEC install when we have 11597 // the external flag without a UUID 11598 installFlags |= PackageManager.INSTALL_EXTERNAL; 11599 } 11600 if (ps.isForwardLocked()) { 11601 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11602 } 11603 return installFlags; 11604 } 11605 11606 private void deleteTempPackageFiles() { 11607 final FilenameFilter filter = new FilenameFilter() { 11608 public boolean accept(File dir, String name) { 11609 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11610 } 11611 }; 11612 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11613 file.delete(); 11614 } 11615 } 11616 11617 @Override 11618 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11619 int flags) { 11620 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11621 flags); 11622 } 11623 11624 @Override 11625 public void deletePackage(final String packageName, 11626 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11627 mContext.enforceCallingOrSelfPermission( 11628 android.Manifest.permission.DELETE_PACKAGES, null); 11629 final int uid = Binder.getCallingUid(); 11630 if (UserHandle.getUserId(uid) != userId) { 11631 mContext.enforceCallingPermission( 11632 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11633 "deletePackage for user " + userId); 11634 } 11635 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11636 try { 11637 observer.onPackageDeleted(packageName, 11638 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11639 } catch (RemoteException re) { 11640 } 11641 return; 11642 } 11643 11644 boolean uninstallBlocked = false; 11645 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11646 int[] users = sUserManager.getUserIds(); 11647 for (int i = 0; i < users.length; ++i) { 11648 if (getBlockUninstallForUser(packageName, users[i])) { 11649 uninstallBlocked = true; 11650 break; 11651 } 11652 } 11653 } else { 11654 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11655 } 11656 if (uninstallBlocked) { 11657 try { 11658 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11659 null); 11660 } catch (RemoteException re) { 11661 } 11662 return; 11663 } 11664 11665 if (DEBUG_REMOVE) { 11666 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11667 } 11668 // Queue up an async operation since the package deletion may take a little while. 11669 mHandler.post(new Runnable() { 11670 public void run() { 11671 mHandler.removeCallbacks(this); 11672 final int returnCode = deletePackageX(packageName, userId, flags); 11673 if (observer != null) { 11674 try { 11675 observer.onPackageDeleted(packageName, returnCode, null); 11676 } catch (RemoteException e) { 11677 Log.i(TAG, "Observer no longer exists."); 11678 } //end catch 11679 } //end if 11680 } //end run 11681 }); 11682 } 11683 11684 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11685 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11686 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11687 try { 11688 if (dpm != null) { 11689 if (dpm.isDeviceOwner(packageName)) { 11690 return true; 11691 } 11692 int[] users; 11693 if (userId == UserHandle.USER_ALL) { 11694 users = sUserManager.getUserIds(); 11695 } else { 11696 users = new int[]{userId}; 11697 } 11698 for (int i = 0; i < users.length; ++i) { 11699 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11700 return true; 11701 } 11702 } 11703 } 11704 } catch (RemoteException e) { 11705 } 11706 return false; 11707 } 11708 11709 /** 11710 * This method is an internal method that could be get invoked either 11711 * to delete an installed package or to clean up a failed installation. 11712 * After deleting an installed package, a broadcast is sent to notify any 11713 * listeners that the package has been installed. For cleaning up a failed 11714 * installation, the broadcast is not necessary since the package's 11715 * installation wouldn't have sent the initial broadcast either 11716 * The key steps in deleting a package are 11717 * deleting the package information in internal structures like mPackages, 11718 * deleting the packages base directories through installd 11719 * updating mSettings to reflect current status 11720 * persisting settings for later use 11721 * sending a broadcast if necessary 11722 */ 11723 private int deletePackageX(String packageName, int userId, int flags) { 11724 final PackageRemovedInfo info = new PackageRemovedInfo(); 11725 final boolean res; 11726 11727 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11728 ? UserHandle.ALL : new UserHandle(userId); 11729 11730 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11731 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11732 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11733 } 11734 11735 boolean removedForAllUsers = false; 11736 boolean systemUpdate = false; 11737 11738 // for the uninstall-updates case and restricted profiles, remember the per- 11739 // userhandle installed state 11740 int[] allUsers; 11741 boolean[] perUserInstalled; 11742 synchronized (mPackages) { 11743 PackageSetting ps = mSettings.mPackages.get(packageName); 11744 allUsers = sUserManager.getUserIds(); 11745 perUserInstalled = new boolean[allUsers.length]; 11746 for (int i = 0; i < allUsers.length; i++) { 11747 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11748 } 11749 } 11750 11751 synchronized (mInstallLock) { 11752 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11753 res = deletePackageLI(packageName, removeForUser, 11754 true, allUsers, perUserInstalled, 11755 flags | REMOVE_CHATTY, info, true); 11756 systemUpdate = info.isRemovedPackageSystemUpdate; 11757 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11758 removedForAllUsers = true; 11759 } 11760 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11761 + " removedForAllUsers=" + removedForAllUsers); 11762 } 11763 11764 if (res) { 11765 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11766 11767 // If the removed package was a system update, the old system package 11768 // was re-enabled; we need to broadcast this information 11769 if (systemUpdate) { 11770 Bundle extras = new Bundle(1); 11771 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11772 ? info.removedAppId : info.uid); 11773 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11774 11775 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11776 extras, null, null, null); 11777 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11778 extras, null, null, null); 11779 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11780 null, packageName, null, null); 11781 } 11782 } 11783 // Force a gc here. 11784 Runtime.getRuntime().gc(); 11785 // Delete the resources here after sending the broadcast to let 11786 // other processes clean up before deleting resources. 11787 if (info.args != null) { 11788 synchronized (mInstallLock) { 11789 info.args.doPostDeleteLI(true); 11790 } 11791 } 11792 11793 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11794 } 11795 11796 class PackageRemovedInfo { 11797 String removedPackage; 11798 int uid = -1; 11799 int removedAppId = -1; 11800 int[] removedUsers = null; 11801 boolean isRemovedPackageSystemUpdate = false; 11802 // Clean up resources deleted packages. 11803 InstallArgs args = null; 11804 11805 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11806 Bundle extras = new Bundle(1); 11807 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11808 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11809 if (replacing) { 11810 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11811 } 11812 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11813 if (removedPackage != null) { 11814 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11815 extras, null, null, removedUsers); 11816 if (fullRemove && !replacing) { 11817 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11818 extras, null, null, removedUsers); 11819 } 11820 } 11821 if (removedAppId >= 0) { 11822 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11823 removedUsers); 11824 } 11825 } 11826 } 11827 11828 /* 11829 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11830 * flag is not set, the data directory is removed as well. 11831 * make sure this flag is set for partially installed apps. If not its meaningless to 11832 * delete a partially installed application. 11833 */ 11834 private void removePackageDataLI(PackageSetting ps, 11835 int[] allUserHandles, boolean[] perUserInstalled, 11836 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11837 String packageName = ps.name; 11838 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11839 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11840 // Retrieve object to delete permissions for shared user later on 11841 final PackageSetting deletedPs; 11842 // reader 11843 synchronized (mPackages) { 11844 deletedPs = mSettings.mPackages.get(packageName); 11845 if (outInfo != null) { 11846 outInfo.removedPackage = packageName; 11847 outInfo.removedUsers = deletedPs != null 11848 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11849 : null; 11850 } 11851 } 11852 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11853 removeDataDirsLI(ps.volumeUuid, packageName); 11854 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11855 } 11856 // writer 11857 synchronized (mPackages) { 11858 if (deletedPs != null) { 11859 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11860 if (outInfo != null) { 11861 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11862 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11863 } 11864 updatePermissionsLPw(deletedPs.name, null, 0); 11865 if (deletedPs.sharedUser != null) { 11866 // Remove permissions associated with package. Since runtime 11867 // permissions are per user we have to kill the removed package 11868 // or packages running under the shared user of the removed 11869 // package if revoking the permissions requested only by the removed 11870 // package is successful and this causes a change in gids. 11871 for (int userId : UserManagerService.getInstance().getUserIds()) { 11872 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11873 userId); 11874 if (userIdToKill == UserHandle.USER_ALL 11875 || userIdToKill >= UserHandle.USER_OWNER) { 11876 // If gids changed for this user, kill all affected packages. 11877 mHandler.post(new Runnable() { 11878 @Override 11879 public void run() { 11880 // This has to happen with no lock held. 11881 killSettingPackagesForUser(deletedPs, userIdToKill, 11882 KILL_APP_REASON_GIDS_CHANGED); 11883 } 11884 }); 11885 break; 11886 } 11887 } 11888 } 11889 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11890 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11891 } 11892 // make sure to preserve per-user disabled state if this removal was just 11893 // a downgrade of a system app to the factory package 11894 if (allUserHandles != null && perUserInstalled != null) { 11895 if (DEBUG_REMOVE) { 11896 Slog.d(TAG, "Propagating install state across downgrade"); 11897 } 11898 for (int i = 0; i < allUserHandles.length; i++) { 11899 if (DEBUG_REMOVE) { 11900 Slog.d(TAG, " user " + allUserHandles[i] 11901 + " => " + perUserInstalled[i]); 11902 } 11903 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11904 } 11905 } 11906 } 11907 // can downgrade to reader 11908 if (writeSettings) { 11909 // Save settings now 11910 mSettings.writeLPr(); 11911 } 11912 } 11913 if (outInfo != null) { 11914 // A user ID was deleted here. Go through all users and remove it 11915 // from KeyStore. 11916 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11917 } 11918 } 11919 11920 static boolean locationIsPrivileged(File path) { 11921 try { 11922 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11923 .getCanonicalPath(); 11924 return path.getCanonicalPath().startsWith(privilegedAppDir); 11925 } catch (IOException e) { 11926 Slog.e(TAG, "Unable to access code path " + path); 11927 } 11928 return false; 11929 } 11930 11931 /* 11932 * Tries to delete system package. 11933 */ 11934 private boolean deleteSystemPackageLI(PackageSetting newPs, 11935 int[] allUserHandles, boolean[] perUserInstalled, 11936 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11937 final boolean applyUserRestrictions 11938 = (allUserHandles != null) && (perUserInstalled != null); 11939 PackageSetting disabledPs = null; 11940 // Confirm if the system package has been updated 11941 // An updated system app can be deleted. This will also have to restore 11942 // the system pkg from system partition 11943 // reader 11944 synchronized (mPackages) { 11945 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11946 } 11947 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11948 + " disabledPs=" + disabledPs); 11949 if (disabledPs == null) { 11950 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11951 return false; 11952 } else if (DEBUG_REMOVE) { 11953 Slog.d(TAG, "Deleting system pkg from data partition"); 11954 } 11955 if (DEBUG_REMOVE) { 11956 if (applyUserRestrictions) { 11957 Slog.d(TAG, "Remembering install states:"); 11958 for (int i = 0; i < allUserHandles.length; i++) { 11959 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11960 } 11961 } 11962 } 11963 // Delete the updated package 11964 outInfo.isRemovedPackageSystemUpdate = true; 11965 if (disabledPs.versionCode < newPs.versionCode) { 11966 // Delete data for downgrades 11967 flags &= ~PackageManager.DELETE_KEEP_DATA; 11968 } else { 11969 // Preserve data by setting flag 11970 flags |= PackageManager.DELETE_KEEP_DATA; 11971 } 11972 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11973 allUserHandles, perUserInstalled, outInfo, writeSettings); 11974 if (!ret) { 11975 return false; 11976 } 11977 // writer 11978 synchronized (mPackages) { 11979 // Reinstate the old system package 11980 mSettings.enableSystemPackageLPw(newPs.name); 11981 // Remove any native libraries from the upgraded package. 11982 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11983 } 11984 // Install the system package 11985 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11986 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11987 if (locationIsPrivileged(disabledPs.codePath)) { 11988 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11989 } 11990 11991 final PackageParser.Package newPkg; 11992 try { 11993 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11994 } catch (PackageManagerException e) { 11995 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11996 return false; 11997 } 11998 11999 // writer 12000 synchronized (mPackages) { 12001 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12002 updatePermissionsLPw(newPkg.packageName, newPkg, 12003 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12004 if (applyUserRestrictions) { 12005 if (DEBUG_REMOVE) { 12006 Slog.d(TAG, "Propagating install state across reinstall"); 12007 } 12008 for (int i = 0; i < allUserHandles.length; i++) { 12009 if (DEBUG_REMOVE) { 12010 Slog.d(TAG, " user " + allUserHandles[i] 12011 + " => " + perUserInstalled[i]); 12012 } 12013 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12014 } 12015 // Regardless of writeSettings we need to ensure that this restriction 12016 // state propagation is persisted 12017 mSettings.writeAllUsersPackageRestrictionsLPr(); 12018 } 12019 // can downgrade to reader here 12020 if (writeSettings) { 12021 mSettings.writeLPr(); 12022 } 12023 } 12024 return true; 12025 } 12026 12027 private boolean deleteInstalledPackageLI(PackageSetting ps, 12028 boolean deleteCodeAndResources, int flags, 12029 int[] allUserHandles, boolean[] perUserInstalled, 12030 PackageRemovedInfo outInfo, boolean writeSettings) { 12031 if (outInfo != null) { 12032 outInfo.uid = ps.appId; 12033 } 12034 12035 // Delete package data from internal structures and also remove data if flag is set 12036 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12037 12038 // Delete application code and resources 12039 if (deleteCodeAndResources && (outInfo != null)) { 12040 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12041 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12042 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12043 } 12044 return true; 12045 } 12046 12047 @Override 12048 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12049 int userId) { 12050 mContext.enforceCallingOrSelfPermission( 12051 android.Manifest.permission.DELETE_PACKAGES, null); 12052 synchronized (mPackages) { 12053 PackageSetting ps = mSettings.mPackages.get(packageName); 12054 if (ps == null) { 12055 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12056 return false; 12057 } 12058 if (!ps.getInstalled(userId)) { 12059 // Can't block uninstall for an app that is not installed or enabled. 12060 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12061 return false; 12062 } 12063 ps.setBlockUninstall(blockUninstall, userId); 12064 mSettings.writePackageRestrictionsLPr(userId); 12065 } 12066 return true; 12067 } 12068 12069 @Override 12070 public boolean getBlockUninstallForUser(String packageName, int userId) { 12071 synchronized (mPackages) { 12072 PackageSetting ps = mSettings.mPackages.get(packageName); 12073 if (ps == null) { 12074 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12075 return false; 12076 } 12077 return ps.getBlockUninstall(userId); 12078 } 12079 } 12080 12081 /* 12082 * This method handles package deletion in general 12083 */ 12084 private boolean deletePackageLI(String packageName, UserHandle user, 12085 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12086 int flags, PackageRemovedInfo outInfo, 12087 boolean writeSettings) { 12088 if (packageName == null) { 12089 Slog.w(TAG, "Attempt to delete null packageName."); 12090 return false; 12091 } 12092 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12093 PackageSetting ps; 12094 boolean dataOnly = false; 12095 int removeUser = -1; 12096 int appId = -1; 12097 synchronized (mPackages) { 12098 ps = mSettings.mPackages.get(packageName); 12099 if (ps == null) { 12100 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12101 return false; 12102 } 12103 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12104 && user.getIdentifier() != UserHandle.USER_ALL) { 12105 // The caller is asking that the package only be deleted for a single 12106 // user. To do this, we just mark its uninstalled state and delete 12107 // its data. If this is a system app, we only allow this to happen if 12108 // they have set the special DELETE_SYSTEM_APP which requests different 12109 // semantics than normal for uninstalling system apps. 12110 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12111 ps.setUserState(user.getIdentifier(), 12112 COMPONENT_ENABLED_STATE_DEFAULT, 12113 false, //installed 12114 true, //stopped 12115 true, //notLaunched 12116 false, //hidden 12117 null, null, null, 12118 false, // blockUninstall 12119 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12120 if (!isSystemApp(ps)) { 12121 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12122 // Other user still have this package installed, so all 12123 // we need to do is clear this user's data and save that 12124 // it is uninstalled. 12125 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12126 removeUser = user.getIdentifier(); 12127 appId = ps.appId; 12128 scheduleWritePackageRestrictionsLocked(removeUser); 12129 } else { 12130 // We need to set it back to 'installed' so the uninstall 12131 // broadcasts will be sent correctly. 12132 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12133 ps.setInstalled(true, user.getIdentifier()); 12134 } 12135 } else { 12136 // This is a system app, so we assume that the 12137 // other users still have this package installed, so all 12138 // we need to do is clear this user's data and save that 12139 // it is uninstalled. 12140 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12141 removeUser = user.getIdentifier(); 12142 appId = ps.appId; 12143 scheduleWritePackageRestrictionsLocked(removeUser); 12144 } 12145 } 12146 } 12147 12148 if (removeUser >= 0) { 12149 // From above, we determined that we are deleting this only 12150 // for a single user. Continue the work here. 12151 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12152 if (outInfo != null) { 12153 outInfo.removedPackage = packageName; 12154 outInfo.removedAppId = appId; 12155 outInfo.removedUsers = new int[] {removeUser}; 12156 } 12157 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12158 removeKeystoreDataIfNeeded(removeUser, appId); 12159 schedulePackageCleaning(packageName, removeUser, false); 12160 synchronized (mPackages) { 12161 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12162 scheduleWritePackageRestrictionsLocked(removeUser); 12163 } 12164 } 12165 return true; 12166 } 12167 12168 if (dataOnly) { 12169 // Delete application data first 12170 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12171 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12172 return true; 12173 } 12174 12175 boolean ret = false; 12176 if (isSystemApp(ps)) { 12177 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12178 // When an updated system application is deleted we delete the existing resources as well and 12179 // fall back to existing code in system partition 12180 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12181 flags, outInfo, writeSettings); 12182 } else { 12183 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12184 // Kill application pre-emptively especially for apps on sd. 12185 killApplication(packageName, ps.appId, "uninstall pkg"); 12186 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12187 allUserHandles, perUserInstalled, 12188 outInfo, writeSettings); 12189 } 12190 12191 return ret; 12192 } 12193 12194 private final class ClearStorageConnection implements ServiceConnection { 12195 IMediaContainerService mContainerService; 12196 12197 @Override 12198 public void onServiceConnected(ComponentName name, IBinder service) { 12199 synchronized (this) { 12200 mContainerService = IMediaContainerService.Stub.asInterface(service); 12201 notifyAll(); 12202 } 12203 } 12204 12205 @Override 12206 public void onServiceDisconnected(ComponentName name) { 12207 } 12208 } 12209 12210 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12211 final boolean mounted; 12212 if (Environment.isExternalStorageEmulated()) { 12213 mounted = true; 12214 } else { 12215 final String status = Environment.getExternalStorageState(); 12216 12217 mounted = status.equals(Environment.MEDIA_MOUNTED) 12218 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12219 } 12220 12221 if (!mounted) { 12222 return; 12223 } 12224 12225 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12226 int[] users; 12227 if (userId == UserHandle.USER_ALL) { 12228 users = sUserManager.getUserIds(); 12229 } else { 12230 users = new int[] { userId }; 12231 } 12232 final ClearStorageConnection conn = new ClearStorageConnection(); 12233 if (mContext.bindServiceAsUser( 12234 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12235 try { 12236 for (int curUser : users) { 12237 long timeout = SystemClock.uptimeMillis() + 5000; 12238 synchronized (conn) { 12239 long now = SystemClock.uptimeMillis(); 12240 while (conn.mContainerService == null && now < timeout) { 12241 try { 12242 conn.wait(timeout - now); 12243 } catch (InterruptedException e) { 12244 } 12245 } 12246 } 12247 if (conn.mContainerService == null) { 12248 return; 12249 } 12250 12251 final UserEnvironment userEnv = new UserEnvironment(curUser); 12252 clearDirectory(conn.mContainerService, 12253 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12254 if (allData) { 12255 clearDirectory(conn.mContainerService, 12256 userEnv.buildExternalStorageAppDataDirs(packageName)); 12257 clearDirectory(conn.mContainerService, 12258 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12259 } 12260 } 12261 } finally { 12262 mContext.unbindService(conn); 12263 } 12264 } 12265 } 12266 12267 @Override 12268 public void clearApplicationUserData(final String packageName, 12269 final IPackageDataObserver observer, final int userId) { 12270 mContext.enforceCallingOrSelfPermission( 12271 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12272 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12273 // Queue up an async operation since the package deletion may take a little while. 12274 mHandler.post(new Runnable() { 12275 public void run() { 12276 mHandler.removeCallbacks(this); 12277 final boolean succeeded; 12278 synchronized (mInstallLock) { 12279 succeeded = clearApplicationUserDataLI(packageName, userId); 12280 } 12281 clearExternalStorageDataSync(packageName, userId, true); 12282 if (succeeded) { 12283 // invoke DeviceStorageMonitor's update method to clear any notifications 12284 DeviceStorageMonitorInternal 12285 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12286 if (dsm != null) { 12287 dsm.checkMemory(); 12288 } 12289 } 12290 if(observer != null) { 12291 try { 12292 observer.onRemoveCompleted(packageName, succeeded); 12293 } catch (RemoteException e) { 12294 Log.i(TAG, "Observer no longer exists."); 12295 } 12296 } //end if observer 12297 } //end run 12298 }); 12299 } 12300 12301 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12302 if (packageName == null) { 12303 Slog.w(TAG, "Attempt to delete null packageName."); 12304 return false; 12305 } 12306 12307 // Try finding details about the requested package 12308 PackageParser.Package pkg; 12309 synchronized (mPackages) { 12310 pkg = mPackages.get(packageName); 12311 if (pkg == null) { 12312 final PackageSetting ps = mSettings.mPackages.get(packageName); 12313 if (ps != null) { 12314 pkg = ps.pkg; 12315 } 12316 } 12317 } 12318 12319 if (pkg == null) { 12320 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12321 } 12322 12323 // Always delete data directories for package, even if we found no other 12324 // record of app. This helps users recover from UID mismatches without 12325 // resorting to a full data wipe. 12326 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12327 if (retCode < 0) { 12328 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12329 return false; 12330 } 12331 12332 if (pkg == null) { 12333 return false; 12334 } 12335 12336 if (pkg != null && pkg.applicationInfo != null) { 12337 final int appId = pkg.applicationInfo.uid; 12338 removeKeystoreDataIfNeeded(userId, appId); 12339 } 12340 12341 // Create a native library symlink only if we have native libraries 12342 // and if the native libraries are 32 bit libraries. We do not provide 12343 // this symlink for 64 bit libraries. 12344 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12345 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12346 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12347 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12348 nativeLibPath, userId) < 0) { 12349 Slog.w(TAG, "Failed linking native library dir"); 12350 return false; 12351 } 12352 } 12353 12354 return true; 12355 } 12356 12357 /** 12358 * Remove entries from the keystore daemon. Will only remove it if the 12359 * {@code appId} is valid. 12360 */ 12361 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12362 if (appId < 0) { 12363 return; 12364 } 12365 12366 final KeyStore keyStore = KeyStore.getInstance(); 12367 if (keyStore != null) { 12368 if (userId == UserHandle.USER_ALL) { 12369 for (final int individual : sUserManager.getUserIds()) { 12370 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12371 } 12372 } else { 12373 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12374 } 12375 } else { 12376 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12377 } 12378 } 12379 12380 @Override 12381 public void deleteApplicationCacheFiles(final String packageName, 12382 final IPackageDataObserver observer) { 12383 mContext.enforceCallingOrSelfPermission( 12384 android.Manifest.permission.DELETE_CACHE_FILES, null); 12385 // Queue up an async operation since the package deletion may take a little while. 12386 final int userId = UserHandle.getCallingUserId(); 12387 mHandler.post(new Runnable() { 12388 public void run() { 12389 mHandler.removeCallbacks(this); 12390 final boolean succeded; 12391 synchronized (mInstallLock) { 12392 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12393 } 12394 clearExternalStorageDataSync(packageName, userId, false); 12395 if(observer != null) { 12396 try { 12397 observer.onRemoveCompleted(packageName, succeded); 12398 } catch (RemoteException e) { 12399 Log.i(TAG, "Observer no longer exists."); 12400 } 12401 } //end if observer 12402 } //end run 12403 }); 12404 } 12405 12406 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12407 if (packageName == null) { 12408 Slog.w(TAG, "Attempt to delete null packageName."); 12409 return false; 12410 } 12411 PackageParser.Package p; 12412 synchronized (mPackages) { 12413 p = mPackages.get(packageName); 12414 } 12415 if (p == null) { 12416 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12417 return false; 12418 } 12419 final ApplicationInfo applicationInfo = p.applicationInfo; 12420 if (applicationInfo == null) { 12421 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12422 return false; 12423 } 12424 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12425 if (retCode < 0) { 12426 Slog.w(TAG, "Couldn't remove cache files for package: " 12427 + packageName + " u" + userId); 12428 return false; 12429 } 12430 return true; 12431 } 12432 12433 @Override 12434 public void getPackageSizeInfo(final String packageName, int userHandle, 12435 final IPackageStatsObserver observer) { 12436 mContext.enforceCallingOrSelfPermission( 12437 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12438 if (packageName == null) { 12439 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12440 } 12441 12442 PackageStats stats = new PackageStats(packageName, userHandle); 12443 12444 /* 12445 * Queue up an async operation since the package measurement may take a 12446 * little while. 12447 */ 12448 Message msg = mHandler.obtainMessage(INIT_COPY); 12449 msg.obj = new MeasureParams(stats, observer); 12450 mHandler.sendMessage(msg); 12451 } 12452 12453 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12454 PackageStats pStats) { 12455 if (packageName == null) { 12456 Slog.w(TAG, "Attempt to get size of null packageName."); 12457 return false; 12458 } 12459 PackageParser.Package p; 12460 boolean dataOnly = false; 12461 String libDirRoot = null; 12462 String asecPath = null; 12463 PackageSetting ps = null; 12464 synchronized (mPackages) { 12465 p = mPackages.get(packageName); 12466 ps = mSettings.mPackages.get(packageName); 12467 if(p == null) { 12468 dataOnly = true; 12469 if((ps == null) || (ps.pkg == null)) { 12470 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12471 return false; 12472 } 12473 p = ps.pkg; 12474 } 12475 if (ps != null) { 12476 libDirRoot = ps.legacyNativeLibraryPathString; 12477 } 12478 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12479 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12480 if (secureContainerId != null) { 12481 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12482 } 12483 } 12484 } 12485 String publicSrcDir = null; 12486 if(!dataOnly) { 12487 final ApplicationInfo applicationInfo = p.applicationInfo; 12488 if (applicationInfo == null) { 12489 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12490 return false; 12491 } 12492 if (p.isForwardLocked()) { 12493 publicSrcDir = applicationInfo.getBaseResourcePath(); 12494 } 12495 } 12496 // TODO: extend to measure size of split APKs 12497 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12498 // not just the first level. 12499 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12500 // just the primary. 12501 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12502 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12503 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12504 if (res < 0) { 12505 return false; 12506 } 12507 12508 // Fix-up for forward-locked applications in ASEC containers. 12509 if (!isExternal(p)) { 12510 pStats.codeSize += pStats.externalCodeSize; 12511 pStats.externalCodeSize = 0L; 12512 } 12513 12514 return true; 12515 } 12516 12517 12518 @Override 12519 public void addPackageToPreferred(String packageName) { 12520 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12521 } 12522 12523 @Override 12524 public void removePackageFromPreferred(String packageName) { 12525 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12526 } 12527 12528 @Override 12529 public List<PackageInfo> getPreferredPackages(int flags) { 12530 return new ArrayList<PackageInfo>(); 12531 } 12532 12533 private int getUidTargetSdkVersionLockedLPr(int uid) { 12534 Object obj = mSettings.getUserIdLPr(uid); 12535 if (obj instanceof SharedUserSetting) { 12536 final SharedUserSetting sus = (SharedUserSetting) obj; 12537 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12538 final Iterator<PackageSetting> it = sus.packages.iterator(); 12539 while (it.hasNext()) { 12540 final PackageSetting ps = it.next(); 12541 if (ps.pkg != null) { 12542 int v = ps.pkg.applicationInfo.targetSdkVersion; 12543 if (v < vers) vers = v; 12544 } 12545 } 12546 return vers; 12547 } else if (obj instanceof PackageSetting) { 12548 final PackageSetting ps = (PackageSetting) obj; 12549 if (ps.pkg != null) { 12550 return ps.pkg.applicationInfo.targetSdkVersion; 12551 } 12552 } 12553 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12554 } 12555 12556 @Override 12557 public void addPreferredActivity(IntentFilter filter, int match, 12558 ComponentName[] set, ComponentName activity, int userId) { 12559 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12560 "Adding preferred"); 12561 } 12562 12563 private void addPreferredActivityInternal(IntentFilter filter, int match, 12564 ComponentName[] set, ComponentName activity, boolean always, int userId, 12565 String opname) { 12566 // writer 12567 int callingUid = Binder.getCallingUid(); 12568 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12569 if (filter.countActions() == 0) { 12570 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12571 return; 12572 } 12573 synchronized (mPackages) { 12574 if (mContext.checkCallingOrSelfPermission( 12575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12576 != PackageManager.PERMISSION_GRANTED) { 12577 if (getUidTargetSdkVersionLockedLPr(callingUid) 12578 < Build.VERSION_CODES.FROYO) { 12579 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12580 + callingUid); 12581 return; 12582 } 12583 mContext.enforceCallingOrSelfPermission( 12584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12585 } 12586 12587 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12588 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12589 + userId + ":"); 12590 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12591 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12592 scheduleWritePackageRestrictionsLocked(userId); 12593 } 12594 } 12595 12596 @Override 12597 public void replacePreferredActivity(IntentFilter filter, int match, 12598 ComponentName[] set, ComponentName activity, int userId) { 12599 if (filter.countActions() != 1) { 12600 throw new IllegalArgumentException( 12601 "replacePreferredActivity expects filter to have only 1 action."); 12602 } 12603 if (filter.countDataAuthorities() != 0 12604 || filter.countDataPaths() != 0 12605 || filter.countDataSchemes() > 1 12606 || filter.countDataTypes() != 0) { 12607 throw new IllegalArgumentException( 12608 "replacePreferredActivity expects filter to have no data authorities, " + 12609 "paths, or types; and at most one scheme."); 12610 } 12611 12612 final int callingUid = Binder.getCallingUid(); 12613 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12614 synchronized (mPackages) { 12615 if (mContext.checkCallingOrSelfPermission( 12616 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12617 != PackageManager.PERMISSION_GRANTED) { 12618 if (getUidTargetSdkVersionLockedLPr(callingUid) 12619 < Build.VERSION_CODES.FROYO) { 12620 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12621 + Binder.getCallingUid()); 12622 return; 12623 } 12624 mContext.enforceCallingOrSelfPermission( 12625 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12626 } 12627 12628 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12629 if (pir != null) { 12630 // Get all of the existing entries that exactly match this filter. 12631 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12632 if (existing != null && existing.size() == 1) { 12633 PreferredActivity cur = existing.get(0); 12634 if (DEBUG_PREFERRED) { 12635 Slog.i(TAG, "Checking replace of preferred:"); 12636 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12637 if (!cur.mPref.mAlways) { 12638 Slog.i(TAG, " -- CUR; not mAlways!"); 12639 } else { 12640 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12641 Slog.i(TAG, " -- CUR: mSet=" 12642 + Arrays.toString(cur.mPref.mSetComponents)); 12643 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12644 Slog.i(TAG, " -- NEW: mMatch=" 12645 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12646 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12647 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12648 } 12649 } 12650 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12651 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12652 && cur.mPref.sameSet(set)) { 12653 // Setting the preferred activity to what it happens to be already 12654 if (DEBUG_PREFERRED) { 12655 Slog.i(TAG, "Replacing with same preferred activity " 12656 + cur.mPref.mShortComponent + " for user " 12657 + userId + ":"); 12658 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12659 } 12660 return; 12661 } 12662 } 12663 12664 if (existing != null) { 12665 if (DEBUG_PREFERRED) { 12666 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12667 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12668 } 12669 for (int i = 0; i < existing.size(); i++) { 12670 PreferredActivity pa = existing.get(i); 12671 if (DEBUG_PREFERRED) { 12672 Slog.i(TAG, "Removing existing preferred activity " 12673 + pa.mPref.mComponent + ":"); 12674 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12675 } 12676 pir.removeFilter(pa); 12677 } 12678 } 12679 } 12680 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12681 "Replacing preferred"); 12682 } 12683 } 12684 12685 @Override 12686 public void clearPackagePreferredActivities(String packageName) { 12687 final int uid = Binder.getCallingUid(); 12688 // writer 12689 synchronized (mPackages) { 12690 PackageParser.Package pkg = mPackages.get(packageName); 12691 if (pkg == null || pkg.applicationInfo.uid != uid) { 12692 if (mContext.checkCallingOrSelfPermission( 12693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12694 != PackageManager.PERMISSION_GRANTED) { 12695 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12696 < Build.VERSION_CODES.FROYO) { 12697 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12698 + Binder.getCallingUid()); 12699 return; 12700 } 12701 mContext.enforceCallingOrSelfPermission( 12702 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12703 } 12704 } 12705 12706 int user = UserHandle.getCallingUserId(); 12707 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12708 scheduleWritePackageRestrictionsLocked(user); 12709 } 12710 } 12711 } 12712 12713 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12714 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12715 ArrayList<PreferredActivity> removed = null; 12716 boolean changed = false; 12717 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12718 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12719 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12720 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12721 continue; 12722 } 12723 Iterator<PreferredActivity> it = pir.filterIterator(); 12724 while (it.hasNext()) { 12725 PreferredActivity pa = it.next(); 12726 // Mark entry for removal only if it matches the package name 12727 // and the entry is of type "always". 12728 if (packageName == null || 12729 (pa.mPref.mComponent.getPackageName().equals(packageName) 12730 && pa.mPref.mAlways)) { 12731 if (removed == null) { 12732 removed = new ArrayList<PreferredActivity>(); 12733 } 12734 removed.add(pa); 12735 } 12736 } 12737 if (removed != null) { 12738 for (int j=0; j<removed.size(); j++) { 12739 PreferredActivity pa = removed.get(j); 12740 pir.removeFilter(pa); 12741 } 12742 changed = true; 12743 } 12744 } 12745 return changed; 12746 } 12747 12748 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12749 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12750 if (userId == UserHandle.USER_ALL) { 12751 mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds()); 12752 for (int oneUserId : sUserManager.getUserIds()) { 12753 scheduleWritePackageRestrictionsLocked(oneUserId); 12754 } 12755 } else { 12756 mSettings.removeIntentFilterVerificationLPw(packageName, userId); 12757 scheduleWritePackageRestrictionsLocked(userId); 12758 } 12759 } 12760 12761 @Override 12762 public void resetPreferredActivities(int userId) { 12763 /* TODO: Actually use userId. Why is it being passed in? */ 12764 mContext.enforceCallingOrSelfPermission( 12765 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12766 // writer 12767 synchronized (mPackages) { 12768 int user = UserHandle.getCallingUserId(); 12769 clearPackagePreferredActivitiesLPw(null, user); 12770 mSettings.readDefaultPreferredAppsLPw(this, user); 12771 scheduleWritePackageRestrictionsLocked(user); 12772 } 12773 } 12774 12775 @Override 12776 public int getPreferredActivities(List<IntentFilter> outFilters, 12777 List<ComponentName> outActivities, String packageName) { 12778 12779 int num = 0; 12780 final int userId = UserHandle.getCallingUserId(); 12781 // reader 12782 synchronized (mPackages) { 12783 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12784 if (pir != null) { 12785 final Iterator<PreferredActivity> it = pir.filterIterator(); 12786 while (it.hasNext()) { 12787 final PreferredActivity pa = it.next(); 12788 if (packageName == null 12789 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12790 && pa.mPref.mAlways)) { 12791 if (outFilters != null) { 12792 outFilters.add(new IntentFilter(pa)); 12793 } 12794 if (outActivities != null) { 12795 outActivities.add(pa.mPref.mComponent); 12796 } 12797 } 12798 } 12799 } 12800 } 12801 12802 return num; 12803 } 12804 12805 @Override 12806 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12807 int userId) { 12808 int callingUid = Binder.getCallingUid(); 12809 if (callingUid != Process.SYSTEM_UID) { 12810 throw new SecurityException( 12811 "addPersistentPreferredActivity can only be run by the system"); 12812 } 12813 if (filter.countActions() == 0) { 12814 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12815 return; 12816 } 12817 synchronized (mPackages) { 12818 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12819 " :"); 12820 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12821 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12822 new PersistentPreferredActivity(filter, activity)); 12823 scheduleWritePackageRestrictionsLocked(userId); 12824 } 12825 } 12826 12827 @Override 12828 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12829 int callingUid = Binder.getCallingUid(); 12830 if (callingUid != Process.SYSTEM_UID) { 12831 throw new SecurityException( 12832 "clearPackagePersistentPreferredActivities can only be run by the system"); 12833 } 12834 ArrayList<PersistentPreferredActivity> removed = null; 12835 boolean changed = false; 12836 synchronized (mPackages) { 12837 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12838 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12839 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12840 .valueAt(i); 12841 if (userId != thisUserId) { 12842 continue; 12843 } 12844 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12845 while (it.hasNext()) { 12846 PersistentPreferredActivity ppa = it.next(); 12847 // Mark entry for removal only if it matches the package name. 12848 if (ppa.mComponent.getPackageName().equals(packageName)) { 12849 if (removed == null) { 12850 removed = new ArrayList<PersistentPreferredActivity>(); 12851 } 12852 removed.add(ppa); 12853 } 12854 } 12855 if (removed != null) { 12856 for (int j=0; j<removed.size(); j++) { 12857 PersistentPreferredActivity ppa = removed.get(j); 12858 ppir.removeFilter(ppa); 12859 } 12860 changed = true; 12861 } 12862 } 12863 12864 if (changed) { 12865 scheduleWritePackageRestrictionsLocked(userId); 12866 } 12867 } 12868 } 12869 12870 /** 12871 * Non-Binder method, support for the backup/restore mechanism: write the 12872 * full set of preferred activities in its canonical XML format. Returns true 12873 * on success; false otherwise. 12874 */ 12875 @Override 12876 public byte[] getPreferredActivityBackup(int userId) { 12877 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12878 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12879 } 12880 12881 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12882 try { 12883 final XmlSerializer serializer = new FastXmlSerializer(); 12884 serializer.setOutput(dataStream, "utf-8"); 12885 serializer.startDocument(null, true); 12886 serializer.startTag(null, TAG_PREFERRED_BACKUP); 12887 12888 synchronized (mPackages) { 12889 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 12890 } 12891 12892 serializer.endTag(null, TAG_PREFERRED_BACKUP); 12893 serializer.endDocument(); 12894 serializer.flush(); 12895 } catch (Exception e) { 12896 if (DEBUG_BACKUP) { 12897 Slog.e(TAG, "Unable to write preferred activities for backup", e); 12898 } 12899 return null; 12900 } 12901 12902 return dataStream.toByteArray(); 12903 } 12904 12905 @Override 12906 public void restorePreferredActivities(byte[] backup, int userId) { 12907 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12908 throw new SecurityException("Only the system may call restorePreferredActivities()"); 12909 } 12910 12911 try { 12912 final XmlPullParser parser = Xml.newPullParser(); 12913 parser.setInput(new ByteArrayInputStream(backup), null); 12914 12915 int type; 12916 while ((type = parser.next()) != XmlPullParser.START_TAG 12917 && type != XmlPullParser.END_DOCUMENT) { 12918 } 12919 if (type != XmlPullParser.START_TAG) { 12920 // oops didn't find a start tag?! 12921 if (DEBUG_BACKUP) { 12922 Slog.e(TAG, "Didn't find start tag during restore"); 12923 } 12924 return; 12925 } 12926 12927 // this is supposed to be TAG_PREFERRED_BACKUP 12928 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 12929 if (DEBUG_BACKUP) { 12930 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 12931 } 12932 return; 12933 } 12934 12935 // skip interfering stuff, then we're aligned with the backing implementation 12936 while ((type = parser.next()) == XmlPullParser.TEXT) { } 12937 synchronized (mPackages) { 12938 mSettings.readPreferredActivitiesLPw(parser, userId); 12939 } 12940 } catch (Exception e) { 12941 if (DEBUG_BACKUP) { 12942 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 12943 } 12944 } 12945 } 12946 12947 @Override 12948 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12949 int sourceUserId, int targetUserId, int flags) { 12950 mContext.enforceCallingOrSelfPermission( 12951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12952 int callingUid = Binder.getCallingUid(); 12953 enforceOwnerRights(ownerPackage, callingUid); 12954 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12955 if (intentFilter.countActions() == 0) { 12956 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12957 return; 12958 } 12959 synchronized (mPackages) { 12960 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12961 ownerPackage, targetUserId, flags); 12962 CrossProfileIntentResolver resolver = 12963 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12964 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12965 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12966 if (existing != null) { 12967 int size = existing.size(); 12968 for (int i = 0; i < size; i++) { 12969 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12970 return; 12971 } 12972 } 12973 } 12974 resolver.addFilter(newFilter); 12975 scheduleWritePackageRestrictionsLocked(sourceUserId); 12976 } 12977 } 12978 12979 @Override 12980 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 12981 mContext.enforceCallingOrSelfPermission( 12982 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12983 int callingUid = Binder.getCallingUid(); 12984 enforceOwnerRights(ownerPackage, callingUid); 12985 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12986 synchronized (mPackages) { 12987 CrossProfileIntentResolver resolver = 12988 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12989 ArraySet<CrossProfileIntentFilter> set = 12990 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12991 for (CrossProfileIntentFilter filter : set) { 12992 if (filter.getOwnerPackage().equals(ownerPackage)) { 12993 resolver.removeFilter(filter); 12994 } 12995 } 12996 scheduleWritePackageRestrictionsLocked(sourceUserId); 12997 } 12998 } 12999 13000 // Enforcing that callingUid is owning pkg on userId 13001 private void enforceOwnerRights(String pkg, int callingUid) { 13002 // The system owns everything. 13003 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13004 return; 13005 } 13006 int callingUserId = UserHandle.getUserId(callingUid); 13007 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13008 if (pi == null) { 13009 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13010 + callingUserId); 13011 } 13012 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13013 throw new SecurityException("Calling uid " + callingUid 13014 + " does not own package " + pkg); 13015 } 13016 } 13017 13018 @Override 13019 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13020 Intent intent = new Intent(Intent.ACTION_MAIN); 13021 intent.addCategory(Intent.CATEGORY_HOME); 13022 13023 final int callingUserId = UserHandle.getCallingUserId(); 13024 List<ResolveInfo> list = queryIntentActivities(intent, null, 13025 PackageManager.GET_META_DATA, callingUserId); 13026 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13027 true, false, false, callingUserId); 13028 13029 allHomeCandidates.clear(); 13030 if (list != null) { 13031 for (ResolveInfo ri : list) { 13032 allHomeCandidates.add(ri); 13033 } 13034 } 13035 return (preferred == null || preferred.activityInfo == null) 13036 ? null 13037 : new ComponentName(preferred.activityInfo.packageName, 13038 preferred.activityInfo.name); 13039 } 13040 13041 @Override 13042 public void setApplicationEnabledSetting(String appPackageName, 13043 int newState, int flags, int userId, String callingPackage) { 13044 if (!sUserManager.exists(userId)) return; 13045 if (callingPackage == null) { 13046 callingPackage = Integer.toString(Binder.getCallingUid()); 13047 } 13048 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13049 } 13050 13051 @Override 13052 public void setComponentEnabledSetting(ComponentName componentName, 13053 int newState, int flags, int userId) { 13054 if (!sUserManager.exists(userId)) return; 13055 setEnabledSetting(componentName.getPackageName(), 13056 componentName.getClassName(), newState, flags, userId, null); 13057 } 13058 13059 private void setEnabledSetting(final String packageName, String className, int newState, 13060 final int flags, int userId, String callingPackage) { 13061 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13062 || newState == COMPONENT_ENABLED_STATE_ENABLED 13063 || newState == COMPONENT_ENABLED_STATE_DISABLED 13064 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13065 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13066 throw new IllegalArgumentException("Invalid new component state: " 13067 + newState); 13068 } 13069 PackageSetting pkgSetting; 13070 final int uid = Binder.getCallingUid(); 13071 final int permission = mContext.checkCallingOrSelfPermission( 13072 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13073 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13074 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13075 boolean sendNow = false; 13076 boolean isApp = (className == null); 13077 String componentName = isApp ? packageName : className; 13078 int packageUid = -1; 13079 ArrayList<String> components; 13080 13081 // writer 13082 synchronized (mPackages) { 13083 pkgSetting = mSettings.mPackages.get(packageName); 13084 if (pkgSetting == null) { 13085 if (className == null) { 13086 throw new IllegalArgumentException( 13087 "Unknown package: " + packageName); 13088 } 13089 throw new IllegalArgumentException( 13090 "Unknown component: " + packageName 13091 + "/" + className); 13092 } 13093 // Allow root and verify that userId is not being specified by a different user 13094 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13095 throw new SecurityException( 13096 "Permission Denial: attempt to change component state from pid=" 13097 + Binder.getCallingPid() 13098 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13099 } 13100 if (className == null) { 13101 // We're dealing with an application/package level state change 13102 if (pkgSetting.getEnabled(userId) == newState) { 13103 // Nothing to do 13104 return; 13105 } 13106 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13107 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13108 // Don't care about who enables an app. 13109 callingPackage = null; 13110 } 13111 pkgSetting.setEnabled(newState, userId, callingPackage); 13112 // pkgSetting.pkg.mSetEnabled = newState; 13113 } else { 13114 // We're dealing with a component level state change 13115 // First, verify that this is a valid class name. 13116 PackageParser.Package pkg = pkgSetting.pkg; 13117 if (pkg == null || !pkg.hasComponentClassName(className)) { 13118 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13119 throw new IllegalArgumentException("Component class " + className 13120 + " does not exist in " + packageName); 13121 } else { 13122 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13123 + className + " does not exist in " + packageName); 13124 } 13125 } 13126 switch (newState) { 13127 case COMPONENT_ENABLED_STATE_ENABLED: 13128 if (!pkgSetting.enableComponentLPw(className, userId)) { 13129 return; 13130 } 13131 break; 13132 case COMPONENT_ENABLED_STATE_DISABLED: 13133 if (!pkgSetting.disableComponentLPw(className, userId)) { 13134 return; 13135 } 13136 break; 13137 case COMPONENT_ENABLED_STATE_DEFAULT: 13138 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13139 return; 13140 } 13141 break; 13142 default: 13143 Slog.e(TAG, "Invalid new component state: " + newState); 13144 return; 13145 } 13146 } 13147 scheduleWritePackageRestrictionsLocked(userId); 13148 components = mPendingBroadcasts.get(userId, packageName); 13149 final boolean newPackage = components == null; 13150 if (newPackage) { 13151 components = new ArrayList<String>(); 13152 } 13153 if (!components.contains(componentName)) { 13154 components.add(componentName); 13155 } 13156 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13157 sendNow = true; 13158 // Purge entry from pending broadcast list if another one exists already 13159 // since we are sending one right away. 13160 mPendingBroadcasts.remove(userId, packageName); 13161 } else { 13162 if (newPackage) { 13163 mPendingBroadcasts.put(userId, packageName, components); 13164 } 13165 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13166 // Schedule a message 13167 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13168 } 13169 } 13170 } 13171 13172 long callingId = Binder.clearCallingIdentity(); 13173 try { 13174 if (sendNow) { 13175 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13176 sendPackageChangedBroadcast(packageName, 13177 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13178 } 13179 } finally { 13180 Binder.restoreCallingIdentity(callingId); 13181 } 13182 } 13183 13184 private void sendPackageChangedBroadcast(String packageName, 13185 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13186 if (DEBUG_INSTALL) 13187 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13188 + componentNames); 13189 Bundle extras = new Bundle(4); 13190 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13191 String nameList[] = new String[componentNames.size()]; 13192 componentNames.toArray(nameList); 13193 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13194 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13195 extras.putInt(Intent.EXTRA_UID, packageUid); 13196 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13197 new int[] {UserHandle.getUserId(packageUid)}); 13198 } 13199 13200 @Override 13201 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13202 if (!sUserManager.exists(userId)) return; 13203 final int uid = Binder.getCallingUid(); 13204 final int permission = mContext.checkCallingOrSelfPermission( 13205 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13206 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13207 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13208 // writer 13209 synchronized (mPackages) { 13210 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13211 allowedByPermission, uid, userId)) { 13212 scheduleWritePackageRestrictionsLocked(userId); 13213 } 13214 } 13215 } 13216 13217 @Override 13218 public String getInstallerPackageName(String packageName) { 13219 // reader 13220 synchronized (mPackages) { 13221 return mSettings.getInstallerPackageNameLPr(packageName); 13222 } 13223 } 13224 13225 @Override 13226 public int getApplicationEnabledSetting(String packageName, int userId) { 13227 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13228 int uid = Binder.getCallingUid(); 13229 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13230 // reader 13231 synchronized (mPackages) { 13232 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13233 } 13234 } 13235 13236 @Override 13237 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13238 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13239 int uid = Binder.getCallingUid(); 13240 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13241 // reader 13242 synchronized (mPackages) { 13243 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13244 } 13245 } 13246 13247 @Override 13248 public void enterSafeMode() { 13249 enforceSystemOrRoot("Only the system can request entering safe mode"); 13250 13251 if (!mSystemReady) { 13252 mSafeMode = true; 13253 } 13254 } 13255 13256 @Override 13257 public void systemReady() { 13258 mSystemReady = true; 13259 13260 // Read the compatibilty setting when the system is ready. 13261 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13262 mContext.getContentResolver(), 13263 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13264 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13265 if (DEBUG_SETTINGS) { 13266 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13267 } 13268 13269 synchronized (mPackages) { 13270 // Verify that all of the preferred activity components actually 13271 // exist. It is possible for applications to be updated and at 13272 // that point remove a previously declared activity component that 13273 // had been set as a preferred activity. We try to clean this up 13274 // the next time we encounter that preferred activity, but it is 13275 // possible for the user flow to never be able to return to that 13276 // situation so here we do a sanity check to make sure we haven't 13277 // left any junk around. 13278 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13279 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13280 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13281 removed.clear(); 13282 for (PreferredActivity pa : pir.filterSet()) { 13283 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13284 removed.add(pa); 13285 } 13286 } 13287 if (removed.size() > 0) { 13288 for (int r=0; r<removed.size(); r++) { 13289 PreferredActivity pa = removed.get(r); 13290 Slog.w(TAG, "Removing dangling preferred activity: " 13291 + pa.mPref.mComponent); 13292 pir.removeFilter(pa); 13293 } 13294 mSettings.writePackageRestrictionsLPr( 13295 mSettings.mPreferredActivities.keyAt(i)); 13296 } 13297 } 13298 } 13299 sUserManager.systemReady(); 13300 13301 // Kick off any messages waiting for system ready 13302 if (mPostSystemReadyMessages != null) { 13303 for (Message msg : mPostSystemReadyMessages) { 13304 msg.sendToTarget(); 13305 } 13306 mPostSystemReadyMessages = null; 13307 } 13308 13309 // Watch for external volumes that come and go over time 13310 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13311 storage.registerListener(mStorageListener); 13312 13313 mInstallerService.systemReady(); 13314 } 13315 13316 @Override 13317 public boolean isSafeMode() { 13318 return mSafeMode; 13319 } 13320 13321 @Override 13322 public boolean hasSystemUidErrors() { 13323 return mHasSystemUidErrors; 13324 } 13325 13326 static String arrayToString(int[] array) { 13327 StringBuffer buf = new StringBuffer(128); 13328 buf.append('['); 13329 if (array != null) { 13330 for (int i=0; i<array.length; i++) { 13331 if (i > 0) buf.append(", "); 13332 buf.append(array[i]); 13333 } 13334 } 13335 buf.append(']'); 13336 return buf.toString(); 13337 } 13338 13339 static class DumpState { 13340 public static final int DUMP_LIBS = 1 << 0; 13341 public static final int DUMP_FEATURES = 1 << 1; 13342 public static final int DUMP_RESOLVERS = 1 << 2; 13343 public static final int DUMP_PERMISSIONS = 1 << 3; 13344 public static final int DUMP_PACKAGES = 1 << 4; 13345 public static final int DUMP_SHARED_USERS = 1 << 5; 13346 public static final int DUMP_MESSAGES = 1 << 6; 13347 public static final int DUMP_PROVIDERS = 1 << 7; 13348 public static final int DUMP_VERIFIERS = 1 << 8; 13349 public static final int DUMP_PREFERRED = 1 << 9; 13350 public static final int DUMP_PREFERRED_XML = 1 << 10; 13351 public static final int DUMP_KEYSETS = 1 << 11; 13352 public static final int DUMP_VERSION = 1 << 12; 13353 public static final int DUMP_INSTALLS = 1 << 13; 13354 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13355 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13356 13357 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13358 13359 private int mTypes; 13360 13361 private int mOptions; 13362 13363 private boolean mTitlePrinted; 13364 13365 private SharedUserSetting mSharedUser; 13366 13367 public boolean isDumping(int type) { 13368 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13369 return true; 13370 } 13371 13372 return (mTypes & type) != 0; 13373 } 13374 13375 public void setDump(int type) { 13376 mTypes |= type; 13377 } 13378 13379 public boolean isOptionEnabled(int option) { 13380 return (mOptions & option) != 0; 13381 } 13382 13383 public void setOptionEnabled(int option) { 13384 mOptions |= option; 13385 } 13386 13387 public boolean onTitlePrinted() { 13388 final boolean printed = mTitlePrinted; 13389 mTitlePrinted = true; 13390 return printed; 13391 } 13392 13393 public boolean getTitlePrinted() { 13394 return mTitlePrinted; 13395 } 13396 13397 public void setTitlePrinted(boolean enabled) { 13398 mTitlePrinted = enabled; 13399 } 13400 13401 public SharedUserSetting getSharedUser() { 13402 return mSharedUser; 13403 } 13404 13405 public void setSharedUser(SharedUserSetting user) { 13406 mSharedUser = user; 13407 } 13408 } 13409 13410 @Override 13411 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13412 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13413 != PackageManager.PERMISSION_GRANTED) { 13414 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13415 + Binder.getCallingPid() 13416 + ", uid=" + Binder.getCallingUid() 13417 + " without permission " 13418 + android.Manifest.permission.DUMP); 13419 return; 13420 } 13421 13422 DumpState dumpState = new DumpState(); 13423 boolean fullPreferred = false; 13424 boolean checkin = false; 13425 13426 String packageName = null; 13427 13428 int opti = 0; 13429 while (opti < args.length) { 13430 String opt = args[opti]; 13431 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13432 break; 13433 } 13434 opti++; 13435 13436 if ("-a".equals(opt)) { 13437 // Right now we only know how to print all. 13438 } else if ("-h".equals(opt)) { 13439 pw.println("Package manager dump options:"); 13440 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13441 pw.println(" --checkin: dump for a checkin"); 13442 pw.println(" -f: print details of intent filters"); 13443 pw.println(" -h: print this help"); 13444 pw.println(" cmd may be one of:"); 13445 pw.println(" l[ibraries]: list known shared libraries"); 13446 pw.println(" f[ibraries]: list device features"); 13447 pw.println(" k[eysets]: print known keysets"); 13448 pw.println(" r[esolvers]: dump intent resolvers"); 13449 pw.println(" perm[issions]: dump permissions"); 13450 pw.println(" pref[erred]: print preferred package settings"); 13451 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13452 pw.println(" prov[iders]: dump content providers"); 13453 pw.println(" p[ackages]: dump installed packages"); 13454 pw.println(" s[hared-users]: dump shared user IDs"); 13455 pw.println(" m[essages]: print collected runtime messages"); 13456 pw.println(" v[erifiers]: print package verifier info"); 13457 pw.println(" version: print database version info"); 13458 pw.println(" write: write current settings now"); 13459 pw.println(" <package.name>: info about given package"); 13460 pw.println(" installs: details about install sessions"); 13461 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13462 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13463 return; 13464 } else if ("--checkin".equals(opt)) { 13465 checkin = true; 13466 } else if ("-f".equals(opt)) { 13467 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13468 } else { 13469 pw.println("Unknown argument: " + opt + "; use -h for help"); 13470 } 13471 } 13472 13473 // Is the caller requesting to dump a particular piece of data? 13474 if (opti < args.length) { 13475 String cmd = args[opti]; 13476 opti++; 13477 // Is this a package name? 13478 if ("android".equals(cmd) || cmd.contains(".")) { 13479 packageName = cmd; 13480 // When dumping a single package, we always dump all of its 13481 // filter information since the amount of data will be reasonable. 13482 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13483 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13484 dumpState.setDump(DumpState.DUMP_LIBS); 13485 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13486 dumpState.setDump(DumpState.DUMP_FEATURES); 13487 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13488 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13489 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13490 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13491 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13492 dumpState.setDump(DumpState.DUMP_PREFERRED); 13493 } else if ("preferred-xml".equals(cmd)) { 13494 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13495 if (opti < args.length && "--full".equals(args[opti])) { 13496 fullPreferred = true; 13497 opti++; 13498 } 13499 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13500 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13501 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13502 dumpState.setDump(DumpState.DUMP_PACKAGES); 13503 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13504 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13505 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13506 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13507 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13508 dumpState.setDump(DumpState.DUMP_MESSAGES); 13509 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13510 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13511 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13512 || "intent-filter-verifiers".equals(cmd)) { 13513 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13514 } else if ("version".equals(cmd)) { 13515 dumpState.setDump(DumpState.DUMP_VERSION); 13516 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13517 dumpState.setDump(DumpState.DUMP_KEYSETS); 13518 } else if ("installs".equals(cmd)) { 13519 dumpState.setDump(DumpState.DUMP_INSTALLS); 13520 } else if ("write".equals(cmd)) { 13521 synchronized (mPackages) { 13522 mSettings.writeLPr(); 13523 pw.println("Settings written."); 13524 return; 13525 } 13526 } 13527 } 13528 13529 if (checkin) { 13530 pw.println("vers,1"); 13531 } 13532 13533 // reader 13534 synchronized (mPackages) { 13535 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13536 if (!checkin) { 13537 if (dumpState.onTitlePrinted()) 13538 pw.println(); 13539 pw.println("Database versions:"); 13540 pw.print(" SDK Version:"); 13541 pw.print(" internal="); 13542 pw.print(mSettings.mInternalSdkPlatform); 13543 pw.print(" external="); 13544 pw.println(mSettings.mExternalSdkPlatform); 13545 pw.print(" DB Version:"); 13546 pw.print(" internal="); 13547 pw.print(mSettings.mInternalDatabaseVersion); 13548 pw.print(" external="); 13549 pw.println(mSettings.mExternalDatabaseVersion); 13550 } 13551 } 13552 13553 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13554 if (!checkin) { 13555 if (dumpState.onTitlePrinted()) 13556 pw.println(); 13557 pw.println("Verifiers:"); 13558 pw.print(" Required: "); 13559 pw.print(mRequiredVerifierPackage); 13560 pw.print(" (uid="); 13561 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13562 pw.println(")"); 13563 } else if (mRequiredVerifierPackage != null) { 13564 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13565 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13566 } 13567 } 13568 13569 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13570 packageName == null) { 13571 if (mIntentFilterVerifierComponent != null) { 13572 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13573 if (!checkin) { 13574 if (dumpState.onTitlePrinted()) 13575 pw.println(); 13576 pw.println("Intent Filter Verifier:"); 13577 pw.print(" Using: "); 13578 pw.print(verifierPackageName); 13579 pw.print(" (uid="); 13580 pw.print(getPackageUid(verifierPackageName, 0)); 13581 pw.println(")"); 13582 } else if (verifierPackageName != null) { 13583 pw.print("ifv,"); pw.print(verifierPackageName); 13584 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13585 } 13586 } else { 13587 pw.println(); 13588 pw.println("No Intent Filter Verifier available!"); 13589 } 13590 } 13591 13592 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13593 boolean printedHeader = false; 13594 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13595 while (it.hasNext()) { 13596 String name = it.next(); 13597 SharedLibraryEntry ent = mSharedLibraries.get(name); 13598 if (!checkin) { 13599 if (!printedHeader) { 13600 if (dumpState.onTitlePrinted()) 13601 pw.println(); 13602 pw.println("Libraries:"); 13603 printedHeader = true; 13604 } 13605 pw.print(" "); 13606 } else { 13607 pw.print("lib,"); 13608 } 13609 pw.print(name); 13610 if (!checkin) { 13611 pw.print(" -> "); 13612 } 13613 if (ent.path != null) { 13614 if (!checkin) { 13615 pw.print("(jar) "); 13616 pw.print(ent.path); 13617 } else { 13618 pw.print(",jar,"); 13619 pw.print(ent.path); 13620 } 13621 } else { 13622 if (!checkin) { 13623 pw.print("(apk) "); 13624 pw.print(ent.apk); 13625 } else { 13626 pw.print(",apk,"); 13627 pw.print(ent.apk); 13628 } 13629 } 13630 pw.println(); 13631 } 13632 } 13633 13634 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13635 if (dumpState.onTitlePrinted()) 13636 pw.println(); 13637 if (!checkin) { 13638 pw.println("Features:"); 13639 } 13640 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13641 while (it.hasNext()) { 13642 String name = it.next(); 13643 if (!checkin) { 13644 pw.print(" "); 13645 } else { 13646 pw.print("feat,"); 13647 } 13648 pw.println(name); 13649 } 13650 } 13651 13652 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13653 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13654 : "Activity Resolver Table:", " ", packageName, 13655 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13656 dumpState.setTitlePrinted(true); 13657 } 13658 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13659 : "Receiver Resolver Table:", " ", packageName, 13660 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13661 dumpState.setTitlePrinted(true); 13662 } 13663 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13664 : "Service Resolver Table:", " ", packageName, 13665 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13666 dumpState.setTitlePrinted(true); 13667 } 13668 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13669 : "Provider Resolver Table:", " ", packageName, 13670 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13671 dumpState.setTitlePrinted(true); 13672 } 13673 } 13674 13675 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13676 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13677 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13678 int user = mSettings.mPreferredActivities.keyAt(i); 13679 if (pir.dump(pw, 13680 dumpState.getTitlePrinted() 13681 ? "\nPreferred Activities User " + user + ":" 13682 : "Preferred Activities User " + user + ":", " ", 13683 packageName, true, false)) { 13684 dumpState.setTitlePrinted(true); 13685 } 13686 } 13687 } 13688 13689 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13690 pw.flush(); 13691 FileOutputStream fout = new FileOutputStream(fd); 13692 BufferedOutputStream str = new BufferedOutputStream(fout); 13693 XmlSerializer serializer = new FastXmlSerializer(); 13694 try { 13695 serializer.setOutput(str, "utf-8"); 13696 serializer.startDocument(null, true); 13697 serializer.setFeature( 13698 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13699 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13700 serializer.endDocument(); 13701 serializer.flush(); 13702 } catch (IllegalArgumentException e) { 13703 pw.println("Failed writing: " + e); 13704 } catch (IllegalStateException e) { 13705 pw.println("Failed writing: " + e); 13706 } catch (IOException e) { 13707 pw.println("Failed writing: " + e); 13708 } 13709 } 13710 13711 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13712 pw.println(); 13713 int count = mSettings.mPackages.size(); 13714 if (count == 0) { 13715 pw.println("No domain preferred apps!"); 13716 pw.println(); 13717 } else { 13718 final String prefix = " "; 13719 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13720 if (allPackageSettings.size() == 0) { 13721 pw.println("No domain preferred apps!"); 13722 pw.println(); 13723 } else { 13724 pw.println("Domain preferred apps status:"); 13725 pw.println(); 13726 count = 0; 13727 for (PackageSetting ps : allPackageSettings) { 13728 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13729 if (ivi == null || ivi.getPackageName() == null) continue; 13730 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13731 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13732 pw.println(prefix + "Status: " + ivi.getStatusString()); 13733 pw.println(); 13734 count++; 13735 } 13736 if (count == 0) { 13737 pw.println(prefix + "No domain preferred app status!"); 13738 pw.println(); 13739 } 13740 for (int userId : sUserManager.getUserIds()) { 13741 pw.println("Domain preferred apps for User " + userId + ":"); 13742 pw.println(); 13743 count = 0; 13744 for (PackageSetting ps : allPackageSettings) { 13745 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13746 if (ivi == null || ivi.getPackageName() == null) { 13747 continue; 13748 } 13749 final int status = ps.getDomainVerificationStatusForUser(userId); 13750 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13751 continue; 13752 } 13753 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13754 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13755 String statusStr = IntentFilterVerificationInfo. 13756 getStatusStringFromValue(status); 13757 pw.println(prefix + "Status: " + statusStr); 13758 pw.println(); 13759 count++; 13760 } 13761 if (count == 0) { 13762 pw.println(prefix + "No domain preferred apps!"); 13763 pw.println(); 13764 } 13765 } 13766 } 13767 } 13768 } 13769 13770 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13771 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13772 if (packageName == null) { 13773 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13774 if (iperm == 0) { 13775 if (dumpState.onTitlePrinted()) 13776 pw.println(); 13777 pw.println("AppOp Permissions:"); 13778 } 13779 pw.print(" AppOp Permission "); 13780 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13781 pw.println(":"); 13782 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13783 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13784 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13785 } 13786 } 13787 } 13788 } 13789 13790 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13791 boolean printedSomething = false; 13792 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13793 if (packageName != null && !packageName.equals(p.info.packageName)) { 13794 continue; 13795 } 13796 if (!printedSomething) { 13797 if (dumpState.onTitlePrinted()) 13798 pw.println(); 13799 pw.println("Registered ContentProviders:"); 13800 printedSomething = true; 13801 } 13802 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13803 pw.print(" "); pw.println(p.toString()); 13804 } 13805 printedSomething = false; 13806 for (Map.Entry<String, PackageParser.Provider> entry : 13807 mProvidersByAuthority.entrySet()) { 13808 PackageParser.Provider p = entry.getValue(); 13809 if (packageName != null && !packageName.equals(p.info.packageName)) { 13810 continue; 13811 } 13812 if (!printedSomething) { 13813 if (dumpState.onTitlePrinted()) 13814 pw.println(); 13815 pw.println("ContentProvider Authorities:"); 13816 printedSomething = true; 13817 } 13818 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13819 pw.print(" "); pw.println(p.toString()); 13820 if (p.info != null && p.info.applicationInfo != null) { 13821 final String appInfo = p.info.applicationInfo.toString(); 13822 pw.print(" applicationInfo="); pw.println(appInfo); 13823 } 13824 } 13825 } 13826 13827 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13828 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13829 } 13830 13831 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13832 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13833 } 13834 13835 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13836 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13837 } 13838 13839 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13840 // XXX should handle packageName != null by dumping only install data that 13841 // the given package is involved with. 13842 if (dumpState.onTitlePrinted()) pw.println(); 13843 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13844 } 13845 13846 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13847 if (dumpState.onTitlePrinted()) pw.println(); 13848 mSettings.dumpReadMessagesLPr(pw, dumpState); 13849 13850 pw.println(); 13851 pw.println("Package warning messages:"); 13852 BufferedReader in = null; 13853 String line = null; 13854 try { 13855 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13856 while ((line = in.readLine()) != null) { 13857 if (line.contains("ignored: updated version")) continue; 13858 pw.println(line); 13859 } 13860 } catch (IOException ignored) { 13861 } finally { 13862 IoUtils.closeQuietly(in); 13863 } 13864 } 13865 13866 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13867 BufferedReader in = null; 13868 String line = null; 13869 try { 13870 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13871 while ((line = in.readLine()) != null) { 13872 if (line.contains("ignored: updated version")) continue; 13873 pw.print("msg,"); 13874 pw.println(line); 13875 } 13876 } catch (IOException ignored) { 13877 } finally { 13878 IoUtils.closeQuietly(in); 13879 } 13880 } 13881 } 13882 } 13883 13884 // ------- apps on sdcard specific code ------- 13885 static final boolean DEBUG_SD_INSTALL = false; 13886 13887 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 13888 13889 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 13890 13891 private boolean mMediaMounted = false; 13892 13893 static String getEncryptKey() { 13894 try { 13895 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 13896 SD_ENCRYPTION_KEYSTORE_NAME); 13897 if (sdEncKey == null) { 13898 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 13899 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 13900 if (sdEncKey == null) { 13901 Slog.e(TAG, "Failed to create encryption keys"); 13902 return null; 13903 } 13904 } 13905 return sdEncKey; 13906 } catch (NoSuchAlgorithmException nsae) { 13907 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 13908 return null; 13909 } catch (IOException ioe) { 13910 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 13911 return null; 13912 } 13913 } 13914 13915 /* 13916 * Update media status on PackageManager. 13917 */ 13918 @Override 13919 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 13920 int callingUid = Binder.getCallingUid(); 13921 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 13922 throw new SecurityException("Media status can only be updated by the system"); 13923 } 13924 // reader; this apparently protects mMediaMounted, but should probably 13925 // be a different lock in that case. 13926 synchronized (mPackages) { 13927 Log.i(TAG, "Updating external media status from " 13928 + (mMediaMounted ? "mounted" : "unmounted") + " to " 13929 + (mediaStatus ? "mounted" : "unmounted")); 13930 if (DEBUG_SD_INSTALL) 13931 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 13932 + ", mMediaMounted=" + mMediaMounted); 13933 if (mediaStatus == mMediaMounted) { 13934 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 13935 : 0, -1); 13936 mHandler.sendMessage(msg); 13937 return; 13938 } 13939 mMediaMounted = mediaStatus; 13940 } 13941 // Queue up an async operation since the package installation may take a 13942 // little while. 13943 mHandler.post(new Runnable() { 13944 public void run() { 13945 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 13946 } 13947 }); 13948 } 13949 13950 /** 13951 * Called by MountService when the initial ASECs to scan are available. 13952 * Should block until all the ASEC containers are finished being scanned. 13953 */ 13954 public void scanAvailableAsecs() { 13955 updateExternalMediaStatusInner(true, false, false); 13956 if (mShouldRestoreconData) { 13957 SELinuxMMAC.setRestoreconDone(); 13958 mShouldRestoreconData = false; 13959 } 13960 } 13961 13962 /* 13963 * Collect information of applications on external media, map them against 13964 * existing containers and update information based on current mount status. 13965 * Please note that we always have to report status if reportStatus has been 13966 * set to true especially when unloading packages. 13967 */ 13968 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 13969 boolean externalStorage) { 13970 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 13971 int[] uidArr = EmptyArray.INT; 13972 13973 final String[] list = PackageHelper.getSecureContainerList(); 13974 if (ArrayUtils.isEmpty(list)) { 13975 Log.i(TAG, "No secure containers found"); 13976 } else { 13977 // Process list of secure containers and categorize them 13978 // as active or stale based on their package internal state. 13979 13980 // reader 13981 synchronized (mPackages) { 13982 for (String cid : list) { 13983 // Leave stages untouched for now; installer service owns them 13984 if (PackageInstallerService.isStageName(cid)) continue; 13985 13986 if (DEBUG_SD_INSTALL) 13987 Log.i(TAG, "Processing container " + cid); 13988 String pkgName = getAsecPackageName(cid); 13989 if (pkgName == null) { 13990 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 13991 continue; 13992 } 13993 if (DEBUG_SD_INSTALL) 13994 Log.i(TAG, "Looking for pkg : " + pkgName); 13995 13996 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13997 if (ps == null) { 13998 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 13999 continue; 14000 } 14001 14002 /* 14003 * Skip packages that are not external if we're unmounting 14004 * external storage. 14005 */ 14006 if (externalStorage && !isMounted && !isExternal(ps)) { 14007 continue; 14008 } 14009 14010 final AsecInstallArgs args = new AsecInstallArgs(cid, 14011 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14012 // The package status is changed only if the code path 14013 // matches between settings and the container id. 14014 if (ps.codePathString != null 14015 && ps.codePathString.startsWith(args.getCodePath())) { 14016 if (DEBUG_SD_INSTALL) { 14017 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14018 + " at code path: " + ps.codePathString); 14019 } 14020 14021 // We do have a valid package installed on sdcard 14022 processCids.put(args, ps.codePathString); 14023 final int uid = ps.appId; 14024 if (uid != -1) { 14025 uidArr = ArrayUtils.appendInt(uidArr, uid); 14026 } 14027 } else { 14028 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14029 + ps.codePathString); 14030 } 14031 } 14032 } 14033 14034 Arrays.sort(uidArr); 14035 } 14036 14037 // Process packages with valid entries. 14038 if (isMounted) { 14039 if (DEBUG_SD_INSTALL) 14040 Log.i(TAG, "Loading packages"); 14041 loadMediaPackages(processCids, uidArr); 14042 startCleaningPackages(); 14043 mInstallerService.onSecureContainersAvailable(); 14044 } else { 14045 if (DEBUG_SD_INSTALL) 14046 Log.i(TAG, "Unloading packages"); 14047 unloadMediaPackages(processCids, uidArr, reportStatus); 14048 } 14049 } 14050 14051 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14052 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14053 final int size = infos.size(); 14054 final String[] packageNames = new String[size]; 14055 final int[] packageUids = new int[size]; 14056 for (int i = 0; i < size; i++) { 14057 final ApplicationInfo info = infos.get(i); 14058 packageNames[i] = info.packageName; 14059 packageUids[i] = info.uid; 14060 } 14061 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14062 finishedReceiver); 14063 } 14064 14065 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14066 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14067 sendResourcesChangedBroadcast(mediaStatus, replacing, 14068 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14069 } 14070 14071 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14072 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14073 int size = pkgList.length; 14074 if (size > 0) { 14075 // Send broadcasts here 14076 Bundle extras = new Bundle(); 14077 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14078 if (uidArr != null) { 14079 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14080 } 14081 if (replacing) { 14082 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14083 } 14084 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14085 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14086 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14087 } 14088 } 14089 14090 /* 14091 * Look at potentially valid container ids from processCids If package 14092 * information doesn't match the one on record or package scanning fails, 14093 * the cid is added to list of removeCids. We currently don't delete stale 14094 * containers. 14095 */ 14096 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14097 ArrayList<String> pkgList = new ArrayList<String>(); 14098 Set<AsecInstallArgs> keys = processCids.keySet(); 14099 14100 for (AsecInstallArgs args : keys) { 14101 String codePath = processCids.get(args); 14102 if (DEBUG_SD_INSTALL) 14103 Log.i(TAG, "Loading container : " + args.cid); 14104 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14105 try { 14106 // Make sure there are no container errors first. 14107 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14108 Slog.e(TAG, "Failed to mount cid : " + args.cid 14109 + " when installing from sdcard"); 14110 continue; 14111 } 14112 // Check code path here. 14113 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14114 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14115 + " does not match one in settings " + codePath); 14116 continue; 14117 } 14118 // Parse package 14119 int parseFlags = mDefParseFlags; 14120 if (args.isExternalAsec()) { 14121 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14122 } 14123 if (args.isFwdLocked()) { 14124 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14125 } 14126 14127 synchronized (mInstallLock) { 14128 PackageParser.Package pkg = null; 14129 try { 14130 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14131 } catch (PackageManagerException e) { 14132 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14133 } 14134 // Scan the package 14135 if (pkg != null) { 14136 /* 14137 * TODO why is the lock being held? doPostInstall is 14138 * called in other places without the lock. This needs 14139 * to be straightened out. 14140 */ 14141 // writer 14142 synchronized (mPackages) { 14143 retCode = PackageManager.INSTALL_SUCCEEDED; 14144 pkgList.add(pkg.packageName); 14145 // Post process args 14146 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14147 pkg.applicationInfo.uid); 14148 } 14149 } else { 14150 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14151 } 14152 } 14153 14154 } finally { 14155 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14156 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14157 } 14158 } 14159 } 14160 // writer 14161 synchronized (mPackages) { 14162 // If the platform SDK has changed since the last time we booted, 14163 // we need to re-grant app permission to catch any new ones that 14164 // appear. This is really a hack, and means that apps can in some 14165 // cases get permissions that the user didn't initially explicitly 14166 // allow... it would be nice to have some better way to handle 14167 // this situation. 14168 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14169 if (regrantPermissions) 14170 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14171 + mSdkVersion + "; regranting permissions for external storage"); 14172 mSettings.mExternalSdkPlatform = mSdkVersion; 14173 14174 // Make sure group IDs have been assigned, and any permission 14175 // changes in other apps are accounted for 14176 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14177 | (regrantPermissions 14178 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14179 : 0)); 14180 14181 mSettings.updateExternalDatabaseVersion(); 14182 14183 // can downgrade to reader 14184 // Persist settings 14185 mSettings.writeLPr(); 14186 } 14187 // Send a broadcast to let everyone know we are done processing 14188 if (pkgList.size() > 0) { 14189 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14190 } 14191 } 14192 14193 /* 14194 * Utility method to unload a list of specified containers 14195 */ 14196 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14197 // Just unmount all valid containers. 14198 for (AsecInstallArgs arg : cidArgs) { 14199 synchronized (mInstallLock) { 14200 arg.doPostDeleteLI(false); 14201 } 14202 } 14203 } 14204 14205 /* 14206 * Unload packages mounted on external media. This involves deleting package 14207 * data from internal structures, sending broadcasts about diabled packages, 14208 * gc'ing to free up references, unmounting all secure containers 14209 * corresponding to packages on external media, and posting a 14210 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14211 * that we always have to post this message if status has been requested no 14212 * matter what. 14213 */ 14214 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14215 final boolean reportStatus) { 14216 if (DEBUG_SD_INSTALL) 14217 Log.i(TAG, "unloading media packages"); 14218 ArrayList<String> pkgList = new ArrayList<String>(); 14219 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14220 final Set<AsecInstallArgs> keys = processCids.keySet(); 14221 for (AsecInstallArgs args : keys) { 14222 String pkgName = args.getPackageName(); 14223 if (DEBUG_SD_INSTALL) 14224 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14225 // Delete package internally 14226 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14227 synchronized (mInstallLock) { 14228 boolean res = deletePackageLI(pkgName, null, false, null, null, 14229 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14230 if (res) { 14231 pkgList.add(pkgName); 14232 } else { 14233 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14234 failedList.add(args); 14235 } 14236 } 14237 } 14238 14239 // reader 14240 synchronized (mPackages) { 14241 // We didn't update the settings after removing each package; 14242 // write them now for all packages. 14243 mSettings.writeLPr(); 14244 } 14245 14246 // We have to absolutely send UPDATED_MEDIA_STATUS only 14247 // after confirming that all the receivers processed the ordered 14248 // broadcast when packages get disabled, force a gc to clean things up. 14249 // and unload all the containers. 14250 if (pkgList.size() > 0) { 14251 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14252 new IIntentReceiver.Stub() { 14253 public void performReceive(Intent intent, int resultCode, String data, 14254 Bundle extras, boolean ordered, boolean sticky, 14255 int sendingUser) throws RemoteException { 14256 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14257 reportStatus ? 1 : 0, 1, keys); 14258 mHandler.sendMessage(msg); 14259 } 14260 }); 14261 } else { 14262 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14263 keys); 14264 mHandler.sendMessage(msg); 14265 } 14266 } 14267 14268 private void loadPrivatePackages(VolumeInfo vol) { 14269 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14270 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14271 synchronized (mInstallLock) { 14272 synchronized (mPackages) { 14273 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14274 for (PackageSetting ps : packages) { 14275 final PackageParser.Package pkg; 14276 try { 14277 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14278 loaded.add(pkg.applicationInfo); 14279 } catch (PackageManagerException e) { 14280 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14281 } 14282 } 14283 14284 // TODO: regrant any permissions that changed based since original install 14285 14286 mSettings.writeLPr(); 14287 } 14288 } 14289 14290 Slog.d(TAG, "Loaded packages " + loaded); 14291 sendResourcesChangedBroadcast(true, false, loaded, null); 14292 } 14293 14294 private void unloadPrivatePackages(VolumeInfo vol) { 14295 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14296 synchronized (mInstallLock) { 14297 synchronized (mPackages) { 14298 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14299 for (PackageSetting ps : packages) { 14300 if (ps.pkg == null) continue; 14301 14302 final ApplicationInfo info = ps.pkg.applicationInfo; 14303 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14304 if (deletePackageLI(ps.name, null, false, null, null, 14305 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14306 unloaded.add(info); 14307 } else { 14308 Slog.w(TAG, "Failed to unload " + ps.codePath); 14309 } 14310 } 14311 14312 mSettings.writeLPr(); 14313 } 14314 } 14315 14316 Slog.d(TAG, "Unloaded packages " + unloaded); 14317 sendResourcesChangedBroadcast(false, false, unloaded, null); 14318 } 14319 14320 private void unfreezePackage(String packageName) { 14321 synchronized (mPackages) { 14322 final PackageSetting ps = mSettings.mPackages.get(packageName); 14323 if (ps != null) { 14324 ps.frozen = false; 14325 } 14326 } 14327 } 14328 14329 @Override 14330 public int movePackage(final String packageName, final String volumeUuid) { 14331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14332 14333 final int moveId = mNextMoveId.getAndIncrement(); 14334 try { 14335 movePackageInternal(packageName, volumeUuid, moveId); 14336 } catch (PackageManagerException e) { 14337 Slog.d(TAG, "Failed to move " + packageName, e); 14338 mMoveCallbacks.notifyStatusChanged(moveId, 14339 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14340 } 14341 return moveId; 14342 } 14343 14344 private void movePackageInternal(final String packageName, final String volumeUuid, 14345 final int moveId) throws PackageManagerException { 14346 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14347 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14348 final PackageManager pm = mContext.getPackageManager(); 14349 14350 final boolean currentAsec; 14351 final String currentVolumeUuid; 14352 final File codeFile; 14353 final String installerPackageName; 14354 final String packageAbiOverride; 14355 final int appId; 14356 final String seinfo; 14357 final String label; 14358 14359 // reader 14360 synchronized (mPackages) { 14361 final PackageParser.Package pkg = mPackages.get(packageName); 14362 final PackageSetting ps = mSettings.mPackages.get(packageName); 14363 if (pkg == null || ps == null) { 14364 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14365 } 14366 14367 if (pkg.applicationInfo.isSystemApp()) { 14368 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14369 "Cannot move system application"); 14370 } 14371 14372 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14373 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14374 "Package already moved to " + volumeUuid); 14375 } 14376 14377 final File probe = new File(pkg.codePath); 14378 final File probeOat = new File(probe, "oat"); 14379 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14380 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14381 "Move only supported for modern cluster style installs"); 14382 } 14383 14384 if (ps.frozen) { 14385 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14386 "Failed to move already frozen package"); 14387 } 14388 ps.frozen = true; 14389 14390 currentAsec = pkg.applicationInfo.isForwardLocked() 14391 || pkg.applicationInfo.isExternalAsec(); 14392 currentVolumeUuid = ps.volumeUuid; 14393 codeFile = new File(pkg.codePath); 14394 installerPackageName = ps.installerPackageName; 14395 packageAbiOverride = ps.cpuAbiOverrideString; 14396 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14397 seinfo = pkg.applicationInfo.seinfo; 14398 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14399 } 14400 14401 // Now that we're guarded by frozen state, kill app during move 14402 killApplication(packageName, appId, "move pkg"); 14403 14404 final Bundle extras = new Bundle(); 14405 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14406 extras.putString(Intent.EXTRA_TITLE, label); 14407 mMoveCallbacks.notifyCreated(moveId, extras); 14408 14409 int installFlags; 14410 final boolean moveCompleteApp; 14411 final File measurePath; 14412 14413 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14414 installFlags = INSTALL_INTERNAL; 14415 moveCompleteApp = !currentAsec; 14416 measurePath = Environment.getDataAppDirectory(volumeUuid); 14417 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14418 installFlags = INSTALL_EXTERNAL; 14419 moveCompleteApp = false; 14420 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14421 } else { 14422 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14423 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14424 || !volume.isMountedWritable()) { 14425 unfreezePackage(packageName); 14426 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14427 "Move location not mounted private volume"); 14428 } 14429 14430 Preconditions.checkState(!currentAsec); 14431 14432 installFlags = INSTALL_INTERNAL; 14433 moveCompleteApp = true; 14434 measurePath = Environment.getDataAppDirectory(volumeUuid); 14435 } 14436 14437 final PackageStats stats = new PackageStats(null, -1); 14438 synchronized (mInstaller) { 14439 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14440 unfreezePackage(packageName); 14441 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14442 "Failed to measure package size"); 14443 } 14444 } 14445 14446 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14447 14448 final long startFreeBytes = measurePath.getFreeSpace(); 14449 final long sizeBytes; 14450 if (moveCompleteApp) { 14451 sizeBytes = stats.codeSize + stats.dataSize; 14452 } else { 14453 sizeBytes = stats.codeSize; 14454 } 14455 14456 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14457 unfreezePackage(packageName); 14458 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14459 "Not enough free space to move"); 14460 } 14461 14462 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14463 14464 final CountDownLatch installedLatch = new CountDownLatch(1); 14465 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14466 @Override 14467 public void onUserActionRequired(Intent intent) throws RemoteException { 14468 throw new IllegalStateException(); 14469 } 14470 14471 @Override 14472 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14473 Bundle extras) throws RemoteException { 14474 Slog.d(TAG, "Install result for move: " 14475 + PackageManager.installStatusToString(returnCode, msg)); 14476 14477 installedLatch.countDown(); 14478 14479 // Regardless of success or failure of the move operation, 14480 // always unfreeze the package 14481 unfreezePackage(packageName); 14482 14483 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14484 switch (status) { 14485 case PackageInstaller.STATUS_SUCCESS: 14486 mMoveCallbacks.notifyStatusChanged(moveId, 14487 PackageManager.MOVE_SUCCEEDED); 14488 break; 14489 case PackageInstaller.STATUS_FAILURE_STORAGE: 14490 mMoveCallbacks.notifyStatusChanged(moveId, 14491 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14492 break; 14493 default: 14494 mMoveCallbacks.notifyStatusChanged(moveId, 14495 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14496 break; 14497 } 14498 } 14499 }; 14500 14501 final MoveInfo move; 14502 if (moveCompleteApp) { 14503 // Kick off a thread to report progress estimates 14504 new Thread() { 14505 @Override 14506 public void run() { 14507 while (true) { 14508 try { 14509 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14510 break; 14511 } 14512 } catch (InterruptedException ignored) { 14513 } 14514 14515 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14516 final int progress = 10 + (int) MathUtils.constrain( 14517 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14518 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14519 } 14520 } 14521 }.start(); 14522 14523 final String dataAppName = codeFile.getName(); 14524 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14525 dataAppName, appId, seinfo); 14526 } else { 14527 move = null; 14528 } 14529 14530 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14531 14532 final Message msg = mHandler.obtainMessage(INIT_COPY); 14533 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14534 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14535 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14536 mHandler.sendMessage(msg); 14537 } 14538 14539 @Override 14540 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14541 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14542 14543 final int realMoveId = mNextMoveId.getAndIncrement(); 14544 final Bundle extras = new Bundle(); 14545 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14546 mMoveCallbacks.notifyCreated(realMoveId, extras); 14547 14548 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14549 @Override 14550 public void onCreated(int moveId, Bundle extras) { 14551 // Ignored 14552 } 14553 14554 @Override 14555 public void onStatusChanged(int moveId, int status, long estMillis) { 14556 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14557 } 14558 }; 14559 14560 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14561 storage.setPrimaryStorageUuid(volumeUuid, callback); 14562 return realMoveId; 14563 } 14564 14565 @Override 14566 public int getMoveStatus(int moveId) { 14567 mContext.enforceCallingOrSelfPermission( 14568 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14569 return mMoveCallbacks.mLastStatus.get(moveId); 14570 } 14571 14572 @Override 14573 public void registerMoveCallback(IPackageMoveObserver callback) { 14574 mContext.enforceCallingOrSelfPermission( 14575 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14576 mMoveCallbacks.register(callback); 14577 } 14578 14579 @Override 14580 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14581 mContext.enforceCallingOrSelfPermission( 14582 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14583 mMoveCallbacks.unregister(callback); 14584 } 14585 14586 @Override 14587 public boolean setInstallLocation(int loc) { 14588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14589 null); 14590 if (getInstallLocation() == loc) { 14591 return true; 14592 } 14593 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14594 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14595 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14596 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14597 return true; 14598 } 14599 return false; 14600 } 14601 14602 @Override 14603 public int getInstallLocation() { 14604 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14605 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14606 PackageHelper.APP_INSTALL_AUTO); 14607 } 14608 14609 /** Called by UserManagerService */ 14610 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14611 mDirtyUsers.remove(userHandle); 14612 mSettings.removeUserLPw(userHandle); 14613 mPendingBroadcasts.remove(userHandle); 14614 if (mInstaller != null) { 14615 // Technically, we shouldn't be doing this with the package lock 14616 // held. However, this is very rare, and there is already so much 14617 // other disk I/O going on, that we'll let it slide for now. 14618 final StorageManager storage = StorageManager.from(mContext); 14619 final List<VolumeInfo> vols = storage.getVolumes(); 14620 for (VolumeInfo vol : vols) { 14621 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14622 final String volumeUuid = vol.getFsUuid(); 14623 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14624 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14625 } 14626 } 14627 } 14628 mUserNeedsBadging.delete(userHandle); 14629 removeUnusedPackagesLILPw(userManager, userHandle); 14630 } 14631 14632 /** 14633 * We're removing userHandle and would like to remove any downloaded packages 14634 * that are no longer in use by any other user. 14635 * @param userHandle the user being removed 14636 */ 14637 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14638 final boolean DEBUG_CLEAN_APKS = false; 14639 int [] users = userManager.getUserIdsLPr(); 14640 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14641 while (psit.hasNext()) { 14642 PackageSetting ps = psit.next(); 14643 if (ps.pkg == null) { 14644 continue; 14645 } 14646 final String packageName = ps.pkg.packageName; 14647 // Skip over if system app 14648 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14649 continue; 14650 } 14651 if (DEBUG_CLEAN_APKS) { 14652 Slog.i(TAG, "Checking package " + packageName); 14653 } 14654 boolean keep = false; 14655 for (int i = 0; i < users.length; i++) { 14656 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14657 keep = true; 14658 if (DEBUG_CLEAN_APKS) { 14659 Slog.i(TAG, " Keeping package " + packageName + " for user " 14660 + users[i]); 14661 } 14662 break; 14663 } 14664 } 14665 if (!keep) { 14666 if (DEBUG_CLEAN_APKS) { 14667 Slog.i(TAG, " Removing package " + packageName); 14668 } 14669 mHandler.post(new Runnable() { 14670 public void run() { 14671 deletePackageX(packageName, userHandle, 0); 14672 } //end run 14673 }); 14674 } 14675 } 14676 } 14677 14678 /** Called by UserManagerService */ 14679 void createNewUserLILPw(int userHandle, File path) { 14680 if (mInstaller != null) { 14681 mInstaller.createUserConfig(userHandle); 14682 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14683 } 14684 } 14685 14686 void newUserCreatedLILPw(int userHandle) { 14687 // Adding a user requires updating runtime permissions for system apps. 14688 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14689 } 14690 14691 @Override 14692 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14693 mContext.enforceCallingOrSelfPermission( 14694 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14695 "Only package verification agents can read the verifier device identity"); 14696 14697 synchronized (mPackages) { 14698 return mSettings.getVerifierDeviceIdentityLPw(); 14699 } 14700 } 14701 14702 @Override 14703 public void setPermissionEnforced(String permission, boolean enforced) { 14704 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14705 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14706 synchronized (mPackages) { 14707 if (mSettings.mReadExternalStorageEnforced == null 14708 || mSettings.mReadExternalStorageEnforced != enforced) { 14709 mSettings.mReadExternalStorageEnforced = enforced; 14710 mSettings.writeLPr(); 14711 } 14712 } 14713 // kill any non-foreground processes so we restart them and 14714 // grant/revoke the GID. 14715 final IActivityManager am = ActivityManagerNative.getDefault(); 14716 if (am != null) { 14717 final long token = Binder.clearCallingIdentity(); 14718 try { 14719 am.killProcessesBelowForeground("setPermissionEnforcement"); 14720 } catch (RemoteException e) { 14721 } finally { 14722 Binder.restoreCallingIdentity(token); 14723 } 14724 } 14725 } else { 14726 throw new IllegalArgumentException("No selective enforcement for " + permission); 14727 } 14728 } 14729 14730 @Override 14731 @Deprecated 14732 public boolean isPermissionEnforced(String permission) { 14733 return true; 14734 } 14735 14736 @Override 14737 public boolean isStorageLow() { 14738 final long token = Binder.clearCallingIdentity(); 14739 try { 14740 final DeviceStorageMonitorInternal 14741 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14742 if (dsm != null) { 14743 return dsm.isMemoryLow(); 14744 } else { 14745 return false; 14746 } 14747 } finally { 14748 Binder.restoreCallingIdentity(token); 14749 } 14750 } 14751 14752 @Override 14753 public IPackageInstaller getPackageInstaller() { 14754 return mInstallerService; 14755 } 14756 14757 private boolean userNeedsBadging(int userId) { 14758 int index = mUserNeedsBadging.indexOfKey(userId); 14759 if (index < 0) { 14760 final UserInfo userInfo; 14761 final long token = Binder.clearCallingIdentity(); 14762 try { 14763 userInfo = sUserManager.getUserInfo(userId); 14764 } finally { 14765 Binder.restoreCallingIdentity(token); 14766 } 14767 final boolean b; 14768 if (userInfo != null && userInfo.isManagedProfile()) { 14769 b = true; 14770 } else { 14771 b = false; 14772 } 14773 mUserNeedsBadging.put(userId, b); 14774 return b; 14775 } 14776 return mUserNeedsBadging.valueAt(index); 14777 } 14778 14779 @Override 14780 public KeySet getKeySetByAlias(String packageName, String alias) { 14781 if (packageName == null || alias == null) { 14782 return null; 14783 } 14784 synchronized(mPackages) { 14785 final PackageParser.Package pkg = mPackages.get(packageName); 14786 if (pkg == null) { 14787 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14788 throw new IllegalArgumentException("Unknown package: " + packageName); 14789 } 14790 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14791 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14792 } 14793 } 14794 14795 @Override 14796 public KeySet getSigningKeySet(String packageName) { 14797 if (packageName == null) { 14798 return null; 14799 } 14800 synchronized(mPackages) { 14801 final PackageParser.Package pkg = mPackages.get(packageName); 14802 if (pkg == null) { 14803 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14804 throw new IllegalArgumentException("Unknown package: " + packageName); 14805 } 14806 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14807 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14808 throw new SecurityException("May not access signing KeySet of other apps."); 14809 } 14810 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14811 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14812 } 14813 } 14814 14815 @Override 14816 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14817 if (packageName == null || ks == null) { 14818 return false; 14819 } 14820 synchronized(mPackages) { 14821 final PackageParser.Package pkg = mPackages.get(packageName); 14822 if (pkg == null) { 14823 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14824 throw new IllegalArgumentException("Unknown package: " + packageName); 14825 } 14826 IBinder ksh = ks.getToken(); 14827 if (ksh instanceof KeySetHandle) { 14828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14829 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14830 } 14831 return false; 14832 } 14833 } 14834 14835 @Override 14836 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14837 if (packageName == null || ks == null) { 14838 return false; 14839 } 14840 synchronized(mPackages) { 14841 final PackageParser.Package pkg = mPackages.get(packageName); 14842 if (pkg == null) { 14843 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14844 throw new IllegalArgumentException("Unknown package: " + packageName); 14845 } 14846 IBinder ksh = ks.getToken(); 14847 if (ksh instanceof KeySetHandle) { 14848 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14849 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14850 } 14851 return false; 14852 } 14853 } 14854 14855 public void getUsageStatsIfNoPackageUsageInfo() { 14856 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14857 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14858 if (usm == null) { 14859 throw new IllegalStateException("UsageStatsManager must be initialized"); 14860 } 14861 long now = System.currentTimeMillis(); 14862 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14863 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14864 String packageName = entry.getKey(); 14865 PackageParser.Package pkg = mPackages.get(packageName); 14866 if (pkg == null) { 14867 continue; 14868 } 14869 UsageStats usage = entry.getValue(); 14870 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14871 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14872 } 14873 } 14874 } 14875 14876 /** 14877 * Check and throw if the given before/after packages would be considered a 14878 * downgrade. 14879 */ 14880 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14881 throws PackageManagerException { 14882 if (after.versionCode < before.mVersionCode) { 14883 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14884 "Update version code " + after.versionCode + " is older than current " 14885 + before.mVersionCode); 14886 } else if (after.versionCode == before.mVersionCode) { 14887 if (after.baseRevisionCode < before.baseRevisionCode) { 14888 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14889 "Update base revision code " + after.baseRevisionCode 14890 + " is older than current " + before.baseRevisionCode); 14891 } 14892 14893 if (!ArrayUtils.isEmpty(after.splitNames)) { 14894 for (int i = 0; i < after.splitNames.length; i++) { 14895 final String splitName = after.splitNames[i]; 14896 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 14897 if (j != -1) { 14898 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 14899 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14900 "Update split " + splitName + " revision code " 14901 + after.splitRevisionCodes[i] + " is older than current " 14902 + before.splitRevisionCodes[j]); 14903 } 14904 } 14905 } 14906 } 14907 } 14908 } 14909 14910 private static class MoveCallbacks extends Handler { 14911 private static final int MSG_CREATED = 1; 14912 private static final int MSG_STATUS_CHANGED = 2; 14913 14914 private final RemoteCallbackList<IPackageMoveObserver> 14915 mCallbacks = new RemoteCallbackList<>(); 14916 14917 private final SparseIntArray mLastStatus = new SparseIntArray(); 14918 14919 public MoveCallbacks(Looper looper) { 14920 super(looper); 14921 } 14922 14923 public void register(IPackageMoveObserver callback) { 14924 mCallbacks.register(callback); 14925 } 14926 14927 public void unregister(IPackageMoveObserver callback) { 14928 mCallbacks.unregister(callback); 14929 } 14930 14931 @Override 14932 public void handleMessage(Message msg) { 14933 final SomeArgs args = (SomeArgs) msg.obj; 14934 final int n = mCallbacks.beginBroadcast(); 14935 for (int i = 0; i < n; i++) { 14936 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 14937 try { 14938 invokeCallback(callback, msg.what, args); 14939 } catch (RemoteException ignored) { 14940 } 14941 } 14942 mCallbacks.finishBroadcast(); 14943 args.recycle(); 14944 } 14945 14946 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 14947 throws RemoteException { 14948 switch (what) { 14949 case MSG_CREATED: { 14950 callback.onCreated(args.argi1, (Bundle) args.arg2); 14951 break; 14952 } 14953 case MSG_STATUS_CHANGED: { 14954 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 14955 break; 14956 } 14957 } 14958 } 14959 14960 private void notifyCreated(int moveId, Bundle extras) { 14961 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 14962 14963 final SomeArgs args = SomeArgs.obtain(); 14964 args.argi1 = moveId; 14965 args.arg2 = extras; 14966 obtainMessage(MSG_CREATED, args).sendToTarget(); 14967 } 14968 14969 private void notifyStatusChanged(int moveId, int status) { 14970 notifyStatusChanged(moveId, status, -1); 14971 } 14972 14973 private void notifyStatusChanged(int moveId, int status, long estMillis) { 14974 Slog.v(TAG, "Move " + moveId + " status " + status); 14975 14976 final SomeArgs args = SomeArgs.obtain(); 14977 args.argi1 = moveId; 14978 args.argi2 = status; 14979 args.arg3 = estMillis; 14980 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 14981 14982 synchronized (mLastStatus) { 14983 mLastStatus.put(moveId, status); 14984 } 14985 } 14986 } 14987} 14988